code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
|---|---|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# %matplotlib inline
import sys
import pprint
import numpy as np
import inspect
import os
import matplotlib.pyplot as plt
root_path = os.path.abspath(os.path.join(os.path.pardir))
sys.path.insert(0, root_path)
import pymoca.parser
import pymoca.backends.sympy.generator as generator
import pylab as pl
import sympy
import sympy.physics.mechanics as mech
sympy.init_printing()
mech.mechanics_printing()
# %load_ext autoreload
# %autoreload 2
# -
frame_i = mech.ReferenceFrame('i')
t = sympy.symbols('t')
phi, theta, psi, P, Q, R, x, y, z, U, V, W = mech.dynamicsymbols(
'phi, theta, psi, P, Q, R, x, y, z, U, V, W')
frame_b = frame_i.orientnew('b', 'Body', (psi, theta, phi), '321')
omega_ib = P*frame_b.x + Q*frame_b.y + R*frame_b.z
euler_sol = sympy.solve((frame_b.ang_vel_in(frame_i) - omega_ib).to_matrix(frame_b),
[v.diff(t) for v in [phi, theta, psi]])
frame_b.set_ang_vel(frame_i, omega_ib)
euler_sol
point_o = mech.Point('o')
point_cm = point_o.locatenew('cm', x*frame_i.x + y*frame_i.y + z*frame_i.z)
point_cm.set_vel(frame_b, 0)
M_x, M_y, M_z, F_x, F_y, F_z = mech.dynamicsymbols('M_x, M_y, M_z, F_x, F_y, F_z')
M_b = M_x*frame_b.x + M_y*frame_b.y + M_z*frame_b.z
F_b = F_x*frame_b.x + F_y*frame_b.y + F_z*frame_b.z
V_i = U*frame_b.x + V*frame_b.y + W*frame_b.z
point_cm.set_vel(frame_i, V_i)
J_x, J_y, J_z, m = sympy.symbols('J_x, J_y, J_z, m')
aircraft = mech.RigidBody('aircraft', point_cm,
frame_b, m,
(mech.inertia(frame_b, J_x, J_y, J_z), point_cm))
H_i = aircraft.angular_momentum(point_cm, frame_i)
i_H_i = H_i.diff(t, frame_b) + frame_b.ang_acc_in(frame_i).cross(H_i)
(i_H_i - M_b).to_matrix(frame_b)
L_i = aircraft.linear_momentum(frame_i)
i_L_i = L_i.diff(t, frame_b) + frame_b.ang_acc_in(frame_i).cross(L_i)
(i_L_i - F_b).to_matrix(frame_b)
ast = pymoca.parser.parse('''
model Quad
Real F_x, F_y, F_z;
Real M_x, M_y, M_z;
Real phi, theta, psi;
Real P, Q, R;
Real x, y, z;
Real U, V, W;
parameter Real J_x=1, J_y=1, J_z=1, m=1;
equation
M_x = -P - phi;
M_y = -Q - theta;
M_z = -R - psi;
F_x = -U -x;
F_y = -V -y;
F_z = -W -z;
der(x) = U;
der(y) = V;
der(z) = W;
-m*V*der(R) + m*W*der(Q) + m*der(U) = F_x;
m*U*der(R) - m*W*der(P) + m*der(V) = F_y;
-m*U*der(Q) + m*V*der(P) + m*der(W) = F_z;
der(phi) = P + Q*sin(phi)*tan(theta) + R*cos(phi)*tan(theta);
der(theta) = Q*cos(phi) - R*sin(phi);
cos(theta)*der(psi) = Q*sin(phi) + R*cos(phi);
J_x*der(P) = M_x;
J_y*der(Q) = M_y;
J_z*der(R) = M_z;
end Quad;
''')
#print(ast)
quad_src = generator.generate(ast, 'Quad')
exec(quad_src)
print(quad_src)
exec(quad_src)
quad = Quad()
res = quad.simulate(x0 = [0,0,0, 1,2,3, 0, 0, 0, 1, 0, 0], tf=20)
plt.plot(res['t'], res['x']);
plt.grid()
v_x, v_y, v_z, x, y, z = sympy.physics.mechanics.dynamicsymbols('v_x, v_y, v_z, x, y, z')
m, g = sympy.symbols('m, g')
Lyap = aircraft.kinetic_energy(frame_i) + phi**2/2 + theta**2/2 + psi**2/2 + \
x**2/2 + y**2/2 + z**2/2
Lyap
LyapDot = sympy.Matrix([Lyap]).jacobian(quad.x).dot(quad.f).expand().simplify()
LyapDot = LyapDot.expand().collect([P, Q, R, U, V, W], sympy.factor)
LyapDot
|
test/notebooks/Quad.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Cipher import AES
from Crypto import Random
from random import randint
from base64 import b64encode
from os import urandom
import base64,string,random,rsa
# export AES key to file
key = RSA.generate(1024)
f = open('mykey', 'wb')
f.write(key.exportKey())
f.close()
# RSA encryption and decryption
msg = "this is a stupid project"
r = RSA.generate(1024)
encrypted = r.encrypt(msg.encode("utf-8"), randint(0, 10))[0]
print(b64encode(encrypted))
decrypted = r.decrypt(encrypted)
print(decrypted.decode('ascii'))
def aespadding(ciphertext, padding = ' '):
l = len(ciphertext) % 16
n = int((16 - l)/len(padding))
if not l == 0:
return (16 - l), (ciphertext + padding*n)
# AES encryption and decryption
msg = "I don't really give a fuck"
# generate 128 bit AES key
key = urandom(16)
print("AES key : {0}".format(b64encode(key)))
iv = urandom(AES.block_size)
print("AES Initialization vector : {0}".format(b64encode(iv)))
cipher = AES.new(key, AES.MODE_ECB, iv)
padlen, padded = aespadding(msg)
encrypted = cipher.encrypt(padded)
# note that actual transfer, need to transfer encrypted = iv + encrypted text
print("encrypted : {0}".format(b64encode(encrypted)))
decrypted = cipher.decrypt(encrypted)
print(decrypted.decode('utf-8'))
key = b64encode(urandom(12))
key.decode('utf-8')
''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(16))
b64encode(key)
publicKey, privateKey = rsa.newkeys(128)
msg = rsa.encrypt('hello'.encode(),publicKey)
rsa.decrypt(msg,privateKey).decode()
a = b"4\xf8\xad\xd7\xf6z*c\x9c2m\xe6\xf7\xc5\x94\x06\x10\xcb\xfe\xc0\xa5\xee\r\xb5\xa3;\x8f\x15~B\x85\x08\x9e\xd0\nL(\xf3\xec\x0f\x98z}\x89\x9d({\x8c\x1b\xbc]\x8a\\\x1f\xb9\xce\x93\x00\xebP\xbd\xe20=y\xd39\x901=5\x1e\x12.'\xa7\xd8D\x7f\xf2\xa1u.\xcfc\\r\x89eNJ\x1eQA3\x8a\xfa\xbbM\x80^\x967\xea!\x82&\x8b\x03\xdc\x01E\xdf\x83T\xe33\xdf\x08\xf7\xb8\xea8]\xb5\xc4\xe2c"
type(a)
|
examples/encrypt.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] colab_type="text" id="0b22pthXn4Nz"
# # Simulating Microlensing graphs
#
# $I_{obs} \left( t \right) = I_{s0} + I_{A} + N \left( \sigma^{2} \right) $
#
# $I_{s0}$ is baseline, $I_{A}$ is lens magnification
#
# + colab_type="code" id="fKIUFbKqkv9I" colab={}
import numpy as np
from matplotlib import pyplot as plt
# + [markdown] colab_type="text" id="tympBdUqp0ed"
# ## Baseline
# + [markdown] colab_type="text" id="QzCbgPnHo4m-"
# $I_{s0} = m_{A} \mbox{sin} \left( \frac{2 \pi t}{T} + \phi \right) $
#
# where
#
# $m_{A}$ is amplitude
#
# $T$ is period
#
# $\phi$ is phase
#
# + colab_type="code" id="KD8m7Mknjji7" colab={}
def intensity_baseline(period, amplitude, phase, t):
return amplitude * np.sin((2 * np.pi * t / period) + phase)
# + colab_type="code" id="hIanYheMlDLN" colab={}
is0_ex1 = [intensity_baseline(5, 0.00005, 0, x) for x in range(100)]
# + colab_type="code" executionInfo={"status": "ok", "timestamp": 1575386917640, "user_tz": 300, "elapsed": 1916, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}} id="9cxT2obtlJ5Q" outputId="092ffab9-99e0-447a-b833-05e06cfba727" colab={"base_uri": "https://localhost:8080/", "height": 282}
plt.plot(is0_ex1)
# + [markdown] colab_type="text" id="g3pDqz16p27e"
# ## Lens Magnification
# + [markdown] colab_type="text" id="Jdr_c0Esp61T"
# $A \left( t \right) = \frac{\left[ u(t) \right]^{2} + 2}{u(t) + \sqrt{[u(t)]^2 + 4}} $
#
# $u(t) = u_0 + \left| \frac{t-t_0}{T_E} \right|$
#
# where
#
# $u_0$ is minimum impact parameter
#
# $T_E$ and $t_0$ determins the radius and shift in time
# + colab_type="code" id="o3nfpKMwlLCu" colab={}
def lens_magnification(u0, t0, tE, t):
ut = u0 + np.abs((t - t0) / tE)
return (ut ** 2 + 2) / (ut * np.sqrt(ut**2 + 4))
# + colab_type="code" id="aSuZoDi8mHwv" colab={}
iA_ex1 = [lens_magnification(10, 50, 2, x) for x in range(100)]
# + colab_type="code" executionInfo={"status": "ok", "timestamp": 1575386918134, "user_tz": 300, "elapsed": 2394, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}} id="5VyWn8fKmOJQ" outputId="66761cbc-8d39-469d-cd0e-bd76fc7f603d" colab={"base_uri": "https://localhost:8080/", "height": 293}
plt.plot(iA_ex1)
# + [markdown] colab_type="text" id="C6fYlz37q4Pf"
# ## Putting all together
# + colab_type="code" executionInfo={"status": "ok", "timestamp": 1575386918135, "user_tz": 300, "elapsed": 2384, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}} id="wRLbXwCOmWh2" outputId="3704ffcd-fb39-4c73-8655-daaa7222d368" colab={"base_uri": "https://localhost:8080/", "height": 293}
iobs_ex1 = np.array(iA_ex1) + np.array(is0_ex1) + np.random.normal(scale=0.00003, size=100)
plt.plot(iobs_ex1)
# + [markdown] colab_type="text" id="5TirjZikq9Vk"
# Perhaps its a good idea to normalize the graph so that it will have mean=0 and stdev=1
# + colab_type="code" id="g03B4LtNq7tD" colab={}
iobs_ex1_normalized = iobs_ex1 / np.linalg.norm(iobs_ex1)
# + colab_type="code" executionInfo={"status": "ok", "timestamp": 1575386918136, "user_tz": 300, "elapsed": 2373, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}} id="iVfc8xJfrRpx" outputId="6b4add94-a9bd-4dd2-f022-ffd821331a17" colab={"base_uri": "https://localhost:8080/", "height": 293}
plt.plot(iobs_ex1_normalized)
# + colab_type="code" id="-0tw8WYbrTJn" colab={}
import numpy as np
import matplotlib.pyplot as plt
def intensity_baseline(period, amplitude, phase, t):
return amplitude * np.sin((2 * np.pi * t / period) + phase)
def lens_magnification(u0, t0, tE, t):
ut = u0 + np.abs((t - t0) / tE)
return (ut ** 2 + 2) / (ut * np.sqrt(ut**2 + 4))
def simulate_microlensing(baseline_period, baseline_amplitude, baseline_phase,
lens_min_impact, lens_shift, lens_radius, noise, t_range=range(100)):
i_s0 = np.array([intensity_baseline(baseline_period, baseline_amplitude, baseline_phase, t) for t in t_range])
i_A = np.array([lens_magnification(lens_min_impact, lens_shift, lens_radius, t) for t in t_range])
n = np.random.normal(scale=noise, size=len(t_range))
return i_s0 + i_A + n
# + colab_type="code" executionInfo={"status": "ok", "timestamp": 1575386918137, "user_tz": 300, "elapsed": 2361, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}} id="I-tUXNKer4qK" outputId="e719b90b-fe31-4e63-852b-f3a4369a47b3" colab={"base_uri": "https://localhost:8080/", "height": 293}
plt.plot(simulate_microlensing(baseline_period=2, baseline_amplitude=0.00001, baseline_phase=0,
lens_min_impact=10, lens_shift=75, lens_radius=1, noise=0.00003, t_range=range(100)))
# + [markdown] colab_type="text" id="EMapxiS3f6lR"
# # Fitting sampled data into ARIMA
# + [markdown] colab_type="text" id="tdKTna0bhzIg"
# Installing pyflux (library for time series analysis). Will be using ARIMA class for fitting the sampled data into ARIMA model and make prediction.
# + colab_type="code" executionInfo={"status": "ok", "timestamp": 1575387012046, "user_tz": 300, "elapsed": 96263, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}} id="m5WghyvWtn7n" outputId="fb6b0bba-4c62-4eb2-e5e0-5a9b6e7540dc" colab={"base_uri": "https://localhost:8080/", "height": 357}
pip install pyflux
# + colab_type="code" id="hapI7Slshpe3" colab={}
import pyflux as pf
# + [markdown] colab_type="text" id="o3DFt71uiHTe"
# Creating the model
# + colab_type="code" id="dN4TyNqhi3tG" colab={}
data = simulate_microlensing(baseline_period=2, baseline_amplitude=0.00001, baseline_phase=0,
lens_min_impact=10, lens_shift=75, lens_radius=1, noise=0.00003, t_range=range(100))
model = pf.ARIMA(data=data-1, ar=4, integ=0, ma=4, target='microlense', family=pf.Laplace())
# + id="IPMrGBOtrjt9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 293} outputId="f32f0be8-77e1-47aa-e5cf-231acfe4f933" executionInfo={"status": "ok", "timestamp": 1575387991455, "user_tz": 300, "elapsed": 1170, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}}
plt.plot(data)
# + [markdown] colab_type="text" id="BTT9rWlMjY-_"
# Fitting the data and getting the summary
# + colab_type="code" id="_ct2b7hhjjQY" colab={"base_uri": "https://localhost:8080/", "height": 357} outputId="78c9d8fc-e9b7-4aec-b2bd-ca978743bc3c" executionInfo={"status": "ok", "timestamp": 1575387992894, "user_tz": 300, "elapsed": 1501, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}}
fit = model.fit("MLE")
fit.summary()
# + [markdown] colab_type="text" id="lC7mPOpaqdqv"
# Plotting the fit-
# + colab_type="code" id="IBQzG_xjqtgO" colab={"base_uri": "https://localhost:8080/", "height": 607} outputId="3162285d-47ee-4d75-9df7-9cd31419e930" executionInfo={"status": "ok", "timestamp": 1575387014286, "user_tz": 300, "elapsed": 98475, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}}
model.plot_fit(figsize=(15,10))
# + colab_type="code" id="IWW8kjeRrIKu" colab={"base_uri": "https://localhost:8080/", "height": 350} outputId="fdf3591a-add1-486d-b6a2-a3b02fdce428" executionInfo={"status": "ok", "timestamp": 1575387811069, "user_tz": 300, "elapsed": 8322, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}}
model.plot_predict(h=20,past_values=40,figsize=(15,5))
# + id="k9q2FxDjrTap" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 444} outputId="e8e23462-7214-4ff5-ccd9-4bab06e7b4d3" executionInfo={"status": "ok", "timestamp": 1575387022858, "user_tz": 300, "elapsed": 107032, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}}
model.plot_predict_is(h=50)
# + colab_type="code" id="pY2LOz0_PExN" colab={"base_uri": "https://localhost:8080/", "height": 323} outputId="2d638d6b-c1af-4e9c-c43c-8b416b8d5bbc" executionInfo={"status": "ok", "timestamp": 1575387022859, "user_tz": 300, "elapsed": 107025, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}}
np.array(model.predict(h=70)['Series'])
# + colab_type="code" id="LrNWR4Z3fOoF" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="f9a9f388-facb-4f24-cd8b-190733fdc0c7" executionInfo={"status": "ok", "timestamp": 1575387693204, "user_tz": 300, "elapsed": 1065, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}}
model = pf.ARIMA(data=data-1, ar=5, integ=0, ma=5, target='microlense', family=pf.Normal())
model.fit("MLE")
# + colab_type="code" id="3Ayt5l0eYha3" colab={"base_uri": "https://localhost:8080/", "height": 444} outputId="e905161b-fbb3-47b0-8527-8f11eeb84669" executionInfo={"status": "ok", "timestamp": 1575387778506, "user_tz": 300, "elapsed": 2077, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15277863619286159129"}}
model.plot_predict_is(h=20)
# + [markdown] colab_type="text" id="HSrH4LmmKTKX"
# # Generate Train and Test Data
# + colab_type="code" id="YU2h6iyzNylz" colab={}
def simulate_noevent(baseline_period, baseline_amplitude, baseline_phase, noise, t_range=range(100)):
i_s0 = np.array([intensity_baseline(baseline_period, baseline_amplitude, baseline_phase, t) for t in t_range])
n = np.random.normal(scale=noise, size=len(t_range))
return i_s0 + n
# + colab_type="code" id="nLBC2xkBWNeF" colab={}
from tqdm import tqdm
def generate_dataset(num_dataset):
X_out = np.zeros((num_dataset, 100, 2))
y_out = np.zeros((num_dataset, 100))
for x in tqdm(range(num_dataset)):
seq=None
ys=None
if np.random.uniform() > 0.5:
peak_t = int(np.random.uniform(low=50, high=80))
seq = simulate_microlensing(baseline_period=2,
baseline_amplitude=0.00001,
baseline_phase=0,
lens_min_impact=10,
lens_shift=peak_t,
lens_radius=1,
noise=0.00003,
t_range=range(100))
seq_avg = np.mean(seq[:30])
seq_std = np.std(seq[:30])
seq = (seq - seq_avg) / seq_std
ys = np.zeros(100)
ys[peak_t-10:peak_t] = 1
# print(seq)
# plt.plot(seq)
# break
else:
seq = simulate_noevent(baseline_period=2,
baseline_amplitude=0.00001,
baseline_phase=0,
noise=0.00003,
t_range=range(100))
seq_avg = np.mean(seq[:30])
seq_std = np.std(seq[:30])
seq = (seq - seq_avg) / seq_std
ys = np.zeros(100)
model=pf.ARIMA(data=seq,ar=4, integ=0, ma=4, family=pf.Normal())
model.fit('MLE')
hs = model.predict_is(h=70)
seq_sim = np.concatenate((seq[:30], hs['Series']))
X_out[x,:,0] = seq
X_out[x,:,1] = seq_sim
y_out[x] = ys
return X_out, y_out
# + colab_type="code" id="LgU8xpjNKeYg" colab={}
np.random.seed(420)
X_train, y_train = generate_dataset(10)
# + id="ydy7poGo0E9h" colab_type="code" colab={}
X_train.shape, y_train.shape
# + colab_type="code" id="3MpAJcheZVFm" colab={}
np.random.seed(520)
X_test, y_test = generate_dataset(10)
# + [markdown] colab_type="text" id="RccwnO_wmZ3i"
# # Injecting the residuals into LSTM
# + [markdown] colab_type="text" id="OghjuoCumj9f"
# Building the LSTM model
# + id="95JhaQMZzcnA" colab_type="code" colab={}
# %tensorflow_version 2.x
# + colab_type="code" id="G6zyjgCOfOod" colab={}
from tensorflow.keras import backend as K
def recall_m(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
def precision_m(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
def f1_m(y_true, y_pred):
precision = precision_m(y_true, y_pred)
recall = recall_m(y_true, y_pred)
return 2*((precision*recall)/(precision+recall+K.epsilon()))
# + colab_type="code" id="7n2YrdmLSfF8" colab={}
import tensorflow as tf
from tensorflow.keras import layers
# + colab_type="code" id="PKdOizWumwMP" colab={}
# Initialising the RNN
rnn_lstm = tf.keras.Sequential()
# + colab_type="code" id="-3vInViEnAcF" colab={}
# Adding the LSTM layers and some Dropout regularisation
# Adding the first layer
rnn_lstm.add(layers.LSTM(units=300, return_sequences=True, input_shape=(None, 2)))
rnn_lstm.add(layers.Dropout(0.1))
# Output layer
rnn_lstm.add(layers.Dense(units=1, activation='sigmoid'))
# + id="RWjq10sMzuk6" colab_type="code" colab={}
# + colab_type="code" id="vGoXrZLUoot0" colab={}
# Compiling the RNN
rnn_lstm.compile(optimizer='adam', loss='mean_squared_error', metrics=['acc', f1_m])
rnn_lstm.summary()
# + colab_type="code" id="aTGXJ8t7otfa" colab={}
# Fitting the RNN to training set
rnn_lstm.fit(X_train, y_train, batch_size=32, epochs=10, validation_data=(X_test, y_test))
# + colab_type="code" id="aPZXVhMJWJpn" colab={}
rnn_lstm.evaluate(X_test, y_test)
# + colab_type="code" id="bozdT30VfOop" colab={}
sum(sum(y_test)) / 1000
# + colab_type="code" id="4n6WT8ycfOoq" colab={}
y_pred=rnn_lstm.predict_proba(X_test)
# + colab_type="code" id="fi_xgILhfOos" colab={}
plt.plot(y_pred[4][30:])
# + colab_type="code" id="OPfI3NkbfOou" colab={}
plt.plot(X_test[4,:,0][30:])
# + colab_type="code" id="G1w0il6hfOow" colab={}
|
simulate_curve_lstm_gru_jm.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: PhaseDiagram
# language: python
# name: phasediagram
# ---
# ## Tutorial interativo
# O pacote `PhaseDiagram`, em conjunto com o pacote [ipywidgets](https://ipywidgets.readthedocs.io/en/latest/), é capaz de fazer gráficos interativos, de forma a facilitar o entendimento de diagramas de fases. Com essa união somos capazes de criar diagramas de fases com pontos que podem se mover atráves do gráfico e até mesmo sabermos o estado físico da zona onde o ponto está em forma de texto. Mostraremos isso a seguir.
# Primeiro, vamos importar os pacotes necessários.
from phase_diagram.phase_diagram import PhaseDiagram, ureg
from ipywidgets import interact, interactive
import ipywidgets
import matplotlib.pyplot as plt
from src.plot import Plot
from IPython.display import display
water = PhaseDiagram('water')
# O pacote [ipywidgets](https://ipywidgets.readthedocs.io/en/latest/index.html) pode criar variados tipois de interações, vejamos o básico das que usaremos em nosso gráfico.
# ## Barras deslizantes / controles deslizantes
# Uma barra deslizante, mais conhecida como slider, é um widget que poderá ser variado em um limite predeterminado. Vamos a um exemplo simples:
ipywidgets.FloatSlider()
# Por padrão, se nenhum valor for passado, os limites serão de 0 a 100. Também é possível que o widget seja passado a um objeto, aí usaremos o `display`:
objeto = ipywidgets.FloatSlider()
display(objeto)
# Os widgets criados foram os mais simples possíveis, porém é possível personalizarmos eles. Nesse [link](https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html?highlight=floatslider) é póssível ver outros tipos de padrão para criação de widgets como também é possível ver os parâmetros que podem ser passados neles.
#
# Vamos a um exemplo mais completo, personalizando alguns parâmetros.
# +
style = {'description_width': 'initial'}
temperatura = ipywidgets.FloatSlider(
value=273,
min=200,
max=700,
step=50,
description='Temperatura / K:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.2f',
style=style)
pressao = ipywidgets.FloatLogSlider(
value=10**5,
base=10,
min=1,
max=8,
step=1,
description='Pressão / Pa:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.1e',
style=style)
display(temperatura, pressao)
# -
# Descreveremos brevemente os parâmetros usados nesse tutorial.
#
# * `value`: valor inicial do slider
# * `base` : base usada quando usado no `FloatLogSlider`
# * `min` e `max`: valores dos limites mínimo e máximo
# * `step`: unidades que terá que deslocar até o próximo ponto
# * `description`: descrição do slider
# * `disabled`: desativa o slider. Se o parâmetro for passado como `True`, o slider não se moverá, ficando apenas no valor inicial.
# * `orientation`: orientação do slider
# * `readout`: exibe o valor atual do slider. Se for `False` não exibirá nada
# * `readout_format`: formato usado para representar o valor atual do slider
# Bom, vimos como criamos widgets. Agora veremos como aplicá-los em nossos gráficos
# ## Gráficos interativos
# Os widgets servirão em nosso gráfico para movimentar um ponto. Isso facilitará a compreensão para pessoas que tem dificuldade em entender os estados físicos do diagrama de fases.
#
# Vamos a um exemplo
# +
def funcao_sem_estado_fisico(temperatura, pressao):
fig, ax = plt.subplots(figsize=(10, 8))
water.plot(ax=plt.gca())
ponto = Plot(x_unit='K', y_unit='Pa', ax=plt.gca(), x_label='Temperatura',
y_label='Pressão', legend=True)
ponto.plot_point([temperatura * water.ureg('K'), pressao * water.ureg('Pa')],
zorder=3, s=100, c='black', label='Meu ponto')
graph = interactive(funcao_sem_estado_fisico,
temperatura=temperatura,
pressao=pressao,
)
display(graph)
# -
# Nesse exemplo, pegamos um ponto que criamos usando a classe `Plot` do pacote PhaseDiagram dentro de uma função. Para `interactive` passamos a função criada e os parâmetros que queremos que seja interativo, que nesse caso é temperatura e pressão. O nosso resultado é um gráfico com um ponto capaz de se movimentar por todo o gráfico.
#
# Nós podemos fazer algumas personalizações nesse ponto, como mudar sua cor, aumentar seu diâmetro, etc conforme mostrado em outro tutorial.
# O gráfico anterior pode ser melhorado, pois podemos fazer com que o estado físico onde o ponto estiver seja demonstrado na tela. Isso pode facilitar muito a compreensão.
#
# Vamos a um exemplo.
# +
def funcao_com_estado_fisico(temperatura, pressao):
fig, ax = plt.subplots(figsize=(10, 8), facecolor=(1, 1, 1))
estado_fisico = water.physical_state([temperatura * water.ureg('K'),
pressao * water.ureg('Pa')])
water.plot(ax=plt.gca(), scale_log=True)
a = Plot(x_unit='K', y_unit='Pa', ax=plt.gca(), x_label='Temperatura',
y_label='Pressão', legend=True, scale_log=True)
a.plot_point([temperatura * water.ureg('K'), pressao * water.ureg('Pa')],
zorder=3, s=100, c='black', label=estado_fisico)
plt.gca().annotate(estado_fisico, (temperatura, pressao), fontsize=24, ha='left',
va='top', color='red')
graph = interactive(funcao_com_estado_fisico,
temperatura=temperatura,
pressao=pressao,
)
display(graph)
# -
|
Tutorial_interativo.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # 3.0 Ligand-Receptor Sym-vs-Asym Differential Regulation
from clustergrammer2 import net
df = {}
from glob import glob
# +
all_files = glob('../data/lig-rec_*')
for inst_file in all_files:
inst_comp = inst_file.split('_')[-1].replace('.txt','')
net.load_file(inst_file)
df[inst_comp] = net.export_df()
# -
# # Ligand Receptor Sym/Asym Fold Change: CD4-CD4
net.load_df(df['CD4-CD4'])
net.widget()
# # Ligand Receptor Sym/Asym Fold Change: CD4-CD8
net.load_df(df['CD4-CD8'])
net.widget()
# # Ligand Receptor Sym/Asym Fold Change: CD4-Mac
net.load_df(df['CD4-Mac'])
net.widget()
# # Ligand Receptor Sym/Asym Fold Change: CD8-CD4
net.load_df(df['CD8-CD4'])
net.widget()
# # Ligand Receptor Sym/Asym Fold Change: CD8-CD8
net.load_df(df['CD8-CD8'])
net.widget()
# # Ligand Receptor Sym/Asym Fold Change: CD8-Mac
net.load_df(df['CD8-Mac'])
net.widget()
# # Ligand Receptor Sym/Asym Fold Change: Mac-CD4
net.load_df(df['Mac-CD4'])
net.widget()
# # Ligand Receptor Sym/Asym Fold Change: Mac-CD8
net.load_df(df['Mac-CD8'])
net.widget()
# # Ligand Receptor Sym/Asym Fold Change: Mac-Mac
net.load_df(df['Mac-Mac'])
net.widget()
|
notebooks/3.0_Ligand-Receptor_Sym-vs-Asym_Differential_Regulation.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] slideshow={"slide_type": "slide"}
# # Neural network classifier demonstration
#
# Last revised: 15-Oct-2019 by <NAME> [<EMAIL>]
# + slideshow={"slide_type": "subslide"}
# %matplotlib inline
import numpy as np
import scipy as sp
from scipy.stats import multivariate_normal
import matplotlib.pyplot as plt
# Not really needed, but nicer plots
import seaborn as sns
sns.set_style("darkgrid")
sns.set_context("talk")
# -
# ## Developing a code for doing neural networks with back propagation
#
# One can identify a set of key steps when using neural networks to solve supervised learning problems:
#
# 1. Collect and pre-process data
# 1. Define model and architecture
# 1. Choose cost function and optimizer
# 1. Train the model
# 1. Evaluate model performance on test data
# 1. Adjust hyperparameters (if necessary, network architecture)
# ### Introduction to tensorflow
# This short introduction uses Keras to:
# * Build a neural network that classifies images.
# * Train this neural network.
# * And, finally, evaluate the accuracy of the model.
#
# See [https://www.tensorflow.org/tutorials/quickstart/beginner](https://www.tensorflow.org/tutorials/quickstart/beginner) for more details
# See also the [Tensorflow classification tutorial](https://www.tensorflow.org/tutorials/keras/classification)
# First make sure that your `tif285-env` environment is updated with tensorflow.
# * Download the most recent version of the course git repository (or just download the new version of the [environment.yml](https://physics-chalmers.github.io/tif285/environment.yml) file).
# * Update the environment by running
# `conda env update -f path/to/environment.yml`
# * Restart your jupyter notebook and run the cell below which imports `tensorflow`. The version should be >= 2.0.0.
# +
# Install TensorFlow by updating the conda environment
import tensorflow as tf
print(tf.__version__)
# -
# Load and prepare the [MNIST dataset](http://yann.lecun.com/exdb/mnist/). Convert the samples from integers to floating-point numbers:
# +
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# -
# The images are 28x28 NumPy arrays, with pixel values ranging from 0 to 255. The labels are an array of integers, ranging from 0 to 9.
# ### Explore the data
# The shape of the training data
x_train.shape
# Each training label is an integer
y_train
plt.figure()
plt.imshow(x_train[0])
plt.colorbar()
plt.grid(False)
# Scale these values to a range of 0 to 1 before feeding them to the neural network model. To do so, divide the values by 255. It's important that the training set and the testing set be preprocessed in the same way:
x_train, x_test = x_train / 255.0, x_test / 255.0
# To verify that the data is in the correct format and that you're ready to build and train the network, let's display the first 25 images from the training set and display the class name below each image.
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(x_train[i], cmap=plt.cm.binary)
plt.xlabel(str(y_train[i]))
# ### Build the network
# The basic building block of a neural network is the layer. Layers extract representations from the data fed into them. Hopefully, these representations are meaningful for the problem at hand.
#
# Most of deep learning consists of chaining together simple layers. Most layers, such as [`tf.keras.layers.Dense`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense), have parameters that are learned during training.
# Build the [tf.keras.Sequential](https://www.tensorflow.org/api_docs/python/tf/keras/Sequential) model by stacking layers. Choose an optimizer and loss function for training:
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
# The first layer in this network, [`tf.keras.layers.Flatten`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Flatten), transforms the format of the images from a two-dimensional array (of 28 by 28 pixels) to a one-dimensional array (of 28 * 28 = 784 pixels). Think of this layer as unstacking rows of pixels in the image and lining them up. This layer has no parameters to learn; it only reformats the data.
#
# After the pixels are flattened, the network consists two [`tf.keras.layers.Dense`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense) layers. These are densely connected, or fully connected, neural layers. The first Dense layer has 128 nodes (or neurons). The second (and last) layer is a 10-node softmax layer that returns an array of 10 probability scores that sum to 1. Each node contains a score that indicates the probability that the current image belongs to one of the 10 classes.
#
# In between the Dense layers is a [`tf.keras.layers.Dropout`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dropout) layer. Dropout consists in randomly setting a fraction rate of input units to 0 at each update during training time, which helps prevent overfitting.
# Before the model is ready for training, it needs a few more settings. These are added during the model's compile step:
#
# * *Loss function* — This measures how accurate the model is during training. You want to minimize this function to "steer" the model in the right direction.
# * *Optimizer* — This is how the model is updated based on the data it sees and its loss function.
# * *Metrics* — Used to monitor the training and testing steps. The following example uses accuracy, the fraction of the images that are correctly classified.
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# ### Train and evaluate the model:
model.fit(x_train, y_train, epochs=5)
# ### Evaluate accuracy
# Next, compare how the model performs on the test dataset:
# +
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print('\nTest accuracy:', test_acc)
# -
# ### Make predictions
# With the model trained, you can use it to make predictions about some images.
# +
predictions = model.predict(x_test)
# Let's look at the prediction for the first test image
predictions[0]
# -
# Check the normalization of the output probabilities
np.sum(predictions[0])
# Which prob is largest?
np.argmax(predictions[0])
# Examining the test label shows that this classification is correct:
y_test[0]
# +
# Some helper functions for nice plotting
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(str(predicted_label),
100*np.max(predictions_array),
true_label),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array, true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
# -
# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions[i], y_test, x_test)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions[i], y_test)
plt.tight_layout()
|
doc/src/NeuralNet/demo-NeuralNet.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/drewmadiesteban/Linear-Algebra_ChE_2nd-Sem-2021-2022/blob/main/Assignment9_Esteban_Evangelista.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="39JinJ1ikQGu"
# # Lab 2 - Plotting Vector using NumPy and MatPlotLib
# + [markdown] id="31_bu1YokTrq"
# In this laboratory we will be discussing the basics of numerical and scientific programming by working with Vectors using NumPy and MatPlotLib.
# + [markdown] id="wAq_-rfEkUOa"
# ### Objectives
# At the end of this activity you will be able to:
# 1. Be familiar with the libraries in Python for numerical and scientific programming.
# 2. Visualize vectors through Python programming.
# 3. Perform simple vector operations through code.
# + [markdown] id="8b6PZ96WkYFa"
# ## Discussion
# + [markdown] id="4v8IyAy-kY6q"
# ### NumPy
# + [markdown] id="4yUvxr4ekb1y"
# NumPy or Numerical Python, is mainly used for matrix and vector operations. It is capable of declaring computing and representing matrices. Most Python scientific programming libraries uses NumPy as the basic code.
# + [markdown] id="nieIBoJxkfTU"
# Scalars \\
# Represent magnitude or a single value
#
# Vectors \\
# Represent magnitude with directors
# + [markdown] id="HZsBJ-58kiLq"
# #### Representing Vectors
# + [markdown] id="ONGd38MwkkZL"
# Now that you know how to represent vectors using their component and matrix form we can now hard-code them in Python. Let's say that you have the vectors:
# + [markdown] id="fc2iYfLykml7"
# $$ A = 4\hat{x} + 3\hat{y} \\
# B = 2\hat{x} - 5\hat{y}\\
# C = 4ax + 3ay - 2az \\
# D = 2\hat{i} - 2\hat{j} + 3\hat{k}$$
# + [markdown] id="eHSkNUnlkqDi"
# In which it's matrix equivalent is:
# + [markdown] id="09EUb-Y4ksys"
# $$ A = \begin{bmatrix} 4 \\ 3\end{bmatrix} , B = \begin{bmatrix} 2 \\ -5\end{bmatrix} , C = \begin{bmatrix} 4 \\ 3 \\ -2 \end{bmatrix}, D = \begin{bmatrix} 2 \\ -2 \\ 3\end{bmatrix}
# $$
# $$ A = \begin{bmatrix} 4 & 3\end{bmatrix} , B = \begin{bmatrix} 2 & -5\end{bmatrix} , C = \begin{bmatrix} 4 & 3 & -2\end{bmatrix} , D = \begin{bmatrix} 2 & -2 & 3\end{bmatrix}
# $$
# + [markdown] id="Gy_YtmMLkwWw"
# We can then start doing numpy code with this by:
# + id="ZbRaMoBHk2BS"
## Importing necessary libraries
import numpy as np ## 'np' here is short-hand name of the library (numpy) or a nickname.
# + colab={"base_uri": "https://localhost:8080/"} id="0pRDjxmZk3A7" outputId="0a4ae5ed-79c3-4fd7-c4ff-603078ef55a6"
A = np.array([4, 3])
B = np.array([2, -5])
C = np.array([
[43],
[33],
[-42]
])
D = np.array ([[7],
[-6],
[4]])
print('Vector A is ', A)
print('Vector B is ', B)
print('Vector C is ', C)
print('Vector D is ', D)
# + [markdown] id="wL7gHE1blAzD"
# #### Describing vectors in NumPy
# + [markdown] id="ytiXIeAblBo6"
# Describing vectors is very important if we want to perform basic to advanced operations with them. The fundamental ways in describing vectors are knowing their shape, size and dimensions.
# + colab={"base_uri": "https://localhost:8080/"} id="w4lod3fzlGds" outputId="579dca5e-3df0-45ad-c055-05d587a32777"
### Checking shapes
### Shapes tells us how many elements are there on each row and column
A.shape
H = np.array([15, 40, 24, 55, -0.25, 0])
H.shape
C.shape
# + colab={"base_uri": "https://localhost:8080/"} id="T9C3TC-glNGC" outputId="a4ddb2f2-df19-49df-846a-dc4e452dc22c"
### Checking size
### Array/Vector sizes tells us many total number of elements are there in the vector
D.size
# + colab={"base_uri": "https://localhost:8080/"} id="hC2I3PhAlPhz" outputId="7469916f-69f7-4d16-9ec7-bc5e99ab5d83"
### Checking dimensions
### The dimensions or rank of a vector tells us how many dimensions are there for the vector.
D.ndim
# + [markdown] id="EgNgJZfRlU2G"
# Great! Now let's try to explore in performing operations with these vectors.
# + [markdown] id="frLMKru2lVVj"
# #### Addition
# + [markdown] id="xubdYNjyla-q"
# The addition rule is simple, the we just need to add the elements of the matrices according to their index. So in this case if we add vector $A$ and vector $B$ we will have a resulting vector:
# + [markdown] id="Nz_bo3vAldyr"
# $$R = 6\hat{x}-2\hat{y} \\ \\or \\ \\ R = \begin{bmatrix} 6 \\ -2\end{bmatrix} $$
# + [markdown] id="Hq5cMtB8lhFd"
# So let's try to do that in NumPy in several number of ways:
# + id="O2UH_w1Olelj"
R = np.add(A, B) ## this is the functional method usisng the numpy library
P = np.add(C, D)
# + colab={"base_uri": "https://localhost:8080/"} id="e2DnNgSelmVK" outputId="41c16e8e-9099-4354-ce18-02e63ab8e24f"
R = A + B ## this is the explicit method, since Python does a value-reference so it can
## know that these variables would need to do array operations.
R
# + colab={"base_uri": "https://localhost:8080/"} id="KR0QHn8olo5t" outputId="36e6c2fa-5f07-4334-f912-de9ae444799d"
pos1 = np.array([0,0,0])
pos2 = np.array([0,1,3])
pos3 = np.array([16,56,-2])
pos4 = np.array([53,-34,34])
#R = pos1 + pos2 + pos3 + pos4
#R = np.multiply(pos3, pos4)
R = pos3 / pos4
R
# + [markdown] id="qCY2Va2DlzFS"
# ##### Try for yourself!
# + [markdown] id="K3WKjdyRl2Ir"
# Try to implement subtraction, multiplication, and division with vectors $A$ and $B$!
# + id="g973YCODl42V"
### Try out you code here!
# + [markdown] id="48ZQaBrvmXQe"
# ### Scaling
# + [markdown] id="wV91kI-VmCwC"
# Scaling or scalar multiplication takes a scalar value and performs multiplication with a vector. Let's take the example below:
# + [markdown] id="AIMcPlAJmVx7"
# $$S = 5 \cdot A$$
# + [markdown] id="qOEbbblymdtO"
# We can do this in numpy through:
# + colab={"base_uri": "https://localhost:8080/"} id="cWSA38jumf7x" outputId="02970a55-5ef5-4379-afe8-145c6bd0f5a3"
#S = 5 * A
S = np.multiply(5,A)
S
# + [markdown] id="iph9pytCmitC"
# Try to implement scaling with two vectors.
# + [markdown] id="RjGzrpM4moes"
# ### MatPlotLib
# + [markdown] id="hkVPXw_5myZd"
# MatPlotLib or MATLab Plotting library is Python's take on MATLabs plotting feature. MatPlotLib can be used vastly from graping values to visualizing several dimensions of data.
# + [markdown] id="qH_KpFu0m1mS"
# #### Visualizing Data
# + [markdown] id="PLiwozT_m4SC"
# It's not enough just solving these vectors so might need to visualize them. So we'll use MatPlotLib for that. We'll need to import it first.
# + id="6GcuNUKDm8By"
import matplotlib.pyplot as plt
import matplotlib
# %matplotlib inline
# + colab={"base_uri": "https://localhost:8080/", "height": 265} id="NirKqdw4m-SC" outputId="86ab9355-4b9f-47c0-fa8a-ee5615a3d420"
A = [1, -1]
B = [5, -1]
plt.scatter(A[0], A[1], label='A', c='green')
plt.scatter(B[0], B[1], label='B', c='magenta')
plt.grid()
plt.legend()
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 331} id="h7uH2m_BnD7t" outputId="c9ce04e6-4521-493c-aee6-3db82d8b86cb"
A = np.array([1, -1])
B = np.array([1, 5])
R = A + B
Magnitude = np.sqrt(np.sum(R**2))
plt.title("Resultant Vector\nMagnitude:{}" .format(Magnitude))
plt.xlim(-5, 5)
plt.ylim(-5, 5)
plt.quiver(0, 0, A[0], A[1], angles='xy', scale_units='xy', scale=1, color='red')
plt.quiver(A[0], A[1], B[0], B[1], angles='xy', scale_units='xy', scale=1, color='green')
R = A + B
plt.quiver(0, 0, R[0], R[1], angles='xy', scale_units='xy', scale=1, color='black')
plt.grid()
plt.show()
#print(R)
Slope = R[1]/R[0]
print(Slope)
Angle = (np.arctan(Slope))*(180/np.pi)
print(Angle)
# + colab={"base_uri": "https://localhost:8080/", "height": 269} id="Am2PZYWTnhVF" outputId="fa60a86f-d300-4116-f14a-6af6809cd0d3"
n = A.shape[0]
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.quiver(0,0, A[0], A[1], angles='xy', scale_units='xy',scale=1)
plt.quiver(A[0],A[1], B[0], B[1], angles='xy', scale_units='xy',scale=1)
plt.quiver(0,0, R[0], R[1], angles='xy', scale_units='xy',scale=1)
plt.show()
# + [markdown] id="UEFLz0kNnloS"
# Try plotting Three Vectors and show the Resultant Vector as a result.
# Use Head to Tail Method.
# + id="3-ASszNBtw2C" colab={"base_uri": "https://localhost:8080/", "height": 346} outputId="388ee87b-68c8-496f-b8f1-06f593c9e958"
####Three vectors
A = np.array([4 ,7])
B = np.array([13, 15])
C = A + B
D = np.array([-12, 14])
E = D + A + B
magnitude = np.sqrt(np.sum(E**2))
plt.title("Resultant Vector\nMagnitude: {} \n Resultant: {}".format(magnitude, E))
plt.xlim(-10, 40)
plt.ylim(-10, 40)
plt.quiver(0, 0, A[0], A[1], angles='xy', scale_units='xy', scale=1, color='Red')
plt.quiver(A[0], A[1], B[0], B[1], angles='xy', scale_units='xy', scale=1, color='Orange')
plt.quiver(C[0], C[1], D[0], D[1], angles='xy', scale_units='xy', scale=1, color='Blue')
plt.quiver(0, 0, E[0], E[1], angles='xy', scale_units='xy', scale=1, color='Violet')
plt.grid()
plt.show()
Slope = R[1]/R[0]
print(Slope)
Angle = (np.arctan(Slope))*(180/np.pi)
print(Angle)
|
Assignment9_Esteban_Evangelista.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# # DpicNet
#
# DpicNet a deep neural network aimed to achieve good performance on [Intel Multi-class Image Classification](https://www.kaggle.com/puneet6060/intel-image-classification). DpicNet is built by transfering learning procedure from Xception deep neural network and freezing the convolutional parts, which serves as a feature extractor. The top part of DpicNet is created by adding dense hidden layers forming fully-connected network and shaping to match the number of classes in [Intel Multi-class Image Classification](https://www.kaggle.com/puneet6060/intel-image-classification)
from model.model import DpicNet
from model.data import load_train_data, load_test_data, load_predict_data
# + tags=[]
train_data = load_train_data()
test_data = load_test_data()
hidden1_nodes = 256
hidden2_nodes = 32
model = DpicNet(train_data.image_shape, train_data.num_classes, (hidden1_nodes, hidden2_nodes), (None, None))
print(model)
# + tags=[]
model.fit(train_data, 10)
# + tags=[]
model.evaluate(test_data)
# + tags=[]
model.save('/project/cs542sp/DpicNet/src/saved_models/s3')
# +
from os import listdir
from os.path import isfile, join
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
images = [join('./data/predict/', f) for f in listdir('./data/predict/') if isfile(join('./data/predict/', f)) and f[-3:] == 'jpg']
pred_imgs = np.random.choice(np.array(images), 5)
# + tags=[]
mod = DpicNet.load('/project/cs542sp/DpicNet/src/saved_models/s6')
_, ax = plt.subplots(1,pred_imgs.shape[0])
for i in range(pred_imgs.shape[0]):
ax[i].title.set_text(str(mod.predict(load_predict_data(str(pred_imgs[i])))))
ax[i].imshow(mpimg.imread(pred_imgs[i]))
plt.tight_layout()
|
src/main.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# + [markdown] id="LRHTRZG42RbR"
# # Least Absolute Deviation (LAD) Regression
#
# Linear regression is a supervised machine learning technique that produces a linear model predicting values of a dependent variable from known values of one or more independent variables. Linear regression has a long history dating back to at least the 19th century and is a mainstay of modern data analysis.
#
# This notebook demonstrates a technique for linear regression based on linear programming to minimize a sum of absolute errors between the model prediction and data from a training set. The sum of absolute values of errors is the $L_1$ norm which is known to have favorable robustness characteristics in practical use. We follow closely this [paper](https://www.jstor.org/stable/1402501).
# + id="5ssUqKOaPVaE"
# Install Pyomo and solvers for Google Colab
import sys
if "google.colab" in sys.modules:
# !wget -N -q https://raw.githubusercontent.com/jckantor/MO-book/main/tools/install_on_colab.py
# %run install_on_colab.py
# + [markdown] id="VKxb7hUB2pDa"
# ## Generate data
#
# The Python [scikit learn](https://scikit-learn.org/stable/) library for machine learning provides a full-featured collection of tools for regression. The following cell uses `make_regression` from scikit learn to generate a synthetic data set for use in subsequent cells. The data consists of a numpy array `y` containing `n_samples` of one dependent variable $y$, and an array `X` containing `n_samples` observations of `n_features` independent explanatory variables.
# + colab={"base_uri": "https://localhost:8080/", "height": 265} id="u58KqWC5M_FR" outputId="1ba3863d-09e4-4631-a945-75042f26bf88"
from sklearn.datasets import make_regression
import numpy as np
n_features = 1
n_samples = 1000
noise = 30
# generate regression dataset
np.random.seed(2020)
X, y = make_regression(n_samples=n_samples, n_features=n_features, noise=noise)
# -
# ## Data Visualization
#
# Before going further, it is generally useful to prepare an initial visualization of the data. The following cell presents a scatter plot of $y$ versus $x$ for the special case of one explanatory variable, and a histogram of the difference between $y$ and the mean value $\bar{y}$. This histogram will provide a reference against which to compare the residual error in $y$ after regression.
# +
import matplotlib.pyplot as plt
if n_features == 1:
plt.scatter(X, y, alpha=0.3)
plt.xlabel("X")
plt.ylabel("y")
plt.grid(True)
plt.figure()
plt.hist(y - np.mean(y), bins=int(np.sqrt(len(y))))
plt.title('histogram y - mean(y)')
plt.ylabel('counts')
# + [markdown] id="MiHG-Csw2vbM"
# ## Model
#
# Suppose we have a finite dataset consisting of $n$ points $\{({X}^{(i)}, y^{(i)})\}_{i=1,\dots,n}$ with ${X}^{(i)} \in \mathbb{R}^k$ and $y^{(i)} \in \mathbb{R}$. A linear regression model assumes the relationship between the vector of $k$ regressors ${X}$ and the dependent variable $y$ is linear. This relationship is modeled through an error or deviation term $e_i$, which quantifies how much each of the data points diverge from the model prediction and is defined as follows:
#
# $$
# \begin{equation}\label{eq:regression}
# e_i:= y^{(i)} - {m}^\top {X}^{(i)} - b = y^{(i)} - \sum_{j=1}^k X^{(i)}_j m_j - b,
# \end{equation}
# $$
#
# for some real numbers $m_1,\dots,m_k$ and $b$.
#
# The Least Absolute Deviation (LAD) is a possible statistical optimality criterion for such a linear regression. Similar to the well-known least-squares technique, it attempts to find a vector of linear coefficients ${m}=(m_1,\dots,m_k)$ and intercept $b$ so that the model closely approximates the given set of data. The method minimizes the sum of absolute errors, that is $\sum_{i=1}^n \left |e_i \right|$.
#
# The LAD regression is formulated as an optimization problem with the intercept $b$, the coefficients $m_i$'s, and the errors $e_i$'s as decision variables, namely
#
# $$
# \begin{align}
# \min \quad & \sum_{i=1}^n |e_i| \\
# \text{s.t.} \quad & e_i = y^{(i)} - {m}^\top {X}^{(i)} - b & \forall\, i=1,\dots,n.
# \end{align}
# $$
#
# In general, the appearance of an absolute value term indicates the problem is nonlinear and, worse, that the objective function is not differentiable when any $e_i = 0$. However, for this case where the objective is to minimize a sum of absolute errors, one can reformulate the decision variables to transform this into a linear problem. More specifically, introducing for every term $e_i$ two new variables $e_i^-, e_i^+ \geq 0$, we can rewrite the model as
#
# $$
# \begin{align}
# \min \quad & \sum_{i=1}^n ( e_i^+ + e_i^-) \\
# \text{s.t.} \quad & e_i^+ - e_i^- = y^{(i)} - {m}^\top {X}^{(i)}-b & \forall\, i=1, \dots, n \\
# & e_i^+, e_i^- \geq 0 & \forall\, i=1, \dots, n
# \end{align}
# $$
#
# The following cell provides a direct implementation of LAD regression.
# + id="SKIqjt5CPSJf"
import pyomo.environ as pyo
def lad_regression(X, y):
m = pyo.ConcreteModel('LAD Regression')
n, k = X.shape
# note use of Python style zero based indexing
m.I = pyo.RangeSet(0, n-1)
m.J = pyo.RangeSet(0, k-1)
m.ep = pyo.Var(m.I, domain=pyo.NonNegativeReals)
m.em = pyo.Var(m.I, domain=pyo.NonNegativeReals)
m.m = pyo.Var(m.J)
m.b = pyo.Var()
@m.Constraint(m.I)
def residuals(m, i):
return m.ep[i] - m.em[i] == y[i] - sum(X[i][j]*m.m[j] for j in m.J) - m.b
@m.Objective(sense=pyo.minimize)
def sum_of_abs_errors(m):
return sum(m.ep[i] + m.em[i] for i in m.I)
pyo.SolverFactory('glpk').solve(m)
return m
m = lad_regression(X, y)
m.m.display()
m.b.display()
# -
# ## Visualizing the Results
# +
y_fit = np.array([sum(x[j]*m.m[j]() for j in m.J) + m.b() for x in X])
if n_features == 1:
plt.scatter(X, y, alpha=0.3, label="data")
plt.plot(X, y_fit, 'r', label="y_fit")
plt.xlabel("X")
plt.ylabel("y")
plt.grid(True)
plt.legend()
plt.figure()
plt.hist(y - np.mean(y), bins=int(np.sqrt(len(y))), alpha=0.5, label="y - mean(y)")
plt.hist(y - y_fit, bins=int(np.sqrt(len(y))), color='r', alpha=0.8, label="y - y_fit")
plt.title('histogram of residuals')
plt.ylabel('counts')
plt.legend()
# -
|
_build/html/_sources/notebooks/02/lad-regression.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + colab={"base_uri": "https://localhost:8080/", "height": 54} colab_type="code" id="lXfPT7BuejLb" outputId="c6808d39-90c9-4ac3-a567-15d716059419"
# # Run this cell to mount your Google Drive.
# from google.colab import drive
# drive.mount('/content/drive')
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="819EGBI8fLUl" outputId="93d6fddc-7353-4a53-d34e-1427242fa67d"
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
from keras.models import Sequential
from keras.layers import Dense, Dropout, BatchNormalization
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import tensorflow as tf
from sklearn.feature_selection import VarianceThreshold
# from keras.backend import manual_variable_initialization
# # manual_variable_initialization(True)
# + colab={} colab_type="code" id="N1bkqWDgXIbi"
# + colab={"base_uri": "https://localhost:8080/", "height": 246} colab_type="code" id="RgWz2tXdfNax" outputId="50345be1-3694-4638-a873-88697a7d0bc7"
data_p = pd.read_csv("points.csv",dtype=object,error_bad_lines=False)
data_p.head()
data_p["id"] = data_p["id"].map(str) +"_"+ data_p["dir"]
data_p.head()
# data_p.dtypes
# + colab={"base_uri": "https://localhost:8080/", "height": 234} colab_type="code" id="zRQG6QqkfPaM" outputId="7e2cdf06-3933-4496-c78e-813e4afed97b"
data_v = pd.read_csv("values.csv",dtype=object,error_bad_lines=False )
le = preprocessing.LabelEncoder()
data_v['power_state_spec'] = le.fit_transform(data_v['power_state_spec'].astype('str'))
data_v['power_state_value'] = le.fit_transform(data_v['power_state_value'].astype('str'))
data_v["id"] = data_v["id"].map(str) +"_"+data_v["dir"]
data_v.head()
# + colab={} colab_type="code" id="SS5hHAvgfRzw"
arr_v = data_v.values
arr_p = data_p.values
# + colab={} colab_type="code" id="TSE1FojVfUlN"
arr_v = arr_v[0:]
# print(arr_v)
arr_p = arr_p[0:]
# print(arr_p)
# + colab={"base_uri": "https://localhost:8080/", "height": 52} colab_type="code" id="pZMozxZNfdAU" outputId="1371ad9a-922e-48c1-833a-a5cfa5c01b81"
ON_list =[]
OFF_list = []
for i in range(len(arr_p)):
s = arr_p[i][1]
s = str(s)
# print(type(st))
if s.find("N") == -1:
OFF_list.append(arr_p[i])
else:
ON_list.append(arr_p[i])
# calculating for ON
print(len(ON_list),"ON")
print(len(OFF_list),"OFF")
arr_on_p = np.array(OFF_list)
# print(arr_on_p)
# + colab={} colab_type="code" id="Hbaq7jn6fde0"
arr_on_p = np.delete(arr_on_p, 3, axis=1)
arr_on_p_n = arr_on_p[:, 1::2]
arr_on_p_f = np.delete(arr_on_p_n, 1, axis=1)
# print(len(arr_on_p_f))
# print(len(arr_on_p_f[0]))
# print(arr_on_p_f[0])
# + colab={"base_uri": "https://localhost:8080/", "height": 246} colab_type="code" id="nntpfcxlgZsO" outputId="d43b0254-360c-4905-dc50-0c58612e00d8"
data = arr_on_p_f
df=pd.DataFrame(data=data[0:,0:],index=[i for i in range(data.shape[0])],
columns=['y'+str(i) for i in range(data.shape[1])])
df.head()
# df.dtypes
# + colab={"base_uri": "https://localhost:8080/", "height": 300} colab_type="code" id="0SaXXr_ggcFp" outputId="ca27a21d-91be-4121-8efe-6dd58c9d8431"
print(df.shape)
# for j in range(10000):
# var = "y"+str(j+1)
# df[var].fillna(df[var].mean(), inplace=True)
df_no_miss = df.dropna()
print(df_no_miss.shape)
print(df.shape)
df_no_miss.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="VMYfPRjHghm3" outputId="dbf33109-20a1-436e-c2b4-9fb1621e1d18"
arr_p_no = df_no_miss.values
print(len(arr_p_no))
# + colab={"base_uri": "https://localhost:8080/", "height": 246} colab_type="code" id="LGF8F0segjoF" outputId="26312138-8059-4a36-e75b-69b8b4b3f616"
df1= df_no_miss.rename(index=str, columns={"y0": "id"})
df1.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 52} colab_type="code" id="OgI9lWPHgl_2" outputId="a21663e5-9263-4230-fde2-1721c3984a23"
print(df1.shape)
df2 = data_v
# print(df2.shape)
combine = (pd.merge(df1, df2, how='left', on='id'))
# print(df1.unique)
print(combine.shape)
# + colab={"base_uri": "https://localhost:8080/", "height": 263} colab_type="code" id="_Frd3KdYgoVN" outputId="11f0509c-a31b-436c-cd41-7b3ddb0d17be"
combine.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 263} colab_type="code" id="djNeEIiPgq7w" outputId="d24ce3be-3c68-4aa6-ec6d-1bcd3bd0447d"
combine.iloc[:,0:10010].head()
k = combine.drop(['s.no','dir','_file_'], axis = 1)
k.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 263} colab_type="code" id="2vbEb4-ogtJg" outputId="65d9c504-b261-4ecd-9102-3883bcdc8782"
input_1 = k.iloc[:,0:10009]
# filling the missing values
# print(input_1.iloc[:,10008])
miss = input_1.iloc[:,1:]
miss.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 263} colab_type="code" id="5i0q3j2zgvS1" outputId="d7bdae54-970a-43dc-ddb0-69ff22e33f91"
input_1 = k.iloc[:,0:10009]
# filling the missing values
miss = input_1.iloc[:,1:]
miss.head()
for column in (miss.iloc[:,10000:]):
su = 0
div = 0
for r in range(miss.shape[0]):
if (pd.isna(miss[column][r]))== False:
su = float(miss[column][r])+su
div = div+1
fin = float(su/div)
miss[column].fillna(float(fin),inplace=True)
#########converting ever
# thing into float
miss =miss.astype('float64')
# print(miss.dtypes)
miss.head()
# + colab={} colab_type="code" id="jBZnARyHgyfK"
import pandas as pd
from sklearn.ensemble.forest import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import Normalizer
from sklearn.preprocessing import QuantileTransformer
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import robust_scale
scaler_min_x = MinMaxScaler()
scaler_min_y = MinMaxScaler()
scaler_norm_x = Normalizer()
scaler_norm_y = Normalizer()
scaler_stan_x = StandardScaler()
scaler_stan_y = StandardScaler()
scalar_qt_x =QuantileTransformer(output_distribution='uniform')
scalar_qt_y =QuantileTransformer(output_distribution='uniform')
# + colab={"base_uri": "https://localhost:8080/", "height": 161} colab_type="code" id="eyHICz0yg2BJ" outputId="67294fc3-9c83-42a2-dc0a-261d494b5951"
rand_na = miss
# print(miss.shape)
input_1_arr = rand_na.values
input_1_arr[:,:]= input_1_arr[:,:].astype('float64')
X = input_1_arr[:,0:10000]*1000
Y = input_1_arr[:,10002:10004]
# print(X.shape)
# print(Y.shape)
# print(Y)
y=np.reshape(Y, (-1,1))
# X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.20)
X_train= X
y_train= Y
# ######minmax
scaler_min_x = MinMaxScaler().fit(X_train)
scaler_min_y = MinMaxScaler().fit(y_train)
X_minmax_train = scaler_min_x.transform(X_train)
Y_minmax_train = scaler_min_y.transform(y_train)
# print(X)
# print(Y)
#####standard
scaler_stan_x = StandardScaler().fit(X_train)
scaler_stan_y = StandardScaler().fit(y_train)
X_stan_train = scaler_stan_x.transform(X_train)
Y_stan_train = scaler_stan_y.transform(y_train)
#######normlised
scaler_norm_x = Normalizer().fit(X_train)
scaler_norm_y = Normalizer().fit(y_train)
X_norm_train = scaler_norm_x.transform(X_train)
Y_norm_train = scaler_norm_y.transform(y_train)
# ################qt
scaler_qt_x = QuantileTransformer(output_distribution='normal').fit(X_train)
scaler_qt_y = QuantileTransformer(output_distribution='normal').fit(y_train)
X_qt_train = scaler_qt_x.transform(X_train)
Y_qt_train = scaler_qt_y.transform(y_train)
##robust
##robust
print(np.amax(X_train[0,:]))
print(np.amax(y_train[0,:]))
X_train = np.concatenate((X_train, y_train), axis=1)
# print(np.amax(X_train[0,:]))
X_train_t = X_train.transpose()
# y_train_t = y_train.transpose()
# print(X_train,"after")
# print(y_train.shape,"after")
scaler_min_x = MinMaxScaler().fit(X_train_t)
# scaler_rob_y = RobustScaler().fit(y_train_t)
X_min_train = scaler_min_x.transform(X_train_t)
# Y_rob_train = scaler_rob_x.transform(y_train_t)
X_min_train = X_min_train.transpose()
# Y_rob_train = Y_rob_train.transpose()
# print(X_rob_train.shape)
# print(Y_rob_train.shape)
# print(Y_rob_train)
Y_min_train = X_min_train[:,10000:10002]
X_min_train = X_min_train[:,0:10000]
# print(Y_rob_train)
# print(X_rob_train)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="RlJlt7DghBIG" outputId="88bba53c-b75d-458f-cb84-41297679341b"
from sklearn.decomposition import FactorAnalysis
transformer = FactorAnalysis(n_components=30, random_state=0)
factor_fit = transformer.fit(X_min_train)
X_new = factor_fit.transform(X_min_train)
X_new.shape
# + colab={} colab_type="code" id="D5rmicgppLVP"
import pickle
pickle.dump(factor_fit, open( "./app/MODEL/factor_fit_off.pkl", "wb" ) )
# + colab={} colab_type="code" id="1VKNQkEahFjV"
def baseline_model_30(optimizer='adam'):
# create model
model = Sequential()
model.add(Dense(28, activation='relu',
kernel_initializer = 'he_normal',
input_shape=(30,)))
model.add(BatchNormalization())
# model.add(Dropout(0.5))
# model.add(Dense(30, activation='relu',
# kernel_initializer = 'he_normal'))
# model.add(BatchNormalization())
# model.add(Dropout(0.5))
model.add(Dense(12, activation='relu',
kernel_initializer = 'he_normal'))
model.add(BatchNormalization())
# model.add(Dropout(0.5))
model.add(Dense(9, activation='relu',
kernel_initializer = 'he_normal'))
# model.add(BatchNormalization())
# model.add(Dropout(0.5))
model.add(Dense(2, activation='linear',
kernel_initializer='he_normal'))
model.compile(loss = 'mse', optimizer=optimizer, metrics=['mae'])
# model.summary()
return model
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="4thveclshIbz" outputId="f1f13189-5035-4910-cd20-25a91590c6fa"
model = baseline_model_30()
print (model.get_weights())
# estimator = train_data_nn(X_new, Y_rob_train)
print(X_new.shape)
print(y_train.shape)
history = model.fit(X_new, Y_min_train, epochs=200, batch_size=5, verbose=1, validation_split=0.0)
# + colab={} colab_type="code" id="2KIpX4xqhVAU"
def visualize_learning_curve(history):
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['loss'])
# plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['mean_absolute_error'])
# plt.plot(history.history['val_mean_absolute_error'])
plt.title('model mean_absolute_error')
plt.ylabel('mean_absolute_error')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# + colab={} colab_type="code" id="I65fooUhhsKq"
# print(X_test.shape)
# X_test_t = X_test.transpose()
# print(X_test_t.shape)
# scaler_rob_x = MinMaxScaler().fit(X_test_t)
# X_new_test_t = scaler_rob_x.transform(X_test_t)
# X_new_test = X_new_test_t.transpose()
# print(X_new_test.shape)
# y_test_t = y_test.transpose()
# # scaler_rob_y = RobustScaler().fit(y_test_t)
# Y_new_test_t = scaler_rob_x.transform(y_test_t)
# Y_new_test = Y_new_test_t.transpose()
# X_new_test = factor_fit.transform(X_new_test)
# print(X_new_test.shape)
# visualize_learning_curve(history)
# + colab={"base_uri": "https://localhost:8080/", "height": 607} colab_type="code" id="46dPn9dGh0Cz" outputId="24cd3972-a178-4a49-b029-9d8e02fccd99"
from sklearn.metrics import mean_squared_error,mean_absolute_error
import math
# from sklearn.metrics import max_error
pred = model.predict((X_new))
# print(pred)
mse = (mean_squared_error(Y_min_train,pred))
print(mse)
visualize_learning_curve(history)
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="pRkF_i2xh6JG" outputId="b5293546-9fcf-403c-c146-8c2746a0bc84"
X1 = input_1_arr[:,0:10000]*1000
Y1 = input_1_arr[:,10000:10004]
X=X1
Y=Y1[:,2:4]
# print(Y)
Y_new = np.zeros((Y.shape[0],2))
for i in range(len(Y)):
print(Y[i],"y")
X_t= X[i].transpose()
scaler_rob_x = MinMaxScaler().fit((X_t.reshape(-1, 1)))
Xi = (scaler_rob_x.transform(X_t.reshape(-1, 1)))
I = factor_fit.transform(Xi.transpose())
pred = model.predict(I)
Y_ti =Y[i].transpose()
# scaler_rob_y = RobustScaler().fit(Y_ti.reshape(-1, 1))
final_t = scaler_rob_x.inverse_transform(pred.reshape(-1, 1))
final = final_t.transpose()
print(final[0])
h = abs(final-Y[i])
# print(h,"h")
# o=np.divide(h,Y[i])
# print(o*100,"percentage")
Y_new[i]=final[0]
# + colab={"base_uri": "https://localhost:8080/", "height": 70} colab_type="code" id="oTEoOJ1WjJ9T" outputId="183b55c6-fbfe-4a6e-f2fe-a201c83249d1"
X1 = X1
Y1 = Y1
# print(Y1)
# print(Y)
from sklearn.metrics import r2_score
print(Y1[0,2], Y_new[0,0])
# print(Y_new[:,0])
g = r2_score(Y1[:,2], Y_new[:,0])
g1 = r2_score(Y1[:,3], Y_new[:,1])
print(g,g1)
Y1[:,2]= Y_new[:,0]
Y1[:,3]= Y_new[:,1]
# print(Y1[0,2], Y_new[0,0])
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="-z59fc0rjqqp" outputId="6c9f781f-ff8a-4fb8-b8e7-126262f4b607"
X1_new = np.concatenate((X1,Y1[:,2:4]),axis=1)
print(X1_new.shape)
Y1_new = Y1[:,0:2]
# print(Y1_new)
# X_train_c, X_test_c, y_train_c, y_test_c = train_test_split(X1_new, Y1_new, test_size=0.20)
X_train_c= X1_new
y_train_c = Y1_new
# + colab={} colab_type="code" id="w18N-Ahtj3zL"
#standardise
# ######minmax
scaler_min_x = MinMaxScaler().fit(X_train_c)
scaler_min_y = MinMaxScaler().fit(y_train_c)
X_minmax_train = scaler_min_x.transform(X_train_c)
Y_minmax_train = scaler_min_y.transform(y_train_c)
# print(X)
# print(Y)
#####standard
scaler_stan_x = StandardScaler().fit(X_train_c)
scaler_stan_y = StandardScaler().fit(y_train_c)
X_stan_train = scaler_stan_x.transform(X_train_c)
Y_stan_train = scaler_stan_y.transform(y_train_c)
# #######normlised
# scaler_norm_x = Normalizer().fit(X_train_c)
# scaler_norm_y = Normalizer().fit(y_train_c)
# X_norm_train = scaler_norm_x.transform(X_train_c)
# Y_norm_train = scaler_norm_y.transform(y_train_c)
# # ################qt
# scaler_qt_x = QuantileTransformer(output_distribution='normal').fit(X_train_c)
# scaler_qt_y = QuantileTransformer(output_distribution='normal').fit(y_train_c)
# X_qt_train = scaler_qt_x.transform(X_train_c)
# Y_qt_train = scaler_qt_y.transform(y_train_c)
##robust
# print(X_train.shape)
# print(y_train.shape)
# X_train_t = X_train.transpose()
# y_train_t = y_train.transpose()
# print(X_train.shape,"after")
# print(y_train.shape,"after")
scaler_rob_x = MinMaxScaler().fit(X_train_c)
scaler_rob_y = MinMaxScaler().fit(y_train_c)
# X_rob_train = scaler_rob_x.transform(X_train_c)
# Y_rob_train = scaler_rob_y.transform(y_train_c)
# + colab={} colab_type="code" id="gp-_qNnYplqA"
import pickle
pickle.dump(scaler_rob_x, open( "./app/MODEL/scaler_rob_x_1_OFF.pkl", "wb" ) )
pickle.dump(scaler_rob_y, open( "./app/MODEL/scaler_rob_y_1_OFF.pkl", "wb" ) )
X_rob_train_c = scaler_rob_x.transform(X_train_c)
Y_rob_train_c = scaler_rob_y.transform(y_train_c)
# + colab={"base_uri": "https://localhost:8080/", "height": 52} colab_type="code" id="7CFgOiZdkHbW" outputId="cc05189c-42ff-4c34-c3e2-5632f0ea9bcb"
#apply PCA on X1_new
transformer = FactorAnalysis(n_components=30, random_state=0)
factor_fit = transformer.fit(X_rob_train_c[:,0:10000])
X_new1 = factor_fit.transform(X_rob_train_c[:,0:10000])
print(X_new1.shape)
X_new1 = np.concatenate((X_new1,X_rob_train_c[:,10000:10002]),axis=1)
print(X_new1.shape)
# print((X_rob_train[:,0:10000].shape))
# + colab={} colab_type="code" id="d7y6ga_Ap3xd"
# + colab={} colab_type="code" id="tk0ehMK0psFc"
import pickle
pickle.dump(factor_fit, open( "./app/MODEL/factor_fit_1_OFF.pkl", "wb" ) )
# + colab={} colab_type="code" id="l-vIsEvckQiI"
def baseline_model_31(optimizer='adam'):
# create model
model = Sequential()
model.add(Dense(30, activation='relu',
kernel_initializer = 'he_normal',
input_shape=(32,)))
model.add(BatchNormalization())
model.add(Dropout(0.5))
# model.add(Dense(30, activation='relu',
# kernel_initializer = 'he_normal'))
# model.add(BatchNormalization())
# model.add(Dropout(0.5))
model.add(Dense(12, activation='relu',
kernel_initializer = 'he_normal'))
model.add(BatchNormalization())
# model.add(Dropout(0.5))
model.add(Dense(9, activation='relu',
kernel_initializer = 'he_normal'))
model.add(BatchNormalization())
# model.add(Dropout(0.5))
model.add(Dense(2, activation='linear',
kernel_initializer='he_normal'))
model.compile(loss = 'mse', optimizer=optimizer, metrics=['mae'])
# model.summary()
return model
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="nXZHDnp-kTGe" outputId="fa1ed4a9-2620-4af9-b2b6-9fb859f265e0"
model1 = baseline_model_31()
# estimator1 = train_data_nn_1(X_new1, Y_rob_train)
# print(X_new.shape)
# print(y_train.shape)
history_1 = model1.fit(X_new1, Y_rob_train_c, epochs=400, batch_size=5, verbose=1, validation_split=0.0)
# + colab={"base_uri": "https://localhost:8080/", "height": 625} colab_type="code" id="O1YTEBaakaUU" outputId="da7664ff-a38e-43cd-ff9a-d6874599cf22"
from sklearn.metrics import mean_squared_error,mean_absolute_error
import math
# from sklearn.metrics import max_error
pred_c = model1.predict((X_new1))
print(pred_c.shape)
mse = (mean_squared_error(Y_rob_train_c,pred_c))
print(mse)
visualize_learning_curve(history_1)
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="gXSgtNLckt4p" outputId="5a8d75e1-039a-4ec9-969d-35b75b4b4d4f"
Final = []
for i in range(len(y_train_c)):
print(y_train_c[i],"ytest[i]")
# print(X_train_c[i])
X_c = (scaler_rob_x.transform(X_train_c[i].reshape(1, -1)))
# print(X_c)
I = factor_fit.transform(X_c[:,0:10000])
I = np.concatenate((I,X_c[:,10000:10002]),axis=1)
# print(I.shape,"I shape")
pred_c = model1.predict(I)
# print(pred_c,"pred_c.shape")
final = scaler_rob_y.inverse_transform(pred_c.reshape(1, -1))
# print(final,"final")
final[0][0]= np.abs(np.round(final[0][0]))
# print(final[0],"final")
k=[]
k.append(final[0][0])
k.append(final[0][1])
Final.append(k)
print(final[0],"final")
h = abs(final[0]-y_train_c[i])
Final_np = np.asarray(Final, dtype=np.float32)
# print(Final)
print(y_train_c[100,1], Final_np[100,1])
r2_time = r2_score(y_train_c[:,1], Final_np[:,1])
print(r2_time,"stabilization time")
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="mc1vcYm9k37j" outputId="7e978f24-b2ff-416d-98b6-d6f3120736d3"
from keras.backend import manual_variable_initialization
manual_variable_initialization(True)
model.save ("./app/MODEL/my_model_OFF.h5")
model1.save ("./app/MODEL/my_model_1_OFF.h5")
# print(model.get_weights())
print (model1.get_weights())
model1.save_weights("on_1.h5")
# + colab={} colab_type="code" id="jBGZMwMHlLXw"
# from keras.models import load_model
# new_model = load_model('my_model_ON.h5')
# new_model_1 = load_model('my_model_1_ON.h5')
# + colab={} colab_type="code" id="uqP6qSVglPrH"
# pred = new_model_1.predict((X_new1))
# print(pred.shape)
# mse = (mean_squared_error(Y_rob_train,pred))
# print(mse)
# + colab={} colab_type="code" id="MPxe7WHNlSVb"
# + colab={} colab_type="code" id="g05oiTETLRCg"
# -
|
app/perpec_OFF.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
from __future__ import print_function
import numpy as np
import os
import cv2
import pandas as pd
from matplotlib import pyplot
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten,GlobalMaxPooling2D
from keras.layers import Conv2D, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from keras import backend as K
# %matplotlib inline
# -
def rename(prev_path, new_path,val):
os.makedirs(new_path)
os.getcwd()
collection = prev_path
for i, filename in enumerate(os.listdir(collection)):
os.rename(prev_path + filename, new_path + str(val)+"."+ str(i) + ".jpg")
# +
prev_path='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/DermCNN data/1/'
one_path="D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/1/"
#rename(prev_path, one_path,val=1)
prev_path='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/DermCNN data/2/'
two_path="D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/2/"
#rename(prev_path, two_path,val=2)
prev_path='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/DermCNN data/3/'
three_path="D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/3/"
#rename(prev_path, three_path,val=3)
prev_path='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/DermCNN data/4/'
four_path="D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/4/"
#rename(prev_path, four_path,val=4)
prev_path='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/DermCNN data/5/'
five_path="D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/5/"
#rename(prev_path, five_path,val=5)
prev_path='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/DermCNN data/6/'
six_path="D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/6/"
#rename(prev_path, six_path,val=6)
prev_path='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/DermCNN data/7/'
seven_path="D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/7/"
#rename(prev_path, seven_path,val=7)
# -
data = []
label = []
images= []
img_labels= []
im_width = 64
im_height = 64
def preprocessing(path):
image_files = [ f for f in os.listdir(path) if os.path.isfile(os.path.join(path,f)) ]
for file in image_files:
image_file = str(path + file)
img = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
new_img = cv2.resize(img, (im_width, im_height))
pnt=file[:1]
#if file[:1] == '1':
label.append(pnt)
data.append(new_img / 255)
print(len(data))
print(len(label))
def augmentation(aug_path,bs,vl):
(X_train, X_test, y_train, y_test) = train_test_split(data,label, test_size=0.30, random_state=42)
K.set_image_dim_ordering('th')
# load data
#(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape to be [samples][pixels][width][height]
X_train = X_train.reshape(X_train.shape[0], 1, 64, 64)
X_test = X_test.reshape(X_test.shape[0], 1, 64, 64)
# convert from int to float
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
# define data preparation
shift = 0.2
datagen = ImageDataGenerator(width_shift_range=shift, height_shift_range=shift)
# fit parameters from data
datagen.fit(X_train)
# configure batch size and retrieve one batch of images
#os.makedirs(aug_path)
for X_batch, y_batch in datagen.flow(X_train, y_train, batch_size=bs, save_to_dir=aug_path, save_prefix=vl, save_format='jpg'):
# create a grid of 3x3 images
#for i in range(0, bs):
# pyplot.subplot(630 + 1 + i)
# pyplot.imshow(X_batch[i].reshape(64, 64), cmap=pyplot.get_cmap('gray'))
# show the plot
#pyplot.show()
break
# +
#preprocessing('D:\\University_MS\\1- FIRST SEMESTER\\Deep Learning\\Project\\Project3\\Dataset\\7\\')
#data = np.array(data)
#print(data.shape)
#data = data.reshape((data.shape)[0], (data.shape)[1], (data.shape)[2], 1)
#print(data.shape)
#label = np.array(label)
#print(label.shape)
#for x in range(1824):
# augmentation('D:\\University_MS\\1- FIRST SEMESTER\\Deep Learning\\Project\\Project3\\Dataset\\7\\',1,7.1)
# -
one = 'D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/1/'
two='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/2/'
three='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/3/'
four='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/4/'
five='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/5/'
six='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/6/'
seven='D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/Dataset/7/'
one_image_files = [ f for f in os.listdir(one) if os.path.isfile(os.path.join(one,f)) ]
two_image_files = [ f for f in os.listdir(two) if os.path.isfile(os.path.join(two,f)) ]
three_image_files = [ f for f in os.listdir(three) if os.path.isfile(os.path.join(three,f)) ]
four_image_files = [ f for f in os.listdir(four) if os.path.isfile(os.path.join(four,f)) ]
five_image_files = [ f for f in os.listdir(five) if os.path.isfile(os.path.join(five,f)) ]
six_image_files = [ f for f in os.listdir(six) if os.path.isfile(os.path.join(six,f)) ]
seven_image_files = [ f for f in os.listdir(seven) if os.path.isfile(os.path.join(seven,f)) ]
image_file = str(four + four_image_files[62])
img = cv2.imread(image_file)
plt.imshow(img)
print(len(one_image_files))
print(len(two_image_files))
print(len(three_image_files))
print(len(four_image_files))
print(len(five_image_files))
print(len(six_image_files))
print(len(seven_image_files))
def preprocessing(path,image_files,lab):
progress = 0
for file in image_files:
image_file = str(path + file)
img = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
new_img = cv2.resize(img, (im_width, im_height))
img=new_img.astype('float32')
img_labels.append(lab)
images.append(img / 255)
progress = progress + 1
if progress % 1000 == 0:
print('Progress: ' + str(progress) + ' Images Done')
# +
l=1
preprocessing(one,one_image_files,l)
l=2
preprocessing(two,two_image_files,l)
l=3
preprocessing(three,three_image_files,l)
l=4
preprocessing(four,four_image_files,l)
l=5
preprocessing(five,five_image_files,l)
l=6
preprocessing(six,six_image_files,l)
l=7
preprocessing(seven,seven_image_files,l)
print(len(images))
print(len(img_labels))
# -
images,img_labels= shuffle(images,img_labels)
# + active=""
# # Slicing of the data and labels are done to decrease computional time and try to avoid some noisy data to increase accuracy.
# images=images[0:800] + images[2000:2364]
# img_labels=img_labels[0:800] + img_labels[2000:2364]
# -
print(img_labels[1000])
images = np.array(images)
print(images.shape)
# Converting it into a Tensor
images = images.reshape((images.shape)[0],(images.shape)[1], (images.shape)[2],1)
print(images.shape)
img_labels = np.array(img_labels)
print(img_labels.shape)
# partition the data into training and testing splits using 70% of the data for training and the remaining 30% for testing
(trainX, testX, trainY, testY) = train_test_split(images,img_labels, test_size=0.30, random_state=2018)
batch_size = 64
epochs = 49
im_width = 64
im_height = 64
num_classes=8
# convert class vectors to binary class matrices
trainY = keras.utils.to_categorical(trainY, num_classes)
testY = keras.utils.to_categorical(testY, num_classes)
# +
model = Sequential()
model.add(Conv2D(10, kernel_size=(2, 2),activation='relu',input_shape= (im_width , im_height,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(15, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(30, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Flatten())
#model.add(GlobalMaxPooling2D())
model.add(Dense(256, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(optimizer="adadelta",loss="categorical_crossentropy",metrics=["accuracy"])
History =model.fit(trainX,trainY,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(testX, testY)
)
score = model.evaluate(testX, testY, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
print("CNN Error: %.2f%%" % (100-score[1]*100))
# -
model.summary()
# +
# Training and Validation Accuracy/loss plot below:
accuracy = History.history['acc']
val_accuracy = History.history['val_acc']
loss = History.history['loss']
val_loss = History.history['val_loss']
epochs = range(len(accuracy))
plt.plot(epochs, accuracy, 'bo', label='Training Accuracy')
plt.plot(epochs, val_accuracy, 'b', label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training Loss')
plt.plot(epochs, val_loss, 'b', label='Validation Loss')
plt.title('Training and Validation Loss')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend()
plt.show()
# -
model.save_weights('D:/University_MS/1- FIRST SEMESTER/Deep Learning/Project/Project3/part1_weights.h5')
|
Deep Learning - Project 2/18L-2097/Part1.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# 
#
# <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=SocialStudies/Globalization/languages-an-important-identity-in-globalizing-world.ipynb&depth=1" target="_parent"><img src="https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true" width="123" height="24" alt="Open in Callysto"/></a>
# # Languages: An important identity in globalizing world
#
# Language is an important identity of the people. Not only does language provide a medium to communicate, but also it binds the community together. Therefore, it is essential to preserve linguistic diversity in the globalizing world.
#
# Let's check out various languages that once existed or currently exist on Earth. [UNESCO](https://en.unesco.org/) has compiled an [atlas](http://www.unesco.org/languages-atlas/index.php?hl=en&page=atlasmap) which contains various statistics about languages. A [choropleth map](https://en.wikipedia.org/wiki/Choropleth_map) is used to visualize this linguistic geographical dataset.
# +
# You can comment out the following lines if these modules are already installed
# !pip install googletrans
# !pip install gTTS
# Import Python libraries
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from ipywidgets import interact, fixed, widgets, Layout, Button, Box, fixed, HBox, VBox
import googletrans
import gtts
from IPython.display import Audio, display, clear_output
# Don't show warnings in output
import warnings
warnings.filterwarnings('ignore')
clear_output()
print('Libraries successfully imported.')
# +
# Import the dataset
df = pd.read_csv('./Data/languoid.csv')
# Data clean up - keep required columns
df = df[df['level'] == 'language'] \
[['name','child_dialect_count','latitude','longitude','status']] \
.dropna() # remove rows with missing entries
# Display top 5 rows
df.head()
# +
# This cell will take at least couple of minutes to run as we are trying to plot more than 7000 languages
# Define color scheme
colors = {'safe':'rgb(61,145,64)', 'vulnerable':'rgb(31,117,254)', 'definitely endangered':'rgb(137,207,240)', \
'severely endangered':'rgb(255,191,0)', 'critically endangered':'rgb(255,0,0)', 'extinct':'rgb(0,0,0)'}
# Create a plotly figure object (like an empty figure)
fig = go.Figure()
# Create a marker with desired properties for each language in the dataset
for i in range(0,df.shape[0]):
df_row = df.iloc[i] # Pass each row in the dataset
fig.add_trace(go.Scattergeo(
lon = [df_row['longitude']], # longitude
lat = [df_row['latitude']], # latitude
text = 'Dialects: {0} <br>Status: {1}'.format(df_row['child_dialect_count'],df_row['status']), # text accompanying the dataset
name = df_row['name'], # name of the language
hoverinfo = 'name + text', # specify information to be shown when a pointer is hovered over a marker
marker = dict(
size=9,
color=colors[df_row['status']],
line_width=0), # marker properties
showlegend = False # remove legend
)
)
# Update figure properties
fig.update_layout(
# Add title (see how hyperlink is added)
title_text = 'Languages around the world<br>\
Source: <a href="http://www.unesco.org/languages-atlas/index.php?hl=en&page=atlasmap">\
UNESCO</a>',
# Other geological properties of the map
geo = dict(
resolution=50,
showcoastlines=True,
showframe=False,
showland=True,
landcolor="lightgray",
showcountries=True,
countrycolor="white" ,
coastlinecolor="white",
bgcolor='rgba(255, 255, 255, 0.0)'
)
)
# Show the figure
fig.show()
# -
# Hover over markers in the map and see the dialects and status of various languages. Feel free to zoom in/out as necessary to spot various languages in a country of your choice.
#
# The colors indicate the [status of a language](http://www.unesco.org/languages-atlas/en/statistics.html).
#
# ### Questions:
#
# 1. Which color indicates a language that is safe from extinction? Which are the two continents with most safe languages?
# 2. Why do you think languages disappear? What are possible threats to linguistic diversity?
# 3. Could we revive a language that is on the brink of extinction? How?
# 4. Do you think that having more dialects makes a language safer or more vulnerable?
# ## Languages spoken within a country
#
# Now that we know about various languages, let's dive a bit deeper. We'll analyze languages spoken in various countries and how they have changed over time, using a demographic dataset from the [United Nations](http://data.un.org/Data.aspx?d=POP&f=tableCode:27).
# +
# Import the dataset
df2 = pd.read_csv('./Data/UNdata_Countrywise.csv')
df2 = df2.iloc[:-79] # Remove footnotes
# Display top 5 rows
df2.head()
# -
def show_bar_chart(ev):
clear_output(wait=True)
# Define display order for the buttons and menus
display(Box(children = [country_menu], layout = box_layout))
display(VBox(children = [show_button], layout = Layout(display= 'flex', flex_flow= 'column', align_items= 'center', width='100%', justify_content = 'center')))
# Filter the data for given country and gender type
to_be_removed = ['Unknown','Not stated','None','Total'] # Remove these categories
df2_sub = df2[df2['Country or Area'] == country_menu.value] \
[df2['Sex'] == 'Both Sexes'] \
[df2['Area'] == 'Total'] \
[~df2['Language'].isin(to_be_removed)]
# Plot the pie chart
if(df2_sub.shape[0] == 0):
print('Sorry... data not available :-(') # Show comment if data is not available
else:
years = df2_sub['Year'].unique()[0:2] # Show data for two latest years
# Make subplots
fig = make_subplots(rows=1, cols=len(years), subplot_titles=['Year {}'.format(i) for i in years])
# Add trace for each year's bar chart
for i,j in enumerate(years):
new_df = df2_sub[df2_sub['Year'] == j] # Filter the data for each subplot
new_df['Value'] = (100 * new_df['Value'] / new_df['Value'].sum()).round(1) # Convert population to percent
new_df = new_df.sort_values('Value',ascending=False)[:5] # Sort values in descending order
fig.add_trace(go.Bar(name='Year {}'.format(j),x=new_df['Language'],y=new_df['Value'],
showlegend=False),1,i+1) # Add the trace for each subplot
# Update yaxis properties of subplots
fig.update_yaxes(title_text="Population (%)", row=1, col=1, range=[0,100])
fig.update_yaxes(title_text="Population (%)", row=1, col=2, range=[0,100])
# Update the title of the figure
fig.update_layout(title_text='Top 5 languages spoken in {}<br>\
Source: <a href="http://data.un.org/Data.aspx?d=POP&f=tableCode:27">\
United Nations</a>'.format(country_menu.value))
fig.show()
print('Defined the function show_bar_chart')
# Run the cell below and select the country and gender you want to visualize. Don't forget to click on `Show Bar Chart` button.
# +
# Layout for widgets
box_layout = Layout(display='flex', flex_flow='row', align_items='center', width='100%', justify_content = 'center')
style = {'description_width': 'initial'}
# Create dropdown menu for Country and Gender
country_menu = widgets.Dropdown(options = df2['Country or Area'].unique(), description ='Country: ', style = style, disabled=False)
# Create Show Pie Chart button and define click events
show_button = widgets.Button(button_style= 'info', description="Show Bar Chart")
show_button.on_click(show_bar_chart)
# Define display order for the buttons and menus
display(Box(children = [country_menu], layout = box_layout))
display(VBox(children = [show_button], layout = Layout(display= 'flex', flex_flow= 'column', align_items= 'center', width='100%', justify_content = 'center')))
# -
# Each bar chart here is for a year in which data were collected. Move your cursor around to see how much of the total population speak a particular language and how that pattern has changed over time.
#
# ### Questions:
# 1. List the top 5 languages in Canada according to the latest data (2016).
# 2. Has use of languages other than *English* and *French* increased among Canadians over time?
# 3. How do you think globalization affects the spread languages across the borders?
# ## Exploring other languages
#
# Let's learn a little of some other languages. Here we will translate some English words into a language of your choice. The translation will be accompanied by an audio clip to show you how the translated word is pronounced.
# +
all_languages = gtts.lang.tts_langs()
all_languages = {v: k for k, v in all_languages.items()}
def translate_and_pronounce(ev):
clear_output(wait=True)
# Define display order for the buttons and menus
display(Box(children = [textbox_input, languages_menu], layout = box_layout))
display(VBox(children = [show_button], layout = Layout(display= 'flex', flex_flow= 'column', align_items= 'center', width='100%', justify_content = 'center')))
# Create a translator class (like a template) using Google Translator
translator = googletrans.Translator()
translation_data = translator.translate(textbox_input.value,\
dest=all_languages[languages_menu.value]) # Supply text to translate and language
translation = translation_data.extra_data['translation'][0][0] # Extract translated data
# Extract pronunciation for the translated text
if(len(translation_data.extra_data['translation']) == 2):
pronunciation = translation_data.extra_data['translation'][1][-1]
else:
pronunciation = 'None - Speak as you read' # For languages using Roman letters
print('\n')
# Create and display textbox for "Text" and dropdown menu for languages
textbox_translation = widgets.Text(value = translation, description = 'Translation: ', disabled = True, style = style)
textbox_pronunciation = widgets.Text(value = pronunciation, description = 'Pronunciation: ', disabled = True, style = style)
display(Box(children = [textbox_translation, textbox_pronunciation], layout = box_layout))
# Create an audio file for the translated text using Google Text-to-Speech
tts = gtts.gTTS(translation, lang=all_languages[languages_menu.value])
tts.save('audio.mp3')
# Display audio widget
display(Audio('audio.mp3'))
print('Defined the translate_and_pronounce function, run the cell below to use it.')
# +
# Layout for widgets
box_layout = Layout(display='flex', flex_flow='row', align_items='center', width='100%', justify_content = 'center')
style = {'description_width': 'initial'}
# Create textbox for "Text" and dropdown menu for languages
textbox_input = widgets.Text(value = '',description = 'Text: ', disabled = False)
languages_menu = widgets.Dropdown(options = list(all_languages.keys())[:-18], description ='Language: ', style = style, disabled=False)
# Create Translate button and define click events
show_button = widgets.Button(button_style= 'info', description="Translate")
show_button.on_click(translate_and_pronounce)
# Define display order for the buttons and menus
display(Box(children = [textbox_input, languages_menu], layout = box_layout))
display(VBox(children = [show_button], layout = Layout(display= 'flex', flex_flow= 'column', align_items= 'center', width='100%', justify_content = 'center')))
# -
# ### Questions:
#
# 1. In this era of globalization, how important do you think it is for people to learn additional languages?
# 2. List some scripts (alphabets) that are different from the [Roman](https://en.wikipedia.org/wiki/Latin_script) one we use in English (e.g. [Devanagari](https://en.wikipedia.org/wiki/Devanagari)).
# [](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
|
_build/jupyter_execute/curriculum-notebooks/SocialStudies/Globalization/languages-an-important-identity-in-globalizing-world.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Validation
#
# Here we tested accuracy, True Positive Rate (TPR) and True Negative Rate (TNR). The test is done on a small dataset.
# +
from tools import plot_roc, plot_pdf
import matplotlib.pyplot as plt
import numpy as np
import csv
# +
original_labels = {}
rates = {}
wl, bl = [], []
wl2, bl2 = [], []
wl3, bl3 = [], []
wl4, bl4 = [], []
with open("data/data-zealot.csv") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
original_labels[row[0]] = int(float(row[1]))
with open("data/graph-small-validation.csv") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if row[1] in original_labels:
rates[row[1]] = float(row[3])
if original_labels[row[1]] == 1:
wl.append(float(row[3]))
else:
bl.append(float(row[3]))
with open("data/graph-small-validation2.csv") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if row[1] in original_labels:
rates[row[1]] = float(row[3])
if original_labels[row[1]] == 1:
wl2.append(float(row[3]))
else:
bl2.append(float(row[3]))
with open("data/graph-small-validation3.csv") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if row[1] in original_labels:
rates[row[1]] = float(row[3])
if original_labels[row[1]] == 1:
wl3.append(float(row[3]))
else:
bl3.append(float(row[3]))
with open("data/graph-small-validation4.csv") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if row[1] in original_labels:
rates[row[1]] = float(row[3])
if original_labels[row[1]] == 1:
wl4.append(float(row[3]))
else:
bl4.append(float(row[3]))
l = 50
hist_wl, bins = np.histogram(wl, bins=np.linspace(0, 1, l + 1), density=True)
hist_bl, bins = np.histogram(bl, bins=np.linspace(0, 1, l + 1), density=True)
hist_wl2, bins = np.histogram(wl2, bins=np.linspace(0, 1, l + 1), density=True)
hist_bl2, bins = np.histogram(bl2, bins=np.linspace(0, 1, l + 1), density=True)
hist_wl3, bins = np.histogram(wl3, bins=np.linspace(0, 1, l + 1), density=True)
hist_bl3, bins = np.histogram(bl3, bins=np.linspace(0, 1, l + 1), density=True)
hist_wl4, bins = np.histogram(wl4, bins=np.linspace(0, 1, l + 1), density=True)
hist_bl4, bins = np.histogram(bl4, bins=np.linspace(0, 1, l + 1), density=True)
fig, ax = plt.subplots(1, 1, figsize=(7, 7))
ax.plot(np.arange(0, l), np.arange(0, l), "--")
ax.set_xlim([-0, 1])
ax.set_ylim([-0, 1])
ax.set_title("ROC Curve", fontsize=14)
ax.set_ylabel("TPR", fontsize=12)
ax.set_xlabel("FPR", fontsize=12)
ax.grid()
plot_roc(hist_bl, hist_wl, ax, np.arange(0, l), False)
plot_roc(hist_bl2, hist_wl2, ax, np.arange(0, l), False)
plot_roc(hist_bl3, hist_wl3, ax, np.arange(0, l), False)
plot_roc(hist_bl4, hist_wl4, ax, np.arange(0, l), False)
ax.legend(["Random", "100", "200", "300", "1000"])
plt.show()
# -
x = np.linspace(0, 1, num=l)
fig, ax = plt.subplots(1, 1, figsize=(10, 5))
plot_pdf(hist_bl4, hist_wl4, ax, x)
plt.show()
n = len(bl4) + len(wl4)
print("Confusion matrix, relative numbers")
print([round(sum(np.array(wl4) > 0.5) / len(wl4), 3), round(sum(np.array(wl4) < 0.5)/len(wl4), 3)])
print([round(sum(np.array(bl4) > 0.5)/len(bl4), 3), round(sum(np.array(bl4) < 0.5)/len(bl4), 3)])
print(f"Accuracy: {round((sum(np.array(wl4) > 0.5) + sum(np.array(bl4) < 0.5)) / n, 3)}")
# ### Sources:
# [1] Receiver Operating Characteristic Curves Demystified (in Python), https://towardsdatascience.com/receiver-operating-characteristic-curves-demystified-in-python-bd531a4364d0
|
validation.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# # Simple Customer Insights
# _version 0.7_
#
# February 17, 2016
# https://developer.ibm.com/clouddataservices/
#
#
# ## Overview
#
# Today, an ever growing wealth of public data, e.g. census, geospatial, demographic, incident, traffic, etc., is available to fuel analytic insights when combined with corporate data. Your own data only tells you what your business is doing. With open data, you learn what the world is doing. And the combination of the two allows you to align business practices with the market.
#
# **Simple Customer Insights** is about democratizing big data analytics with open data and cloud-based analytics. It's a [Jupyter notebook](http://jupyter.org/) that runs best in [IBM's Spark-as-a-service](http://www.ibm.com/analytics/us/en/technology/cloud-data-services/spark-as-a-service/) that enables a Bluemix user to integrate customer sales data with US Census demographic data, and in minutes perform common analyses that once took days or weeks to complete.
#
# This notebook goes through a complete analysis using sample data readily available on the web. But it also serves as a template for your own work with your own data. Just substitute the sample sales data with your own!
#
# Here are some of the insights produced in this notebook:
# 1. demographic characteristics of good customers
# 1. most important demographic characteristics in understanding product appeal
# 1. location of places that are like those areas currently enjoying strong sales
# <a id="toc"></a>
# ## Table of Contents
#
# - [Setup](#setup)
# - [Census Data](#censusdata)
# - [Census data description](#censusdatadesc)
# - [Import](#censusdataimport)
# - [Descriptive statistics](#censusdatastats)
# - [Sales data](#salesdata)
# - [Import](#salesdataimport)
# - [Merge with Census](#salesdatamerge)
# - [Insights](#insights)
# - [Visualization](#viz)
# - [Summary](#summary)
# - [Finding high potential zip codes](#zipfind)
# - [Target zip codes](#targetregions)
# - [Mapping](#map)
#
# <a id="setup"></a>
# ## Setup
# ### Python Imports
# [back to top](#toc)
# Import libraries and connection information to connect to Swift Object Storage on IBM Bluemix to get data from CSV text files.
import os, requests, StringIO, pandas as pd, numpy as np, json, matplotlib.pyplot as plt, seaborn as sns
# %matplotlib inline
credentials = {}
credentials['auth_url'] = 'https://identity.open.softlayer.com'
credentials['user_id'] = os.environ['OBJECTSTORE_USER_ID']
credentials['domain_id'] = os.environ['OBJECTSTORE_DOMAIN_ID']
credentials['username'] = os.environ['OBJECTSTORE_USERNAME']
credentials['password'] = <PASSWORD>['OBJECTSTORE_PASSWORD']
credentials['container'] = os.environ['OBJECTSTORE_CONTAINER']
# ### ObjectStore credentials
#
# My working environment is set up to get my ObjectStore credentials above from variables I've set at the operating system level. You may want to go a simpler route and just enter the values as strings above. And when you copy this notebook to the [IBM Analytics for Apache Spark service](https://console.ng.bluemix.net/catalog/services/apache-spark/?cm_mmc=developerWorks-_-dWdevcenter-_-clouddataservices-_-lp), embedding your credentials directly in the notebook is your only option. You can find your ObjectStore credentials by finding your instance of the ObjectStore service in Bluemix and clicking on the 'Service Credentials'.
#
# 
# +
# A function returning a StringIO object containing text file content from Object Storage.
def getFileContent(credentials):
url1 = ''.join([credentials['auth_url'], '/v3/auth/tokens'])
data = {'auth':
{'identity':
{'methods': ['password'],
'password': {
'user':
{'name': credentials['username'],
'domain': {'id': credentials['domain_id']},
'password': <PASSWORD>['password']
}
}
}
}
}
headers1 = {'Content-Type': 'application/json'}
resp1 = requests.post(url=url1, data=json.dumps(data), headers=headers1)
resp1_body = resp1.json()
for e1 in resp1_body['token']['catalog']:
if(e1['type']=='object-store'):
for e2 in e1['endpoints']:
if(e2['interface']=='public'):
url2 = ''.join([e2['url'],'/',
credentials['container'], '/',
credentials['filename']])
s_subject_token = resp1.headers['x-subject-token']
headers2 = {'X-Auth-Token': s_subject_token, 'accept': 'application/json'}
resp2 = requests.get(url=url2, headers=headers2)
return StringIO.StringIO(resp2.content)
# -
# <a id="censusdata"></a>
# ## Census data
# [back to top](#toc)
#
# Census data from the 2013 US Census American Community Survey (ACS), 5-year estimates.
#
# Created from the "zip code tabulation area" (ZCTA) [TIGER/Line® with Selected Demographic and Economic Data product in Geodatabase format](http://www.census.gov/geo/maps-data/data/tiger-data.html). This particular version of the ACS is used for the folowing reasons:
# 1. 5-year estimates are the most accurate data outside of the decennial census [as explained here](http://www.census.gov/programs-surveys/acs/guidance/estimates.html).
# 1. 2013 is the most recent data set with 5-year estimates
# 1. TIGER/Line® gives you the geographic boundaries of the zip codes so you can perform spatial analyses
# 1. This data set is smaller than the full Census, but still has the important income, education, race, age and occupation demographics we want to use.
#
# If you want to do this yourself, [this article](https://developer.ibm.com/clouddataservices/2015/09/08/census-open-data-on-ibm-cloud/) explains how to get a CSV out of that format.
# <a id="censusdatadesc"></a>
# ### Census data description
#
# Here are the data fields we will use from the Census
#
# ```
# GEOID: Zip code
# ```
#
# ### Income
# ```
# B19049e1: Median household income
# ```
#
# #### Age
# ```
# B01002e1: Median age
# ```
#
# #### Educational attainment (population >= 25 years old)
# ```
# B15003e1: Total population
# B15003e2: No schooling completed
# B15003e3: Nursery school
# B15003e4 to B15003e16: Kindergarten to 12th grade
# B15003e17: Regular high school diploma
# B15003e18: GED or alternative
# B15003e19: Some college, < 1 year
# B15003e20: Some college, 1 or more years, no degree
# B15003e21: Associates degree
# B15003e22: Bachelors degree
# B15003e23: Masters degree
# B15003e24: Professional degree
# B15003e25: Doctorate degree
# ```
#
# #### Race
# ```
# B02001e1: Total population
# B02001e2: White alone
# B02001e3: Black or African American alone
# B02001e4: American Indian and Alaska Native alone
# B02001e5: Asian alone
# B02001e6: Native Hawaiian and Other Pacific Islander alone
# B02001e7: Some other race alone
# B02001e8: Two or more races
# B03001e3: Hispanic or Latino: Total population
# ```
# <a id="censusdataimport"></a>
# ### Import Census data
# +
#credentials['filename'] = 'sci.csv'
#raw_data = getFileContent(credentials)
# -
raw_data = "/Users/rajrsingh/Desktop/csv/outfiles/sci.csv.gz"
census_df = pd.read_csv(raw_data, usecols=['GEOID','B19049e1','B01002e1',
'B15003e1','B15003e2','B15003e3','B15003e4','B15003e5','B15003e6','B15003e7','B15003e8','B15003e9','B15003e10','B15003e11','B15003e12','B15003e13','B15003e14','B15003e15','B15003e16','B15003e17','B15003e18','B15003e19','B15003e20','B15003e21','B15003e22','B15003e23','B15003e24','B15003e25',
'B02001e1','B02001e2','B02001e3','B02001e4','B02001e5','B02001e6','B02001e7','B02001e8','B03001e3'])
# Group educational attainment into 4 major categories, and normalize by making it a percentage of the zip code's population
# +
census_df['INCOME'] = census_df['B19049e1']
census_df['AGE'] = census_df['B01002e1']
census_df.drop(['B19049e1','B01002e1'],inplace=True,axis=1)
census_df['NOHSDIP'] = (census_df['B15003e2']+census_df['B15003e3']+census_df['B15003e4']+census_df['B15003e5']+census_df['B15003e6']+census_df['B15003e7']+census_df['B15003e8']+census_df['B15003e9']+census_df['B15003e10']+census_df['B15003e11']+census_df['B15003e12']+census_df['B15003e13']+census_df['B15003e14']+census_df['B15003e15']+census_df['B15003e16'])/census_df['B15003e1']
census_df['HSDIPSOMECOL'] = (census_df['B15003e17']+census_df['B15003e18']+census_df['B15003e19']+census_df['B15003e20']+census_df['B15003e21'])/census_df['B15003e1']
census_df['BA'] = census_df['B15003e22']/census_df['B15003e1']
census_df['GRAD'] = (census_df['B15003e23']+census_df['B15003e24']+census_df['B15003e25'])/census_df['B15003e1']
census_df['POPULATION'] = census_df['B15003e1']
census_df['WHITE'] = census_df['B02001e2']/census_df['B02001e1']
census_df['BLACK'] = census_df['B02001e3']/census_df['B02001e1']
census_df['NATAMER'] = census_df['B02001e4']/census_df['B02001e1']
census_df['ASIAN'] = census_df['B02001e5']/census_df['B02001e1']
census_df['PACISL'] = census_df['B02001e6']/census_df['B02001e1']
census_df['OTHERRACE'] = census_df['B02001e7']/census_df['B02001e1']
census_df['MULTIRACE'] = census_df['B02001e8']/census_df['B02001e1']
census_df['HISPLAT'] = census_df['B03001e3']/census_df['B02001e1']
census_df.drop(['B02001e1','B02001e2','B02001e3','B02001e4','B02001e5','B02001e6','B02001e7','B02001e8','B03001e3'],inplace=True,axis=1)
census_df = census_df.set_index('GEOID')
# +
# Compute national averages
nat_edu_nohsdip = census_df['B15003e2'].sum()+census_df['B15003e3'].sum()+census_df['B15003e4'].sum()+census_df['B15003e5'].sum()+census_df['B15003e6'].sum()+census_df['B15003e7'].sum()+census_df['B15003e8'].sum()+census_df['B15003e9'].sum()+census_df['B15003e10'].sum()+census_df['B15003e11'].sum()+census_df['B15003e12'].sum()+census_df['B15003e13'].sum()+census_df['B15003e14'].sum()+census_df['B15003e15'].sum()+census_df['B15003e16'].sum()
nat_edu_hsdipsomecol = census_df['B15003e17'].sum()+census_df['B15003e18'].sum()+census_df['B15003e19'].sum()+census_df['B15003e20'].sum()+census_df['B15003e21'].sum()
nat_edu_ba = census_df['B15003e22'].sum()
nat_edu_grad = census_df['B15003e23'].sum()+census_df['B15003e24'].sum()+census_df['B15003e25'].sum()
census_df_national = pd.DataFrame( [ {'NOHSDIP': nat_edu_nohsdip, 'HSDIPSOMECOL': nat_edu_hsdipsomecol, 'BA': nat_edu_ba, 'GRAD': nat_edu_grad, 'POPULATION': census_df['B15003e1'].sum()} ] )
# Now safely drop unneeded original data columns
census_df.drop(['B15003e1','B15003e2','B15003e3','B15003e4','B15003e5','B15003e6','B15003e7','B15003e8','B15003e9','B15003e10','B15003e11','B15003e12','B15003e13','B15003e14','B15003e15','B15003e16','B15003e17','B15003e18','B15003e19','B15003e20','B15003e21','B15003e22','B15003e23','B15003e24','B15003e25'],inplace=True,axis=1)
census_df_national_rate = census_df_national.truediv(census_df_national['POPULATION'], axis=0)
census_df_national_rate #will be used later
# -
# <a id="censusdatastats"></a>
# ### Descriptive statistics for Census data
#
# #### Summary statistics
summary_df = census_df.describe(percentiles=[0.4,0.5,0.6])
summary_df = summary_df.drop(summary_df.index[[0,2]])
summary_df
# #### Examining correlation
#
# In this section, we take a quick look at the correlation coefficients of many of our variables of interest to make sure it's worth looking at each one separately. This function computes the [Pearson product-moment correlation coefficient](https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient), which looks at two variables and computes a number between -1 and 1, where -1 is perfect negative correlation, 1 is perfect positive correlation, and 0 is no correlation.
#
# None of our variables of interest have a particularly strong correlation with each other (except for the obvious ones like income with bachelor's (BA) or graduate degree (GRAD)), so we can proceed with analysis knowing that it's worth looking at all of them.
# +
corr = census_df.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(10, 200, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3,
square=True,
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
plt.title('Correlation Matrix', size=20)
plt.show()
# -
# <a id="salesdata"></a>
# ## Sales data
# <a id="salesdataimport"></a>
# ### Import sample sales data set
#
# Here we bring in a relatively small sample sales data set. There are only about 400 U.S. sales for the product we are interested in -- "Product1". But this is good enough to illustrate the analysis.
#
# If you were to do this yourself with your own sales data, your data should organized as follows:
# 1. there should be sales in the U.S. (since we're analyzing it against U.S. Census data)
# 1. each row should represent a unique sale
# 1. the data set should contain columns for zip code, price, product ID and Country name
# 1. the data set should be in a CSV text file format
# +
credentials['filename'] = 'SalesJan2009.csv'
country = 'United States'
product = 'Product1'
# import the CSV file
#raw_data = getFileContent(credentials)
raw_data = "/Users/rajrsingh/Box Sync/CDS/Developer Advocacy/Open Data/sales2009/SalesJan2009.csv"
# create a data frame with just the columns we need
sales_df = pd.read_csv(raw_data, dtype={"US Zip": np.str},
usecols=['Product','US Zip','Country'])
# just get US sales for a single product
sales_df = sales_df[ (sales_df.Product == product)
& (sales_df.Country == country)]
# make the zip code format match the zip code format in the census data
sales_df['GEOID'] = "86000US" + sales_df['US Zip']
# drop columns we don't need anymore
sales_df.drop(['Product','Country','US Zip'],inplace=True,axis=1)
# -
sales_counts = sales_df['GEOID'].value_counts()
sales_counts.name = 'Sales'
sales_counts.describe()
# <a id="salesdatamerge"></a>
# ### Merge sales to Census
# [back to top](#toc)
saleszips = census_df.join(sales_counts, how='right')
saleszips['Zip'] = saleszips.index
saleszips.describe(percentiles=[0.4,0.5,0.6])
# ### Identify sales zips with strongest correlation to customers
# [back to top](#toc)
#
# e.g. zips with at least 2 sales - or the top 75% of zips with sales
# 25% threshold is 1, so select zips with sales > 1
highsaleszips = saleszips[ ( saleszips.Sales > 1)]
highsaleszipssum_df = highsaleszips.describe(percentiles=[.40,.50,.60])
highsaleszipssum_df = highsaleszipssum_df.drop(highsaleszipssum_df.index[[0,2]])
highsaleszipssum_df.drop(['Sales'],inplace=True,axis=1)
highsaleszipssum_df
# <a id="insights"></a>
# ## Insights
# <a id="viz"></a>
# ### Visualization
# %matplotlib inline
plt.rcParams['figure.figsize'] = (16, 8)
highzipaxlabel = '# of zips - zips with high sales'
nationalaxlabel = '# of zips - nation'
# #### Demographics Histograms
# +
## Income
fig = plt.figure()
common_params = dict(bins=20, alpha=0.85, range=(0.0,100000))
ax = fig.add_subplot(211)
plt.hist(highsaleszips['INCOME'], label='Sales Zips', **common_params)
ax.set_ylabel(highzipaxlabel)
ax.axhline(0, color='gray', lw=2)
ax_national = ax.twinx()
ax_national.set_ylabel(nationalaxlabel)
ax_national.hist(census_df['INCOME'], label='Nation', histtype='step', linewidth=3, color='orange', **common_params)
plt.title("Median Income")
plt.legend(loc='upper right')
plt.show()
# +
## Age
fig = plt.figure()
common_params = dict(bins=20, alpha=0.85, range=(20,60))
ax = fig.add_subplot(211)
plt.hist(highsaleszips['AGE'], label='Sales Zips', **common_params)
ax.set_ylabel(highzipaxlabel)
ax.axhline(0, color='gray', lw=2)
ax_national = ax.twinx()
ax_national.set_ylabel(nationalaxlabel)
ax_national.hist(census_df['AGE'], label='National distribution', histtype='step', linewidth=3, color='orange', **common_params)
plt.title("Median Age")
plt.legend(loc='upper right')
plt.show()
# +
## No H.S. diploma
fig = plt.figure()
common_params = dict(bins=20, alpha=0.85, range=(0,0.5))
ax = fig.add_subplot(211)
plt.hist(highsaleszips['NOHSDIP'], label='Sales Zips', **common_params)
ax.set_ylabel(highzipaxlabel)
ax.axhline(0, color='gray', lw=2)
ax_national = ax.twinx()
ax_national.set_ylabel(nationalaxlabel)
ax_national.hist(census_df['NOHSDIP'], label='National distribution', histtype='step', linewidth=3, color='orange', **common_params)
plt.title("Proportion with no High School Diploma")
plt.legend(loc='upper right')
plt.show()
# +
## Bachelors degree
fig = plt.figure()
common_params = dict(bins=20, alpha=0.85, range=(0,0.5))
ax = fig.add_subplot(211)
plt.hist(highsaleszips['BA'], label='Sales Zips', **common_params)
ax.set_ylabel(highzipaxlabel)
ax.axhline(0, color='gray', lw=2)
ax_national = ax.twinx()
ax_national.set_ylabel(nationalaxlabel)
ax_national.hist(census_df['BA'], label='National distribution', histtype='step', linewidth=3, color='orange', **common_params)
plt.title("Proportion with Bachelors Degree")
plt.legend(loc='upper right')
plt.show()
# +
## White
fig = plt.figure()
common_params = dict(bins=20, alpha=0.85, range=(0,1))
ax = fig.add_subplot(211)
plt.hist(highsaleszips['WHITE'], label='Sales Zips', **common_params)
ax.set_ylabel(highzipaxlabel)
ax.axhline(0, color='gray', lw=2)
ax_national = ax.twinx()
ax_national.set_ylabel(nationalaxlabel)
ax_national.hist(census_df['WHITE'], label='National distribution', histtype='step', linewidth=3, color='orange', **common_params)
plt.title("Proportion, White race")
plt.legend(loc='upper right')
plt.show()
# +
## Black
fig = plt.figure()
common_params = dict(bins=20, alpha=0.85, range=(0,0.4))
ax = fig.add_subplot(211)
plt.hist(highsaleszips['BLACK'], label='Sales Zips', **common_params)
ax.set_ylabel(highzipaxlabel)
ax.axhline(0, color='gray', lw=2)
ax_national = ax.twinx()
ax_national.set_ylabel(nationalaxlabel)
ax_national.hist(census_df['BLACK'], label='National distribution', histtype='step', linewidth=3, color='orange', **common_params)
plt.title("Proportion, Black race")
plt.legend(loc='upper right')
plt.show()
# +
## Asian
fig = plt.figure()
common_params = dict(bins=20, alpha=0.85, range=(0,0.4))
ax = fig.add_subplot(211)
plt.hist(highsaleszips['ASIAN'], label='Sales Zips', **common_params)
ax.set_ylabel(highzipaxlabel)
ax.axhline(0, color='gray', lw=2)
ax_national = ax.twinx()
ax_national.set_ylabel(nationalaxlabel)
ax_national.hist(census_df['ASIAN'], label='National distribution', histtype='step', linewidth=3, color='orange', **common_params)
plt.title("Proportion, Asian race")
plt.legend(loc='upper right')
plt.show()
# +
## Hispanic or Latino
fig = plt.figure()
common_params = dict(bins=20, alpha=0.85, range=(0,0.4))
ax = fig.add_subplot(211)
plt.hist(highsaleszips['HISPLAT'], label='Sales Zips', **common_params)
ax.set_ylabel(highzipaxlabel)
ax.axhline(0, color='gray', lw=2)
ax_national = ax.twinx()
ax_national.set_ylabel(nationalaxlabel)
ax_national.hist(census_df['HISPLAT'], label='National distribution', histtype='step', linewidth=3, color='orange', **common_params)
plt.title("Proportion of Hispanic or Latino race")
plt.legend(loc='upper right')
plt.show()
# -
# #### Major racial groups for zip codes in which we have sales
highsaleszips.loc[:,'WHITE':'ASIAN'].plot(kind='bar', stacked=True, figsize=(12,8), title='Race in sales areas')
plt.ylim(0, 1)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
# Compare characteristics of the country as a whole to zip codes with sales
salesdiff_df = highsaleszipssum_df.sub(summary_df)
salesdiff_df
# <a id="summary"></a>
# ### Summary
#
# #### Incomes are much higher
# Median household income overall is about $22,000 higher than the country as a whole, which is **very** significant as that represents a nearly 50% increase in income in these zip codes we sell to.
#
# #### Education is greater
# The percentage of people with high school diplomas but no college degree is almost 24% lower in our sales zips, and that is compensated by a much greater number of college grads (16% higher) and people with graduate degrees of some sort (12% higher).
#
# #### People are a little younger
# Males and females are about 3 1/2 years younger in our zip codes than in the country as a whole.
#
#
# #### White population is lower
# The white population is lower, and there is a corresponding higher number of other races.
#
#
# <a id="zipfind"></a>
# ## Finding high potential zip codes
#
# Here we take the variables we found to best explain the population of sales areas, and we look for other zip codes whose demographic characteristics for those variables are within 10 percentage points of the median.
censusgood_df = census_df [
( census_df.INCOME > highsaleszipssum_df.loc['40%','INCOME'] )
& ( census_df.INCOME < highsaleszipssum_df.loc['60%','INCOME'] )
& ( census_df.AGE > highsaleszipssum_df.loc['40%','AGE'] )
& ( census_df.AGE < highsaleszipssum_df.loc['60%','AGE'] )
& ( census_df.BA > highsaleszipssum_df.loc['40%','BA'] )
& ( census_df.BA < highsaleszipssum_df.loc['60%','BA'] )
& ( census_df.WHITE > highsaleszipssum_df.loc['40%','WHITE'] )
& ( census_df.WHITE < highsaleszipssum_df.loc['60%','WHITE'] )
]
censusgood_df.describe()
# <a id="targetregions"></a>
# ### Target regions
#
# Here we list the matching zip codes. From this point you could use this list in a variety of ways. Here are some ideas:
# - Guidance for where to spend marketing dollars
# - Filter existing direct mail lists to target those most likely to buy
# - Guidance on where to build retail outlets, or if you're a wholesaler, where you want to get your products retailed.
censusgood_df.index.tolist()
# <a id="map"></a>
# ## Mapping great prospective zip codes with CartoDB
#
# Having a list of zip codes is great, but it's extremely useful to be able to see the results on a map. This is the best way to do a 'reality check' and see if the results make sense. It's also interesting to survey the country in this way -- a birds-eye view of where your product is selling and where there's potential demand.
#
# Here we show an integration with a good friend of ours, CartoDB. CartoDB is a firm specializing in mapping-as-a-service. They use the excellent open source database, PostgreSQL and it's geospatial extension, PostGIS to power their service.
#
# What we need to do to dynamically create maps of our analytics results is:
# 1. Manually import the raw census zip code boundaries into CartoDB's platform (with no demographic data attached to reduce the file size)
# 1. Create a map in CartoDB of the zip code boundaries
# 1. Add 2 empty tables to the map that represent zip codes with sales, and good potential zip codes
# 1. When we run an analysis, populate those tables with the results of the analysis
# ### Update data tables in CartoDB
# !pip install --user cartodb
# Set up cartodb module for use
from cartodb import CartoDBAPIKey, CartoDBException
API_KEY = os.environ['CARTODB_APIKEY']
CARTODB_ACCOUNT = os.environ['CARTODB_ACCOUNT']
cl = CartoDBAPIKey(API_KEY, CARTODB_ACCOUNT)
# #### Update Sales table in CartoDB
# output good Census zips to a list
ziplist = highsaleszips.index.tolist()
# generate PostgreSQL INSERT statements for CartoDB
insertsql = ';'.join(map(lambda x: "INSERT INTO highsaleszips(zipcode) VALUES ('%s')" %x, ziplist))
# update sales table
try:
print(cl.sql('delete from highsaleszips'))
print(cl.sql(insertsql))
except CartoDBException as e:
print("some error ocurred", e)
# #### Update prospective zip codes in CartoDB
# output good Census zips to a list
ziplist = censusgood_df.index.tolist()
# generate PostgreSQL INSERT statements for CartoDB
insertsql = ';'.join(map(lambda x: "INSERT INTO prospectzips(zipcode) VALUES ('%s')" %x, ziplist))
try:
print(cl.sql('delete from prospectzips'))
print(cl.sql(insertsql))
except CartoDBException as e:
print("some error ocurred", e)
# ## Display the dynamic map
# + language="javascript"
# element.append('<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" />');
# element.append('<h2>High value target sales areas</h2>');
# element.append('<div id="map" style="height:450px;width:850px;padding:0;margin:0"></div>');
#
# require.config({
# paths: {
# cartodblib: '//libs.cartocdn.com/cartodb.js/v3/3.15/cartodb'
# }
# });
#
# var main = function() {
# cartodb.createVis('map', 'https://ibmanalytics.cartodb.com/u/ibm/api/v2/viz/2bd6ea76-9f7f-11e5-a024-0e674067d321/viz.json', {
# shareable: true,title: true,description: true,search: true,tiles_loader: true,
# center_lat: 40, center_lon: -100, zoom: 3
# })
# .done(function(vis, layers) {
# // layer 0 is the base layer, layer 1 is cartodb layer
# //layers[1].setInteraction(true);
# //layers[1].on('featureOver', function(e, latlng, pos, data) {
# // cartodb.log.log(e, latlng, pos, data);
# //});
# var map = vis.getNativeMap(); // get the native map to work with it
# })
# .error(function(err) {
# console.log(err);
# });
# }
#
# require(['cartodblib'], main);
# -
# ## The end
|
samples/sci.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Employee Attrition Prediction
# #### Add import statement
# +
import pandas as pd
import seaborn as sns
# %matplotlib inline
import numpy as np
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, roc_curve, roc_auc_score
from sklearn.model_selection import train_test_split, cross_val_score
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import StratifiedKFold
# Import and suppress warnings
import warnings
warnings.filterwarnings('ignore')
# -
# #### load employee data
emp_data = pd.read_csv(".\data.csv", sep='\t')
emp_data.head()
# #### check the data type
emp_data.dtypes
# #### check for null data
emp_data.isnull().any()
#No nulls present data is fairly clean
#No need to insert synthetic data for missing values
# #### Process Data
#Checking basic health of data for outliers and other issues which can bring noise
emp_data.describe()
## EmployeeCount , StandardHours, Over18 and EmployeeNumber are irrelevant, hence dropping these
emp_data=emp_data.drop(["EmployeeCount","StandardHours","Over18",'EmployeeNumber'],axis=1)
# +
## Encode binary categorical data
emp_data["Gender"] = emp_data["Gender"].astype('category')
emp_data["OverTime"] = emp_data["OverTime"].astype('category')
emp_data["Attrition"] = emp_data["Attrition"].astype('category')
emp_data["Gender"] = emp_data["Gender"].cat.codes
emp_data["OverTime"] = emp_data["OverTime"].cat.codes
emp_data["Attrition"] = emp_data["Attrition"].cat.codes
# -
# #### Plotting Data
# +
# Refining our list of numerical variables
numerical = [u'Age', u'DailyRate', u'JobSatisfaction',
u'MonthlyIncome', u'PerformanceRating',
u'WorkLifeBalance', u'YearsAtCompany', u'Attrition']
g = sns.pairplot(emp_data[numerical], hue='Attrition', palette='seismic', diag_kind = 'kde',diag_kws=dict(shade=True))
g.set(xticklabels=[])
# +
## list down all the features and categorize them
emp_data = pd.get_dummies(emp_data, columns=["MaritalStatus","EducationField"])
emp_data = pd.get_dummies(emp_data, columns=["Department","JobRole"])
personal_features = ['Age','DistanceFromHome','Education','EducationField_Human Resources','EducationField_Life Sciences','EducationField_Marketing','EducationField_Medical','EducationField_Other','EducationField_Technical Degree','Gender','MaritalStatus_Divorced','MaritalStatus_Married','MaritalStatus_Single','NumCompaniesWorked']
money_features = ['DailyRate','HourlyRate','MonthlyIncome','MonthlyRate','PercentSalaryHike','StockOptionLevel']
satisfication_features = ['EnvironmentSatisfaction','JobSatisfaction','RelationshipSatisfaction','WorkLifeBalance']
emp_data = pd.get_dummies(emp_data, columns=["BusinessTravel"])
perks_info_features = ['BusinessTravel_Travel_Rarely','BusinessTravel_Travel_Frequently','BusinessTravel_Non-Travel','JobInvolvement','OverTime','PerformanceRating']
job_role_features = ['JobRole_Healthcare Representative','JobRole_Human Resources','JobRole_Laboratory Technician','JobRole_Manager','JobRole_Manufacturing Director','JobRole_Research Director','JobRole_Research Scientist','JobRole_Sales Executive','JobRole_Sales Representative']
department_features = ['Department_Human Resources','Department_Research & Development','Department_Sales']
employee_work_features = ['JobLevel','TotalWorkingYears','TrainingTimesLastYear','YearsAtCompany','YearsInCurrentRole','YearsSinceLastPromotion','YearsWithCurrManager']
emp_imp_features = job_role_features + department_features + employee_work_features + perks_info_features
# +
## Normalize data (Feature Scaling) #TO bring data in a specific range
#Improves performance and accuracy
emp_data["MonthlyRateLog"] = np.log1p(emp_data["MonthlyRate"])
emp_data["MonthlyIncomeLog"] = np.log1p(emp_data["MonthlyIncome"])
emp_data["HourlyRateLog"] = np.log1p(emp_data["HourlyRate"])
emp_data["DailyRateLog"] = np.log1p(emp_data["DailyRate"])
money_log_features = ['DailyRateLog','HourlyRateLog','MonthlyIncomeLog','MonthlyRateLog','PercentSalaryHike','StockOptionLevel']
all_featues = personal_features + money_log_features + satisfication_features + emp_imp_features + perks_info_features
#TODO: find best features using
#rfc.feature_importances_
best_features = ['MonthlyIncome','Age','DailyRate','OverTime','MonthlyRate','TotalWorkingYears','HourlyRate','YearsAtCompany','YearsWithCurrManager','PercentSalaryHike','NumCompaniesWorked','DistanceFromHome','JobLevel','EnvironmentSatisfaction','RelationshipSatisfaction','JobInvolvement','YearsInCurrentRole','WorkLifeBalance','StockOptionLevel']
# -
# #### Define model train and model performance function
# +
def train_model(model,features,dataset):
# extract features from the dataset
X_train = dataset[features]
Y_train = dataset['Attrition']
# spilt the data for training and testing
X_tr, X_te, Y_tr, Y_te = train_test_split(X_train, Y_train, test_size=0.2)
# train the model
model.fit(X_tr, Y_tr)
Y_pr = model.predict(X_te)
accuracy = model.score(X_te,Y_te)
print("Model accuracy score is ",accuracy)
return Y_te,Y_pr
def measure_perform_matrix(Y_pr,Y_te):
confMat = confusion_matrix(Y_pr,Y_te)
TP=confMat[0][0]
FP=confMat[0][1]
FN=confMat[1][0]
TN=confMat[1][1]
print("True Positive :",TP)
print("False Positive :",FP)
print("False Negative :",FN)
print("True Negative :",TN)
Acc = (TP + TN)/(TP+FP+FN+TN)
print(Acc)
Sensitivity = TP/(TP + FN)
Specificity = TN/(TN + FP)
print("Sensitivity :",Sensitivity)
print("Specificity :",Specificity)
Precision = TP/(TP+FP)
invRecall = 1/Sensitivity
invPrecision = 1/Precision
F1_Score = 2/(invRecall + invPrecision)
print("Precision : ",Precision)
print("F1 Score",F1_Score)
##Computing false and true positive rates
fpr, tpr,_=roc_curve(Y_pr,Y_te,drop_intermediate=False)
plt.figure()
#plot the ROC curve
plt.plot(fpr, tpr, color='red',lw=2, label='ROC curve')
#Adding Random FPR and TPR
plt.plot([0, 1], [0, 1], color='blue', lw=2, linestyle='--')
#Title and label
plt.xlabel('False Positive Rate')
plt.ylabel('Total Positive Rate')
plt.title('ROC curve')
plt.show()
#Train model
def train_model_grad(model,features,dataset,val):
# extract features from the dataset
X_train = dataset[features]
Y_train = dataset['Attrition']
# spilt the data for training and testing
X_tr, X_te, Y_tr, Y_te = train_test_split(X_train, Y_train, test_size=0.2,random_state=val)
# train the model
model.fit(X_tr, Y_tr)
Y_pr = model.predict(X_te)
accuracy = model.score(X_te,Y_te)
print("Model accuracy score is ",accuracy)
return Y_te,Y_pr
# -
# #### Logistic Regression
lReg = LogisticRegression()
Y_test, Y_predict= train_model_grad(lReg,all_featues,emp_data,26)
measure_perform_matrix(Y_test, Y_predict)
# #### Random Forest Model
forest=RandomForestClassifier(n_estimators=1000,criterion="gini",max_depth=10,n_jobs=-1)
Y_test, Y_predict = train_model_grad(forest,all_featues,emp_data,26)
measure_perform_matrix(Y_test, Y_predict)
# #### Neural Network
#TO DO:Bring Scaled Features as input
neuNet = MLPClassifier(activation='relu', solver='adam', hidden_layer_sizes=(256,), max_iter=500,random_state=26)
#y_te,y_pr = train_model(neuNet,all_featues,emp_data)
y_te, y_pr = train_model_grad(neuNet,all_featues,emp_data,26)
measure_perform_matrix(y_pr,y_te)
# #### Gradient boosting classifier
gradBoost = GradientBoostingClassifier(n_estimators=45)
y_te,y_pr = train_model_grad(gradBoost,all_featues,emp_data,26)
measure_perform_matrix(y_pr,y_te)
# #### KNeighbors Classifier
knn = KNeighborsClassifier(n_neighbors=10)
y_te,y_pr = train_model_grad(knn,all_featues,emp_data,26)
measure_perform_matrix(y_pr,y_te)
# ### Hyperparameter Tuning
# +
from sklearn.grid_search import GridSearchCV
#parameters range
params_range=[100,250,500,1000]
params_depth=[2,3,5]
param_grid={'n_estimators':params_range,
'criterion':['entropy','gini'],
'max_depth':params_depth}
gridsearch=GridSearchCV(estimator=forest,
param_grid=param_grid,
scoring='accuracy',
cv=5,
n_jobs=1)
##
X_train = emp_data[all_featues]
Y_train = emp_data['Attrition']
# spilt the data for training and testing
X_tr, X_te, y_tr, y_te = train_test_split(X_train, Y_train, test_size=0.2)
##
gridsearch.fit(X_tr,y_tr)
print(gridsearch.best_score_)
print(gridsearch.best_params_)
#running on the test set
clf=gridsearch.best_estimator_
clf.fit(X_tr,y_tr)
print('Test accuracy : %.3f' %clf.score(X_te,y_te))
svm=gridsearch.best_estimator_
svm.fit(X_tr,y_tr)
print('Test accuracy: %.3f' %svm.score(X_te,y_te))
# +
#seeing how model performs for diff values of neighbors
#searching for optimal value of K in KNN
X_train = emp_data[all_featues]
Y_train = emp_data['Attrition']
k_range= range(1,51)
k_scores=[]
for k in k_range:
knn=KNeighborsClassifier(n_neighbors=k)
scores=cross_val_score(knn,X_train,Y_train,cv=10,scoring='accuracy')
k_scores.append(scores.mean())
print(k_scores)
# -
#Plotting k_range vs k_scores
plt.plot(k_range,k_scores)
plt.xlabel('Value of K for KNN')
plt.ylabel('Cross Validated Accuracy')
# # Summary
# ## Steps followed to create above models:
# * **Data Wrangling** : Data was fairly clean with not specific outliers and missing values.
# * **Feature engineering**: Selecting features which help us maximize accuracy. As part of this activity we have:
# > * Dropped some parameters as they were not not relevant and were bringing noise for eg EmployeeCount,StandardHours etc
# > * Also we scaled some of the features which had high range (this improved model accuracy and performance)
# * **Choosing a model** : We researched about different types of models to select the best one suitable for our problem.
# * **Training** : We trained the models which were selected as part of the above exercise. We found *Neural Network* performed the best.
# * **Evaluation** : Created custom function to evaluate different performance parameters of a given model for better evaluation
# * **Hyperparameter tuning** : On the selected model, we tuned the hyperparameters to get best performance metrics such as ROC curve and accuracy out of the given models
# * **Prediction**: The model with the best metrics was selected.
#
# ## Model Persistence
import pickle
def load_model(filename,X_test,Y_test):
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.score(X_test, Y_test)
print('Model accuracy is ',result)
#Save model to disk
def save_model(model):
filename = 'SavedModel.sav'
pickle.dump(model, open(filename, 'wb'))
save_model(neuNet)
X_tr, X_te, Y_tr, Y_te = train_test_split(X_train, Y_train, test_size=0.2, random_state=26)
filename = 'SavedModel.sav'
X_tr.head()
load_model(filename,X_te,Y_te)
|
Notebook/.ipynb_checkpoints/Employee_Attrition_Prediction_-checkpoint.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Hierarchical Clustering
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
sns.set()
# %matplotlib inline
import json
data = pd.read_csv('../result/caseolap.csv')
data = data.set_index('protein')
ndf = data
ndf.head(2)
ndf.shape
ndata = ndf.copy(deep = True)
ndf.describe()
# #### Clustering
# +
size=(25,25)
g = sns.clustermap(ndf.T.corr(),\
figsize=size,\
cmap = "YlGnBu",\
metric='seuclidean')
g.savefig('plots/cluster.pdf', format='pdf', dpi=300)
g.savefig('plots/cluster.png', format='png', dpi=300)
indx = g.dendrogram_row.reordered_ind
# -
protein_cluster = []
for num in indx:
for i,ndx in enumerate(ndf.index):
if num == i:
protein_cluster.append({'id':i,"protein": ndx,\
'CM' : list(ndf.loc[ndx,:])[0],\
'ARR': list(ndf.loc[ndx,:])[1],\
'CHD' : list(ndf.loc[ndx,:])[2],\
'VD' : list(ndf.loc[ndx,:])[3],\
'IHD' : list(ndf.loc[ndx,:])[4],\
'CCS' : list(ndf.loc[ndx,:])[5],\
'VOO' : list(ndf.loc[ndx,:])[6],\
'OHD' : list(ndf.loc[ndx,:])[7]})
protein_cluster_df = pd.DataFrame(protein_cluster)
protein_cluster_df = protein_cluster_df.set_index("protein")
protein_cluster_df = protein_cluster_df.drop(["id"], axis = 1)
protein_cluster_df.head()
# #### Barplot
protein_cluster_df.plot.barh(stacked=True,figsize=(10,20))
plt.gca().invert_yaxis()
plt.legend(fontsize =10)
plt.savefig('plots/cluster-bar.pdf')
plt.savefig('plots/cluster-bar.png')
# +
with open("data/id2name.json","r")as f:
id2name = json.load(f)
names = []
for item in protein_cluster_df.index:
names.append(id2name[item])
protein_cluster_df['names'] =names
protein_cluster_df.head(1)
# -
protein_cluster_df.to_csv("data/protein-cluster-bar-data.csv")
|
Jupyter-Notebooks/Cluster.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import requests
from config import settings
def build_headers(oauth_token):
token = "Bearer {}".format(oauth_token)
return {'Authorization': token}
response = requests.get(
settings.BASE_URL,
headers=build_headers(settings.OAUTH_TOKEN),
#params={'organizer.id': '6453217513', 'include_unavailable_events': True},
params={'organizer.id': '6453217513'},
verify=True,
)
r = response.json()
# +
events = r.get('events', None)
for event in events:
print(event['name']['text'])
# -
|
api_research.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# # DataFrame creation in Python
# ## Loading data from a CSV file
# Download Google Spreadsheet data as CSV.
# +
import urllib
tb_deaths_url_csv = 'https://docs.google.com/spreadsheets/d/12uWVH_IlmzJX_75bJ3IH5E-Gqx6-zfbDKNvZqYjUuso/pub?gid=0&output=CSV'
tb_existing_url_csv = 'https://docs.google.com/spreadsheets/d/1X5Jp7Q8pTs3KLJ5JBWKhncVACGsg5v4xu6badNs4C7I/pub?gid=0&output=csv'
tb_new_url_csv = 'https://docs.google.com/spreadsheets/d/1Pl51PcEGlO9Hp4Uh0x2_QM0xVb53p2UDBMPwcnSjFTk/pub?gid=0&output=csv'
local_tb_deaths_file = 'tb_deaths_100.csv'
local_tb_existing_file = 'tb_existing_100.csv'
local_tb_new_file = 'tb_new_100.csv'
deaths_f = urllib.urlretrieve(tb_deaths_url_csv, local_tb_deaths_file)
existing_f = urllib.urlretrieve(tb_existing_url_csv, local_tb_existing_file)
new_f = urllib.urlretrieve(tb_new_url_csv, local_tb_new_file)
# -
# Read CSV into `DataFrame` by using `read_csv()`.
# +
import pandas as pd
deaths_df = pd.read_csv(local_tb_deaths_file, index_col = 0, thousands = ',').T
existing_df = pd.read_csv(local_tb_existing_file, index_col = 0, thousands = ',').T
new_df = pd.read_csv(local_tb_new_file, index_col = 0, thousands = ',').T
# -
# We have specified `index_col` to be 0 since we want the country names to be the row labels. We also specified the `thousands` separator to be ',' so Pandas automatially parses cells as numbers. Then, we `traspose()` the table to make the time series for each country correspond to each column.
# We will concentrate on the existing cases for a while. We can use `head()` to check the first few lines.
existing_df.head()
# By using the attribute `columns` we can read and write column names.
existing_df.columns
# Similarly, we can access row names by using `index`.
existing_df.index
# We will use them to assign proper names to our column and index names.
deaths_df.index.names = ['year']
deaths_df.columns.names = ['country']
existing_df.index.names = ['year']
existing_df.columns.names = ['country']
new_df.index.names = ['year']
new_df.columns.names = ['country']
existing_df
# ## Data indexing
# There is a [whole section](http://pandas.pydata.org/pandas-docs/stable/indexing.html) devoted to indexing and selecting data in `DataFrames` in the oficial documentation. Let's apply them to our Tuberculosis cases dataframe.
# We can acces each data frame `Series` object by using its column name, as with a Python dictionary. In our case we can access each country series by its name.
existing_df['United Kingdom']
# Or just using the key value as an attribute.
existing_df.Spain
# Or we can access multiple series passing their column names as a Python list.
existing_df[['Spain', 'United Kingdom']]
# We can also access individual cells as follows.
existing_df.Spain['1990']
# Or using any Python list indexing for slicing the series.
existing_df[['Spain', 'United Kingdom']][0:5]
# With the whole DataFrame, slicing inside of [] slices the rows. This is provided largely as a convenience since it is such a common operation.
existing_df[0:5]
# ### Indexing in production Python code
# As stated in the official documentation, the Python and NumPy indexing operators [] and attribute operator . provide quick and easy access to pandas data structures across a wide range of use cases. This makes interactive work intuitive, as there’s little new to learn if you already know how to deal with Python dictionaries and NumPy arrays. However, since the type of the data to be accessed isn’t known in advance, directly using standard operators has some optimization limits. For production code, it is recommended that you take advantage of the optimized pandas data access methods exposed in this section.
# For example, the `.iloc` method can be used for **positional** index access.
existing_df.iloc[0:2]
# While `.loc` is used for **label** access.
existing_df.loc['1992':'2005']
# And we can combine that with series indexing by column.
existing_df.loc[['1992','1998','2005'],['Spain','United Kingdom']]
# This last approach is the recommended when using Pandas data frames, specially when doing assignments (something we are not doing here). Otherwise, we might have assignment problems as described [here](http://pandas-docs.github.io/pandas-docs-travis/indexing.html#why-does-the-assignment-when-using-chained-indexing-fail).
# ## Data selection by value
# We can also use logical expression to select just data that satisfy certain conditions. So first, let's see what happens when we use logical operators with data frames or series objects.
existing_df>10
# And if applied to individual series.
existing_df['United Kingdom'] > 10
# The result of these expressions can be used as a indexing vector (with `[]` or `.iloc') as follows.
existing_df.Spain[existing_df['United Kingdom'] > 10]
# An interesting case happens when indexing several series and some of them happen to have `False` as index and other `True` at the same position. For example:
existing_df[ existing_df > 10 ]
# Those cells where `existing_df` doesn't happen to have more than 10 cases per 100K give `False` for indexing. The resulting data frame have a `NaN` value for those cells. A way of solving that (if we need to) is by using the `where()` method that, apart from providing a more expressive way of reading data selection, acceps a second argument that we can use to impute the `NaN` values. For example, if we want to have 0 as a value.
existing_df.where(existing_df > 10, 0)
# ## Descriptive statistics
# MORE: http://pandas.pydata.org/pandas-docs/stable/api.html#api-dataframe-stats
# The basic data descriptive statistics method for a `pandas.DataFrame` is `describe()`. It is the equivalent to R `data.frame` function `summary()`.
df_summary = existing_df.describe()
df_summary
# There is a lot of information there. We can access individual summaries as follows.
df_summary[['Spain','United Kingdom']]
# There is a plethora of descriptive statistics methods in Pandas (check the [documentation](http://pandas.pydata.org/pandas-docs/stable/api.html#api-dataframe-stats)). Some of them are already included in our summary object, but there are many more. In following tutorials we will make good use of them in order to better understand our data.
# For example, we can obtain the percentage change over the years for the number of tuberculosis cases in Spain.
tb_pct_change_spain = existing_df.Spain.pct_change()
tb_pct_change_spain
# And from there get the maximum value.
tb_pct_change_spain.max()
# And do the same for the United Kingdom.
existing_df['United Kingdom'].pct_change().max()
# If we want to know the index value (year) we use `argmax` (callex `idmax` in later versions of Pandas) as follows.
existing_df['Spain'].pct_change().argmax()
existing_df['United Kingdom'].pct_change().argmax()
# That is, 1998 and 1992 were the worst years in Spain and the UK respectibely regarding the increase of infectious TB cases.
# ### Plotting
# Pandas DataFrames implement up to three plotting methods out of the box (check the [documentation](http://pandas.pydata.org/pandas-docs/stable/api.html#id11)). The first one is a basic line plot for each of the series we include in the indexing. The first line might be needed when plotting while using IPython notebook.
# +
# %matplotlib inline
existing_df[['United Kingdom', 'Spain', 'Colombia']].plot()
# -
# Or we can use boxplots to obtain a summarised view of a given series as follows.
existing_df[['United Kingdom', 'Spain', 'Colombia']].boxplot()
# There is also a histogram() method, but we can't use it with this type of data right now.
# ### Function application and grouping
# The `pandas.DataFrame` class defines several [ways of applying functions](http://pandas.pydata.org/pandas-docs/stable/api.html#id5) both, index-wise and element-wise. Some of them are already predefined, and are part of the descriptive statistics methods we have talked about.
existing_df.sum()
# We have just calculated the total number of TB cases from 1990 to 2007 for each country. We can do the same by year if we pass `axis=1` to use `columns` instead of `index` as axis.
existing_df.sum(axis=1)
# It looks like there is a descent in the existing number of TB cases per 100K accross the world. Let's plot it.
existing_df.sum(axis=1).plot()
# However, what if we plot individual countries?
existing_df.Ethiopia.plot()
# Saddly, some countries doesn't happen to improve at the same rate. There is a lot exploratory analysis we can do here, but we will answer our questions a bit later.
# Pandas also provides methods to apply other functions to data frames. They are three: `apply`, `applymap`, and `groupby`.
# #### apply and applymap
# By using [`apply()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html#pandas.DataFrame.apply) we can apply a function along an input axis of a `DataFrame`. Objects passed to the functions we apply are `Series` objects having as index either the DataFrame’s **index** (axis=0) or the **columns** (axis=1). Return type depends on whether passed function aggregates, or the reduce argument if the DataFrame is empty. For example, if we want to obtain the number of existing cases per million (instead of 100K) we can use the following.
from __future__ import division # we need this to have float division without using a cast
existing_df.apply(lambda x: x/10)
# We have seen how `apply` works element-wise. If the function we pass is applicable to single elements (e.g. division) pandas will broadcast that to every single element and we will get again a Series with the function applied to each element and hence, a data frame as a result in our case. However, the function intended to be used for element-wise maps is `applymap`.
# #### groupby
# Grouping is a powerful an important data frame operation in Exploratory Data Analysis. In Pandas we can do this easily. For example, imagine we want the mean number of existing cases per year in two different periods, before and after the year 2000. We can do the following.
mean_cases_by_period = existing_df.groupby(lambda x: int(x)>1999).mean()
mean_cases_by_period.index = ['1990-1999', '2000-2007']
mean_cases_by_period
# The `groupby` method accepts different types of grouping, including a mapping function as we passed, a dictionary, a Series, or a tuple / list of column names. The mapping function for example will be called on each element of the object `.index` (the year string in our case) to determine the groups. If a `dict` or `Series` is passed, the `Series` or `dict` values are used to determine the groups (e.g. we can pass a column that contains categorical values).
# We can index the resulting data frame as usual.
mean_cases_by_period[['United Kingdom', 'Spain', 'Colombia']]
# ### Time series specific operations
# Each column in a `pandas.DataFrame` is a `pandas.Series` as mentioned, and this is a central concept in Pandas. When our data frame index is a date, we can make the conversion and have access to some specific operations.
# There are many useful time series specific methods, but most of them work with finer grained dates (i.e. up to days), and we have years. However, this is how we should convert a date to the right format using Pandas.
existing_tdf = existing_df.copy()
existing_tdf.index = pd.to_datetime(existing_tdf.index)
existing_tdf.head()
# You can find more about time series operations in the [Pandas oficial documentation](http://pandas.pydata.org/pandas-docs/stable/api.html#id10).
# ## Answering our questions
# Let's use now what we have learnt to answer each of the questions we made in the introductory section.
# ### Countries with highest TB prevalence and incidence
# **Question**: We want to know, per year, what country has the highest number of existing and new TB cases.
# If we want just the top ones we can make use of `apply` and `argmax`. Remember that, be default, `apply` works wit columns (the countries in our case), and we want to apply it to each year. Therefore we need to traspose the data frame before using it, or we can pass the argument `axis=1`.
existing_df.apply(pd.Series.argmax, axis=1)
# But this is too simplistic. Instead, we want to get those countries that are in the fourth quartile. But first we need to find out the world general tendency.
# ### World trends in TB cases
# In order to explore the world general tendency, we need to sum up every countrie's values for the three datasets,p er year.
deaths_total_per_year_df = deaths_df.sum(axis=1)
existing_total_per_year_df = existing_df.sum(axis=1)
new_total_per_year_df = new_df.sum(axis=1)
# Now we will create a new `DataFrame` with each sum in a series that we will plot using the data frame `plot()` method.
world_trends_df = pd.DataFrame({'Total deaths per 100K' : deaths_total_per_year_df,
'Total existing cases per 100K' : existing_total_per_year_df,
'Total new cases per 100K' : new_total_per_year_df},
index=deaths_total_per_year_df.index)
world_trends_df.plot(figsize=(12,6)).legend(loc='center left', bbox_to_anchor=(1, 0.5))
# It seems that the general tendency is for a decrease in the total number of **existing cases** per 100K. However the number of **new cases** has been increasing, although it seems reverting from 2005. So how is possible that the total number of existing cases is decreasing if the total number of new cases has been growing? One of the reasons could be the observed increae in the number of **deaths** per 100K, but the main reason we have to consider is that people recovers form tuberculosis thanks to treatment. The sum of the recovery rate plus the death rate is greater than the new cases rate. In any case, it seems that there are more new cases, but also that we cure them better. We need to improve prevention and epidemics control.
# ### Countries out of tendency
# So the previous was the general tendency of the world as a whole. So what countries are out of that tendency (for bad)? In order to find this out, first we need to know the distribution of countries in an average year.
deaths_by_country_mean = deaths_df.mean()
deaths_by_country_mean_summary = deaths_by_country_mean.describe()
existing_by_country_mean = existing_df.mean()
existing_by_country_mean_summary = existing_by_country_mean.describe()
new_by_country_mean = new_df.mean()
new_by_country_mean_summary = new_by_country_mean.describe()
# We can plot these distributions to have an idea of how the countries are distributed in an average year.
deaths_by_country_mean.order().plot(kind='bar', figsize=(24,6))
# We want those countries beyond 1.5 times the inter quartile range (50%). We have thes evalues in:
deaths_outlier = deaths_by_country_mean_summary['50%']*1.5
existing_outlier = existing_by_country_mean_summary['50%']*1.5
new_outlier = new_by_country_mean_summary['50%']*1.5
# Now we can use these values to get those countries that, accross the period 1990-2007 has been beyond those levels.
# Now compare with the outlier threshold
outlier_countries_by_deaths_index = deaths_by_country_mean > deaths_outlier
outlier_countries_by_existing_index = existing_by_country_mean > existing_outlier
outlier_countries_by_new_index = new_by_country_mean > new_outlier
# What proportion of countries do we have out of trend? For deaths:
num_countries = len(deaths_df.T)
sum(outlier_countries_by_deaths_index)/num_countries
# For existing cases:
sum(outlier_countries_by_existing_index)/num_countries
# For new cases:
sum(outlier_countries_by_new_index)/num_countries
# Now we can use these indices to filter our original dataframes.
outlier_deaths_df = deaths_df.T[ outlier_countries_by_deaths_index ].T
outlier_existing_df = existing_df.T[ outlier_countries_by_existing_index ].T
outlier_new_df = new_df.T[ outlier_countries_by_new_index ].T
# This is serious stuff. We have more than one third of the world being outliers on the distribution of existings cases, new cases, and deaths by infectious tuberculosis. But what if we consider an outlier to be 5 times the IQR? Let's repeat the previous process.
# +
deaths_super_outlier = deaths_by_country_mean_summary['50%']*5
existing_super_outlier = existing_by_country_mean_summary['50%']*5
new_super_outlier = new_by_country_mean_summary['50%']*5
super_outlier_countries_by_deaths_index = deaths_by_country_mean > deaths_super_outlier
super_outlier_countries_by_existing_index = existing_by_country_mean > existing_super_outlier
super_outlier_countries_by_new_index = new_by_country_mean > new_super_outlier
# -
# What proportion do we have now?
sum(super_outlier_countries_by_deaths_index)/num_countries
# Let's get the data frames.
super_outlier_deaths_df = deaths_df.T[ super_outlier_countries_by_deaths_index ].T
super_outlier_existing_df = existing_df.T[ super_outlier_countries_by_existing_index ].T
super_outlier_new_df = new_df.T[ super_outlier_countries_by_new_index ].T
# Let's concentrate on epidemics control and have a look at the new cases data frame.
super_outlier_new_df
# Let's make some plots to get a better imppression.
super_outlier_new_df.plot(figsize=(12,4)).legend(loc='center left', bbox_to_anchor=(1, 0.5))
# We have 22 countries where the number of new cases on an average year is greater than 5 times the median value of the distribution. Let's create a country that represents on average these 22.
average_super_outlier_country = super_outlier_new_df.mean(axis=1)
average_super_outlier_country
# Now let's create a country that represents the rest of the world.
avearge_better_world_country = new_df.T[ - super_outlier_countries_by_new_index ].T.mean(axis=1)
avearge_better_world_country
# Now let's plot this country with the average world country.
two_world_df = pd.DataFrame({ 'Average Better World Country': avearge_better_world_country,
'Average Outlier Country' : average_super_outlier_country},
index = new_df.index)
two_world_df.plot(title="Estimated new TB cases per 100K",figsize=(12,8))
# The increase in new cases tendency is really stronger in the average super outlier country, so stronget that is difficult to percieve that same tendency in the *better world* country. The 90's decade brought a terrible increse in the number of TB cases in those countries. But let's have a look at the exact numbers.
two_world_df.pct_change().plot(title="Percentage change in estimated new TB cases", figsize=(12,8))
# The deceleration and reversion of that tendency seem to happen at the same time in both average countries, something around 2002? We will try to find out in the next section.
# ### Googling about events and dates in Tuberculosis
# Well, actually we just went straight to [Wikipedia's entry about the disease](https://en.wikipedia.org/wiki/Tuberculosis#Epidemiology). In the epidemics sections we found the following:
#
# - The total number of tuberculosis cases has been decreasing since 2005, while **new cases** have decreased since 2002.
# - This is confirmed by our previous analysis.
#
# - China has achieved particularly dramatic progress, with about an 80% reduction in its TB mortality rate between 1990 and 2010. Let's check it:
#
#
existing_df.China.plot(title="Estimated existing TB cases in China")
# - In 2007, the country with the highest estimated incidence rate of TB was Swaziland, with 1,200 cases per 100,000 people.
new_df.apply(pd.Series.argmax, axis=1)['2007']
# There are many more findings Wikipedia that we can confirm with these or other datasets from Gapmind world. For example, TB and HIV are frequently associated, together with poverty levels. It would be interesting to joind datasets and explore tendencies in each of them. We challenge the reader to give them a try and share with us their findings.
# ### Other web pages to explore
# http://www.gatesfoundation.org/What-We-Do/Global-Health/Tuberculosis
# http://www.gatesfoundation.org/Media-Center/Press-Releases/2007/09/New-Grants-to-Fight-Tuberculosis-Epidemic
#
|
01-data-frames/python-data-frames.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Synapse PySpark
# name: synapse_pyspark
# ---
# + [markdown] nteract={"transient": {"deleting": false}}
# # Intune Module Setup Example Notebook
#
# This notebook creates 1 table (devices) into a two new Spark databases called s2p_intune and s2np_intune.
#
# Attach this notebook to your configured spark pool, and click "Run all" for the initial module setup (outlined in the tutorial).
# + [markdown] nteract={"transient": {"deleting": false}}
# ### Provision storage accounts
#
# The storage account variable has to be changed to the name of the storage account associated with your Azure resource group.
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DoubleType, ArrayType, TimestampType
from pyspark.sql.functions import *
from pyspark.sql.window import Window
# data lake and container information
storage_account = 'stoeadaihackathon'
use_test_env = False
if use_test_env:
stage1np = 'abfss://test-env@' + storage_account + '.dfs.core.windows.net/stage1np'
stage2np = 'abfss://test-env@' + storage_account + '.dfs.core.windows.net/stage2np'
stage2p = 'abfss://test-env@' + storage_account + '.dfs.core.windows.net/stage2p'
else:
stage1np = 'abfss://stage1np@' + storage_account + '.dfs.core.windows.net'
stage2np = 'abfss://stage2np@' + storage_account + '.dfs.core.windows.net'
stage2p = 'abfss://stage2p@' + storage_account + '.dfs.core.windows.net'
# + [markdown] nteract={"transient": {"deleting": false}}
# ### Load Raw Data from Lake
# To ensure that that the right tables are loaded, confirm that the file paths match your data lake storage containers.
#
# Make sure to reference either the tutorial guide or the note below, as the current notebook setup for this module reads *.csv rather than a specific CSV file.
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
# load needed device table from the CSV in the data lake storage
# Note: you can change the "*.csv" to the specific devices CSV file name (which is generated as the date and time of the pipeline trigger)
dfIntuneDevices = spark.read.format('csv').load(f'{stage1np}/intune/devices/*.csv', header='true')
# + [markdown] nteract={"transient": {"deleting": false}}
# ## 1. Devices table
# Contains all devices (from students and teachers) at a school-system level
#
# ** Databases and tables used: **
#
# - None
#
# **CSV files used:**
#
# - the file from: stage1np/intune/devices/*.csv
#
# **Database and table created:**
#
# 1. Spark DB: s2p_intune
# - Table: devices
# 2. Spark DB: s2np_intune
# - Table: devices
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
display(dfIntuneDevices.limit(10))
# + [markdown] nteract={"transient": {"deleting": false}}
# ### Rename the column names to be get rid of hyphens and spaces
# Uncomment the cell below if you have triggered the pipeline and wish to ingest your own data, rather than the test data.
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
#dfIntuneDevices = dfIntuneDevices.withColumnRenamed('Device name', 'DeviceName').withColumnRenamed('Managed by', 'ManagedBy')
#dfIntuneDevices = dfIntuneDevices.withColumnRenamed('OS version', 'OSVersion').withColumnRenamed('Last check-in', 'LastCheckIn')
#dfIntuneDevices = dfIntuneDevices.withColumnRenamed('Primary user UPN', 'PrimaryUserUPN').withColumnRenamed('Device ID', 'DeviceID')
# + [markdown] nteract={"transient": {"deleting": false}}
# ### Add an additional column "accessOutsideOfSchool"
#
# This "accessOutsideOfSchool" column uses the "lastCheckIn" column information to determine if a specific student's device has access outside of school, based on the conditions:
#
# - If the last check in was on a weekend (i.e. Saturday or Sunday), then "accessOutsideOfSchool" is true.
# - If the last check in was before 9 AM (9:00) on a weekday, then "accessOutsideOfSchool" is true.
# - If the last check in was after 4 PM (16:00) on a weekday, then "accessOutsideOfSchool" is true.
#
# Otherwise, "accessOutsideOfSchool" is defaulted to false.
#
# Also this code creates a "lastCheckInDate" date-type column, used for the date filter in the PowerBI dashboard.
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
dfIntuneDevices = dfIntuneDevices.withColumn('lastCheckInTime', split(col('lastCheckIn'), ' ').getItem(1))
dfIntuneDevices = dfIntuneDevices.withColumn('lastCheckInDate', split(col('lastCheckIn'), ' ').getItem(0))
dfIntuneDevices = dfIntuneDevices.withColumn('lastCheckInHourOfDay', split(col('lastCheckInTime'), ':').getItem(0))
dfIntuneDevices = dfIntuneDevices.drop('lastCheckInTime')
dfIntuneDevices = dfIntuneDevices.withColumn('lastCheckInDate', to_date(col('lastCheckInDate'), 'yyyy-MM-dd'))
dfIntuneDevices = dfIntuneDevices.withColumn('lastCheckInDayOfWeek', date_format(col('lastCheckIn'), "E"))
dfIntuneDevices = dfIntuneDevices.withColumn('AccessOutsideOfSchool', when(col('lastCheckInDayOfWeek') == "Sat", "true").otherwise(when(col('lastCheckInDayOfWeek') == "Sun", "true").otherwise(when(col('lastCheckInHourOfDay') >= 16, "true").otherwise(when(col('lastCheckInHourOfDay') < 9, "true").otherwise("false")))))
# Can comment out this drop if you don't want to drop these two columns
dfIntuneDevices = dfIntuneDevices.drop('lastCheckInDayOfWeek').drop('lastCheckInHourOfDay')
display(dfIntuneDevices.limit(10))
# + [markdown] nteract={"transient": {"deleting": false}}
# ## Write Data Back to Lake
#
# ### Writing to Stage 2np
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
# write back to the lake in stage 2 ds2_main directory
dfIntuneDevices.coalesce(1).write.format('parquet').mode('overwrite').save(stage2np + '/intune/devices')
# + [markdown] nteract={"transient": {"deleting": false}}
# ### Writing to Stage 2p
# Pseudonymizing the primaryUserUPNs (userPrincipalNames) data from the devices CSV.
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
# %run /OEA_py
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
oea = OEA()
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
devicesSchema = [['DeviceName', 'string', 'no-op'],
['ManagedBy', 'string', 'no-op'],
['Ownership', 'string', 'no-op'],
['Compliance','string','no-op'],
['OS', 'string', 'no-op'],
['OSVersion', 'string', 'no-op'],
['LastCheckIn', 'timestamp', 'no-op'],
['PrimaryUserUPN', 'string', 'hash'],
['DeviceID', 'string', 'no-op'],
['AccessOutsideOfSchool', 'boolean', 'no-op']]
df_pseudo, df_lookup = oea.pseudonymize(dfIntuneDevices, devicesSchema)
df_pseudo.coalesce(1).write.format('parquet').mode('overwrite').save(stage2p + '/intune/devices')
# + [markdown] nteract={"transient": {"deleting": false}}
# ### Load to Spark DB
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
# Create spark db to allow for access to the data in the delta-lake via SQL on-demand.
# This is only creating metadata for SQL on-demand, pointing to the data in the delta-lake.
# This also makes it possible to connect in Power BI via the azure sql data source connector.
def create_spark_db(db_name, source_path):
spark.sql(f'CREATE DATABASE IF NOT EXISTS {db_name}')
spark.sql(f"DROP TABLE IF EXISTS {db_name}.devices")
spark.sql(f"create table if not exists {db_name}.devices using PARQUET location '{source_path}'")
create_spark_db('s2np_intune', stage2np + '/intune/devices')
create_spark_db('s2p_intune', stage2p + '/intune/devices')
# + [markdown] nteract={"transient": {"deleting": false}}
# ## Reset Data Processing
# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
# Uncomment line 8 if you would like to walk through the process again from the beginning
def reset_all_processing():
oea.rm_if_exists(stage2np + '/intune/devices')
oea.rm_if_exists(stage2p + '/intune/devices')
oea.drop_db('s2np_intune')
oea.drop_db('s2p_intune')
#reset_all_processing()
|
modules/Intune/notebook/Intune_module_setup.ipynb
|
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .r
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernel_info:
# name: ir
# kernelspec:
# display_name: R
# language: R
# name: ir
# ---
# + [markdown] inputHidden=false outputHidden=false
# # Principal Component Analysis in Villes Dataset
#
# ### Description:
# This code example tries to emulate the example of "Aprender de los Datos, El Análisis de Componentes Principales, una aproximación desde el Data Mining" book of "Tomas Aluja" and "Alain Morineau"
#
# ## Project:
# [r-examples](https://github.com/garciparedes/r-examples)
#
# ## Author:
# [<NAME>](garciparedes.me)
#
# ### Date:
# 2017-12
# + inputHidden=false outputHidden=false
rm(list = ls())
# + inputHidden=false outputHidden=false
column.index <- function(data, columns.name) {
match(columns.name, colnames(data))
}
# + inputHidden=false outputHidden=false
filter.by.factor <- function(data, columns.name, factor, columns.remove = TRUE) {
col.index <- column.index(data, columns.name)
indexer <- is.element(villes[, col.index], factor)
if (columns.remove) {
return(data[indexer, - col.index])
} else {
return(data[indexer, ])
}
}
# + inputHidden=false outputHidden=false
filter.by.columns <- function(data, columns.name, reverse = FALSE) {
col.index <- column.index(data, columns.name)
if (reverse){
col.index <- - col.index
}
return(data[, col.index])
}
# + inputHidden=false outputHidden=false
filter.complete <- function(data) {
data[complete.cases(data),]
}
# + inputHidden=false outputHidden=false
villes <- read.csv("./../datasets/villes.csv")
summary(villes)
# + inputHidden=false outputHidden=false
head(villes)
# + inputHidden=false outputHidden=false
cols <- c("Ciudad", "Región.del.mundo", "Maestro", "Chófer.de.autobús",
"Mecánico.de.coche", "Obrero.de.la.construcción", "Tornero",
"Jefe.de.cocina", "Director.de.fábrica", "Ingeniero", "Cajero.banco",
"Secretaria.de.dirección", "Dependienta", "Trabajador.textil")
villes.use <- filter.complete(filter.by.columns(filter.by.factor(
villes, "Año", "edition 1994"), cols))
# villes.use <- villes.use[- 1,]
villes.use[,-c(1,2)] <- villes.use[, -c(1, 2)] / rowMeans(villes.use[, -c(1, 2)])
head(villes.use)
# + inputHidden=false outputHidden=false
print(dim(villes.use))
# + outputHidden=false inputHidden=false
villes.use.scaled <- scale(filter.by.columns(
villes.use, c("Ciudad", "Región.del.mundo"), reverse = TRUE))
head(villes.use.scaled)
# + inputHidden=false outputHidden=false
villes.use.pca <- princomp(villes.use.scaled)
# + inputHidden=false outputHidden=false
print(villes.use.pca)
# -
# ## Variance Ratio by Component
# + inputHidden=false outputHidden=false
(villes.use.pca$sdev ^ 2) / sum(villes.use.pca$sdev ^ 2)
# -
# ### Row Proyection Weights
# + inputHidden=false outputHidden=false
villes.use.pca$loadings
# -
# ## Absolute Contributions
# + inputHidden=false outputHidden=false
villes.use.pca.ctr.abs <- t(t(villes.use.pca$scores) ^ 2 / (dim(villes.use)[1] * villes.use.pca$sdev ^ 2))
data.frame(villes.use[, "Ciudad"], round(villes.use.pca.ctr.abs, digits = 6))
# -
# ## Relative Contributions
# + inputHidden=false outputHidden=false
villes.use.pca.ctr.rel <- (villes.use.pca$scores ^ 2 / (rowSums(villes.use.pca$scores ^ 2)))
data.frame(villes.use[, "Ciudad"], round(villes.use.pca.ctr.rel, digits = 6))
# + inputHidden=false outputHidden=false
plot(villes.use.pca)
# + inputHidden=false outputHidden=false
plot(villes.use.pca$scores[,1:2], pch = 20, cex = rowSums(villes.use.pca.ctr.rel[,1:2]) * 1.5,
col = as.numeric(villes.use[, "Región.del.mundo"]) + 1)
text(villes.use.pca$scores[,1:2], cex = 0.7, pos = 3,
labels = sub("94", "", villes.use[,"Ciudad"]))
#legend(1,-2.2,levels(villes.use[, "Región.del.mundo"]), pch=20,cex=0.5, col=2:nlevels(villes.use[, "Región.del.mundo"]))
# + inputHidden=false outputHidden=false
villes.use.pca.scores.vars <- t(villes.use.pca$sdev * t(villes.use.pca$loadings))
print(round(villes.use.pca.scores.vars[, 1:2], digits = 2))
# + inputHidden=false outputHidden=false
plot(villes.use.pca.scores.vars[, 1:2], pch = 20)
arrows(0, 0, villes.use.pca.scores.vars[, 1], villes.use.pca.scores.vars[, 2])
text(villes.use.pca.scores.vars[, 1:2], cex = 0.7, pos = 3,
labels = colnames(villes.use[, -c(1, 2)]))
# -
# ### Column Proyection Weights
# + outputHidden=false inputHidden=false
villes.use.pca.loadings.columns <- villes.use.scaled %*%
villes.use.pca$loadings %*%
diag(1/svd(scale(villes.use[, -c(1, 2)]))$d)
head(villes.use.pca.loadings.columns)
# -
# ### Data Matrix Reconstruction
# + outputHidden=false inputHidden=false
head(villes.use.pca.loadings.columns %*%
diag(svd(villes.use.scaled)$d) %*%
t(villes.use.pca$loadings))
# -
# ## Relationship between SVD and PCA Standard Deviations
# + outputHidden=false inputHidden=false
as.matrix(round(svd(villes.use.scaled)$d, digits = 5))
# + outputHidden=false inputHidden=false
as.matrix(round(villes.use.pca$sdev * sqrt(dim(villes.use.scaled)[1]), digits = 5))
|
notebooks/villes-analysis.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python (condadev)
# language: python
# name: condadev
# ---
# # Title: msticpy - GeoIP Lookup
#
# ## Introduction
# This module contains two classes that allow you to look up the Geolocation of IP Addresses.
#
# ### MaxMind GeoIPLite
# This product includes GeoLite2 data created by MaxMind, available from
# <a>https://www.maxmind.com</a>.
#
# This uses a local database which is downloaded first time when class object is instantiated. It gives very fast lookups but you need to download updates regularly. Maxmind offers a free tier of this database, updated monthly. For greater accuracy and more detailed information they have varying levels of paid service. Please check out their site for more details.
#
# The geoip module uses official maxmind pypi package - geoip2 and also has options to customize the behavior of local maxmind database.
# * ```db_folder``` : Specify custom path containing local maxmind city database. If not specified, download to .msticpy dir under user\`s home dir.
# * ```force_update``` : can be set to True/False to issue force update despite of age check.
# * Check age of maxmind city database based on database info and download new if it is not updated in last 30 days.
# * ``auto_update``` : can be set to True/False Allow option to override auto update database if user is desired not to update database older than 30 days.
#
# ### IPStack
# This library uses services provided by ipstack.
# <a>https://ipstack.com</a>
#
# IPStack is an online service and also offers a free tier of their service. Again, the paid tiers offer greater accuracy, more detailed information and higher throughput. Please check out their site for more details.
#
#
# <a></a>
# ## Table of Contents
# - [Maxmind GeoIP Lookup](#geoip_lookups)
# - [IPStack GeoIP Lookup](#ipstack_lookups)
# - [Dataframe input](#dataframe_input)
# - [Creating your own GeoIP Class](#custom_lookup)
# - [Calculating Geographical Distances](#calc_distance)
# +
# Imports
import sys
MIN_REQ_PYTHON = (3,6)
if sys.version_info < MIN_REQ_PYTHON:
print('Check the Kernel->Change Kernel menu and ensure that Python 3.6')
print('or later is selected as the active kernel.')
sys.exit("Python %s.%s or later is required.\n" % MIN_REQ_PYTHON)
from IPython.display import display
import pandas as pd
import msticpy.sectools as sectools
from msticpy.nbtools import *
from msticpy.nbtools.entityschema import IpAddress, GeoLocation
from msticpy.sectools.geoip import GeoLiteLookup, IPStackLookup
# -
# <a></a>[Contents](#contents)
# ## Maxmind GeoIP Lite Lookup Class
# Signature:
# ```
# iplocation.lookup_ip(ip_address: str = None,
# ip_addr_list: collections.abc.Iterable = None,
# ip_entity: msticpy.nbtools.entityschema.IpAddress = None)
# Docstring:
# Lookup IP location from GeoLite2 data created by MaxMind.
#
# Keyword Arguments:
# ip_address {str} -- a single address to look up (default: {None})
# ip_addr_list {Iterable} -- a collection of addresses to lookup (default: {None})
# ip_entity {IpAddress} -- an IpAddress entity
#
# Returns:
# tuple(list{dict}, list{entity}) -- returns raw geolocation results and
# same results as IP/Geolocation entities
# ```
# +
iplocation = GeoLiteLookup()
loc_result, ip_entity = iplocation.lookup_ip(ip_address='192.168.127.12')
print('Raw result')
display(loc_result)
print('IP Address Entity')
display(ip_entity[0])
# +
import tempfile
from pathlib import Path
tmp_folder = tempfile.gettempdir()
iplocation = GeoLiteLookup(db_folder=str(Path(tmp_folder).joinpath('geolite')))
loc_result, ip_entity = iplocation.lookup_ip(ip_address='192.168.127.12')
print('Raw result')
display(loc_result)
print('IP Address Entity')
display(ip_entity[0])
# +
iplocation = GeoLiteLookup(force_update=True)
loc_result, ip_entity = iplocation.lookup_ip(ip_address='192.168.127.12')
print('Raw result')
display(loc_result)
print('IP Address Entity')
display(ip_entity[0])
# +
iplocation = GeoLiteLookup(auto_update=False)
loc_result, ip_entity = iplocation.lookup_ip(ip_address='192.168.127.12')
print('Raw result')
display(loc_result)
print('IP Address Entity')
display(ip_entity[0])
# +
import socket
socket_info = socket.getaddrinfo("pypi.org",0,0,0,0)
ips = [res[4][0] for res in socket_info]
print(ips)
_, ip_entities = iplocation.lookup_ip(ip_addr_list=ips)
display(ip_entities)
# -
# <a></a>[Contents](#contents)
# ## IPStack Geo-lookup Class
#
# #### Class Initialization
#
# Note - requires IPStack API Key, Optional parameter bulk_lookup allows multiple IPs in a single request. This is only available with the paid Professional tier and above.
# ```
# Init signature: IPStackLookup(api_key: str, bulk_lookup: bool = False)
# Docstring:
# GeoIP Lookup using IPStack web service.
#
# Raises:
# ConnectionError -- Invalid status returned from http request
# PermissionError -- Service refused request (e.g. requesting batch of addresses
# on free tier API key)
# Init docstring:
# Create a new instance of IPStackLookup.
#
# Arguments:
# api_key {str} -- API Key from IPStack - see https://ipstack.com
# bulk_lookup {bool} -- For Professional and above tiers allowing you to
# submit multiple IPs in a single request.
#
# ```
#
# #### lookup_ip method
# ```
# Signature:
# iplocation.lookup_ip(
# ['ip_address: str = None', 'ip_addr_list: collections.abc.Iterable = None', 'ip_entity: msticpy.nbtools.entityschema.IpAddress = None'],
# ) -> tuple
# Docstring:
# Lookup IP location from IPStack web service.
#
# Keyword Arguments:
# ip_address {str} -- a single address to look up (default: {None})
# ip_addr_list {Iterable} -- a collection of addresses to lookup (default: {None})
# ip_entity {IpAddress} -- an IpAddress entity
#
# Raises:
# ConnectionError -- Invalid status returned from http request
# PermissionError -- Service refused request (e.g. requesting batch of addresses
# on free tier API key)
#
# Returns:
# tuple(list{dict}, list{entity}) -- returns raw geolocation results and
# same results as IP/Geolocation entities
# ```
# <a></a>[Contents](#contents)
# ### You will need a IPStack API key
# You will get more detailed results and a higher throughput allowance if you have a paid tier. See IPStack website for more details
iplocation = IPStackLookup()
# Enter your IPStack Key here (if not set in msticpyconfig.yaml)
ips_key = nbwidgets.GetEnvironmentKey(env_var='IPSTACK_AUTH',
help_str='To obtain an API key sign up here https://www.ipstack.com/',
prompt='IPStack API key:')
if not iplocation.settings.args.get("AuthKey"):
ips_key.display()
# +
if not iplocation.settings.args.get("AuthKey") and not ips_key.value:
raise ValueError("No Authentication key in config/environment or supplied by user.")
if ips_key.value:
iplocation = IPStackLookup(api_key=ips_key.value)
loc_result, ip_entity = iplocation.lookup_ip(ip_address='192.168.127.12')
print('Raw result')
display(loc_result)
print('IP Address Entity')
display(ip_entity[0])
# +
loc_result, ip_entities = iplocation.lookup_ip(ip_addr_list=ips)
print('Raw results')
display(loc_result)
print('IP Address Entities')
display(ip_entities)
# -
# <a></a>[Contents](#contents)
# ## Taking input from a pandas DataFrame
#
# The base class for both implementations has a method that sources the ip addresses from a dataframe column and returns a new dataframe with the location information merged with the input frame
# ```
# Signature: iplocation.df_lookup_ip(data: pandas.core.frame.DataFrame, column: str)
# Docstring:
# Lookup Geolocation data from a pandas Dataframe.
#
# Keyword Arguments:
# data {pd.DataFrame} -- pandas dataframe containing IpAddress column
# column {str} -- the name of the dataframe column to use as a source
# ```
import pandas as pd
netflow_df = pd.read_csv("data/az_net_flows.csv")
netflow_df = netflow_df[["AllExtIPs"]].drop_duplicates()
iplocation = GeoLiteLookup()
iplocation.df_lookup_ip(netflow_df, column="AllExtIPs")
# <a></a>[Contents](#contents)
# ## Creating a Custom GeopIP Lookup Class
#
# You can derive a class that implements the same operations to use with a different GeoIP service.
#
# The class signature is as follows:
# ```
# class GeoIpLookup(ABC):
# """Abstract base class for GeoIP Lookup classes."""
#
# @abstractmethod
# def lookup_ip(self, ip_address: str = None, ip_addr_list: Iterable = None,
# ip_entity: IpAddress = None):
# """
# Lookup IP location.
#
# Keyword Arguments:
# ip_address {str} -- a single address to look up (default: {None})
# ip_addr_list {Iterable} -- a collection of addresses to lookup (default: {None})
# ip_entity {IpAddress} -- an IpAddress entity
#
# Returns:
# tuple(list{dict}, list{entity}) -- returns raw geolocation results and
# same results as IP/Geolocation entities
#
# """
# ```
# You should override the lookup_ip method implementing your own method of geoip lookup.
# <a></a>[Contents](#contents)
# ## Calculating Geographical Distances
#
# Use the geo_distance function from msticpy.sectools.geoip to calculated distances between two locations.
# I am indebted to <NAME> who posted this solution (which I've modified slightly) on Stackoverflow.
#
#
# ```
# Signature: geo_distance(origin: Tuple[float, float], destination: Tuple[float, float]) -> float
# Docstring:
# Calculate the Haversine distance.
#
# Author: <NAME> - stackoverflow
#
# Parameters
# ----------
# origin : tuple of float
# (lat, long)
# destination : tuple of float
# (lat, long)
#
# Returns
# -------
# distance_in_km : float
# ```
#
#
# Or where you have source and destination IpAddress entities, you can use the wrapper entity_distance.
# ```
# Signature:
# entity_distance(
# ['ip_src: msticpy.nbtools.entityschema.IpAddress', 'ip_dest: msticpy.nbtools.entityschema.IpAddress'],
# ) -> float
# Docstring:
# Return distance between two IP Entities.
#
# Arguments:
# ip_src {IpAddress} -- Source IpAddress Entity
# ip_dest {IpAddress} -- Destination IpAddress Entity
#
# Raises:
# AttributeError -- if either entity has no location information
#
# Returns:
# float -- Distance in kilometers.
# ```
# +
from msticpy.sectools.geoip import geo_distance
_, ip_entity1 = iplocation.lookup_ip(ip_address='192.168.127.12')
_, ip_entity2 = iplocation.lookup_ip(ip_address='192.168.127.12')
print(ip_entity1[0])
print(ip_entity2[0])
dist = geo_distance(origin=(ip_entity1[0].Location.Latitude, ip_entity1[0].Location.Longitude),
destination=(ip_entity2[0].Location.Latitude, ip_entity2[0].Location.Longitude))
print(f'\nDistance between IP Locations = {round(dist, 1)}km')
|
docs/notebooks/GeoIPLookups.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Load Data and Cleaning Data
dataset = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data", skipinitialspace=True)
dataset = dataset.drop(['77516','13','2174','0', 'Not-in-family', '40'],axis=1)
dataset = dataset.rename(columns={'39': 'Age', 'State-gov': 'WorkClass',' Bachelors': 'Education', 'Never-married': 'Marriage Status', 'Adm-clerical': 'Occupation', 'Not-in-family': 'Relationship', 'White': 'Race', 'Male': 'Gender','United-States': 'Country of Origin', '<=50K': 'Income'})
dataset = dataset.fillna(np.nan)
dataset = dataset.drop_duplicates()
dataset = dataset.dropna()
dataset = dataset.sort_values("Age", ascending=True)
dataset = dataset.reset_index()
dataset = dataset.drop(columns=['index'])
dataset.shape
dataset.head()
dataset.columns
display(dataset)
# # Analysis Pipeline
#
# How to create the same Dataset:
# 1. Importing
# * Import numpy, pandas, matplotlib and seaborn
# * Import the csv at https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data using pandas and matplotlib, make sure to include skipinitialspace as there is one in this dataset
# 1. Clean data
# * Fill empty values with NaN and drop those values
# * Drop any duplicates that may exist
# 1. Wrangle/Process Data
# * Drop unecessary columns like Capital Gains Losses and family relationship
# * Rename the columns of the dataset since the first row does not include the catagories for each column
# * Sorting the age by ascending order, makes age based graphs more easier and allows us to see max and min age
# * Be sure to reset index and drop the newly created index column
# 1. Wrangle/Graphing
# * Create a countplot for Income
# * Create a countplot for Gender
# * Create a dist plot for Age
# * Create a value count graph for Race
#
# Note: Sometimes you may get an error like "Tuple does not support attribute head", to fix this simply restart Jupyter Lab.
#
# +
def load_and_process(url_or_path_to_csv_file):
dataset = (
pd.read_csv(url_or_path_to_csv_file, skipinitialspace=True)
.rename(columns={'39': 'Age', 'State-gov': 'WorkClass', '77516': 'fnlwgt', ' Bachelors': 'Education', 'Never-married': 'Marriage Status', 'Adm-clerical': 'Occupation', 'Not-in-family': 'Relationship', 'White': 'Race', 'Male': 'Gender', '2174': 'Capital Gain', ' 0': 'Capital Loss', '40': 'Hours Worked Per Week', 'United-States': 'Country of Origin', '<=50K': 'Income'})
.drop(['77516','13','2174','0', 'Not-in-family', '40'],axis=1)
.fillna(np.nan)
.drop_duplicates()
.dropna()
.sort_values("Age", ascending=True)
.reset_index()
.drop(columns=['index'])
)
return dataset
# +
#Data Processing
sns.countplot(dataset['Income'],label="Income Distribution")
# +
#Data Processing
sns.countplot(dataset['Gender'],label="Gender Distribution")
# -
sns.distplot(dataset["Age"])
dataset.Race.value_counts().plot(kind='bar', figsize=(10,5))
# # EDA
# The question I want to research is wether there is a correlation between Income and Gender and Income and Race. To try to tackle this question I plotted the data given so I could get a better scope of the data I was using.
#
# At first I wanted to do an analysis on wether older people made more money than younger people so, I plotted a graph which showed the age density in the dataset. This showed that there was a stronger density around middle age people and therefore may make my data on older people less reliable since there is a smaller pool of data to analyse. I decided not to do an analysis because of this reason.
#
# As for the Gender graphs I wanted to see if they were directly proportional which in this Census data, it was not. There were almost double the amount of men than women in the pool. With the under representation of women the data may not be as precise as to the true income of women compared to men, I would probably need to use percentages instead of simply counting values to represent the difference in wage between men and women.
#
# The income graph tells the same story, there is an over representation is people making under 50k. This data makes sense since the average income in the USA was 34,076$ (https://www.census.gov/library/publications/1996/demo/p60-193.html) . Observing the gender and income graphs we can see that the highest representation is of males and making over 50k which could represent the possibility of men making more than women.
#
# After graphing the representations of different races, there are much more white people represented in the census data than any other race. I believe this is because this census data was taken in the 90s. If this census data were to be taken today, there would be a much higher representation of other races due to immigration. With this gathered data, I hypothesize that White men would make the most amount of money since they are the majority in both race and gender.
#
#
|
notebooks/Aaron.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/pranavkantgaur/curves_and_surfaces/blob/master/parametric_representations/Hermite_curves_lec_3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="eW4Y9y4UukfO" colab_type="text"
# ## Objectives:
#
# 0. Leftovers from last lecture:
# * 3D plotting in Matplotlib
# * Plotly
# * Discussion on continuity:
# * Continuity of velocity vector is neccessary for continuity of accelaration vector?
# 1. Context for upcoming parametric curves
# 2. Concept of _Blending functions_
# 3. Intro to the Hermite curves
# + [markdown] id="xqB7bcOL-4t8" colab_type="text"
# ## 3D interactive plotting
# Using _plotly_ we will be able to plot interactive figures for visualization and interaction with curves and surfaces, as shown [here](https://colab.research.google.com/drive/1f4fZMmsQTdKXIloznL8Ubiw_kO_Uj3kf#scrollTo=-1qqsGWlx3Ah&line=8&uniqifier=1).
# + [markdown] id="XEom-519CyQb" colab_type="text"
# ## Does $C^n$ implies $C^{n-1}$?
# * Differentiability requires continuity.
# * $C^n$ requires continuity of $d^{n-1}Q_{i}/ dt^{n-1}$ which is $C^{n-1}$
#
# ## Relation between Geometric and Parametric continuity:
#
# * Issues with parametric continuity:
# * https://pages.mtu.edu/~shene/COURSES/cs3621/NOTES/curves/continuity.html
# * Curvature (or the rate of turning) continuity does not imply second-order continuity but second-order continuity does imply curvature-continuity:
# * https://en.wikipedia.org/wiki/Curvature#In_terms_of_a_general_parametrization
# * Reparameterizing the curve segments may affect their continuity:
# * Changing their parametric equations without changing their shapes.
# * _Arc length parameterization_ gives a unique parameterization which returns the true measure of continuity of curve. Not used in practice though due to its non-triviality.
# * Motivation for Geometric continuity is the effect of reparameterization on continuity of the associated functions:
# * Parametric continuity is not a true representative of the continuity/smoothness of shapes:
# * It indicates smoothness of one (parametric) function which may represent the shape we are interested in.
# * Therefore, if we are able to find _atleast_ one such parametric representation for the shape of interest and prove its continuity, our shape of interest is bound to be continous. But the converse is not true, in general.
# * Geometric continuity(based on above discussion):
# * Two curve segments are said $G_k$ geometric continuous at the joining point if and only if all $i^{th}$ derivatives, for $i \leq k$, computed with arc length parameters agree at the joining point.
# * Alternatively, if there exists a parametrization of curves such that $k^{th}$ order derivatives are _proportional_.
# * Lets solve:
# * Consider the curves, $\gamma(t) = (t, t^2)$ and $\eta(t) = (2t + 1, t^3 + 4t + 1)$, both defined on $0 \leq t \leq 1$. Note that $\gamma(1) = \eta(0)$. Does the curves show $C_1$ continuity and $G_1$ continuity at their joint points?
# * Visualize $\gamma$ and $\eta$ in [geogebra](https://www.geogebra.org/graphing).
# * Write a code to implement these curves. You may refer [this](https://colab.research.google.com/drive/1f4fZMmsQTdKXIloznL8Ubiw_kO_Uj3kf#scrollTo=-1qqsGWlx3Ah&line=3&uniqifier=1)
# * Write a function to return the order of geometric and parametric continuity.(check upto second order)
# ``` python
# # Ci represents the coefficient matrix for ith curve
# # Assume dimensions of Ci to be # (curve_order + 1) X num_dimensions
# # 0 <= t <= 1
# def check_cubic_curve_continuity(C1, C2):
# C = None # YOUR CODE HERE
# G = None
# return C, G # C, G are of type 'int' containing the Parametric and Geometric continuity order value respectively.
# ```
# + [markdown] id="TsAgXT4pv1vz" colab_type="text"
# ## Context for upcoming parametric curves
# The geometric constraints--in terms of their number and type--depend on the required nature of curves (cubic vs lower vs higher than cubic), nature of continuity desired at endpoints of the curve segments. The geometric contraints are as follows (for cubic curves):
# * 2 endpoints and corresponding tangent vectors: Hermite curves
# * 2 endpoints and other points(not on the curve) which define tangent vectors: Bezier curves
# * 4 control points: Splines
# + [markdown] id="z6MBpWCfCHdc" colab_type="text"
# ## Blending functions
# \begin{equation*}
# B = T.M \\
# x(t) = B.G_x \\
# y(t) = B.G_y \\
# z(t) = B.G_z
# \end{equation*}
# Here, $T$ reprsents the parameter vector, $M$ represents the _basis matrix_ and $B$ represents the blending function.
# * For a (3D) straight line:
# \begin{equation*}
# x(t) = g_{1x} * (1 - t) + g_{2x} * t \\
# y(t) = g_{1y} * (1 - t) + g_{2y} * t \\
# z(t) = g_{1z} * (1 - t) + g_{2z} * t
# \end{equation*}
# where,
# \begin{equation*}
# T =
# \begin{bmatrix}
# t & 1
# \end{bmatrix} \\
# M =
# \begin{bmatrix}
# -1 & 1 \\
# 1 & 0
# \end{bmatrix}
# \end{equation*}
# and,
# \begin{equation*}
# G =
# \begin{bmatrix}
# G_1\\
# G_2
# \end{bmatrix} =
# \begin{bmatrix}
# g_{1x} & g_{1y} & g_{1z}\\
# g_{2x} & g_{2y} & g_{2z}
# \end{bmatrix}
# \end{equation*}
# * In general,
# \begin{equation*}
# x(t) = T.M.G_x \\
# T =
# \begin{bmatrix}
# t^3 & t^2 & t & 1
# \end{bmatrix} \\
# G_x =
# \begin{bmatrix}
# G_{1} \\
# G_{2} \\
# G_3 \\
# G_4
# \end{bmatrix} =
# \begin{bmatrix}
# g_{1x} & g_{1y} & g_{1z} \\
# g_{2x} & g_{2y} & g_{2z} \\
# g_{3x} & g_{3y} & g_{3z} \\
# g_{4x} & g_{4y} & g_{4z}
# \end{bmatrix} \\
# \end{equation*}
# Similarly for other dimensions.
# Further,
# \begin{equation*}
# C = M*G
# \end{equation*}
# where, $C$ is the coefficient matrix discussed in an [earlier lecture](https://colab.research.google.com/drive/1f4fZMmsQTdKXIloznL8Ubiw_kO_Uj3kf#scrollTo=3dYDJieIysdL).
# + [markdown] id="A3DTbSyXg1OW" colab_type="text"
# ## Some properties of blending functions
# * What all insights could be drawn from this?
# * Blending functions(in this course) are the parametric functions which are constrained to satisfy the geometric constraints.
# * These functions may or may not interpolate the control points.
# * These functions may or may not all sum to 1, thereby, may or may not be contrained to lie within the convex hull of their control points.
# * These functions however _weigh_ each control point as observed in the straight-line example.
# + [markdown] id="j_ybLG9jn5e5" colab_type="text"
# ## An implementation of straight line with geometric constraints
# + id="WETTpOTQoaOA" colab_type="code" colab={}
import matplotlib.pyplot as plt # for drawing 2D curves
import math
import numpy as np
from numpy import arange
import plotly.graph_objects as go
# + id="OqshcHMEkuO-" colab_type="code" outputId="7c30295b-4ed7-4f03-9c68-5a1e5cd2c20b" colab={"base_uri": "https://localhost:8080/", "height": 542}
class ParametricLine(object):
def __init__(self, basis_matrix):
self.basis_matrix = basis_matrix
self.geometric_constraints_matrix = None
def set_geometric_constraints_matrix(self, geometric_constraints_matrix):
self.geometric_constraints_matrix = geometric_constraints_matrix
def sample_curve_segment(self, t):
g = np.dot(self.basis_matrix, self.geometric_constraints_matrix) # #n constraints X # curve dimension
t_vector = np.array([t, 1]).reshape(1, 2) # 1X #degree of polynomial
q = np.dot(t_vector, g) # 1 X curve dimension
q = np.squeeze(q)
return q
def sample_blending_function(self, t):
t_vector = np.array([pow(t, 3), pow(t, 2), pow(t, 1), 1])
b = np.dot(t_vector, self.basis_matrix)
return b # samples the blending functions at 't'
if __name__ == '__main__' :
basis_matrix = np.array([[-1, 1],[1, 0]]) # #polynomial degree x #curve dimension
pline = ParametricLine(basis_matrix)
geometric_constraints_matrix = np.array([[2, 3, 5],[20, 45, 96]]) # #endpoints X #curve dimension
pline.set_geometric_constraints_matrix(geometric_constraints_matrix)
# generate list of (x, y)
n_points = 1000
x = [t for t in arange(0, 1, 1 / n_points)]
y = []
for i in x:
y.append(pline.sample_curve_segment(i))
xt = [y[i][0] for i in range(n_points)]
yt = [y[i][1] for i in range(n_points)]
zt = [y[i][2] for i in range(n_points)]
'''
plt.plot(x, xt) # xt
plt.title('Parametric representation, x vs t')
plt.ylabel('x')
plt.xlabel('t')
plt.show()
plt.plot(x, yt) # yt
plt.title('Parametric representation, y vs t')
plt.ylabel('y')
plt.xlabel('t')
plt.show()
plt.plot(x, zt) # zt
plt.title('Parametric representation, z vs t')
plt.ylabel('z')
plt.xlabel('t')
plt.show()
'''
fig = go.Figure(data=[go.Scatter3d(x=xt, y=yt, z=x,
mode='markers', marker = dict(size = 1))])
fig.show()
# + [markdown] id="cLTiflaozmGZ" colab_type="text"
# Parametric cubic curves are just a generalization of straight-line approximations!!
# + [markdown] id="W6rIuMb7CO9k" colab_type="text"
# ## Hermite curves
# * Formulation:
# * Geometric constraint vector,
# \begin{equation*}
# G_{H_{x}} =
# \begin{bmatrix}
# P_1 \\
# P_4 \\
# R_1 \\
# R_4
# \end{bmatrix}
# \end{equation*}
# where, $P_i$ represents an endpoint and $R_i$ represents the corresponding tangent vector.
# * The basis matrix,
# \begin{equation*}
# M_H =
# \begin{bmatrix}
# 2 & -2 & 1 & 1 \\
# -3 & 3 & -2 & -2 \\
# 0 & 0 & 1 & 0 \\
# 1 & 0 & 0 & 0
# \end{bmatrix}
# \end{equation*}
# * As earlier,
# \begin{equation*}
# x(t) = T.M.G_x \\
# y(t) = T.M.G_y \\
# z(t) = T.M.G_z
# \end{equation*}
# * Algebraic form,
# \begin{equation*}
# Q(t) = (2t^3 - 3t^2 + 1)*P_1 + (-2t^3 + 3t^2) * P_4 + (t^3 - 2t^2 + t)* R_1
# + (t^3 - t^2)*R_4 \end{equation*}
# * A demo:
# * https://www.geogebra.org/m/wTneDg9v
# + [markdown] id="hX_YWlzSfweG" colab_type="text"
# ### Test your understanding
# * Derive $M_H$ for Hermite curves
# * Plot $Q(t)$ for Hermite curves
# * Explain the effect of varying endpoints and tangent vectors on the resultant curve. (Use demo)
# * WAP to perform following transformations on Hermite curves:
# * Translation
# * Rotation
# * Scaling
# * Perspective projection
# * Under which conditions do the two joining Hermite curves will have $C_1$ continuity?
|
parametric_representations/Hermite_curves_lec_3.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import json
import re
of = open('raw_code_all_per_line.txt', 'w')
jf = open('vulnerables.json')
examples = json.load(jf)
for i, e in enumerate(examples):
code = e['code']
code = code.strip()
#code = re.sub('\s+', ' ', code)
if i == 1:
print(code)
of.write(code + '\n')
of.flush()
jf.close()
jf = open('non-vulnerables.json')
examples = json.load(jf)
for i, e in enumerate(examples):
code = e['code']
code = code.strip()
#code = re.sub('\s+', ' ', code)
if i == 1:
print(code)
of.write(code + '\n')
of.flush()
jf = open('/home/saikatc/DATA/security-bias/VulnerabilityDetectionProject/Baseline/data/neurips.json')
examples = json.load(jf)
for i, e in enumerate(examples):
code = e['func']
code = code.strip()
#code = re.sub('\s+', ' ', code)
if i == 1:
print(code)
of.write(code + '\n')
of.flush()
of.close()
# -
import json
jf = open('/home/saikatc/DATA/security-bias/VulnerabilityDetectionProject/Baseline/data/neurips.json')
examples = json.load(jf)
print(examples[0].keys())
|
data_collection/gather_all.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Data Preparation for Feature-Based Cluster Queries
# +
# %load_ext autoreload
# %autoreload 2
# %matplotlib inline
import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
sys.path.append(module_path)
# +
chrom = 'chr7'
bin_size = 100000
chrom_sizes_file = '../data/hg19/hg19.chrom.sizes'
chromhmm_5kb_bed_file = '../data/carlo/HG19_chromhmm_5.0Kb_allchr.bed.gz'
ffr_motif_bed_file = '../data/carlo/FFR_constels_0607_50k-1M.BED'
frf_motif_bed_file = '../data/carlo/FRF_constels_0607_50k-1M.BED'
frr_motif_bed_file = '../data/carlo/FRR_constels_0607_50k-1M.BED'
rfr_motif_bed_file = '../data/carlo/RFR_constels_0607_50k-1M.BED'
# +
from hgmc.utils import get_chrom_sizes
chrom_size = get_chrom_sizes(chrom_sizes_file).get(chrom)
num_bins = math.ceil(chrom_size / bin_size)
# -
# # Convert Data
# ### Convert BED to SQL
# +
from hgmc.bed import bed_to_sql
bed_to_sql(chromhmm_5kb_bed_file, chrom_sizes_file)
# +
from hgmc.bed import bed_to_sql
bed_to_sql(ffr_motif_bed_file, chrom_sizes_file)
bed_to_sql(frf_motif_bed_file, chrom_sizes_file)
bed_to_sql(frr_motif_bed_file, chrom_sizes_file)
bed_to_sql(rfr_motif_bed_file, chrom_sizes_file)
# -
columns = [
'chrom',
'start',
'end',
'score',
'unknown1',
'strand',
'thickStart',
'thickEnd',
'itemRgb',
'unknown4',
'unknown5',
'unknown6'
]
# +
import pandas as pd
ffr = pd.read_table(ffr_motif_bed_file, sep=' ', header=None)
ffr.columns = columns
ffr['name'] = 'ffr'
frf = pd.read_table(frf_motif_bed_file, sep=' ', header=None)
frf.columns = columns
frf['name'] = 'frf'
frr = pd.read_table(frr_motif_bed_file, sep=' ', header=None)
frr.columns = columns
frr['name'] = 'frr'
rfr = pd.read_table(rfr_motif_bed_file, sep=' ', header=None)
rfr.columns = columns
rfr['name'] = 'rfr'
# -
combined_motifs = pd.concat([
ffr[['chrom', 'start', 'end', 'name']],
frf[['chrom', 'start', 'end', 'name']],
frr[['chrom', 'start', 'end', 'name']],
rfr[['chrom', 'start', 'end', 'name']]
], ignore_index=True)
all_motifs_bed_file = '../data/carlo/all_constels_0607_50k-1M.bed'
combined_motifs.to_csv(all_motifs_bed_file, sep='\t', index=False, header=False)
bed_to_sql(all_motifs_bed_file, chrom_sizes_file)
# ---
chromhmm_5kb = pd.read_table(chromhmm_5kb_bed_file, header=None)
chromhmm_5kb.head()
|
notebooks/query-data-preparation-new-data.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Task 12: Hands on Neural Nets
#
# _All credit for the code examples of this notebook goes to the book "Hands-On Machine Learning with Scikit-Learn, Keras & TensorFlow" by <NAME>. Modifications were made and text was added <NAME> in preparation for the hands-on sessions_
# # Setup
#
# First, let's import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures. We also check that Python 3.5 or later is installed (although Python 2.x may work, it is deprecated so we strongly recommend you use Python 3 instead), as well as Scikit-Learn ≥0.20.
# +
# Python ≥3.5 is required
import sys
assert sys.version_info >= (3, 5)
# Scikit-Learn ≥0.20 is required
import sklearn
assert sklearn.__version__ >= "0.20"
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
# %matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)
# Function to save a figure. This also decides that all output files
# should stored in the subdirectory 'forests'.
PROJECT_ROOT_DIR = "."
EXERCISE = "hands_on_neural_nets"
IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", EXERCISE)
os.makedirs(IMAGES_PATH, exist_ok=True)
def save_fig(fig_id, tight_layout=True):
path = os.path.join(PROJECT_ROOT_DIR, "images", EXERCISE, fig_id + ".png")
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(path, format='png', dpi=300)
# -
# ## The Perceptron
# In the lecture you already encountered the concept of the perceptron which is one of the simplest ANN architectures. This artificial neuron is a "threshold logical unit" (TLU) or "linear threshold unit" (LTU).
# It computes the weighted sum `z`
#
# $$
# z=w\cdot x_1+\dots w_n\cdot x_n = w^T\cdot x
# $$
#
# It then uses step functions like the Heaviside function $\mathcal{H}(z)$ or the Signum function $\text{sgn}(z)$
#
# $$
# \mathcal{H}(z)=
# \begin{cases}
# 0 & \text{if $z<0$} \\
# 1 & \text{if $z\geq0$}
# \end{cases}
# \quad\quad
# \text{sgn}(z)=
# \begin{cases}
# -1 & \text{if $z<0$} \\
# 0 & \text{if $z=0$} \\
# +1 & \text{if $z>0$}
# \end{cases}
# $$
# Let's play around with perceptrons a little bit. Scikit-Learn provides a [Perceptron class](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Perceptron.html). It implements a single TLU network.
#
# We will use two datasets. The `iris dataset` and the `moons dataset`.
# +
from sklearn.datasets import load_iris # iris dataset
from sklearn.datasets import make_moons # moon dataset
X_moons, y_moons = make_moons(n_samples=100, noise=0.15, random_state=42)
iris = load_iris()
X_iris = iris.data[:, (2, 3)] # petal length, petal width
y_iris = (iris.target == 0).astype(np.int)
def plot_dataset(X, y, axes):
plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs") # some blue squares
plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^") # some green triangles
plt.axis(axes)
plt.grid(True, which='both') # to visialize things we add a grid
plt.xlabel(r"$x_1$", fontsize=20)
plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
# Now start the plotting.
plt.figure(figsize=(11, 4))
plt.subplot(121)
plot_dataset(X_iris, y_iris, [0, 7.5, 0, 3])
plt.title("Iris Dataset", fontsize=18)
plt.subplot(122)
plot_dataset(X_moons, y_moons, [-1.5, 2.5, -1, 1.5])
plt.title("Moons Dataset", fontsize=18)
plt.show()
# -
# Now we want to train a perceptron model for each of the datasets to classifiy the points within the dataset.
# +
from sklearn.linear_model import Perceptron
per_iris_clf = Perceptron(max_iter=1000, tol=1e-3, random_state=42)
per_iris_clf.fit(X_iris, y_iris)
per_moons_clf = Perceptron(max_iter=1000, tol=1e-3, random_state=42)
per_moons_clf.fit(X_moons, y_moons)
# -
# You can repeat the training of the model and set some additional parameters. What happens when you set `verbose` to 1?
# +
from matplotlib.colors import ListedColormap
axes_iris = [0, 7.5, 0, 3]
axes_moons = [-1.5, 2.5, -1, 1.5]
def get_plot(X, y, axes, clf):
x0, x1 = np.meshgrid(
np.linspace(axes[0], axes[1], 500).reshape(-1, 1),
np.linspace(axes[2], axes[3], 200).reshape(-1, 1),
)
a = -clf.coef_[0][0] / clf.coef_[0][1]
b = -clf.intercept_ / clf.coef_[0][1]
X_new = np.c_[x0.ravel(), x1.ravel()]
y_predict = clf.predict(X_new)
zz = y_predict.reshape(x0.shape)
plt.plot(X[y==0, 0], X[y==0, 1], "bs")
plt.plot(X[y==1, 0], X[y==1, 1], "yo")
plt.plot([axes[0], axes[1]], [a * axes[0] + b, a * axes[1] + b], "k-", linewidth=3)
custom_cmap = ListedColormap(['#9898ff', '#fafab0'])
plt.contourf(x0, x1, zz, cmap=custom_cmap)
plt.xlabel("$x_1$", fontsize=14)
plt.ylabel("$x_2$", fontsize=14)
plt.axis(axes)
plt.figure(figsize=(11, 4))
plt.subplot(121)
get_plot(X_iris, y_iris, axes_iris, per_iris_clf)
plt.title("Iris Dataset", fontsize=18)
plt.subplot(122)
get_plot(X_moons, y_moons, axes_moons, per_moons_clf)
plt.title("Moons Dataset", fontsize=18)
save_fig("perceptron_iris_moons_plot")
# -
# Ok. This does not look bad when looking at the iris dataset. But when we look at the other dataset we see, that our classifier performs rather poorly. Why is that?
# We try to solve this problem using the [Multi-Layer-Perceptron Class](https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html#sklearn.neural_network.MLPClassifier) from `Scikit-learn`.
#
# Play around with the parameters a little bit and answer these questions:
#
# * What happens if you change `learning_rate_init` or the layer structure and the number of nodes?
# * What happens when you set `verbose` to 1?
# * Which activation function is used by default?
# * Why is this function a good choice?
#
# The initial parameters are not very well chosen. Can you find better parameters?
# +
from sklearn.neural_network import MLPClassifier
mlp_clf = MLPClassifier(solver='sgd', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=42, max_iter=1000, learning_rate_init=0.01)
mlp_clf.fit(X_moons, y_moons)
# +
plt.figure(figsize=(11, 4))
axes = axes_moons
x0, x1 = np.meshgrid(
np.linspace(axes[0], axes[1], 500).reshape(-1, 1),
np.linspace(axes[2], axes[3], 200).reshape(-1, 1),
)
Z = mlp_clf.predict_proba(np.c_[x0.ravel(), x1.ravel()])[:, 1]
Z = Z.reshape(x0.shape)
custom_cmap = ListedColormap(['#9898ff', '#fafab0'])
plt.plot(X_moons[y_moons==0, 0], X_moons[y_moons==0, 1], "bs")
plt.plot(X_moons[y_moons==1, 0], X_moons[y_moons==1, 1], "yo")
plt.contourf(x0, x1, Z, cmap=custom_cmap, alpha=.8)
plt.title("MLP Classification of Moon Dataset", fontsize=18)
plt.xlabel("$x_1$", fontsize=14)
plt.ylabel("$x_2$", fontsize=14)
plt.show()
# -
# ## Tensorflow and Keras
# You have also learned that we can use Tensorflow and Keras to train (deep) neural networks. Let's try it out.
#
# This time we also want to import [TensorFlow](https://www.tensorflow.org/) and [Keras](https://keras.io/). So let's do that right away!
#
# TensorFlow will serve as our backend and Keras as our high level API that works on top of Tensorflow.
# +
import tensorflow as tf
from tensorflow import keras
print("TensorFlow Version: %s"%tf.__version__)
print("Keras Version: %s"%keras.__version__)
# -
# ### Fashion Mnist
# [Fashion-MNIST](https://keras.io/api/datasets/fashion_mnist/) is a dataset of Zalando’s article images consisting of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28×28 grayscale image, associated with a label from 10 classes. `Fashion-MNIST` is intended to serve as a direct drop-in replacement of the original `MNIST` dataset for benchmarking machine learning algorithms.
# +
# The fashion mnist dataset is accesible via the keras.dataset module
fashion_mnist = keras.datasets.fashion_mnist
# We again split into training and testing
(X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data()
# -
# Let's quickly check the size of the dataset and the used type. We should get 60,000 examples of size 28x28 and they should all be `integers`.
print(X_train_full.shape,X_train_full.dtype)
# Ok this looks good!
# We now want to scale the greyscale values down from the range (0,255) to the range (0,1). We do this by simply dividing our training and testing arrays by 255.
# Furthermore, we set 5,000 examples aside for validation purposes.
X_valid, X_train = X_train_full[:5000]/255.0, X_train_full[5000:]/255.0
y_valid, y_train = y_train_full[:5000], y_train_full[5000:]
# Lets look at a few of these images to get an idea of our dataset.
# +
def plot_piece(data):
image = data.reshape(28, 28)
plt.imshow(image, cmap = mpl.cm.binary,
interpolation="nearest")
plt.axis("off")
def plot_pieces(instances, images_per_row=10, **options):
size = 28
images_per_row = min(len(instances), images_per_row)
images = [instance.reshape(size,size) for instance in instances]
n_rows = (len(instances) - 1) // images_per_row + 1
row_images = []
n_empty = n_rows * images_per_row - len(instances)
images.append(np.zeros((size, size * n_empty)))
for row in range(n_rows):
rimages = images[row * images_per_row : (row + 1) * images_per_row]
row_images.append(np.concatenate(rimages, axis=1))
image = np.concatenate(row_images, axis=0)
plt.imshow(image, cmap = mpl.cm.binary, **options)
plt.axis("off")
plt.figure(figsize=(9,9))
example_images = np.r_[X_train[:12000:600], X_train[13000:30600:600], X_train[30600:60000:590]]
plot_pieces(example_images, images_per_row=10)
save_fig("more_clothing_pieces_plot")
plt.show()
# -
# These are the classes of the fashion mnist dataset
class_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
"Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
# The distribution of classes is not flat. This means that some pieces of clothing occur more often than others.
# We can use the [np.unique](https://numpy.org/doc/stable/reference/generated/numpy.unique.html) function to determine the unique elements of an array.
# We apply this function to our training labels and retrieve the number of counts by setting `return_counts=True`.
# +
unique, counts = np.unique(y_train, return_counts=True)
print("Unique labels:", unique)
print("Counts:", counts)
# Now we determine class weights to take this imbalance into account during training.
class_weight = [c/55000 for c in counts]
print("Class Weights:", [round(num, 4) for num in class_weight])
# -
# Ok this imbalance does not look to bad. The distribution of classes is almost flat.
# Nevertheless, you should always make sure that the classes are balanced during training.
# ### Building our First Neural Network with Keras
#
# You have already learned a lot about TensorFlow in the lecture. However, you will probably only encounter TensorFlow syntax and functions directly, when you want to customize things. For example when you want very specific layers, gradient calculations, weighting schemes or loss functions.
#
# In practice you will work with Keras 95% of your time and it is likeley that you do not have to dive deeply into Tensorflow itself. That is the magic and power of Keras. It is an API designed for human beings, not machines. Let's dive into it!
# Keras models are build starting from the input. For the beginning we will use the [Sequential](https://keras.io/api/models/sequential/) API which provides you with a very intuitive way of building simple neural networks.
# For more complex neural networks with several independent inputs, outputs and concatenations Keras provides the [Functional](https://keras.io/guides/functional_api/) API.
#
# The Keras functional API is a way to create models that is more flexible than the Sequential API. The functional API can handle models with non-linear topology, models with shared layers, and models with multiple inputs or outputs.
# +
# We will start with a very simple model
# First we initialise a sequential model
model = keras.models.Sequential()
# Now we can simply add layers to the sequential model
# Here we simply flatten the 28x28 images
model.add(keras.layers.Flatten(input_shape=[28,28]))
# Now we add some hidden layers with 100 and 50 nodes and the relu activation function
model.add(keras.layers.Dense(100, activation=tf.nn.leaky_relu))
model.add(keras.layers.Dense(50, activation=tf.nn.leaky_relu))
#Since we are doing a multi-class classification we apply the softmax activation function
model.add(keras.layers.Dense(10, activation="softmax"))
# At the end we check the summary of our model.
model.summary()
# -
# To finish the creation of our model we need to compile it.
# Here we add
# * The loss function
# * The optimiser we want to use
# * The metrics that are computed during training
#Since our labels are in the range(0,9) we use the sparse entropy to convert the labels into one-hot-encoded labels
model.compile(loss = "sparse_categorical_crossentropy",
optimizer = "sgd",
metrics = ["accuracy"])
# ### Fitting the Model
#
# Now we can finally start fitting the model to the training data.
# Here we will use
# * The training data `X_train`
# * The training labels `y_train`
# * 30 epochs
# * The validation tuple `(X_valid, y_valid)`
# * The class weights
history = model.fit(X_train, y_train, epochs = 30,
validation_data = (X_valid, y_valid),
class_weight=class_weight)
import pandas as pd
import matplotlib.pyplot as plt
pd.DataFrame(history.history).plot(figsize=(8,5))
plt.grid(True)
plt.gca().set_ylim(0,1) # set the vertical range to (0,1)
plt.show()
model.evaluate(X_test,y_test)
|
12_hands_on_neural_nets.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# + [markdown] tags=[]
# # Analyzing Individual Currencies
#
# Here is where I will analyze a single currency.
# +
# Import libraries/packages
import pandas as pd
import numpy as np
import requests
from datetime import datetime
# !pip install stockstats -q
from stockstats import StockDataFrame
# %matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
# Style
sns.set_context("notebook")
sns.set_style("darkgrid")
# -
# ## Functions To Help With The Data
# +
# Function to download from cryptocompare
def download_data(from_symbol, to_symbol, exchange, datetime_interval, data_points):
supported_intervals = {'minute', 'hour', 'day'}
assert datetime_interval in supported_intervals,\
'datetime_interval should be one of %s' % supported_intervals
print('Downloading %s trading data for %s %s from %s.' %
(datetime_interval, from_symbol, to_symbol, exchange))
base_url = 'https://min-api.cryptocompare.com/data/histo'
url = '%s%s' % (base_url, datetime_interval)
params = {'fsym': from_symbol, 'tsym': to_symbol, 'limit': data_points, 'aggregate': 1, 'e': exchange}
request = requests.get(url, params=params)
data = request.json()
return data
# Function to convert downloaed json to dataframe
def convert_to_dataframe(data):
df = pd.io.json.json_normalize(data, ['Data'])
df['datetime'] = pd.to_datetime(df.time, unit='s')
df = df[['datetime', 'low', 'high', 'open', 'close', 'volumefrom', 'volumeto']]
return df
# Load data from flat file
def read_dataset(filename):
print('Reading data from %s.' %filename)
df = pd.read_csv(filename)
# Change type from object to datetime
df.datetime = pd.to_datetime(df.datetime)
df = df.set_index('datetime')
df = df.sort_index() # sort by datetime
print(df.shape)
return df
# Function to filter out empty records
def filter_empty_datapoints(df):
indices = df[df.sum(axis=1) == 0].index
print("Filtering %d empty datapoints." %indices.shape[0])
df = df.drop(indices)
return df
# Function for naming file to save flat file of downloaded data
def get_filename(from_symbol, to_symbol, exchange, datetime_interval, download_date):
return '%s_%s_%s_%s_%s.csv' % (from_symbol, to_symbol, exchange, datetime_interval, download_date)
# Function to make candlesticks
def get_candlestick_width(datetime_interval):
if datetime_interval == 'minute':
return 30 * 60 * 1000 # half minute in ms
elif datetime_interval == 'hour':
return 0.5 * 60 * 60 * 1000 # half hour in ms
elif datetime_interval == 'day':
return 12 * 60 * 60 * 1000 # half day in ms
# -
# I would like to modify this to where the downloaded data appends to the flat file only the newer data that is not already contained. I see this as an online system that gets updated data in real time and populates an interface as the data arrives.
# ## Downloading Data...
# Set paramters
from_symbol = 'BTC' # as of 2021-09-28 ['BTC', 'ETH','XLM', 'COMP', 'GRT', 'USDT']
to_symbol = 'USD' # likely to remain USD for a bit, I mean, unless...
exchange = 'Bitstamp'
datetime_interval = 'minute' # datetime_interval should be one of {'hour', 'minute', 'day'}
data_points = 2000 # number of data points (max is 2000)
# As of September 28, 2021, only the following currencies are compatible with this:
#
# * BTC
# * ETH
# * XLM
# * COMP
# * GRT
# * USDT
#
# As there are numerous others that I am interested - some *a lot* more than a few in that lost - I will need to explore anothr means of getting data for those. I may need to explore Yahoo! for those.
# Download and load data to dataframe - save to flat file as needed
data = download_data(from_symbol, to_symbol, exchange, datetime_interval, data_points)
df = convert_to_dataframe(data)
df = filter_empty_datapoints(df)
# +
# Write data to flat file -- UNCOMMENT AS NEEDED!
#current_datetime = datetime.now().date().isoformat()
#filename = get_filename(from_symbol, to_symbol, exchange, datetime_interval, current_datetime)
#print('Saving data to %s' % filename)
#df.to_csv(filename, index=False)
# -
# Inspect dataframe
print(df.shape, "\n")
print(df.info(), "\n")
display(df.head())
display(df.tail())
display(df.describe())
# ## If Reading In From Previously Saved Flat File...
#
# Uncomment this section's material and go to town, homey.
'''
# Load tools
import pandas as pd
import numpy as np
!pip install stockstats -q
from stockstats import StockDataFrame
# Load data from flat file
df = read_dataset(filename)
'''
# ## Start Looking
#
# I will also consider Moving Average Convergence Divergence (MACD) here.
#
# More MACD information can be found [here](https://www.investopedia.com/terms/m/macd.asp). This can be something to consider, based on [this information](https://www.investopedia.com/articles/forex/08/macd-combo.asp).Effectively, when the two moving avereges cross it *could* be a sign that a trend is accelerating and signal an entry.
#
# Explore plotly for [candlestick plot](https://plotly.com/python/candlestick-charts/).
#
# **UPDATE**
#
# Check [this nonsense](https://python.plainenglish.io/a-simple-guide-to-plotly-for-plotting-financial-chart-54986c996682) right here. Yeah. This. Definitely boogle this. It could help find the special goodness.
# +
# Make dataframe a time series
df = df.set_index("datetime")
df = df.sort_index()
# Convert dataframe to StockDataFrame
df = StockDataFrame.retype(df)
# Get MACD column
df['macd'] = df.get('macd') # calculate MACD
# -
df.tail()
# +
## TEST PLOTTING CANDLESICKS WITH BOKEH (...meh...)
# Import tools for plotting
from math import pi
from bokeh.plotting import figure, show, output_notebook, output_file
# Output in notebook
output_notebook()
# Timeframe endpoints
datetime_from = '2016-01-01 00:00'
datetime_to = '2017-12-10 00:00'
df_limit = df[datetime_from: datetime_to].copy()
inc = df_limit.close > df_limit.open
dec = df_limit.open > df_limit.close
title = '%s datapoints from %s to %s for %s and %s from %s with MACD strategy' % (datetime_interval, datetime_from, datetime_to, from_symbol, to_symbol, exchange)
p = figure(x_axis_type="datetime", plot_width=1000, title=title)
p.line(df_limit.index, df_limit.close, color='black')
# Plot MACD strategy
p.line(df_limit.index, 0, color='black')
p.line(df_limit.index, df_limit.macd, color='blue')
p.line(df_limit.index, df_limit.macds, color='orange')
p.vbar(x=df_limit.index, bottom=[
0 for _ in df_limit.index], top=df_limit.macdh, width=4, color="purple")
# Plot candlesticks
candlestick_width = get_candlestick_width(datetime_interval)
p.segment(df_limit.index, df_limit.high,
df_limit.index, df_limit.low, color="black")
p.vbar(df_limit.index[inc], candlestick_width, df_limit.open[inc],
df_limit.close[inc], fill_color="#D5E1DD", line_color="black")
p.vbar(df_limit.index[dec], candlestick_width, df_limit.open[dec],
df_limit.close[dec], fill_color="#F2583E", line_color="black")
# Send plot to file
output_file("visualizing_trading_strategy.html", title="visualizing trading strategy")
# Show plot in notebook
show(p)
# +
import plotly.graph_objects as go
import pandas as pd
from datetime import datetime
fig = go.Figure(data=[go.Candlestick(x=df.loc['2021-09-27'].index,
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close'])])
fig.show()
# -
# ### Focus on Bitcoin for a bit...
#
# At first I want to explore daily data to get a sense of high level trend and possible seasonality in the prices. After that I will explore hourly data to see if there is any diurnal seasonality, or perhaps even a common "low" point during the day that may be a good time to apply DCA purchases.
#
# I am not intentionaly ignoring minute frequency, rather; I am not familiar enough yet to know what to even do with such data, and my current thoughts are that such data may help me better prepare for "day trading," or other such moments when I wish to "manage a position" to optimize my gains when selling for profit.
# Set paramters
from_symbol = 'BTC' # as of 2021-09-28 ['BTC', 'ETH','XLM', 'COMP', 'GRT', 'USDT']
to_symbol = 'USD' # likely to remain USD for a bit, I mean, unless...
exchange = 'Bitstamp'
datetime_interval = 'day' # datetime_interval should be one of {'hour', 'minute', 'day'}
data_points = 2000 # number of data points (max is 2000)
# +
# Download and load data to dataframe
data = download_data(from_symbol, to_symbol, exchange, datetime_interval, data_points)
df = convert_to_dataframe(data)
df = filter_empty_datapoints(df)
# Make dataframe a time series
df = df.set_index("datetime", drop=False)
df = df.sort_index()
# Add year, month, and days to dataframe
df['Year'] = df.index.year
df['Month'] = df.index.month
df['Weekday Name'] = df.index.day_name()
# -
# Inspect
print(df.shape)
display(df.index)
display(df.head(3))
display(df.tail(3))
# Line plot of full time series
df['close'].plot(linewidth=0.6, alpha=0.8, figsize=(12,5), title='Bitcoin Daily Closing Prices 2016 - 2021');
# Lineplot focus in on 2021
df['close'].loc['2021'].plot(linewidth=0.6, alpha=0.8, figsize=(12,5), title='Bitcoin Daily Closing Prices 2021');
# Lineplot focus in on August - September 2021
df['close'].loc['2021-08':'2021-09'].plot(linewidth=0.6, alpha=0.8,
marker='o', linestyle='-',
figsize=(12,5), title='Bitcoin Daily Closing Prices 2021');
# ### Seasonality?
# Group by month, inspect yearly seasonality
fig, axes = plt.subplots(4, 1, figsize=(16,16), sharex=True)
for name, ax in zip(['open', 'close', 'low', 'high'], axes):
sns.boxplot(data=df, x='Month', y=name, ax=ax)
ax.set_ylabel('USD ($)')
ax.set_title(name)
# Remove automatic x-axis label from all but bottom subplot
if ax != axes[-1]:
ax.set_xlabel('')
# The opening and closing prices look lower in April andMay historically. October and November also look low as well. Interesting that there are a number of outliers (outside the whiskers) in all months except October and December (few in November). Are early Q2 and Q4 the times to buy and December and January times to sell?
# Drill down into weekly grouping
fig, ax = plt.subplots(figsize=(12,7))
sns.boxplot(data=df, x='Weekday Name', y='close', ax=ax);
# Fairly uniform. About what I expected here.
# +
### Hourly
# -
|
Individual Currency Analysis.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# + [markdown] deletable=false editable=false
# 
#
# Exercise material of the MSc-level course **Numerical Methods in Geotechnical Engineering**.
# Held at Technische Universität Bergakademie Freiberg.
#
# Comments to:
#
# *Prof. Dr. <NAME>
# Chair of Soil Mechanics and Foundation Engineering
# Geotechnical Institute
# Technische Universität Bergakademie Freiberg.*
#
# https://tu-freiberg.de/en/soilmechanics
#
# -
# # Exercise on the least squares method
# You're given a CPT data set consisting of cone resistance $q_\text{c}$ and frictional resistance $f_\text{s}$ measurements. Your first task is to check the results by plotting them and to compute as well as plot the friction ratio $R_\text{f}$.
# +
import numpy as np #numerical methods
#import sympy as sp #symbolic operations
import matplotlib.pyplot as plt #plotting
import pandas as pd
#Some plot settings
plt.style.use('seaborn-deep')
plt.rcParams['lines.linewidth']= 2.0
plt.rcParams['lines.color']= 'black'
plt.rcParams['legend.frameon']=True
plt.rcParams['font.family'] = 'serif'
plt.rcParams['legend.fontsize']=14
plt.rcParams['font.size'] = 14
plt.rcParams['axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.left'] = True
plt.rcParams['axes.spines.bottom'] = True
plt.rcParams['axes.axisbelow'] = True
plt.rcParams['figure.figsize'] = (8, 6)
# -
CPT_data = pd.read_csv('Data/CPT_2015.csv')
z = CPT_data.Teufe[1:].to_numpy(dtype=float)
qc = CPT_data.qc[1:].to_numpy(dtype=float)
fs = CPT_data.fs[1:].to_numpy(dtype=float)
with np.errstate(divide='ignore',invalid='ignore'):
Rf = np.divide(fs,qc)
# +
fig, ax = plt.subplots(figsize=(18,6))
ax.plot(z, qc, label='$q_\\mathrm{c}$ / MPa')
ax.plot(z, fs, label='$f_\\mathrm{s}$ / MPa')
ax2 = ax.twinx()
ax2.spines["right"].set_visible(True)
ax2.plot(z,Rf* 100., color='red', label = '$R_\\mathrm{f}$')
ax.set_xlabel('$z$ / m')
ax.set_ylabel('$q_\\mathrm{c}$, $f_\\mathrm{s}$ / MPa')
ax2.set_ylabel('$R_\\mathrm{f}$ / %')
fig.legend(loc='upper center',ncol=3)
fig.tight_layout()
# -
# You're also given data on the relationship between $q_\text{c}$ and $I_\text{D}$. The data is valid only for $z > 2$ m as well as above the phreatic surface. Your task is now to find a functional relationship $I_\text{D}(q_\text{c})$ in order to estimate the $I_\text{D}$ distribution in the above soil profile investigated with cone prenetration testing.
ID_data = pd.read_csv('Data/qc_ID.csv')
ID_data
qc_ID = ID_data.qc[1:].to_numpy(dtype=float)
ID = ID_data.ID[1:].to_numpy(dtype=float)
# +
fig, ax = plt.subplots()
ax.plot(qc_ID, ID,ls='',marker='o')
ax.set_xlabel('$q_\\mathrm{c}$ / MPa')
ax.set_ylabel('$I_\\mathrm{D}$')
fig.tight_layout()
|
Least_Squares_Exercise.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # 求解十字激光端点与交点
#
# 1Z实验室出品
# **1ZLAB :Make Things Easy**
#
# 程序目标
#
# 获取十字的中心还有四个端点的坐标
# 
import cv2
gray = cv2.imread('shizi.bmp', cv2.IMREAD_GRAYSCALE)
from matplotlib import pyplot as plt
plt.imshow(gray, cmap='gray')
plt.show()
# +
# TODO 其实可以考虑降低分辨率
binary = cv2.inRange(gray, 200, 255)
plt.imshow(binary, cmap='gray')
plt.show()
# -
# 霍夫检测直线的文档
# http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html#hough-lines
# 返回的直线的两个端点
# 需要调这里面的阈值
# 返回的是线段的两个端点
line_segs = cv2.HoughLinesP(binary, rho=2,theta=0.1, threshold=100)
len(line_segs)
# +
# 这段代码只是展示一下,可以删除
import math
for lseg in line_segs:
#
x1,y1,x2,y2 = lseg[0]
# 计算权重
weight = math.sqrt(math.pow(x1-x2, 2) + math.pow(y1-y2, 2))
print('x1: {}, y1: {}, x2: {}, y2: {}, weight: {}'.format(x1, y1, x2, y2, weight))
# -
# 对线段进行加权
# 预备知识是假设已知画面中有两条线,根据线段长度进行加权,获取两个线段。
# ?用机器学习的方法?
# +
def calculate_line(x1, y1, x2, y2):
'''
计算直线
如果直线水平或者垂直,统一向一个方向倾斜特定角度。
TODO 这里面没有考虑水平或者垂直的情况
'''
if x1 > x2:
x1,y1,x2,y2 = x2,y2,x1,y1
if x1 == x2 or y1 == y2:
# 有时候会出现单个像素点 x1 = x2 而且 y1 = y2
print('x1:{} y1:{} x2:{} y2:{}'.format(x1, y1, x2, y2))
k = (y1 - y2) / (x1 - x2)
b = (y2 * x1 - y1*x2) / (x1 - x2)
return k,b
# +
# BUG k b 改一个line,剩余的全改
lines = []
# 最小权值
min_weight = 20
# 相同k之间最大的差距
max_k_distance = 0.3
for lseg in line_segs:
# 获取线段端点值
x1,y1,x2,y2 = lseg[0]
if x1 > x2:
x1, y1, x2, y2 = x2, y2, x1, y1
# 计算权重
weight = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))
if weight != 0 and weight > min_weight:
# 计算K与b
k, b = calculate_line(x1, y1, x2, y2)
# print('k: {:.2f}, b: {:.2f}, weight: {:.2f}'.format(k, b, weight))
if len(lines) == 0:
# 初次填充line
line = {}
line['cur_k'] = k
line['cur_b'] = b
line['k_sum'] = k * weight
line['b_sum'] = b * weight
line['weight_sum'] = weight
line['x1'] = x1
line['y1'] = y1
line['x2'] = x2
line['y2'] = y2
lines.append(line)
continue
# 根据k的差异做加权
# 首先获取lines数组里面k举例最近的那个
neighbor_line = min(lines, key=lambda line:abs(line['cur_k'] - k))
if abs(neighbor_line['cur_k'] - k) < max_k_distance:
# 小于最大k差值,认为是同一条线
neighbor_line['weight_sum'] += weight
neighbor_line['k_sum'] += k * weight
neighbor_line['b_sum'] += b * weight
neighbor_line['cur_k'] = neighbor_line['k_sum'] / neighbor_line['weight_sum']
neighbor_line['cur_b'] = neighbor_line['b_sum'] / neighbor_line['weight_sum']
if neighbor_line['x1'] > x1:
neighbor_line['x1'] = x1
neighbor_line['y1'] = y1
if neighbor_line['x2'] < x2:
neighbor_line['x2'] = x2
neighbor_line['y2'] = y2
else:
# 添加另外一条线
# 初次填充line
line = {}
line['cur_k'] = k
line['cur_b'] = b
line['k_sum'] = k * weight
line['b_sum'] = b * weight
line['weight_sum'] = weight
line['x1'] = x1
line['y1'] = y1
line['x2'] = x2
line['y2'] = y2
lines.append(line)
# +
# 整合后的直线
print(len(lines))
lines
# TODO 如果len(lines)小于2 抛出异常
# -
# 在画面中绘制两条直线与四个顶点
# 根据权重对lines数组进行排序, 取前两个(lines的长度有可能大于2)
sorted_lines = sorted(lines, key=lambda line: line['weight_sum'])[::-1]
line1 = sorted_lines[0]
line2 = sorted_lines[1]
# 计算两个线之间的交点
def calculate_intersection(line1, line2):
a1 = line1['y2'] - line1['y1']
b1 = line1['x1'] - line1['x2']
c1 = line1['x2'] * line1['y1'] - line1['x1'] * line1['y2']
a2 = line2['y2'] - line2['y1']
b2 = line2['x1'] - line2['x2']
c2 = line2['x2'] * line2['y1'] - line2['x1'] * line2['y2']
if (a1 * b2 - a2 * b1) != 0 and (a2 * b1 - a1 * b2) != 0:
cross_x = int((b1*c2-b2*c1)/(a1*b2-a2*b1))
cross_y = int((c1*a2-c2*a1)/(a1*b2-a2*b1))
return (cross_x, cross_y)
return None
(cx, cy) = calculate_intersection(line1, line2)
print('cx: {} cy: {}'.format(cx, cy))
# +
canvas = cv2.cvtColor(binary, cv2.COLOR_GRAY2BGR)
# 绘制第一条线
pt_radius = 20
cv2.circle(canvas, (line1['x1'], line1['y1']),pt_radius, (255, 0, 0), thickness=-1)
cv2.circle(canvas, (line1['x2'], line1['y2']),pt_radius, (0, 255, 0), thickness=-1)
cv2.circle(canvas, (line2['x1'], line2['y1']),pt_radius, (0, 255, 255), thickness=-1)
cv2.circle(canvas, (line2['x2'], line2['y2']),pt_radius, (0, 0, 255), thickness=-1)
cv2.circle(canvas, (cx, cy), 40, (255, 0, 255), thickness=20)
plt.imshow(cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))
plt.show()
|
src/LaserCrossCenter.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/DavidMcK9509/spotify-workshop/blob/master/Spotify_Workshop_final.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="087AV8E0wiYc"
# ## Starting off
# + [markdown] id="8XVldCAQwmS_"
# ##### Try out the following commands in the code block below, replacing the "____________" sections with your code
#
# 1. print("Hello World)
#
# 1. name = "My name"
# 2. print(name)
#
# 2. print(5 * 10)
#
# If your code isn't running make sure you have pressed "Connect" in the top right hand corner
#
# 
#
#
# + id="IbfAPCioxcGC"
"__________" # print("Hello World")
#Make sure you remember the speech marks and don't capatalise the p of print!
# + id="HSYv8oZdy9R9"
"__________" #name = "<NAME>"
"__________" #type print(name)
# + id="yk_NyRgdzA6M"
"__________" #print(5*10)
# + [markdown] id="5ZEA_Qg_t7qW"
# # Day 1
# + [markdown] id="gMtidp38wiWl"
# ## Setup
# + [markdown] id="GZqKNx2amGNI"
# ### Package Import
# + id="93Wu_6CEtY8b"
# Install external packages for Google Colab
if 'google.colab' in str(get_ipython()):
# !pip install rasterfairy-py3 spotipy umap-learn -q
# + [markdown] id="70d6buE1IXg-"
# ###### **<font color='blue'>TO DO 1</font> :** import the `Image` module from the `PIL` package
# + id="7jdu5_hKtpPU" outputId="13c0aa3d-81b0-43e9-ae9c-8fb1f700e370" colab={"base_uri": "https://localhost:8080/", "height": 35}
# Import packages
from getpass import getpass # secure text entry
from io import BytesIO # reading binary data
from IPython.display \
import clear_output # clearing cell output
from sklearn.preprocessing \
import StandardScaler # feature standardisation
# TODO 01 Import the Image module from the PIL package
# (remember: exact capitalisation matters!)
"_____________" # image export
# + [markdown] id="b49zYSZSI6yp"
# ###### **<font color='blue'>TO DO 2</font> :** import the spotify package
# + id="KaGwistMINST"
import numpy as np # mathematics
import os # setting environment variables
import pandas as pd # storing audio features as dataframe
import plotly.express as px # basic interactive visualisation
import plotly.graph_objects as go # advanced plotting functionality
import rasterfairy # rasterfying point clouds
import requests # web requests
"______________" # Python interface to Spotify API
import umap # dimensionality reduction
# + [markdown] id="orSGe_Dr4FUC"
# ### Parameters
# + [markdown] id="NTUrda5UJefA"
# ###### **<font color='blue'>TO DO 3</font> :** assign your username to the variable 'USERNAME'
#
# + id="GycV5BA_3K6o"
# Parameters
# NB: Use 'vr1q8on6ji60ceo0kregujkkx' for playlists from WDSS
# TODO 03: supply a username
USERNAME = '_________________________' # user to extract public playlists from
RESOLUTION = 2 # 0 (extreme); 1 (high); 2 (low)
ORIENTATION = 'landscape' # landscape; portrait
MIN_RATIO = 0.5 # minimum ratio between shortest and longest dimension
# + id="2b7cF-kJsCBy" outputId="8913e4ea-3fa3-4439-f635-7169bf642323" colab={"base_uri": "https://localhost:8080/", "height": 53}
# CKPT: Use `print(USERNAME)` to check that the username has been set correctly
"_____________"
# + [markdown] id="Q6AXIz03mNsP"
# ### Helper Functions
# #### You don't need to look at this but feel free if you are interested. Remember to run it though!
# + id="-AXICFltkE2D"
# Define helper functions
def depaginate(first_page):
"""
Flatten the paginated response from the Spotify API.
The Spotify API returns responses over a certain size using pagination (like
how Google has multiple page of results). This function takes the first page
of a response and uses this to run through all other pages and return the
page items in a flattened format.
"""
page = first_page
while page:
for item in page['items']:
yield item
page = sp.next(page)
def resolution_map(resolution):
"""Return the pixel value corresponding to different resolution levels."""
return [600, 300, 64][resolution]
def mel_to_harm(key):
"""Convert absolute keys to positions relative to the circle of fifths."""
return (key * 7) % 12
def create_hover_text(track_df, features=None):
"""
Create hover text for plots.
Omit the second argument to leave out extra hover text for audio features.
"""
text = (
"Name: " + track_df['name'] + "<br>" +
"Artist: " + track_df['artist'] + "<br>" +
"Album: " + track_df['album'] + "<br><extra>"
)
if features:
for f in features:
text = text + f + ": " + track_df[f].apply(str) + "<br>"
return text + "</extra>"
def find_valid_sample_count(track_df, min_ratio):
"""
Find a sample count that can form a rectangle satisfying a minimum ratio.
For difficult numbers of observations (e.g. a prime), only long rectangles
can be formed in the final visualisation. We therefore keep decreasing the
number of points until we have form a rectangle that satisfies a minimum
ratio between side lengths.
"""
n = len(track_df)
found_solution = False
while not found_solution:
i, j = rasterfairy.getRectArrangements(n)[0]
if i / j >= MIN_RATIO:
found_solution = True
else:
n -= 1
return n
# + [markdown] id="Mo4LnOoKmCln"
# ### API (Application Programming Interface) Connection
# #### Set-up a connection between Python and Spotify
# + [markdown] id="_SJUa43pJ6MP"
# ###### **<font color='blue'>TO DO 4</font> :** add a line asking for the client secret and assign it to the `SPOTIPY_CLIENT_SECRET` environment variable (base client ID line bellow)
# + id="lxWWilRpvNLS"
# Authentication environment variables
overwrite_existing = False # set to True to overwrite existing values
if overwrite_existing or 'SPOTIPY_CLIENT_ID' not in os.environ \
or 'SPOTIPY_CLIENT_SECRET' not in os.environ:
# NB: the input passed to `getpass` is the question asked to the user
# `\n` means create a newline before creating the answer box
os.environ['SPOTIPY_CLIENT_ID'] = getpass("What is your client ID?\n")
# TODO 04: ask for the client secret and assign it to the
# `SPOTIPY_CLIENT_SECRET` environment variable (base this on the line above)
"____________________________________________________________________________"
# + id="q85mdkVpxb-i"
# Initialise client
auth_manager = spotipy.SpotifyClientCredentials()
sp = spotipy.Spotify(auth_manager=auth_manager)
# + id="X2SBG_U1sCB_"
# CKPT: Run `sp.categories(country='GB', limit=3)` to list the first three
# categories in Great Britain. NB: This returns a dictionary with more
# dictionaries and lists nested inside
"__________________________________"
# + [markdown] id="0-l5Dn6z1ot7"
# ## Data Scraping
# + [markdown] id="mh9OfbHa3DgN"
# ### Collect Playlists
# + id="5dUuH50K3qd3"
# Create list to store key playlist information
playlist_info = []
# + [markdown] id="_GQs6Ym2Kdqk"
# ###### **<font color='blue'>TO DO 5</font> :** add the `id` field to the playlist information below
# + id="l2OOW10cKemJ"
# Loop through all playlists
for playlist in depaginate(sp.user_playlists(USERNAME)):
# Add playlist information to list
playlist_info.append({
'name': playlist['name'],
'size': playlist['tracks']['total'],
# TODO 05: add the `id` field to the playlist information
# This will look very similar to 'name' above
"___________________",
})
# + id="LrmA6Y6_sCCI"
# CKPT: What does `playlist_info` look like? Use `print()` to find out
"__________________"
# + id="6i8lDlzX6aIc"
# Display playlist choices
max_digits = len(str(len(playlist_info)))
for i, info in enumerate(playlist_info):
print(f"({str(i).zfill(max_digits)}) {info['name']} [{info['size']} tracks]")
# + [markdown] id="q_Ozk9Wrz5W9"
# ### Playlist Selection
# + id="-tnsEMacyOS1"
# Get user to select a playlist
valid = False # placeholder to start off loop
while not valid:
# Ask user for input
choice_idx = input("Select a playlist index from the list above:\n")
# Check if the input was valid
valid = choice_idx.isnumeric() and 0 < int(choice_idx) <= len(playlist_info)
if not valid:
clear_output(wait=True)
print(f"Selection must be an integer between 1 and {len(playlist_info)}")
# Python returns input as text so convert to an integer
choice_idx = int(choice_idx)
print(f"\nYou selected '{playlist_info[choice_idx-1]['name']}'")
# + [markdown] id="LA1Nd0UM_B3Z"
# ### Collect Tracks Details
# + [markdown] id="EislL8JpK1ZG"
# ###### **<font color='blue'>TO DO 6</font> :** create an empty list called `track_info` (see Collect Playlists)
# + id="UvyeUc0o_NxH"
# Get the ID of the choosen playlist
choice_id = playlist_info[choice_idx-1]['id']
# Create list to store key playlist information
# TODO 06: create an empty list called `track_info` (see Collect Playlists)
"_____________"
# Loop through all playlist items
for item in depaginate(sp.playlist_items(choice_id))::
# Extract track information, ignoring item metadata (e.g. date added)
track = item['track']
track_info.append({
'name': track['name'],
'artist': track['artists'][0]['name'],
'album': track['album']['name'],
# NB: some tracks are missing artworks for all/some resolutions. If this
# is an issue, the simplest solution is to remove them from the playlist
'art_url': track['album']['images'][RESOLUTION]['url'],
'id': track['id'],
})
# + id="7CXbSjCxsCCW"
# CKPT: `track_info` might be quite a big object. Print out the second entry
# using `print(track_info[1])` (remember that we start from zero!)
"__________________"
# + [markdown] id="h0wTfrmj6KKc"
# # Day 2
# + [markdown] id="Gg_Rxq8GLWpY"
# ### Collect Audio Features
# + [markdown] id="lv-s2cdJLgQl"
# ###### **<font color='blue'>TO DO 7</font> :** add valence and tempo to the end of the list of included features
# + id="FdWheYnvLVzI"
# List features to collect. See: https://spoti.fi/2Rhrtye
# TODO 07: add valence and tempo to the end of the list of included features
included = (
'duration_ms', 'key', 'mode', 'time_signature',
'acousticness', 'danceability', 'energy', 'instrumentalness', 'liveness',
'loudness', 'speechiness', '_______', '_____',
)
# + id="wtqg3cUcLy-e"
# Audio feature requests have to be performed in batches of at most 100 IDs
for offset in range(0, len(track_info), 100):
# Collect all features
features = sp.audio_features(t['id'] for t in track_info[offset:offset+100])
# Filter to only include the features listed above
features = [{k: v for k, v in t.items() if k in included} for t in features]
# Add features to track info
for i in range(min(100, len(track_info) - offset)):
track_info[i + offset].update(features[i])
# + id="6qJzajG9sCCl"
# CKPT: Check the second element of `track_info` again to see the additions
"__________________"
# + id="Z_4EwaQ_yyIy"
# Convert to dataframe
track_df = pd.DataFrame(track_info)
# + id="tsRND9GYsCCr"
# CKPT: Use `track_df.head()` to see the first few rows of the dataframe
# Can you remember how to see the last few rows?
"_____________"
# + [markdown] id="mgs_ziIe1uZh"
# ## Pre-processing
# + [markdown] id="rmXcgRt2xwEV"
# ### Sampling
# + [markdown] id="uIcvqpZbL5uO"
# ###### **<font color='blue'>TO DO 8</font> :** find n, the maximum valid sample count by running the `find_valid_sample_count(...)` function with the two arguments `track_df`and `MIN_RATIO` (separate the arguments with a comma)
# + id="FIj5Dx0oL8Fn"
# Find a sample count that satisfies the minimum ratio
# TODO 08: find n, the maximum valid sample count by running the
# `find_valid_sample_count(...)` function with the two arguments `track_df`
# and `MIN_RATIO` (separate the arguments with a comma)
n = "__________________________________________"
# Take random sample of chosen size
print(f"Randomly removing {len(track_df) - n} tracks to leave {n} remaining")
sampled_track_df = track_df.sample(n, random_state=1729).reset_index(drop=True)
# + id="tPGGd5zEsCC1"
# CKPT: Print the dimensions of `track_df` using `print(track_df.shape)`
# Do the same for `sampled_track_df` for comparison
"___________________"
"___________________________"
# + [markdown] id="V44Yb1MMMTWR"
# ###### **<font color='blue'>TO DO 9</font> :** drop the column containing the url for the cover art (see Collect Track Details to find its name)
# + id="yJDvS1r4Dsw_"
# Extract feature columns into own dataframe
# TODO 09: drop the column containing the url for the cover art
# (see Collect Track Details to find its name)
features_df = sampled_track_df.drop(
['name', 'artist', 'album', '_______', 'id'], axis=1
)
# + id="YsZpuho9sCC_"
# CKPT: Whereas `.shape` gives the dimensions, `.columns` gives us column
# names. Use this to print the columns of `feature_df` and `sampled_track_df`
"_____________________________"
"_______________________"
# + [markdown] id="btIWdTiCg0RC"
# ### Feature Engineering
# #### This code helps incorparate which key each song is in as a feature that determines where it goes on your visual
# + id="1U2qapWYNZaZ"
# Transform key from polar coordinates using melodic distance
features_df['key_melodic_x'] = np.cos(features_df['key'] / 6 * np.pi)
features_df['key_melodic_y'] = np.sin(features_df['key'] / 6 * np.pi)
# Transform key from polar coordinates using harmonic distance
features_df['key_harmonic'] = features_df['key'].apply(mel_to_harm)
features_df['key_harmonic_x'] = np.cos(features_df['key_harmonic'] / 6 * np.pi)
features_df['key_harmonic_y'] = np.sin(features_df['key_harmonic'] / 6 * np.pi)
# Remove redundant columns
features_df.drop(['key', 'key_harmonic'], axis=1, inplace=True)
# Handle missing keys
features_df.iloc[:,-4:].fillna(0, inplace=True)
# + [markdown] id="HrkgQb0117qD"
# ### Standardisation
# + [markdown] id="wEJR-loxOQ9I"
# ###### **<font color='blue'>TO DO 10</font> :** use `features_df` as an input to the `.fit_transform` method of the StandardScaler to standardise the features
# + id="LqZiNln8OSg9"
# TODO 10: use `features_df` as an input to the `.fit_transform` method of the
# StandardScaler to standardise the features
scaled_features = StandardScaler().fit_transform("_________")
# Two features represent the key so weight these a factor of one fourth
scaled_features[:,-4:] /= 2
# + [markdown] id="C5OtgHsag9NL"
# ## Dimensionality Reduction
# #### We currently have data in 16 dimensions! Lets reduce that to something more managable!
# + [markdown] id="kVTZRqHJchfW"
# ### Embedding
# + [markdown] id="7ye2dHC7O8qc"
# ###### **<font color='blue'>TO DO 11</font> :** Set initial hyperparameter values to be 10 for `n_neighbors` and 0.5 for `min_dist`
# + id="fNppZx3OOp5G"
# Embedded the audio features into two dimensions
embedding = umap.UMAP(
n_components=2,
# Embedding hyperparameters used to balance local and global structure
# See:
# https://pair-code.github.io/understanding-umap/
# https://umap-learn.readthedocs.io/en/latest/parameters.html
# TODO 11: Set initial hyperparameter values to be 10 for `n_neighbors` and
# 0.5 for `min_dist`
"____________",
"__________",
metric='euclidean',
# Random seed used for reproducibility
random_state=1729).fit_transform(scaled_features)
# + [markdown] id="Y0dZPZcdPzxr"
# ###### **<font color='blue'>TO DO 12</font> :** create a y variable alike the x variable below using the column with index 1
# + id="cg4-OjyXOy1m"
# View embedding
x = embedding[:, 0]
# TODO 12: use the column with index 1 for the y variable
"_________________"
fig = go.Figure()
fig.add_trace(go.Scatter(
x=x, y=y,
hovertemplate = '%{text}',
# Add `included` as a second argument to show audio features on hover
text=create_hover_text(sampled_track_df)
))
fig.update_traces(mode='markers')
fig.show()
# + [markdown] id="dssDxwFF7eG7"
# ### Rasterfication
# + id="9YXnCpdsv0-Z"
# Rasterfy embedding
grid, dims = rasterfairy.transformPointCloud2D(
embedding[:, :], proportionThreshold=MIN_RATIO
)
# Fix grid type
grid = grid.astype(int)
# Fix orientation (portrait by default)
if ORIENTATION == 'portrait':
pass
elif ORIENTATION == 'landscape':
grid = grid[:, ::-1]
dims = dims[::-1]
else:
raise ValueError("invalid orientation")
# + [markdown] id="5OZty8TWQ3qq"
# ###### **<font color='blue'>TO DO 13&14</font> :** plot markers rather than lines (see Embedding - TODO 12)
# + id="7NyMwamGwm89"
# View rasterfied embedding
x = grid[:, 0]
y = grid[:, 1]
fig = go.Figure()
fig.add_trace(go.Scatter(
x=x, y=y,
hovertemplate = '%{text}',
#Add 'included' as a second argument to show audio features on hover
text=create_hover_text(sampled_track_df)
))
# TODO 13: plot markers rather than lines (again, see above)
"_______________________________"
# TODO 14: show the plot
"_______"
# + [markdown] id="INda04TR7qeq"
# ## Visualisation
# + [markdown] id="cUnJFqmi3j_Z"
# ### Create Image
# + [markdown] id="LUmh5XN9RPIh"
# ###### **<font color='blue'>TO DO 15</font> :** create a variable `height` using the 2nd element of `dims`
# + id="YzKIQmAqRs0C"
# Covert resolution level to number of pixels
px = resolution_map(RESOLUTION)
width = px * dims[0]
# TODO 15: create a variable `height` using the 2nd element of `dims`
"___________________"
# Create empty grid to store cover art
art_grid = np.empty((height, width, 3))
for i, row in sampled_track_df.iterrows():
res = requests.get(row['art_url'])
img = Image.open(BytesIO(res.content))
img = img.resize((px, px), Image.ANTIALIAS).convert('RGB')
art_grid[px * grid[i, 1]:px * (grid[i, 1] + 1),
px * grid[i, 0]:px * (grid[i, 0] + 1)] = np.array(img)
# + id="uNlEFTy_RQ9S"
# Create empty grid to store cover art
art_grid = np.empty((height, width, 3))
for i, row in sampled_track_df.iterrows():
res = requests.get(row['art_url'])
img = Image.open(BytesIO(res.content))
img = img.resize((px, px), Image.ANTIALIAS).convert('RGB')
art_grid[px * grid[i, 1]:px * (grid[i, 1] + 1),
px * grid[i, 0]:px * (grid[i, 0] + 1)] = np.array(img)
# + [markdown] id="tFIJ8znk4SOs"
# ### Interactive Visualisation
# + [markdown] id="3mMNg61ZR1DB"
# ###### **<font color='blue'>TO DO 16</font> :** further below set the y axis visibility and range (using `height`) alike what was done with x
# + id="CF9WUj-VUgK_"
fig = go.Figure()
# Add invisible markers in the corners to help with autoscaling
fig.add_trace(go.Scatter(
x=[0, width], y=[0, height],
mode='markers', marker_opacity=0
))
# Add background image
fig.add_layout_image({
'x': 0, 'sizex': width, 'xref': 'x',
'y': height, 'sizey': height, 'yref': 'y',
'opacity': 1.0, 'layer': 'below', 'sizing': 'stretch',
# Images are plotted downwards so reverse first axis
'source': Image.fromarray(art_grid.astype(np.uint8))
})
# Add labels through an invisible heatmap
x = [px // 2 + px * i for i in range(dims[0])]
y = [px // 2 + px * j for j in range(dims[1])]
# Add `included` as a second argument to show audio features on hover
hover_text = create_hover_text(sampled_track_df)
labels = np.empty(dims[::-1], dtype='object')
for i in range(len(sampled_track_df)):
labels[dims[1] - 1 - grid[i, 1], grid[i, 0]] = hover_text[i]
z = np.random.uniform(size=dims[::-1]) # random values for invisible heatmap
fig.add_trace(go.Heatmap(
x=x, y=y, z=z, hovertemplate = '%{text}', text=labels,
opacity=0, showscale=False
))
fig.update_xaxes(
visible=False,
range=[0, width]
)
fig.update_yaxes(
# TODO 16: set axis visibility to false and range (using `height`)
# as was done with the x-axis above
"___________",
"_______________",
# Fix aspect ratio
scaleanchor='x'
)
fig.update_layout(
width=width,
height=height,
margin={"l": 0, "r": 0, "t": 0, "b": 0},
plot_bgcolor='black'
)
# Disable the autosize on double click because it adds unwanted margins
fig.show(config={'doubleClick': 'reset'})
# + [markdown] id="jGT8Z7QD4Vj9"
# ### Image Export
# + id="OKYlX95MRUiC"
# Save image to files - download from the sidebar
Image.fromarray(art_grid.astype(np.uint8)).save('wall_of_music.png')
|
Spotify_Workshop_final.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import quandl
mydata = quandl.get('WIKI/AAPL.1')#,api_key="<KEY>")
import matplotlib.pyplot as plt
# %matplotlib inline
mydata['Open'].plot()
len(mydata)
mydata.head()
|
Data Sources/Quandl.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# +
import uuid
import json
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# -
service_load_balancer = 'http://localhost:8000'
session_id = uuid.uuid4().hex
user_phone_number = 'my_did'
request_content = {'auth_id': session_id, 'recipient': user_phone_number}
result = requests.post(service_load_balancer, json=request_content, verify=False)
assert result.status_code == 200
print(result.text)
# An equivalent curl request:
# ~~~
# curl -v -X POST -d '{"auth_id": "<PASSWORD>256", "recipient": "12069928996"}' -H "Content-Type: application/json" -k https://sms-proxy-lb-1041651126.us-west-2.elb.amazonaws.com
# ~~~
# Now lets make 4 bad attempts to see the behavior, and then we'll generate another code (currently the invalid attempts threshold is 3, and the expiration window is 1 hour)
for invalid_code in ('1232', '9999', '0000000', '44444'):
authorization_args = {'auth_id': session_id, 'code': invalid_code}
response = requests.get(service_load_balancer, params=authorization_args, verify=False)
print(response.text)
result = requests.post(service_load_balancer, json=request_content, verify=False)
print(result.text)
valid_code = '7293' # Fill me in
authorization_args = {'auth_id': session_id, 'code': valid_code}
response = requests.get(service_load_balancer, params=authorization_args, verify=False)
print(response.text)
|
SMS-Authorization.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# + [markdown] id="avmEdecZgjlq"
# ### Gaussian High-pass and Low-pass filters in frequency domain
#
#
# + id="rAUGqM13gjls" executionInfo={"status": "ok", "timestamp": 1648151917035, "user_tz": 240, "elapsed": 875, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10876194588433798562"}}
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
from scipy import signal
from matplotlib.pyplot import imshow
from PIL import Image
import cv2
from scipy import signal
from scipy.fftpack import fft2, fftshift, ifftshift, ifft2
# + id="xt4RTwsHgjlt" executionInfo={"status": "ok", "timestamp": 1648151951156, "user_tz": 240, "elapsed": 985, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10876194588433798562"}}
new_im=cv2.imread("/content/fantasy.jpeg",0) # convert to greyscale
new_im=cv2.resize(new_im, (512,512))# first width, second height
# + colab={"base_uri": "https://localhost:8080/", "height": 287} id="YKWm6l30gjlt" executionInfo={"status": "ok", "timestamp": 1648151957967, "user_tz": 240, "elapsed": 1085, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10876194588433798562"}} outputId="eddd446e-857e-4b89-afa3-626e1453d936"
imshow(new_im, cmap='gray')
#new_im
# + [markdown] id="qiUOaDOegjlu"
# ### The Gaussian window is defined by $ w(n)=\exp^{\frac{-1}{2}{\frac{n}{\sigma}}^2}$ where $n$ is the number of pixels in the output window
# + id="VVSnwQJEgjlu" executionInfo={"status": "ok", "timestamp": 1648151962154, "user_tz": 240, "elapsed": 258, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10876194588433798562"}}
# create a 2D-gaussian kernel、filter with the same size of the image
kernel = np.outer(signal.gaussian(new_im.shape[0], 5), signal.gaussian(new_im.shape[1], 5))# outer product of two vectors,
#each representing a 1D Gaussian window of size of 5 points
# find Fourier transform of the image f(x,y)
freq = fft2(new_im)
# generate a kernel whose origin is in the top-left corner
kern=ifftshift(kernel) # h(x,y)
# calculate FFT of the kernel
freq_kernel = fft2(kern)
# multiply in the frequency domain
product = freq*freq_kernel
# compute the final result
# take the inverse transform of the product and display the real part
im_out = ifft2(product).real # output blurred image
# + colab={"base_uri": "https://localhost:8080/"} id="-z9DmQERgjlv" executionInfo={"status": "ok", "timestamp": 1648151963620, "user_tz": 240, "elapsed": 6, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10876194588433798562"}} outputId="3020da89-396c-4e73-b3e1-0e9d6c759a22"
# scale image to original grey-level intensities in the range from 0 to 255
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 255))
scaler = scaler.fit(im_out)
im_out= scaler.transform(im_out)
im_out
# + colab={"base_uri": "https://localhost:8080/", "height": 287} id="zrlSFj5Kgjlv" executionInfo={"status": "ok", "timestamp": 1648151966268, "user_tz": 240, "elapsed": 834, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10876194588433798562"}} outputId="52782f52-eefa-4996-bbf6-8cf69d13d44e"
imshow(im_out, cmap='gray')
# + [markdown] id="cJL0Qoaqgjlw"
# # Question 1: Is this a high-pass or a low-pass Gaussian filter? By modifying slightly the code above, create a 3-pixel Gaussian kernel and output the resulting image. What do you observe when you narrow the size of the Gaussian wiindow?
#
#
# + colab={"base_uri": "https://localhost:8080/", "height": 287} id="IHhfjb7xgjlw" executionInfo={"status": "ok", "timestamp": 1648152025772, "user_tz": 240, "elapsed": 698, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10876194588433798562"}} outputId="22653007-b8ab-410d-f136-bdb7b849810a"
# type your answer here (that includes code)
#This is a low-pass Gaussian filter because the image is being blured.
######Code######
kernel = np.outer(signal.gaussian(new_im.shape[0], 3), signal.gaussian(new_im.shape[1], 3))# outer product of two vectors,
#each representing a 1D Gaussian window of size of 3 points
# find Fourier transform of the image f(x,y)
freq = fft2(new_im)
# generate a kernel whose origin is in the top-left corner
kern=ifftshift(kernel) # h(x,y)
# calculate FFT of the kernel
freq_kernel = fft2(kern)
# multiply in the frequency domain
product = freq*freq_kernel
# compute the final result
# take the inverse transform of the product and display the real part
im_out = ifft2(product).real # output blurred image
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 255))
scaler = scaler.fit(im_out)
im_out= scaler.transform(im_out)
imshow(im_out, cmap='gray')
# The image become less blur becuase the kernel size is more narrowed than 5-pixel.
# + id="qYVn9QE-gjlw"
# high-pass Gaussian filtered image is found by subtracting low-pass filtered image from the original one
# + [markdown] id="7epztUoCgjlw"
# ### Question 2: What would a high-pass Gaussian filter be useful for in the context of image processing?
# + id="DpF9slBDhFsg" executionInfo={"status": "ok", "timestamp": 1648152048551, "user_tz": 240, "elapsed": 346, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "10876194588433798562"}}
#To highlight edges in the image.
#To remove any “background” brightness that varies smoothly across the image.
#To sharpen the image, one can add a high-pass filtered version of the image (multiplied by a fractional scaling factor) to the original image
# + id="ldKQSfM8hG_F"
|
LabExercise7Answer.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.6 (tensorflow)
# language: python
# name: rga
# ---
# # T81-558: Applications of Deep Neural Networks
# **Module 12: Deep Learning and Security**
# * Instructor: [<NAME>](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)
# * For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/).
# # Module 12 Video Material
#
# * Part 12.1: Introduction to the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=_KbUxgyisjM&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_01_ai_gym.ipynb)
# * **Part 12.2: Introduction to Q-Learning** [[Video]](https://www.youtube.com/watch?v=uwcXWe_Fra0&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_02_qlearningreinforcement.ipynb)
# * Part 12.3: Keras Q-Learning in the OpenAI Gym [[Video]](https://www.youtube.com/watch?v=Ya1gYt63o3M&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_03_keras_reinforce.ipynb)
# * Part 12.4: Atari Games with Keras Neural Networks [[Video]](https://www.youtube.com/watch?v=t2yIu6cRa38&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_04_atari.ipynb)
# * Part 12.5: How Alpha Zero used Reinforcement Learning to Master Chess [[Video]](https://www.youtube.com/watch?v=ikDgyD7nVI8&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](t81_558_class_12_05_alpha_zero.ipynb)
#
# # Part 12.2: Introduction to Q-Learning
#
# ### Single Action Cart
#
# Mountain car actions:
#
# * 0 - Apply left force
# * 1 - Apply no force
# * 2 - Apply right force
#
# State values:
#
# * state[0] - Position
# * state[1] - Velocity
#
# The following shows a cart that simply applies full-force to climb the hill. The cart is simply not strong enough. It will need to use momentum from the hill behind it.
# +
import gym
env = gym.make("MountainCar-v0")
env.reset()
done = False
i = 0
while not done:
i += 1
state, reward, done, _ = env.step(2)
env.render()
print(f"Step {i}: State={state}, Reward={reward}")
env.close()
# -
# ### Programmed Car
#
# This is a car that I hand-programmed. It uses a simple rule, but solves the problem. The programmed car constantly applies force to one direction or another. It does not reset. Whatever direction the car is currently rolling, it applies force in that direction. Therefore, the car begins to climb a hill, is overpowered, and rolls backward. However, once it begins to roll backwards force is immediately applied in this new direction.
# +
import gym
env = gym.make("MountainCar-v0")
state = env.reset()
done = False
i = 0
while not done:
i += 1
if state[1]>0:
action = 2
else:
action = 0
state, reward, done, _ = env.step(action)
env.render()
print(f"Step {i}: State={state}, Reward={reward}")
env.close()
# -
# ### Reinforcement Learning
#
# 
#
#
# ### Q-Learning Car
#
# We will now use Q-Learning to produce a car that learns to drive itself. Look out Tesla!
#
# Q-Learning works by building a table that provides a lookup table to determine which of several actions should be taken. As we move through a number of training episodes this table is refined.
# $ Q^{new}(s_{t},a_{t}) \leftarrow (1-\alpha) \cdot \underbrace{Q(s_{t},a_{t})}_{\text{old value}} + \underbrace{\alpha}_{\text{learning rate}} \cdot \overbrace{\bigg( \underbrace{r_{t}}_{\text{reward}} + \underbrace{\gamma}_{\text{discount factor}} \cdot \underbrace{\max_{a}Q(s_{t+1}, a)}_{\text{estimate of optimal future value}} \bigg) }^{\text{learned value}} $
# +
import gym
import numpy as np
def calc_discrete_state(state):
discrete_state = (state - env.observation_space.low)/buckets
return tuple(discrete_state.astype(np.int))
def run_game(q_table, render, should_update):
done = False
discrete_state = calc_discrete_state(env.reset())
success = False
while not done:
# Exploit or explore
if np.random.random() > epsilon:
# Exploit - use q-table to take current best action (and probably refine)
action = np.argmax(q_table[discrete_state])
else:
# Explore - t
action = np.random.randint(0, env.action_space.n)
# Run simulation step
new_state, reward, done, _ = env.step(action)
#
new_state_disc = calc_discrete_state(new_state)
#
if new_state[0] >= env.goal_position:
success = True
# Update q-table
if should_update:
max_future_q = np.max(q_table[new_state_disc])
current_q = q_table[discrete_state + (action,)]
new_q = (1 - LEARNING_RATE) * current_q + LEARNING_RATE * (reward + DISCOUNT * max_future_q)
q_table[discrete_state + (action,)] = new_q
discrete_state = new_state_disc
if render:
env.render()
return success
# +
LEARNING_RATE = 0.1
DISCOUNT = 0.95
EPISODES = 10000
SHOW_EVERY = 1000
DISCRETE_GRID_SIZE = [10, 10]
START_EPSILON_DECAYING = 1
END_EPSILON_DECAYING = EPISODES//2
# +
env = gym.make("MountainCar-v0")
epsilon = 1
epsilon_change = epsilon/(END_EPSILON_DECAYING - START_EPSILON_DECAYING)
buckets = (env.observation_space.high - env.observation_space.low)/DISCRETE_GRID_SIZE
q_table = np.random.uniform(low=-3, high=0, size=(DISCRETE_GRID_SIZE + [env.action_space.n]))
success = False
# +
episode = 0
success_count = 0
while episode<EPISODES:
episode+=1
done = False
if episode % SHOW_EVERY == 0:
print(f"Current episode: {episode}, success: {success_count} ({float(success_count)/SHOW_EVERY})")
success = run_game(q_table, True, False)
success_count = 0
else:
success = run_game(q_table, False, True)
if success:
success_count += 1
# Move epsilon towards its ending value, if it still needs to move
if END_EPSILON_DECAYING >= episode >= START_EPSILON_DECAYING:
epsilon -= epsilon_change
print(success)
# -
run_game(q_table, True, False)
# +
import pandas as pd
df = pd.DataFrame(q_table.argmax(axis=2))
# -
df.columns = [f'v-{x}' for x in range(DISCRETE_GRID_SIZE[0])]
df.index = [f'p-{x}' for x in range(DISCRETE_GRID_SIZE[1])]
df
np.argmax(q_table[(2,0)])
|
t81_558_class_12_02_qlearningreinforcement.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: tf2
# language: python
# name: tf2
# ---
# %load_ext autoreload
# %autoreload 2
import tictactoe
import cProfile
# +
def run():
epsilon_d = {'first value':0.4, 'second value':0.1, 'epsilon change episode':20}
_= tictactoe.learning_stage_cnndqn_variable_epsilon(N_episodes=100, epsilon_d=epsilon_d, agent_type=2, fig_flag=True)
# cProfile.run('run()')
run()
# +
def run():
epsilon_d = {'first value':0.4, 'second value':0.1, 'epsilon change episode':20}
_= tictactoe.learning_stage_cnndqn_variable_epsilon(N_episodes=100, epsilon_d=epsilon_d, agent_type=2, fig_flag=True)
cProfile.run('run()')
#run()
# -
|
.ipynb_checkpoints/cprofile_ttt-checkpoint.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
train = pd.read_csv("train.csv")
test= pd.read_csv("test.csv")
train['education'] = train['education'].replace('basic.9y', 'basic')
train['education'] = train['education'].replace('basic.6y', 'basic')
train['education'] = train['education'].replace('basic.4y', 'basic')
train.shape, test.shape
test['education'] = test['education'].replace('basic.9y', 'basic')
test['education'] = test['education'].replace('basic.6y', 'basic')
test['education'] = test['education'].replace('basic.4y', 'basic')
from sklearn.preprocessing import LabelEncoder
lb = LabelEncoder()
col = ['customer_id', 'job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome']
for cols in col:
train[cols] = lb.fit_transform(train[cols])
col = ['customer_id', 'job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome']
for cols in col:
test[cols] = lb.fit_transform(test[cols])
# +
#picking X and y
X = train.drop(["customer_id", "subscribed"], axis =1)
y = train["subscribed"]
test = test.drop(["customer_id"], axis = 1)
# -
X.columns
X = train[['duration', 'euribor3m', 'cons_conf_idx', 'nr_employed', 'emp_var_rate', 'pdays', 'poutcome', 'month']]
test = pd.read_csv('test.csv')
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, RobustScaler, MinMaxScaler
from sklearn.feature_selection import VarianceThreshold
test = test[['duration', 'euribor3m', 'cons_conf_idx', 'nr_employed', 'emp_var_rate', 'pdays', 'poutcome', 'month']]
# +
filter = VarianceThreshold(0.5)
X = filter.fit_transform(X)
test = filter.transform(test)
# +
scaler = StandardScaler() # MinMaxScaler
X = scaler.fit_transform(X)
test = scaler.transform(test)
# -
import catboost as cat
catm = cat.CatBoostClassifier(random_seed=1996, bootstrap_type='Bernoulli',
iterations=1000, silent=True, eval_metric='Logloss')
# %%time
catm.fit(X, y, eval_set=[(X,y)], early_stopping_rounds=350, verbose=200); #stopping from 350 to 300
cat_pred = catm.predict(test)
cat_pred.shape
import lightgbm as lgb
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import log_loss, plot_confusion_matrix, plot_roc_curve
print("done")
# +
lgbm = lgb.LGBMClassifier(random_state=1996, n_estimators=1000, metric='binary_logloss', learning_rate=0.04, subsample=0.7,
colsample_bytree=0.8, num_leaves=64, reg_alpha=4, min_child_samples=5,subsample_freq=2)
# -
lgbm.fit(X, y, eval_set=[(X,y), (X,y)], verbose=200, early_stopping_rounds=200);
lgb_pred = lgbm.predict(test)
blend = (0.6 * lgb_pred + 0.4)
# +
sample_submission = pd.read_csv("sample_submission.csv")
test_id = sample_submission.customer_id
lgb_df = pd.DataFrame({'customer_id' : test_id, 'subscribed' : lgb_pred})
cat_df = pd.DataFrame({'customer_id' : test_id, 'subscribed' : cat_pred})
blend_df = pd.DataFrame({'customer_id' : test_id, 'subscribed' : blend})
lgb_df.to_csv('lgblast.csv', index=False)
cat_df.to_csv('catlast.csv', index=False)
blend_df.to_csv('blendlast.csv', index=False)
# -
test
|
AI Invasion Hackathon/dsn_hack2.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + code_folding=[0]
# just imports
# %load_ext autoreload
# %autoreload 2
import sys
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils import data
from torch.optim import Adam
from torchvision import transforms
from torchvision import datasets
import numpy as np
from matplotlib import pyplot as plt
from pandas import read_fwf, DataFrame
from tqdm import tqdm_notebook as tqdm
import matplotlib.gridspec as gridspec
from scipy.ndimage.interpolation import rotate
from sklearn.model_selection import train_test_split
# + code_folding=[0]
# local imports
sys.path.append('../')
from VAE.rg_dataset import LRG, BasicDataset
from VAE.loss_funcs import VAE_Loss
from VAE import vae_models
# +
# %%time
data_path = '../data/'
aug=5
lrg_data_set = LRG(use_kittler=True, n_aug=aug, blur=True, catalog_dir=data_path + 'catalog/mrt-table3.txt',
file_dir=data_path + 'lrg')
unlrg_data_set = LRG(use_kittler=True, n_aug=aug, blur=True, catalog_dir=data_path + 'catalog/mrt-table4.txt',
file_dir=data_path + 'unlrg')
# +
batch_size = 16 #supposedly low batch size helps fater convergence
data_loader_lrg = data.DataLoader(lrg_data_set, batch_size=128, shuffle=False)
data_loader_unlrg = data.DataLoader(unlrg_data_set, batch_size=16, shuffle=False)
sample = iter(data_loader_lrg).next()
# -
class VAE(nn.Module):
def __init__(self, lt_dim=4, k=None, batch_norm=True):
super(VAE, self).__init__()
self.k = k
n_layers = len(self.k)
encoder_layers = []
decoder_layers = []
for i in range( n_layers -1) :
in_c, out_c = self.k[i], self.k[i + 1]
if(in_c == 'M'): continue
stride = 1
if out_c == 'M':
stride = 2
i += 1
out_c = self.k[i + 1]
layer = nn.Conv2d(in_c, out_c, kernel_size=3, padding=1, stride=stride)
encoder_layers.append(layer)
if batch_norm:
encoder_layers.append(nn.BatchNorm2d(out_c))
encoder_layers.append(nn.ReLU(inplace=True))
self.encoder = nn.Sequential(*encoder_layers)
for i in range(n_layers - 1, 0, -1):
in_c, out_c = self.k[i], self.k[i - 1]
if(in_c == 'M'): continue
stride = 1
output_padding=0
if out_c == 'M':
stride = 2
i -= 1
out_c = self.k[i - 1]
output_padding=1
layer = nn.ConvTranspose2d(in_c, out_c, kernel_size=3, padding=1,
output_padding=output_padding, stride=stride)
decoder_layers.append(layer)
if batch_norm:
decoder_layers.append(nn.BatchNorm2d(out_c))
decoder_layers.append(nn.ReLU(inplace=True))
self.decoder = nn.Sequential(*decoder_layers[:-1])
self.fc_mu = nn.Sequential(
nn.Linear(self.k[-1]*2*2, lt_dim*2),
nn.Linear(lt_dim*2, lt_dim)
)
self.fc_ep = nn.Sequential(
nn.Linear(self.k[-1]*2*2, lt_dim*2),
nn.Linear(lt_dim*2, lt_dim)
)
self.fc_dc = nn.Linear(lt_dim, self.k[-1]*2*2)
def encode(self, x):
encoded = self.encoder(x)
encoded = encoded.view(-1, self.k[-1]*2*2)
return self.fc_mu(encoded), self.fc_ep(encoded)
def reparameterize(self, mu, logvar):
std = torch.exp(0.5*logvar)
eps = torch.randn_like(std)
if self.training :
return mu + eps*std
return mu
def decode(self, x):
x = F.relu(self.fc_dc(x))
x = x.view(-1, self.k[-1], 2, 2) #reshape
return torch.sigmoid(self.decoder(x))
def forward(self, x):
mu, var = self.encode(x)
z = self.reparameterize(mu, var)
d = self.decode(z)
return d, mu, var
def train_step_vae(mode, device, data_loader, optim, epoch, loss_fun, log_interval=5, beta=1):
model.train()
s = ''
r_loss = 0
batch_sum = 0
avg_r_loss = 0
for batch_idx, (data, target) in enumerate(data_loader):
batch_sum += len(data)
data = data.to(device)
target = Variable(data, requires_grad=False).to(device)
#Forward Pass
optim.zero_grad()
output = model(data)
# BCE Loss
r_loss, g_loss = loss_fun(output, data)
loss = r_loss + (beta * g_loss)
avg_r_loss += r_loss.item()
#Backpropagation
loss.backward()
optim.step()
s = 'Train Epoch: {:3d} [{:5d}/{:5d} ({:3.0f}%)]\tLoss: {:4.4f}\tR_Loss: {:4.4f}\tDKL: {:4.4f}'
s = s.format(epoch, batch_sum, len(data_loader.dataset),
100. * batch_idx / len(data_loader), loss.item()/len(data),
r_loss.item()/len(data), g_loss.item()/len(data))
if batch_idx % log_interval == 0:
sys.stdout.write('{}\r'.format(s))
sys.stdout.flush()
return s, avg_r_loss / batch_sum
def test_step_vae(model, device, data_loader, loss_fun, learn_rot=False):
model.eval()
avg_r_loss = 0
batch_sum = 0
for batch_idx, (data, target) in enumerate(data_loader):
batch_sum += len(data)
with torch.no_grad():
data = data.to(device)
#Forward Pass
output = model(data)
# BCE Loss
r_loss , g_loss = loss_fun(output, data)
avg_r_loss += r_loss.item()
return avg_r_loss / batch_sum
device = 'cuda'
epochs = 40
# +
k = [1, 16, 'M', 32, 'M', 64, 64,'M', 64, 'M', 128, 128, 'M', 256]
model = VAE(lt_dim=8, k=k).to(device)
# model = vae_models.VAE().to(device)
optimizer = Adam(model.parameters(), lr=0.0005, weight_decay=1E-5)
loss_fun = VAE_Loss()
train_loss = []
test_loss = []
for epoch in range(1, epochs+1):
#LRG, forced params
start = time.time()
s, l = train_step_vae(model, device, data_loader_unlrg, optimizer, epoch, loss_fun=loss_fun)
loss = test_step_vae(model, device, data_loader_lrg, loss_fun=loss_fun)
train_loss.append(l)
test_loss.append(loss)
t = time.time() - start
sys.stdout.write('{}\tAvgR {:.4f}\tTest Loss : {:4.4f} Time : {:.2f}s\n'.format(s, l, loss, t))
if epoch % 10 == 0:
f, ax = plt.subplots(1, 3, figsize=(10, 5))
o = model(sample[0].to(device))
ax[0].imshow(sample[0][1][0], cmap='gray')
ax[1].imshow(o[0][1][0].detach().cpu(), cmap='gray')
diff = sample[0][1][0] - o[0][1][0].detach().cpu()
ax[2].imshow(np.abs(diff), cmap='gray')
ax[0].axis('off')
ax[1].axis('off')
ax[2].axis('off')
plt.show()
# -
i = 1
plt.imshow(sample[0][i][0])
o = model(sample[0].to(device))
# +
# o.shape
# -
plt.imshow(o[0][i][0].detach().cpu())
torch.save(model, 'SimpleVAE')
s = sample[0][i:i+1]
with torch.no_grad():
e = model.encode(s.to(device))[0]
with torch.no_grad():
d = model.decode(e)
plt.imshow(d[0][0].cpu())
# +
f, ax = plt.subplots(1, 9, figsize=(40, 20))
j = 7
for k, i in enumerate(np.arange(-2, 2.5, .5)):
b = torch.tensor(e)
b[0][j] = e[0][j] + 2*i
with torch.no_grad():
d = model.decode(b).cpu()[0][0]
ax[k].imshow(d, cmap='gray')
ax[k].axis('off')
# -
e[0][6]
b = torch.tensor(e)
b[0][0] = 0
np.arange(-4, 4.5, 1)
|
notebooks/SimpleVAE.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Predicting the costs of used cars
# ### Features: <font size=3>
# <ul>
# <li>Name: The brand and model of the car.</li>
# <li>Location: The location in which the car is being sold or is available for purchase.</li>
# <li>Year: The year or edition of the model.</li>
# <li>Kilometers_Driven: The total kilometres driven in the car by the previous owner(s) in KM.</li>
# <li>Fuel_Type: The type of fuel used by the car.</li>
# <li>Transmission: The type of transmission used by the car.</li>
# <li>Owner_Type: Whether the ownership is Firsthand, Second hand or other.</li>
# <li>Mileage: The standard mileage offered by the car company in kmpl or km/kg</li>
# <li>Engine: The displacement volume of the engine in cc.</li>
# <li>Power: The maximum power of the engine in bhp.</li>
# <li>Seats: The number of seats in the car.</li>
# <li>Price: The price of the used car in INR Lakhs.</li>
# </ul>
# +
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %matplotlib inline
import seaborn as sns
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.filterwarnings("ignore", category=RuntimeWarning)
# +
cars = pd.read_excel("Data_Train (1).xlsx")
cars.info()
# -
cars.head()
cars.isnull().sum()
# We have-
# 1. 2 null values in Mileage
# 2. 36 null values in Engine
# 3. 36 null values in Power
# 4. 42 null values in Seats
# +
# target variable: price of car
fig, ax= plt.subplots(1,2,figsize=(15,5))
sns.distplot(cars['Price'], norm_hist=False, kde=False, ax=ax[0], color='blue')
ax[0].set_xlabel('Car Price')
ax[0].set_ylabel('Count of cars',size=20)
ax[0].set_title('Count Of Cars By Price',size=15,weight="bold")
sns.distplot(cars['Price'], kde=True, ax=ax[1], color='green')
ax[1].set_xlabel('Car Price')
ax[1].set_ylabel('Relative Frequency of cars',size=20)
ax[1].set_title('Density or Relative Frequency Of Cars By Price',size=15,weight="bold")
# -
# # Observations on Target Variable- Price:
#
# The target variable price has a positive skew, however majority of the cars are low priced.
#
# More than 50% of the cars are priced between 2 to 15 lakhs and close to 17% cars are priced between 20 to 40 lakhs. So around 85% of cars in market are priced between 2 to 40lakhs.
cars.Price.min()
sns.distplot(cars['Year'])
sns.distplot(cars['Kilometers_Driven'])
cars.Location.value_counts().plot(kind='bar')
plt.title("City",fontdict={'fontsize':16})
# Cars are mostly purchased in Mumbai and Hyderabad citites.
cars.Year.value_counts().sort_index().plot(kind='bar')
plt.title("Year",fontdict={'fontsize':16})
# Sale of cars increased from 1999-2014 and then decreased to some extent during 2014-2019
cars.Owner_Type.value_counts().plot(kind='bar')
plt.title("Owner_type",fontdict={'fontsize':16})
# Most of the people prefered first hand i.e, new cars.
cars.Transmission.value_counts().plot(kind='bar')
plt.title("Transmission",fontdict={'fontsize':16})
# More than 50% opted for manual driving cars
plt.figure(figsize=(20,15))
sns.boxplot(cars['Price'])
plt.title("Price",fontdict={'fontsize':16})
# Most of the people opted to buy cars in the range 3,00,000-10,00,000
#
plt.figure(figsize=(20,5))
cars['Engine'].value_counts().head(50).plot.bar()
plt.figure(figsize=(20,5))
cars['Power'].value_counts().head(50).plot.bar()
cars.head()
# Categorical variables visualisation
plt.figure(figsize=(30,10))
plt.subplot(1,2,1)
sns.countplot(x='Fuel_Type',data=cars)
plt.subplot(1,2,2)
sns.countplot(x='Location',data=cars)
plt.show()
plt.figure(figsize=(30,10))
plt.subplot(1,2,1)
sns.countplot(x='Year',data=cars)
plt.subplot(1,2,2)
sns.countplot(x='Transmission',data=cars)
plt.show()
cars.head()
Name=cars["Name"].str.split(" ",n =5,expand = True)
cars.drop(['Name'],axis=1,inplace=True)
cars=pd.concat([cars,Name],axis=1)
cars.head()
cars["Mileage"]= cars["Mileage"].str.split(" ",n =1,expand = True)
cars["Mileage"]= cars["Mileage"][0]
cars["Engine"]= cars["Engine"].str.split(" ",n =1,expand = True)
cars["Engine"]= cars["Engine"][0]
cars["Power"]= cars["Power"].str.split(" ",n =1,expand = True)
cars["Power"]= cars["Power"][0]
plt.figure(figsize = (30,30))
plt.subplot(3,2,1)
sns.boxplot(x = 'Fuel_Type', y = 'Price', data = cars)
plt.subplot(3,2,2)
sns.boxplot(x = 'Transmission', y = 'Price', data = cars)
plt.subplot(3,2,3)
sns.boxplot(x = 'Owner_Type', y = 'Price', data = cars)
plt.subplot(3,2,4)
sns.boxplot(x = 'Location', y = 'Price', data = cars)
plt.subplot(3,2,5)
sns.boxplot(x = 'Seats', y = 'Price', data = cars)
plt.subplot(3,2,6)
sns.boxplot(x = 'Year', y = 'Price', data = cars)
plt.figure(figsize = (30,15))
sns.boxplot(x = 0, y = 'Price', data = cars)
# 1. From the price boxplot it is clear that The brands with the most expensive vehicles in the dataset belong to Audi, LandRover , Bmw, Jaguar and Porsche.
# 2. Whereas the lower priced cars belong to Maruti, Hyundai, Honda, Nissan, Tata, Ford, Fiat and Chevrolet.
# 3. The median price of gas vehicles is lower than that of Diesel Vehicles.
# 4. 75th percentile of standard aspirated vehicles have a price lower than the median price of turbo aspirated vehicles.
# Model selection by assigning dummies
Brand=pd.get_dummies(cars[0],drop_first=True)
Model=pd.get_dummies(cars[1],drop_first=True)
Version=pd.get_dummies(cars[2],drop_first=True)
type1=pd.get_dummies(cars[3],drop_first=True)
type2=pd.get_dummies(cars[4],drop_first=True)
type3=pd.get_dummies(cars[5],drop_first=True)
Location=pd.get_dummies(cars['Location'],drop_first=True)
Fuel_Type=pd.get_dummies(cars['Fuel_Type'],drop_first=True)
Transmission=pd.get_dummies(cars['Transmission'],drop_first=True)
Owner_Type=pd.get_dummies(cars['Owner_Type'],drop_first=True)
cars.drop([0,1,2,3,4,5,'Location','Fuel_Type','Transmission',
'Owner_Type'],axis=1,inplace=True)
cars=pd.concat([cars,Brand,Model,Version,type1,type2,type3,Location,Fuel_Type,Transmission,
Owner_Type],axis=1)
cars.head(1000)
X=cars[cars.Price<80].drop(['Price'],axis=1)
y=cars[cars.Price<80]['Price']
# +
from sklearn.impute import SimpleImputer
#Training Set Imputation
imputer = SimpleImputer(missing_values = np.nan, strategy = 'most_frequent')
imputer = imputer.fit(X)
X = imputer.transform(X)
# +
#Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
#Scaling Original Training Data
X = sc.fit_transform(X)
# # y = sc.fit_transform(y)
# -
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test= train_test_split(X,y, test_size=0.3,random_state=101)
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV
import math
from math import log
hyperparameters= dict(n_estimators=[1,2,4,8,16,32,64,100,200], max_depth=np.linspace(1,32,32, endpoint=True),min_samples_split=[1,2,5,10,15,100],min_samples_leaf=[1,2,5,10],max_features=[math.log2,math.sqrt, None])
clf=RandomizedSearchCV(RandomForestRegressor(), hyperparameters, random_state=1, cv=5, verbose=0,scoring='neg_mean_squared_error')
best_model=clf.fit(X_train,y_train)
best_model.best_params_
clf=RandomForestRegressor(n_estimators=200,
min_samples_split=10,
min_samples_leaf=2,
max_features=None,
max_depth=32.0)
clf.fit(X_train,y_train)
y_pred=clf.predict(X_test)
from sklearn.metrics import r2_score
r2_score(y_test,y_pred)
plt.scatter(y_test, y_pred)
from sklearn import metrics
metrics.explained_variance_score(y_test, y_pred)
metrics.mean_absolute_error(y_test, y_pred)
from sklearn.metrics import mean_squared_error
from math import sqrt
rms = sqrt(mean_squared_error(y_test, y_pred))
print(rms)
from sklearn.metrics import mean_absolute_error
print("Mean Absolute Error:",mean_absolute_error(y_test, y_pred))
#Test set
cars_test = pd.read_excel("Data_Test (1).xlsx")
cars_test.info()
cars_test.head()
Name=cars_test["Name"].str.split(" ",n =5,expand = True)
cars_test.drop(['Name'],axis=1,inplace=True)
cars_test=pd.concat([cars_test,Name],axis=1)
cars_test.head()
cars_test["Mileage"]= cars_test["Mileage"].str.split(" ",n =1,expand = True)
cars_test["Mileage"]= cars_test["Mileage"][0]
cars_test["Engine"]= cars_test["Engine"].str.split(" ",n =1,expand = True)
cars_test["Engine"]= cars_test["Engine"][0]
cars_test["Power"]= cars_test["Power"].str.split(" ",n =1,expand = True)
cars_test["Power"]= cars_test["Power"][0]
Brand=pd.get_dummies(cars_test[0],drop_first=True)
Model=pd.get_dummies(cars_test[1],drop_first=True)
Version=pd.get_dummies(cars_test[2],drop_first=True)
type1=pd.get_dummies(cars_test[3],drop_first=True)
type2=pd.get_dummies(cars_test[4],drop_first=True)
type3=pd.get_dummies(cars_test[5],drop_first=True)
Location=pd.get_dummies(cars_test['Location'],drop_first=True)
Fuel_Type=pd.get_dummies(cars_test['Fuel_Type'],drop_first=True)
Transmission=pd.get_dummies(cars_test['Transmission'],drop_first=True)
Owner_Type=pd.get_dummies(cars_test['Owner_Type'],drop_first=True)
# +
cars_test.drop([0,1,2,3,4,5,'Location','Fuel_Type','Transmission',
'Owner_Type'],axis=1,inplace=True)
cars_test=pd.concat([cars_test,Brand,Model,Version,type1,type2,type3,Location,Fuel_Type,Transmission,
Owner_Type],axis=1)
# -
cars_test.head()
X=cars_test
# +
from sklearn.impute import SimpleImputer
#Training Set Imputation
imputer = SimpleImputer(missing_values = np.nan, strategy = 'most_frequent')
imputer = imputer.fit(X)
X = imputer.transform(X)
#Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
#Scaling Original Test Data
X_test_set = sc.fit_transform(X)
# -
# Predicting the price of the cars present in the test test
y_pred_test_set=clf.predict(X_test_set)
#
#
#
#
# # Opting for Label Encoder in order to overcome the above problem
df=pd.read_excel('Data_Train (1).xlsx')
dt=pd.read_excel('Data_Test (1).xlsx')
# # Data Cleaning
# Spliting "Name" Feature to 'Brand', 'CarName' and 'Model'.
def splitName(x):
x['Brand'] = x['Name'].apply(lambda x: x.split(' ')[0].strip())
x['CarName'] = x['Name'].apply(lambda x: x.split(' ')[1].strip())
x['Model'] = x['Name'].apply(lambda x:' '.join(x.split(' ')[2:]))
x.drop(['Name'],axis=1, inplace=True)
# # Finding Missing Values
#Splitting Power, Engine, & Mileage to remove Units
def splitIn(x):
x['Power' ].replace('null bhp',np.nan,inplace=True)
x['Mileage'].replace('0.0 kmpl',np.nan,inplace=True)
for i in ['Power', 'Engine', 'Mileage']:
x[i] = x[i].apply(lambda x: float(x.split()[0].strip()) if not pd.isna(x) else x)
def imputeNaN(x):
for i in ['Power', 'Engine', 'Seats','Mileage']:
x[i] = x.groupby(['Model'])[i].transform(lambda y: y.fillna(y.mean()))
#Some Values will still be left with na.
x[i].fillna(x[i].mean(), inplace=True)
def preprocessData(data):
splitName(data)
splitIn(data)
imputeNaN(data)
preprocessData(df)
preprocessData(dt)
df.head()
# # Visualising the data some more data
df.plot(kind='scatter',x='Engine',y='Power')
plt.show()
sns.jointplot(kind='scatter',x='Engine',y='Mileage',data=df)
plt.show()
df.plot(kind='scatter',x='Engine',y='Price')
plt.show()
sns.lmplot(x='Engine',y='Mileage',data=df,hue='Transmission',fit_reg=False)
plt.show()
plt.figure(figsize=(30,5))
plt.subplot(1,2,1)
sns.countplot(x='Fuel_Type', hue='Transmission', data=df);
plt.subplot(1,2,2)
sns.countplot(x='Location', hue='Transmission', data=df);
plt.show()
pd.crosstab(df['Brand'], df['Transmission']).T
# # Categorizing the variables
# +
from sklearn.preprocessing import LabelEncoder
le_brands= LabelEncoder()
le_models = LabelEncoder()
le_locations = LabelEncoder()
le_fuel_types = LabelEncoder()
le_transmissions = LabelEncoder()
le_owner_types = LabelEncoder()
all_brands = list(set(list(df.Brand))) + list(dt.Brand)
all_models = list(set(list(df.Model))) + list(dt.Model)
all_locations = list(set(list(df.Location))) + list(dt.Location)
all_fuel_types = list(set(list(df.Fuel_Type))) + list(dt.Fuel_Type)
all_transmissions = list(set(list(df.Transmission))) + list(dt.Transmission)
all_owner_types = list(set(list(df.Owner_Type))) + list(dt.Owner_Type)
le_brands.fit(all_brands)
le_models.fit(all_models)
le_locations.fit(all_locations)
le_fuel_types.fit(all_fuel_types)
le_transmissions.fit(all_transmissions)
le_owner_types.fit(all_owner_types)
# -
df['Brand'] = le_brands.transform(df['Brand'])
df['Model'] = le_models.transform(df['Model'])
df['Location'] = le_locations.transform(df['Location'])
df['Fuel_Type'] = le_fuel_types.transform(df['Fuel_Type'])
df['Transmission'] = le_transmissions.transform(df['Transmission'])
df['Owner_Type'] = le_owner_types.transform(df['Owner_Type'])
dt['Brand'] = le_brands.transform(dt['Brand'])
dt['Model'] = le_models.transform(dt['Model'])
dt['Location'] = le_locations.transform(dt['Location'])
dt['Fuel_Type'] = le_fuel_types.transform(dt['Fuel_Type'])
dt['Transmission'] = le_transmissions.transform(dt['Transmission'])
dt['Owner_Type'] = le_owner_types.transform(dt['Owner_Type'])
df.head()
#Re-ordering the columns
df = df[['Brand', 'Model', 'Location', 'Year', 'Kilometers_Driven', 'Fuel_Type', 'Transmission',
'Owner_Type', 'Mileage', 'Engine', 'Power', 'Seats', 'Price']]
dt = dt[['Brand', 'Model', 'Location', 'Year', 'Kilometers_Driven', 'Fuel_Type', 'Transmission',
'Owner_Type', 'Mileage', 'Engine', 'Power', 'Seats']]
dt.head()
Y_train_data = df.iloc[:, -1]
X_train_data = df.iloc[:,0 : -1]
X_test = dt.iloc[:,:]
# +
from sklearn.model_selection import train_test_split
#Splitting the training set into Training and validation sets
X_train, X_val, Y_train, Y_val = train_test_split(X_train_data, Y_train_data, test_size = 0.2)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train_data = sc.fit_transform(X_train_data)
Y_train_data = Y_train_data.values.reshape((len(Y_train_data), 1))
# -
# # Model
#XGBoost
from sklearn.model_selection import GridSearchCV
from xgboost import XGBRegressor
xgb = XGBRegressor(n_estimators = 500,learning_rate=0.1, max_depth=4, min_child_weight=2, n_jobs=4)
xgb.fit(X_train, Y_train,
early_stopping_rounds=5,
eval_set=[(X_val, Y_val)],
verbose=False)
Y_pred = xgb.predict(X_val)
def score(y_pred, y_true):
error = np.square(np.log10(y_pred +1) - np.log10(y_true +1)).mean() ** 0.5
score = 1 - error
return score
# +
#Eliminating negative values in prediction for score calculation
for i in range(len(Y_pred)):
if Y_pred[i] < 0:
Y_pred[i] = 0
y_true = Y_val
# +
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import cross_val_score
from statistics import mean
print("Score: ",score(Y_pred,y_true))
print("Mean Absolute Error:",mean_absolute_error(y_true, Y_pred))
# -
plt.scatter(y_true, Y_pred)
from sklearn import metrics
metrics.explained_variance_score(y_true, Y_pred)
from sklearn.metrics import r2_score
r2_score(y_true, Y_pred)
predictions=xgb.predict(X_test)
predictions
predictions.mean()
df['Price'].mean()
#Saving the predictions to an excel sheet
pd.DataFrame(predictions, columns = ['Price']).to_excel("predictions.xlsx")
|
Car_Price_Project.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] colab_type="text"
# # Text classification from scratch
#
# **Authors:** <NAME>, <NAME><br>
# **Date created:** 2019/11/06<br>
# **Last modified:** 2020/05/17<br>
# **Description:** Text sentiment classification starting from raw text files.
# + [markdown] colab_type="text"
# ## Introduction
#
# This example shows how to do text classification starting from raw text (as
# a set of text files on disk). We demonstrate the workflow on the IMDB sentiment
# classification dataset (unprocessed version). We use the `TextVectorization` layer for
# word splitting & indexing.
# + [markdown] colab_type="text"
# ## Setup
# + colab_type="code"
import tensorflow as tf
import numpy as np
# + [markdown] colab_type="text"
# ## Load the data: IMDB movie review sentiment classification
#
# Let's download the data and inspect its structure.
# + colab_type="code"
# !curl -O https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
# !tar -xf aclImdb_v1.tar.gz
# + [markdown] colab_type="text"
# The `aclImdb` folder contains a `train` and `test` subfolder:
# + colab_type="code"
# !ls aclImdb
# + colab_type="code"
# !ls aclImdb/test
# + colab_type="code"
# !ls aclImdb/train
# + [markdown] colab_type="text"
# The `aclImdb/train/pos` and `aclImdb/train/neg` folders contain text files, each of
# which represents one review (either positive or negative):
# + colab_type="code"
# !cat aclImdb/train/pos/6248_7.txt
# + [markdown] colab_type="text"
# We are only interested in the `pos` and `neg` subfolders, so let's delete the rest:
# + colab_type="code"
# !rm -r aclImdb/train/unsup
# + [markdown] colab_type="text"
# You can use the utility `tf.keras.preprocessing.text_dataset_from_directory` to
# generate a labeled `tf.data.Dataset` object from a set of text files on disk filed
# into class-specific folders.
#
# Let's use it to generate the training, validation, and test datasets. The validation
# and training datasets are generated from two subsets of the `train` directory, with 20%
# of samples going to the validation dataset and 80% going to the training dataset.
#
# Having a validation dataset in addition to the test dataset is useful for tuning
# hyperparameters, such as the model architecture, for which the test dataset should not
# be used.
#
# Before putting the model out into the real world however, it should be retrained using all
# available training data (without creating a validation dataset), so its performance is maximized.
#
# When using the `validation_split` & `subset` arguments, make sure to either specify a
# random seed, or to pass `shuffle=False`, so that the validation & training splits you
# get have no overlap.
# + colab_type="code"
batch_size = 32
raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory(
"aclImdb/train",
batch_size=batch_size,
validation_split=0.2,
subset="training",
seed=1337,
)
raw_val_ds = tf.keras.preprocessing.text_dataset_from_directory(
"aclImdb/train",
batch_size=batch_size,
validation_split=0.2,
subset="validation",
seed=1337,
)
raw_test_ds = tf.keras.preprocessing.text_dataset_from_directory(
"aclImdb/test", batch_size=batch_size
)
print(
"Number of batches in raw_train_ds: %d"
% tf.data.experimental.cardinality(raw_train_ds)
)
print(
"Number of batches in raw_val_ds: %d" % tf.data.experimental.cardinality(raw_val_ds)
)
print(
"Number of batches in raw_test_ds: %d"
% tf.data.experimental.cardinality(raw_test_ds)
)
# + [markdown] colab_type="text"
# Let's preview a few samples:
# + colab_type="code"
# It's important to take a look at your raw data to ensure your normalization
# and tokenization will work as expected. We can do that by taking a few
# examples from the training set and looking at them.
# This is one of the places where eager execution shines:
# we can just evaluate these tensors using .numpy()
# instead of needing to evaluate them in a Session/Graph context.
for text_batch, label_batch in raw_train_ds.take(1):
for i in range(5):
print(text_batch.numpy()[i])
print(label_batch.numpy()[i])
# + [markdown] colab_type="text"
# ## Prepare the data
#
# In particular, we remove `<br />` tags.
# + colab_type="code"
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
import string
import re
# Having looked at our data above, we see that the raw text contains HTML break
# tags of the form '<br />'. These tags will not be removed by the default
# standardizer (which doesn't strip HTML). Because of this, we will need to
# create a custom standardization function.
def custom_standardization(input_data):
lowercase = tf.strings.lower(input_data)
stripped_html = tf.strings.regex_replace(lowercase, "<br />", " ")
return tf.strings.regex_replace(
stripped_html, "[%s]" % re.escape(string.punctuation), ""
)
# Model constants.
max_features = 20000
embedding_dim = 128
sequence_length = 500
# Now that we have our custom standardization, we can instantiate our text
# vectorization layer. We are using this layer to normalize, split, and map
# strings to integers, so we set our 'output_mode' to 'int'.
# Note that we're using the default split function,
# and the custom standardization defined above.
# We also set an explicit maximum sequence length, since the CNNs later in our
# model won't support ragged sequences.
vectorize_layer = TextVectorization(
standardize=custom_standardization,
max_tokens=max_features,
output_mode="int",
output_sequence_length=sequence_length,
)
# Now that the vocab layer has been created, call `adapt` on a text-only
# dataset to create the vocabulary. You don't have to batch, but for very large
# datasets this means you're not keeping spare copies of the dataset in memory.
# Let's make a text-only dataset (no labels):
text_ds = raw_train_ds.map(lambda x, y: x)
# Let's call `adapt`:
vectorize_layer.adapt(text_ds)
# + [markdown] colab_type="text"
# ## Two options to vectorize the data
#
# There are 2 ways we can use our text vectorization layer:
#
# **Option 1: Make it part of the model**, so as to obtain a model that processes raw
# strings, like this:
# + [markdown] colab_type="text"
# ```python
# text_input = tf.keras.Input(shape=(1,), dtype=tf.string, name='text')
# x = vectorize_layer(text_input)
# x = layers.Embedding(max_features + 1, embedding_dim)(x)
# ...
# ```
#
# **Option 2: Apply it to the text dataset** to obtain a dataset of word indices, then
# feed it into a model that expects integer sequences as inputs.
#
# An important difference between the two is that option 2 enables you to do
# **asynchronous CPU processing and buffering** of your data when training on GPU.
# So if you're training the model on GPU, you probably want to go with this option to get
# the best performance. This is what we will do below.
#
# If we were to export our model to production, we'd ship a model that accepts raw
# strings as input, like in the code snippet for option 1 above. This can be done after
# training. We do this in the last section.
#
# + colab_type="code"
def vectorize_text(text, label):
text = tf.expand_dims(text, -1)
return vectorize_layer(text), label
# Vectorize the data.
train_ds = raw_train_ds.map(vectorize_text)
val_ds = raw_val_ds.map(vectorize_text)
test_ds = raw_test_ds.map(vectorize_text)
# Do async prefetching / buffering of the data for best performance on GPU.
train_ds = train_ds.cache().prefetch(buffer_size=10)
val_ds = val_ds.cache().prefetch(buffer_size=10)
test_ds = test_ds.cache().prefetch(buffer_size=10)
# + [markdown] colab_type="text"
# ## Build a model
#
# We choose a simple 1D convnet starting with an `Embedding` layer.
# + colab_type="code"
from tensorflow.keras import layers
# A integer input for vocab indices.
inputs = tf.keras.Input(shape=(None,), dtype="int64")
# Next, we add a layer to map those vocab indices into a space of dimensionality
# 'embedding_dim'.
x = layers.Embedding(max_features, embedding_dim)(inputs)
x = layers.Dropout(0.5)(x)
# Conv1D + global max pooling
x = layers.Conv1D(128, 7, padding="valid", activation="relu", strides=3)(x)
x = layers.Conv1D(128, 7, padding="valid", activation="relu", strides=3)(x)
x = layers.GlobalMaxPooling1D()(x)
# We add a vanilla hidden layer:
x = layers.Dense(128, activation="relu")(x)
x = layers.Dropout(0.5)(x)
# We project onto a single unit output layer, and squash it with a sigmoid:
predictions = layers.Dense(1, activation="sigmoid", name="predictions")(x)
model = tf.keras.Model(inputs, predictions)
# Compile the model with binary crossentropy loss and an adam optimizer.
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
# + [markdown] colab_type="text"
# ## Train the model
# + colab_type="code"
epochs = 3
# Fit the model using the train and test datasets.
model.fit(train_ds, validation_data=val_ds, epochs=epochs)
# + [markdown] colab_type="text"
# ## Evaluate the model on the test set
# + colab_type="code"
model.evaluate(test_ds)
# + [markdown] colab_type="text"
# ## Make an end-to-end model
#
# If you want to obtain a model capable of processing raw strings, you can simply
# create a new model (using the weights we just trained):
# + colab_type="code"
# A string input
inputs = tf.keras.Input(shape=(1,), dtype="string")
# Turn strings into vocab indices
indices = vectorize_layer(inputs)
# Turn vocab indices into predictions
outputs = model(indices)
# Our end to end model
end_to_end_model = tf.keras.Model(inputs, outputs)
end_to_end_model.compile(
loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]
)
# Test it with `raw_test_ds`, which yields raw strings
end_to_end_model.evaluate(raw_test_ds)
|
examples/nlp/ipynb/text_classification_from_scratch.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + id="dB69OBzHyn-8" colab_type="code" colab={"resources": {"http://localhost:8080/nbextensions/google.colab/files.js": {"data": "<KEY>", "ok": true, "headers": [["content-type", "application/javascript"]], "status": 200, "status_text": ""}}, "base_uri": "https://localhost:8080/", "height": 73} executionInfo={"status": "ok", "timestamp": 1598200054173, "user_tz": -330, "elapsed": 20464, "user": {"displayName": "<NAME>", "photoUrl": "https://<KEY>", "userId": "05738797283356822773"}} outputId="2bf4bc94-3c4b-417c-f880-bc98aac002cd"
from google.colab import files
uploaded = files.upload()
# + [markdown] id="dvjrFo0_0IXN" colab_type="text"
# #IMPORTING LIBRARIES
# + id="KPgPHSveyeNr" colab_type="code" colab={} executionInfo={"status": "ok", "timestamp": 1598200170981, "user_tz": -330, "elapsed": 1723, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
import seaborn as sns
import matplotlib.pyplot as plt
# %matplotlib inline
# + id="ocu0J1bpyeNx" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 266} executionInfo={"status": "ok", "timestamp": 1598200171987, "user_tz": -330, "elapsed": 2712, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}} outputId="1f333a47-ee86-402d-ac16-b44c4065e1a7"
df = pd.read_excel('data_set.xls')
#used to read csv files and perform operations on it
df.head()
# + [markdown] id="zgdYJ7My51qJ" colab_type="text"
# #HANDLING CATEGORICAL DATA
# + id="OqMT00EZ41yu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 134} executionInfo={"status": "ok", "timestamp": 1598200171991, "user_tz": -330, "elapsed": 2698, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}} outputId="6172821f-9fcf-4abf-d385-7333d1fb39dd"
x = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
import pandas as pd
from sklearn.preprocessing import LabelEncoder
x = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
labelencoder_X1 = LabelEncoder()
x[:,0] = labelencoder_X1.fit_transform(x[:,0])
x[:,1] = labelencoder_X1.fit_transform(x[:,1])
print(x)
#Here we are using LabelEncoder
df = df.dropna(how='all',axis=1)
# + [markdown] id="0e78X5or1118" colab_type="text"
# #SPLITTING OF DATA INTO TRAINING AND TEST
# + id="hONDJ5riyeOL" colab_type="code" colab={} executionInfo={"status": "ok", "timestamp": 1598200171994, "user_tz": -330, "elapsed": 2683, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
from sklearn.model_selection import train_test_split
#import model selection train test split for splitting the data into test and train for model validation.
# + id="lpe2icOsyeOP" colab_type="code" colab={} executionInfo={"status": "ok", "timestamp": 1598200171997, "user_tz": -330, "elapsed": 2674, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=101)
# + [markdown] id="HhQfgC0b6ubT" colab_type="text"
# #NORMALIZING DATA
# + id="Udf-XPOX61Kl" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 252} executionInfo={"status": "ok", "timestamp": 1598200172000, "user_tz": -330, "elapsed": 2660, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}} outputId="81c0f61c-54f6-4ebf-cc5b-b62cc6c74329"
# data normalization with sklearn
from sklearn.preprocessing import MinMaxScaler
# fit scaler on training data
norm = MinMaxScaler().fit(x_train)
# transform training data
X_train_norm = norm.transform(x_train)
# transform testing data
X_test_norm = norm.transform(x_test)
print(X_train_norm)
print(X_test_norm)
# + [markdown] id="MGOrd2VS8Bih" colab_type="text"
# #GRAPHS
# + id="Cz3h6lyR_7Rj" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 442} executionInfo={"status": "ok", "timestamp": 1598200172004, "user_tz": -330, "elapsed": 2648, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}} outputId="753470c3-61da-4224-992a-68039696e1a0"
sns.heatmap(df.corr())
# + [markdown] id="Qt0gKxy68UI-" colab_type="text"
# #ALGORITHM
# + id="a3Y9OdRwyeOS" colab_type="code" colab={} executionInfo={"status": "ok", "timestamp": 1598200172007, "user_tz": -330, "elapsed": 2636, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
knn = KNeighborsClassifier(n_neighbors=11,p=2,metric='euclidean')
# + [markdown] id="vJ0pH0B919Uj" colab_type="text"
# #FITTING OF TRAINING DATA
# + id="U6MpZ38SyeOb" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 320} executionInfo={"status": "error", "timestamp": 1598200172033, "user_tz": -330, "elapsed": 2649, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}} outputId="e402c6f0-0a5f-4e39-c34c-bbf16cc67276"
knn.fit(x_train,y_train)
#training or fitting the train data into the model
# + [markdown] id="Z7fhtK-Preyl" colab_type="text"
# #PREDICTIONS FOR OUR PROBLEM STATEMENT WITH THE RELATED GRAPHS
# + id="GzHMpLiryeOw" colab_type="code" colab={} executionInfo={"status": "aborted", "timestamp": 1598200172010, "user_tz": -330, "elapsed": 2609, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
predictions = knn.predict(x_test)
# + id="Xq_2fBqeyeOz" colab_type="code" colab={} executionInfo={"status": "aborted", "timestamp": 1598200172013, "user_tz": -330, "elapsed": 2598, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
plt.scatter(y_test,predictions)
# + [markdown] id="sg2jV8CD2Gm0" colab_type="text"
# #EVALUATION
# + id="eow--Zp3yeO-" colab_type="code" colab={} executionInfo={"status": "aborted", "timestamp": 1598200172015, "user_tz": -330, "elapsed": 2586, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
from sklearn import metrics
print('MAE:', metrics.mean_absolute_error(y_test, predictions))
print('MSE:', metrics.mean_squared_error(y_test, predictions))
print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))
# + id="XGYTumP8JOSr" colab_type="code" colab={} executionInfo={"status": "aborted", "timestamp": 1598200172017, "user_tz": -330, "elapsed": 2573, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
print(metrics.accuracy_score(y_test, predictions))
# + [markdown] id="xTe649WnuRkv" colab_type="text"
# #SAVING THE MODEL USING PICKLE LIBRARY
# + id="s63Y_glZuXg0" colab_type="code" colab={} executionInfo={"status": "aborted", "timestamp": 1598200172019, "user_tz": -330, "elapsed": 2560, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
import pickle
# Save the trained model as a pickle string.
saved_model = pickle.dumps(knn)
# Load the pickled model
lm_from_pickle = pickle.loads(saved_model)
# Use the loaded pickled model to make predictions
lm_from_pickle.predict(x_test)
# + [markdown] id="Olz2qwKZu9h9" colab_type="text"
# #ACCURACY w.r.t TRAINED DATA
# + [markdown] id="llsvY6b8vAgW" colab_type="text"
# Confusion Matrix
#
# + id="ftv_QwkWvC6_" colab_type="code" colab={} executionInfo={"status": "aborted", "timestamp": 1598200172025, "user_tz": -330, "elapsed": 2554, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
from sklearn.metrics import confusion_matrix
predictions=predictions[0:160]
results =confusion_matrix(y_train, predictions)
print(results)
# + [markdown] id="ZE93FHwf2Gga" colab_type="text"
# Precision, Recall, Support, Fscore
# + id="tVRVdFiH2HMw" colab_type="code" colab={} executionInfo={"status": "aborted", "timestamp": 1598200172027, "user_tz": -330, "elapsed": 2546, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
import numpy
from sklearn.metrics import precision_recall_fscore_support
precision_recall_fscore_support(y_train, predictions, average='macro')
# + [markdown] id="KGS7KAWmCNNC" colab_type="text"
# #ACCURACY w.r.t TEST DATA
# + [markdown] id="FlNY8rEtCSDC" colab_type="text"
# Confusion Matrix
# + id="5a1hM-UeCRUF" colab_type="code" colab={} executionInfo={"status": "aborted", "timestamp": 1598200172029, "user_tz": -330, "elapsed": 2534, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
from sklearn.metrics import confusion_matrix
y_test=y_test[0:160]
results =confusion_matrix(y_test, predictions)
print(results)
# + [markdown] colab_type="text" id="g8OMpIMyDDPc"
# Precision, Recall, Support, Fscore
# + id="vp6XSF6ADExP" colab_type="code" colab={} executionInfo={"status": "aborted", "timestamp": 1598200172031, "user_tz": -330, "elapsed": 2523, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjF3rDtmS8I19pKom2yWOQkHNzqP1a6kbyKsm1lIQ=s64", "userId": "05738797283356822773"}}
import numpy
from sklearn.metrics import precision_recall_fscore_support
precision_recall_fscore_support(y_test, predictions, average='macro')
|
K nearest neighbours/ML-KNN/assignment/ML-ASGN-KNN-02/CODE/employee_absenteeism_knn.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # PV181 Seminar 01 - RNG (python)
#
# This notebook contains python code for several tasks treated in this seminar.
# # Task 0: ANSI C example code
# Following code was taken from [ANSI C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf#page=324) and simplified to other portable implementation (according to implementation of [rand()](https://code.woboq.org/userspace/glibc/stdlib/random_r.c.html#__random_r)) of seeding function `srand` and function for generation `rand()`.
#
# ```
# static unsigned long int next = 1;
#
# void srand(unsigned int seed)
# {
# next = seed;
# }
#
# int rand(void) // RAND_MAX assumed to be 32767
# {
# return next = (next * 1103515245 + 12345) & 0x7fffffff;
# }
# ```
# # Task 1: PRNG in general
# Following class defines generic PRNG. Use`class PRNG` and create generator (object `gcc_old`) equivalent to C code from the '''Task 0'''. Just set the functions (`Init`, `Trans`, `Out`) to appropriate functions (one function needs to be defined). Use methods `srand, rand()` to seed the generator with `0` and generate (print out) 10 random values.
# +
def Id(x): #lambda x: x is equivalent to Id
return x
class PRNG:
def __init__(self, Init = Id, Trans = Id, Out = Id ):
self.Init = Init
self.Trans = Trans
self.Out = Out
self.state = self.Init(1)
def srand(self, seed):
self.state = self.Init(seed)
def rand(self):
self.state = self.Trans(self.state)
return self.Out(self.state)
gcc_old = PRNG()
# -
# # Questions 1, 2: problematic `gcc_old`
# Attacker observed value `x` generated by the `gcc_old` generator:
# 1. He is able to predict **next** values. Why?
# 2. He is able also to reconstruct **previous** values. Why?
#
#
# # Task 2: Inverse LCG
# Implement "inverse" generator `gcc_old_inv = PRNG()` that generates the same values as `gcc_old` but in the oposite direction. you need to revert the `Init`, `Trans` and `Out` functions of the `gcc_old`.
#
# **Hint**: It might be useful to use`pow(a,-1, m) ` that computes inverse of a (i.e. $a^{-1} \pmod m$). But negative exponent is allowed in Python 3.8.
# + [markdown] tags=[]
# # Questions 3, 4: combination of weak sources
# Following code collects entropy based on the time (time stamps in nanoseconds).
#
# 1. Why **xor** operation (denoted usually by $\oplus$) of "random" values is not appropriate in this case?
# 2. What (cryptographic?) function would be more appropriate and why?
# -
import time
stamps = [time.time_ns() for i in range(100)]
res = times[0].to_bytes(8, byteorder='big')
for t in times[1:]:
res = bytes(a ^ b for (a, b) in zip(res, t.to_bytes(8, byteorder='big')))
print(res.hex())
# + [markdown] tags=[]
# # Tasks: Testing (voluntary)
# These tasks can be viewd as BONUS tasks hence should be done at the end (after Tasks in C) of the seminar or at home. They provide some insight to required properties of the PRNG output. Also, you learn basics of hypothesis testing that can be used also in other areas (not only in cryptography).
# -
# # Task 3: Basic testing (Frequency test)
# Use the following test of randomness test (called Frequency or Monobit) that analyzes whether frequencies of bits (0 or 1) is roughly equal. Use the `monobit` test and analyze the LCG generator and standard [`random()`](https://docs.python.org/3/library/random.html) that is based on the Mersenne Twister.
# + tags=[]
def monobit(bytes):
num_ones = 0
for byte in bytes:
for i in range(8):
num_ones += (byte >> i) & 1
n = len(bytes)*8
Sobs = abs(n - 2*num_ones) / math.sqrt(n)
p_val = math.erfc(Sobs / math.sqrt(2))
return p_val
pass
# -
# # Question 5: Test interpretation
# How to interpret the resulted $p$-value of the test (Monobit or other one) e.g., 0.0001 or 0.4? The interpretation is based on the following fact: $p$-value is uniformly distributed on [0,1] interval for a **good** RNG i.e. probability that we obtain $p$-value $\leq 0.01$ for good RNG is 1%.
#
# 1. How to interpret result $p$-value $ =10^{-10}$?
# 2. What is more likely for $p$-value $ =10^{-10}$: it is result of good or bad RNG?
#
# See [wiki](https://en.wikipedia.org/wiki/P-value) or [NIST STS documentation](https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-22r1a.pdf).
#
# + [markdown] tags=[]
# # Task 4: Generalized Monobit test
# Use implementation of monobit function and implement `monobit_i(values, i)` which focuses on `i`-th bit of generated values. It counts frequency of `i`-th bit within values in the `value` list. Find which of the bits (of 4 bytes) generated by the `gcc_old` is biased.
# -
def monobit_i(values, i):
pass
# # Task 5: Test for correlation of bits
# Implement function that compute 4 frequencies of combination of bits on $i$-th and $j$-th position of generated values. Than use $\chi^2$ test to analyze that all frequencies should be equal for RNG. You can use `scipy python` modul that already implements [$\chi^2$ test](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chisquare.html).
#
# 1. Check whether some bits ($i$-th, $j$-th) are correlated with the same generated value (i.e. $0\leq i,j \leq 32$)
# 2. Check whether some bits ($i$-th, $j$-th) are correlated for two consecutive values i.e. for list of generated random values $rnd_0, rnd_1, rnd_2, rnd_3, \cdots$ check if ($i$-th bit of $rnd_0$ is correlated with $j$-th of $rnd_1$, $i$-th bit of $rnd_2$ is correlated with $j$-th of $rnd_3$, etc.).
#
#
#
#
#
#
# +
def histogram(values, i, j):
pass
def correlation_test(values):
pass
|
PV181_RNG_python.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Toy Process A
#
# Normalise the raw data table beta
import pandas as pd
alpha = pd.read_csv('alpha.csv')
alpha_norm = (alpha - alpha.mean()) / (alpha.max() - alpha.min())
alpha.head()
alpha_norm.to_csv('alpha_norm.csv', index=False)
|
examples/toyA.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# + [markdown] id="uPw_GwXUD_0_"
# Demo code for Lec 24. Model selection with Lasso on diabetes data set.
# + executionInfo={"elapsed": 239, "status": "ok", "timestamp": 1644529251685, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhwJbFKBBICkDJdVudgsTuWkkyr0jrw5PxmRvic=s64", "userId": "09527353465813384085"}, "user_tz": 480} id="wSKJosgFEHrw"
import numpy as np
import sklearn as skl
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Lasso, LinearRegression, LassoCV
from sklearn.metrics import mean_squared_error
from sklearn.datasets import load_diabetes, load_breast_cancer
X, Y = load_diabetes(return_X_y=True)
feature_names = load_diabetes()['feature_names']
print('features: ', feature_names)
print('X: ', X)
print('Y: ', Y)
print(X.shape)
print(Y.shape)
# + executionInfo={"elapsed": 38, "status": "ok", "timestamp": 1644528320570, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhwJbFKBBICkDJdVudgsTuWkkyr0jrw5PxmRvic=s64", "userId": "09527353465813384085"}, "user_tz": 480} id="eQ88Iq5WFBWC"
# Split data set into training and test sets
X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size=0.33, random_state= 42)
X_scaler = StandardScaler()
X_scaler.fit(X_train)
X_train_s = X_scaler.transform(X_train)
X_test_s = X_scaler.transform(X_test)
# + colab={"base_uri": "https://localhost:8080/", "height": 493} executionInfo={"elapsed": 659, "status": "ok", "timestamp": 1644528321197, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhwJbFKBBICkDJdVudgsTuWkkyr0jrw5PxmRvic=s64", "userId": "09527353465813384085"}, "user_tz": 480} id="cYYxIWa5GYEk" outputId="921c58c3-0697-4b5b-b23c-0726e5ccb346"
lmbd = 1.2
diabetes_lasso = Lasso(alpha = lmbd)
diabetes_lasso.fit( X_train_s, Y_train)
diabetes_linear = LinearRegression()
diabetes_linear.fit(X_train_s, Y_train)
# bar plot the lasso and linear reg coefficients (not including intercepts)
fig, ax = plt.subplots(2, 1, figsize=(8.2, 6))
ax[1].bar( np.arange(0,10), diabetes_lasso.coef_ )
ax[1].set_xlabel('index j')
ax[1].set_ylabel('b_j')
ax[1].set_title('Lasso coef.')
ax[0].bar( np.arange(0,10), diabetes_linear.coef_ )
ax[0].set_xlabel('index j')
ax[0].set_ylabel('b_j')
ax[0].set_title('Regression coef.')
fig.tight_layout()
# compute test MSE for both models
lasso_MSE = mean_squared_error( Y_test, diabetes_lasso.predict(X_test_s) )
linear_MSE = mean_squared_error( Y_test, diabetes_linear.predict(X_test_s) )
print('Lasso MSE: ', lasso_MSE)
print('Linear MSE: ', linear_MSE)
print(feature_names)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 266, "status": "ok", "timestamp": 1644528321436, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhwJbFKBBICkDJdVudgsTuWkkyr0jrw5PxmRvic=s64", "userId": "09527353465813384085"}, "user_tz": 480} id="2eNpKaoMIpym" outputId="1e4ca8e8-7be9-4cad-f7e4-b506cf9fe7f3"
# repeat lasso with CV
diabetes_lassoCV = LassoCV( alphas = np.linspace(0.1, 5, 20), cv= 20 )
diabetes_lassoCV.fit(X_train_s, Y_train)
print(diabetes_lassoCV.alpha_)
# + colab={"base_uri": "https://localhost:8080/", "height": 493} executionInfo={"elapsed": 511, "status": "ok", "timestamp": 1644528321941, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhwJbFKBBICkDJdVudgsTuWkkyr0jrw5PxmRvic=s64", "userId": "09527353465813384085"}, "user_tz": 480} id="iqhZdlogNxxB" outputId="e39726f3-43cc-471c-8b30-761786284cc0"
# bar plot the lasso and linear reg coefficients (not including intercepts)
fig, ax = plt.subplots(2, 1, figsize=(8.2, 6))
ax[1].bar( np.arange(0,10), diabetes_lassoCV.coef_ )
ax[1].set_xlabel('index j')
ax[1].set_ylabel('b_j')
ax[1].set_title('Lasso coef.')
ax[0].bar( np.arange(0,10), diabetes_linear.coef_ )
ax[0].set_xlabel('index j')
ax[0].set_ylabel('b_j')
ax[0].set_title('Regression coef.')
fig.tight_layout()
lassoCV_MSE = mean_squared_error( Y_test, diabetes_lassoCV.predict(X_test_s) )
print('Lasso MSE: ', lassoCV_MSE)
print('Linear MSE: ', linear_MSE)
print(feature_names)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 24, "status": "ok", "timestamp": 1644528321943, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhwJbFKBBICkDJdVudgsTuWkkyr0jrw5PxmRvic=s64", "userId": "09527353465813384085"}, "user_tz": 480} id="g_c_WEDIOUfR" outputId="89abb5a7-8598-4bb3-d46c-13106561507f"
# so features 5, 7 and 9 are discarded by Lasso
# these are 's1', 's4', and 's6'
print( np.abs(diabetes_lassoCV.coef_))
# WARNING: this is an instance of the use of Lasso for model selection (ie identifying important parameters in the dataset)
# the importance of different parameters can change significantly between different data sets so one should be careful about
# drawing conclusions from a given data set.
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 195, "status": "ok", "timestamp": 1644529329107, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhwJbFKBBICkDJdVudgsTuWkkyr0jrw5PxmRvic=s64", "userId": "09527353465813384085"}, "user_tz": 480} id="kved4ovxPLjT" outputId="96248b3b-ae70-4d69-ad7a-9fb05ecf4af0"
# similar computations for a larger data set with many attributes
X_b, Y_b = load_breast_cancer(return_X_y=True)
feature_names_b = load_breast_cancer()['feature_names']
print('features: ', feature_names_b)
print('X_b: ', X_b)
print('Y_b: ', Y_b)
print(X_b.shape)
print(Y_b.shape)
# + executionInfo={"elapsed": 178, "status": "ok", "timestamp": 1644529446079, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhwJbFKBBICkDJdVudgsTuWkkyr0jrw5PxmRvic=s64", "userId": "09527353465813384085"}, "user_tz": 480} id="8d0HG7E4lCqc"
# preprocessing
X_train_b, X_test_b, Y_train_b, Y_test_b = train_test_split( X_b, Y_b, test_size=0.33, random_state= 42)
X_b_scaler = StandardScaler()
X_b_scaler.fit(X_train_b)
X_train_bs = X_b_scaler.transform(X_train_b)
X_test_bs = X_b_scaler.transform(X_test_b)
# I also like to shift the output so we have +1, -1 for classes
Y_train_bs = 2*Y_train_b - 1
Y_test_bs = 2*Y_test_b - 1
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 2181, "status": "ok", "timestamp": 1644529858731, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhwJbFKBBICkDJdVudgsTuWkkyr0jrw5PxmRvic=s64", "userId": "09527353465813384085"}, "user_tz": 480} id="AXmqU0Dpl-p8" outputId="5116e623-a27a-454e-e59f-ed2ae87cc074"
# repeat lasso with CV
bc_lassoCV = LassoCV( alphas = np.linspace(1e-6, 0.05, 40), cv= 10, max_iter = 50000 )
bc_lassoCV.fit(X_train_bs, Y_train_bs)
print('lmbd CV: ',bc_lassoCV.alpha_)
print('beta_vec: ',np.abs(bc_lassoCV.coef_))
# + colab={"base_uri": "https://localhost:8080/", "height": 421} executionInfo={"elapsed": 719, "status": "ok", "timestamp": 1644529914700, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GhwJbFKBBICkDJdVudgsTuWkkyr0jrw5PxmRvic=s64", "userId": "09527353465813384085"}, "user_tz": 480} id="U-62q2qRmJm8" outputId="015cb5db-5901-4555-fd25-af4d1f09af14"
fig, ax = plt.subplots(1, 1, figsize=(8.2, 6))
ax.bar( np.arange(0,30), np.abs( bc_lassoCV.coef_) )
ax.set_xlabel('index j')
ax.set_ylabel('|b_j|')
ax.set_title('|Lasso coef.| for BC data set')
|
course_notes/AMATH582-Lec24.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Bases de données avec Python
#
# > Cours NSI Terminale - Thème 2.
# - toc: true
# - badges: true
# - comments: false
# - categories: [python, NSI, Terminale, Bases de données, SQL, TP]
# - image: /images/nsi2.png
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "fd767a71ffe9d21dd310723f5a2d4299", "grade": false, "grade_id": "cell-913a611055c9ace2", "locked": true, "schema_version": 3, "solution": false, "task": false}
# # Exploiter une base de données avec Python
#
# Dans ce TP, nous allons reprendre notre base de données d'exemples sur les livres, mais nous allons utiliser Python pour exécuter et exploiter les requêtes SQL. Notre SGBD sera toujours SQLite : le module python que nous utiliserons se nomme **sqlite3**.
#
# Si vous ne possédez pas cette base des TP précédents, vous pouvez la récupérer [ici](https://www.lecluse.fr/nsi/NSI_T/bdd/livres_db).
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "8ad2ee3e03d0a3a40fe2780c3934f9e5", "grade": false, "grade_id": "cell-d9c09986e34e000e", "locked": true, "schema_version": 3, "solution": false, "task": false}
import sqlite3
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "28cad3c4a13594f8d89f4b0b0d5dc24a", "grade": false, "grade_id": "cell-d96a1207648fd4e7", "locked": true, "schema_version": 3, "solution": false, "task": false}
# Le module étant importé, nous devons réaliser deux actions pour pouvoir commencer à utiliser notre base :
# - ouvrir le fichier de base de données
# - créer un curseur
#
# Le *curseur* est un objet python offrant des méthodes pour exécuter des requêtes et récupérer le ou les résultats de ces requêtes.
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "01527bd442ea915f607c7206481d3557", "grade": false, "grade_id": "cell-61552e200fdb388a", "locked": true, "schema_version": 3, "solution": false, "task": false}
bdd = sqlite3.connect("livres_db")
curseur = bdd.cursor()
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "984179863afa15b052ad993802ac08a5", "grade": false, "grade_id": "cell-e5065aa1a786ea15", "locked": true, "schema_version": 3, "solution": false, "task": false}
# *livres_db* est le nom du fichier contenant la base de donnéees SQLite que nous allons exploiter. Si le fichier n'existe pas, une nouvelle base de données sera créée.
#
# ## Exécuter des requêtes de sélection
#
# ### Le principe
#
# Reste ensuite à exécuter notre première requête. Pour cela, nous utiliserons la méthode **execute()** du curseur, la requête étant une chaîne de caractères passée en paramètre.
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "08efb7f266db16b1f6e9a1afa2613935", "grade": false, "grade_id": "cell-e386676405303097", "locked": true, "schema_version": 3, "solution": false, "task": false}
requete = "SELECT * FROM Livres;"
curseur.execute(requete)
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "ea8bcd5569ac7e550458228e93068a3d", "grade": false, "grade_id": "cell-eb1983544af58acb", "locked": true, "schema_version": 3, "solution": false, "task": false}
# Pour visualiser le résultat de notre requête, nous utiliserons encore notre curseur. Deux méthodes permettent principalement de le faire :
# - **fetchone()** pour récupérer un résultat puis avancer le curseur d'un cran
# - **fetchall()** pour récupérer d'un coup tous les résultats.
#
# Regardez les exemples ci-dessous pour mieux comprendre comment fonctionne le curseur : il s'agit littéralement d'un curseur que l'on déplace de résultat en résultat. Vous vous en rendrez compte en exécutant plusieurs fois la cellule ci-dessous.
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "b713e52beb49098f4a7ffa3abbc0df96", "grade": false, "grade_id": "cell-3511ba3e527fd088", "locked": true, "schema_version": 3, "solution": false, "task": false}
curseur.fetchone()
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "dce82abb8e20f0592a3d230e9c7481ea", "grade": false, "grade_id": "cell-abb4d3bb12f0f6ab", "locked": true, "schema_version": 3, "solution": false, "task": false}
# Vous constatez que le résultat est un *tuple* dont les éléments correspondent aux attributs sélectionnés : ici c'est \*. Il n'est pas facile de se rappeler de l'ordre des attributs. Pour cela vous pouvez faire appel à la propriété :
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "b9fa9b7df9425c6bde91f32e4309112b", "grade": false, "grade_id": "cell-f9cd84d0448ba2fe", "locked": true, "schema_version": 3, "solution": false, "task": false}
curseur.description
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "b32be652270b41e86c95a907bc09d4dd", "grade": false, "grade_id": "cell-5cba17a48c54c049", "locked": true, "schema_version": 3, "solution": false, "task": false}
# et pour rendre la réponse plus lisible, une petite liste en compréhension ;). Et voilà les attributs de colonne en clair dans l'ordre ou ils apparaissent dans le résultat de la requête !
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "e3789dfacfd8666fe8cc494f26d76b30", "grade": false, "grade_id": "cell-adebe2b8e3f17588", "locked": true, "schema_version": 3, "solution": false, "task": false}
[d[0] for d in curseur.description]
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "b2e8a0e2335338e7e8151c463b41d094", "grade": false, "grade_id": "cell-857d9bb92faea101", "locked": true, "schema_version": 3, "solution": false, "task": false}
# A présent, le fonctionnement de **fetchall()** ne devrait pas vous étonner : on récupère logiquement un tuple avec tous les résultats.
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "1e8467b069469062f29ee5e5439ad2d2", "grade": false, "grade_id": "cell-2b7dbd28d8a2ee0f", "locked": true, "schema_version": 3, "solution": false, "task": false}
curseur.fetchall()
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "c4f766c265effa4bfd3009a82fb2b150", "grade": false, "grade_id": "cell-a37b42ab77cdf572", "locked": true, "schema_version": 3, "solution": false, "task": false}
# Si vous avez suivi les instructions précédentes, vous devriez constater qu'il manque des enregistrements. Pourquoi ?
# Un indice : si vous réexécutez une nouvelle fois la méthode **fetchall()** du curseur, celle-ci ne renverra rien !
#
# Et oui, c'est la notion de curseur qui se déplace au fur à mesure qu'unb résultat est donné : les précédents appels de **fetchone()** ont fait avancer le curseur, et de même, **fetchall()** positionne le curseur à la toute fin.
#
# Pour retrouver tous les résultats à nouveau, il faut réexécuter la requête. Evitez donc de mélanger **fetchone()** et **fetchall()** sous peine de ne plus trop savoir ou en est le curseur et ce que vous récupérez.
#
# Voici donc le moyen le plus simple de récupérer tous les résultats d'une requête d'un coup.
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "9bfeb4ab536ec2ea9b0784f1c91d0ebd", "grade": false, "grade_id": "cell-5b28fa4bed4af0cf", "locked": true, "schema_version": 3, "solution": false, "task": false}
curseur.execute(requete)
resultats = curseur.fetchall()
resultats
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "75160755a7229b1fe0159dde43f79236", "grade": false, "grade_id": "cell-ec745ce19cc0ddea", "locked": true, "schema_version": 3, "solution": false, "task": false}
# ### Construire des requêtes à partir de variables python
#
# Nous allons dans l'exemple suivant écrire une fonction **prenom()**
# - qui prend en paramètre un curseur et un nom d'auteur
# - qui renvoie son prénom
#
# Si le nom de l'auteur ne figure pas dans la table *Auteurs*, la fonction renverra **None**.
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "bdfa20620174a6919d04ce97edb39d0d", "grade": false, "grade_id": "cell-97db6913b27c6d89", "locked": true, "schema_version": 3, "solution": false, "task": false}
def prenom(c, nom):
requete = "SELECT PrenomAuteur FROM Auteurs WHERE NomAuteur = ?"
c.execute(requete, [nom])
r = c.fetchall()
if len(r) == 0:
return None
elif len(r) == 1:
return r[0][0]
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "b358a15ff3b04edd5d1e54251544fec6", "grade": false, "grade_id": "cell-45e8fa29507a0e4c", "locked": true, "schema_version": 3, "solution": false, "task": false}
prenom(curseur, "Verne")
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "e0693d057e44084de9d2cea813703f7a", "grade": false, "grade_id": "cell-5bb04f1af5083209", "locked": true, "schema_version": 3, "solution": false, "task": false}
# ### Explications
#
# Dans cet exemple, nous construisons une requête à partir d'une variable Python. SQLite propose un mécanisme de substitution sécurisé permettant d'injecter une ou plusieurs variables à l'intérieur d'une requête. **C'est ce mécanisme que vous devez utiliser** : ne construisez pas vous même la chaîne de caractère contenant la requête complète, c'est une mauvaise pratique qui vous conduira inévitablement à des problèmes.
#
# Pour utiliser ce mécanisme de substitution, vous devez
# - mettre des **?** dans votre requête à l'emplacement de la variable à insérer
# - passer en second paramètre la liste des valeurs à substituer dans la requête
#
# C'est simple, fiable et sécurisé, en particulier contre les [injections SQL](https://xkcd.com/327/) !
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "a1579343c3e6b0384650a224ec2c9559", "grade": false, "grade_id": "cell-d745f7db6b31989b", "locked": true, "schema_version": 3, "solution": false, "task": false}
# ### A vous de jouer
#
# Ecrivez une fonction **romans()**
# - qui prend en paramètre un curseur et un nom d'auteur
# - qui renvoie une liste de *Titres* de romans écrits par cet auteur
#
# Si le nom de l'auteur ne figure pas dans la table *Auteurs*, la fonction renverra **None**.
# + deletable=false nbgrader={"cell_type": "code", "checksum": "e591b8be71d5f8f617641c8ec138e462", "grade": false, "grade_id": "cell-4dbc8667ccf5a4b9", "locked": false, "schema_version": 3, "solution": true, "task": false}
def romans(c, nom):
# YOUR CODE HERE
raise NotImplementedError()
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "72deedafe0151c6d90b17b3fe48d5936", "grade": true, "grade_id": "cell-d45629f6b668916f", "locked": true, "points": 1, "schema_version": 3, "solution": false, "task": false}
assert romans(curseur, "Asimov") == ['Fondation', 'Les Robots', 'La Fin de l’éternité']
assert romans(curseur, "Verne") == ['De la Terre à la Lune']
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "5ebdb9a5aa637de0fd22fd51d9b21a75", "grade": false, "grade_id": "cell-861c55abf9706f8c", "locked": true, "schema_version": 3, "solution": false, "task": false}
# ## Insérer de nouveaux enregistrements
#
# Les requêtes de modification sur la base se font de la même manière que les requêtes de sélection, à une petite subtilité près : après exécution de la requête, il faudra faire appel à la méthode **commit()** de l'objet *bdd* (issu de la connexion) afin que les modifications soient prises en compte dans le fichier de base de données.
#
# **Attention** : Si vous oubliez l'appel à commit, vos modifications seront perdues lorsque vous quitterez votre programme car elles ne seront pas inscrites dans le fichier de la base de données.
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "d3e7c4218e8e5eaee36cdf67f30323fe", "grade": false, "grade_id": "cell-7ecd744c03866b11", "locked": true, "schema_version": 3, "solution": false, "task": false}
requete = """
INSERT INTO Auteurs
(NomAuteur, PrenomAuteur, IdLangue, AnneeNaissance)
VALUES
('Lecluse', 'Olivier', 2, 1870);
"""
curseur.execute(requete)
bdd.commit()
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "2d2146d5397e0e30fc3a502819573cd8", "grade": false, "grade_id": "cell-b114c7ac4f8f4b33", "locked": true, "schema_version": 3, "solution": false, "task": false}
# la propriété **lastrowid** peut être intéressante car elle donne accès à la clé primaire créée automatiquement pour notre nouvel enregistrement. En voici une utilisation :
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "92f434f82820651784682733354ea066", "grade": false, "grade_id": "cell-9e5b1774cd6ecf92", "locked": true, "schema_version": 3, "solution": false, "task": false}
last_id = curseur.lastrowid
last_id
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "237cd4ab3745001c977b6b19c1442358", "grade": false, "grade_id": "cell-4eaeef7474110fea", "locked": true, "schema_version": 3, "solution": false, "task": false}
requete = "SELECT * FROM Auteurs WHERE IdAuteur = ?"
curseur.execute(requete, [last_id])
curseur.fetchone()
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "4d6ab34fd3495387fda5a739340de9a3", "grade": false, "grade_id": "cell-5ff41da4672ecf02", "locked": true, "schema_version": 3, "solution": false, "task": false}
# ### A vous de jouer
# Effacez de la table auteur ce dernier enregistrement que nous avons créé.
# + deletable=false nbgrader={"cell_type": "code", "checksum": "348db37dcfa258a60a61c4ff853de265", "grade": false, "grade_id": "cell-56030c508fbdd29b", "locked": false, "schema_version": 3, "solution": true, "task": false}
# YOUR CODE HERE
raise NotImplementedError()
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "2f028a1cee8f1da904e8e8afef40ceb6", "grade": true, "grade_id": "cell-26bbe8cd16b5ed09", "locked": true, "points": 1, "schema_version": 3, "solution": false, "task": false}
requete = "SELECT COUNT(*) from Auteurs"
curseur.execute(requete)
assert curseur.fetchone()[0] == 10
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "4fecdc73d812c1dd4e6284c569cc2ff8", "grade": false, "grade_id": "cell-ce9dd63e7685bf6b", "locked": true, "schema_version": 3, "solution": false, "task": false}
curseur.execute("SELECT * FROM Auteurs")
curseur.fetchall()
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "954a25a110048b19975e639b8512585c", "grade": false, "grade_id": "cell-d9de3f8d2ddcc9a3", "locked": true, "schema_version": 3, "solution": false, "task": false}
# ## Pour Finir
#
# Notre travail sur la BDD exemple est à présent terminé. Afin de fermer le fichier proprement et de s'assurer que les données saisies seront bien inscrites dans le fichier, il faut *impérativement* appeler la méthode **close()** sur l'objet *bdd* :
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "7293dd6fe965c56e8b132142317532e1", "grade": false, "grade_id": "cell-2ed83f05dbe42d2e", "locked": true, "schema_version": 3, "solution": false, "task": false}
bdd.close()
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "d6d507e7794ec70458603db209f12961", "grade": false, "grade_id": "cell-f5dd8cfccd974b89", "locked": true, "schema_version": 3, "solution": false, "task": false}
curseur
# + [markdown] deletable=false editable=false nbgrader={"cell_type": "markdown", "checksum": "b2575bcfd3fcdda77eb6b85be544659e", "grade": false, "grade_id": "cell-6bad013fb4889bab", "locked": true, "schema_version": 3, "solution": false, "task": false}
# A partir de ce moment là, plus acune opération n'est possible sur la base de données comme le montre la cellule suivante :
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "6b9bdd82bf7ce142641bbc3122459034", "grade": false, "grade_id": "cell-56604b1af394c97b", "locked": true, "schema_version": 3, "solution": false, "task": false}
requete = "SELECT COUNT(*) from Auteurs"
curseur.execute(requete)
|
_notebooks/2020-06-25-nsi_t_PythonSql.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# [](https://colab.research.google.com/github/davemlz/eemont/blob/master/docs/tutorials/016-Spectral-Indices-From-Awesome-Spectral-Indices-List.ipynb)
# + [markdown] id="jZEthLln92Ep"
# # Spectral Indices From the [Awesome Spectral Indices for GEE](https://github.com/davemlz/awesome-ee-spectral-indices)
# + [markdown] id="dNa470OZ8Oec"
# _Tutorial created by **<NAME>**_: [GitHub](https://github.com/davemlz) | [Twitter](https://twitter.com/dmlmont)
#
# - GitHub Repo: [https://github.com/davemlz/eemont](https://github.com/davemlz/eemont)
# - PyPI link: [https://pypi.org/project/eemont/](https://pypi.org/project/eemont/)
# - Conda-forge: [https://anaconda.org/conda-forge/eemont](https://anaconda.org/conda-forge/eemont)
# - Documentation: [https://eemont.readthedocs.io/](https://eemont.readthedocs.io/)
# - More tutorials: [https://github.com/davemlz/eemont/tree/master/docs/tutorials](https://github.com/davemlz/eemont/tree/master/docs/tutorials)
# + [markdown] id="CD7h0hbi92Er"
# ## Let's start!
# + [markdown] id="E0rc6Cya92Es"
# If required, please uncomment:
# + id="NYzyvKtk92Es"
# #!pip install eemont
# #!pip install geemap
# + [markdown] id="x3Rm3qt_92Et"
# Import the required packges.
# + id="H0C9S_Hh92Et"
import ee, eemont, geemap
import geemap.colormaps as cm
# + [markdown] id="k1sdX2p592Eu"
# Authenticate and Initialize Earth Engine and geemap.
# + id="7QDXqVwy8Oef"
Map = geemap.Map()
# -
# Let's define a point of interest:
poi = ee.Geometry.PointFromQuery("El Cairo, Egypt",user_agent = "eemont-tutorial-016")
# Let's preprocess the S2 dataset:
S2 = (ee.ImageCollection("COPERNICUS/S2_SR")
.filterBounds(poi)
.filterDate("2020-01-01","2021-01-01")
.maskClouds()
.scaleAndOffset())
# ## New method for computing Spectral Indices
# In order to compute Spectral Indices from the Awesome List of Spectral Indices, please use the `spectralIndices` method for ee.Image and ee.ImageCollection classes (This method will eventually replace the `index` method):
S2offline = S2.spectralIndices(["NDVI","kNDVI","NDWI","SeLI"]).median()
# The `spectralIndices` method will look into the Awesome List of Spectral Indices that comes with the eemont package (offline). If the list is outdated (the local list is updated with every new version or with the dev installation), you can use the `online` argument to use the most recent list directly from the [Awesome Spectral Indices for GEE repositoy](https://github.com/davemlz/awesome-ee-spectral-indices):
S2online = S2.spectralIndices(["NDVI","kNDVI","NDWI","SeLI"],online = True).median()
# The `spectralIndices` has new arguments for some of the new indices that were added to the list:
#
# - cexp (float, default = 1.16) – Exponent used for OCVI.
# - nexp (float, default = 2.0) – Exponent used for GDVI.
# - alpha (float, default = 0.1) – Weighting coefficient used for WDRVI.
# - slope (float, default = 1.0) – Soil line slope.
# - intercept (float, default = 0.0) – Soil line intercept.
# Check the [eemont API Reference](https://eemont.readthedocs.io/en/latest/classes/index.html) and the [Awesome Spectral indices Documentation](https://awesome-ee-spectral-indices.readthedocs.io/en/latest/) for more info.
# Now, let's visualize our indices!
# +
vegetation_vis = {
"min": 0,
"max": 1,
"palette": cm.palettes.ndvi
}
water_vis = {
"min": 0,
"max": 1,
"palette": cm.palettes.ndwi
}
# -
# Visualize everything with `geemap`:
Map.addLayer(S2online.select("NDVI"),vegetation_vis,"NDVI")
Map.addLayer(S2online.select("kNDVI"),vegetation_vis,"kNDVI")
Map.addLayer(S2online.select("SeLI"),vegetation_vis,"SeLI")
Map.addLayer(S2online.select("NDWI"),water_vis,"NDWI")
Map.centerObject(poi,8)
Map
|
docs/tutorials/016-Spectral-Indices-From-Awesome-Spectral-Indices-List.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# ## Sample5.1 Single parameter Bayesian model
# Relationships between prior, likelihood, and posterior
# + nbpresent={"id": "c8f3c26e-0d6b-4a6a-943f-220a167ccb98"}
# %matplotlib inline
#posteior distribution of binomial data
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rc('xtick', labelsize=12)
matplotlib.rc('ytick', labelsize=12)
n0 = 15
y0 = 9
n = 20
y = 11
theta = np.arange(0,1,0.001)
p_post_noninfo = stats.beta.pdf(theta,y+1,n-y+1)
p_prior = stats.beta.pdf(theta,y0+1,n0-y0+1)
p_post = stats.beta.pdf(theta,y+y0+1,n+n0-y0-y+1)
fig = plt.figure(figsize=[4,4])
ax = fig.add_subplot(111)
e1, = ax.plot(theta,p_post_noninfo,'k-')
e2, = ax.plot(theta,p_prior,'r-')
e3, = ax.plot(theta,p_post,'b-')
plt.legend([e1,e2,e3],['Posterior w/o prior','Prior','Posterior w prior'])
ax.set_xlabel(r'$\theta$',fontsize=20)
# fig.show()
# + jupyter={"outputs_hidden": true}
|
sample5.1_SingleParamsModel_binomial.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
def polynomial(x, coeff):
y=sum([coefficient*(x**index) for index, coefficient in enumerate(coeff)])
return(y)
import numpy as np
import matplotlib. pyplot as plt
c=4
coeff=[]
for i in range(c+1): #make a list of the coefficients
coeff.append(np.random.uniform(0.5,2))
x=0 #first x-value to be calculated
datalist=[] #this is the list of the calculated values
for i in range(100):
data=polynomial(x, coeff) #call the calculation for x
datalist.append(data) #register the calculated value in the list
x+=1 #move to the next value to be calculated
plt.plot(datalist)
# -
|
Exercises/QuantEcon/Introduction/Essentials/Exercise2_Polynomial.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### Monte Carlo Simulation with Python
#
# Notebook to accompany article on [Practical Business Python](https://pbpython.com/monte-carlo.html)
#
# Update to use numpy for faster loops based on comments [here](https://www.reddit.com/r/Python/comments/arxwkm/monte_carlo_simulation_with_python/)
import pandas as pd
import numpy as np
import seaborn as sns
sns.set_style('whitegrid')
# Define the variables for the Percent to target based on historical results
avg = 1
std_dev = .1
num_reps = 500
num_simulations = 100000
# Show an example of calculating the percent to target
pct_to_target = np.random.normal(
avg,
std_dev,
size=(num_reps, num_simulations)
)
pct_to_target[0:10]
# Another example for the sales target distribution
sales_target_values = [75_000, 100_000, 200_000, 300_000, 400_000, 500_000]
sales_target_prob = [.3, .3, .2, .1, .05, .05]
sales_target = np.random.choice(sales_target_values, p=sales_target_prob,
size=(num_reps, num_simulations))
sales_target[0:10]
commission_percentages = np.take(
np.array([0.02, 0.03, 0.04]),
np.digitize(pct_to_target, bins=[.9, .99, 10])
)
commission_percentages[0:10]
total_commissions = (commission_percentages * sales_target).sum(axis=0)
total_commissions.std()
# Show how to create the dataframe
df = pd.DataFrame(data={'Total_Commissions': total_commissions})
df.head()
df.plot(kind='hist', title='Commissions Distribution')
df.describe()
|
notebooks/Monte_Carlo_Simulationv2.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Deep Learning Toolkit for Splunk - Causalnex
# This notebook contains a barebone example workflow how to work on custom containerized code that seamlessly interfaces with the Deep Learning Toolkit for Splunk.
# Note: By default every time you save this notebook the cells are exported into a python module which is then invoked by Splunk MLTK commands like <code> | fit ... | apply ... | summary </code>. Please read the Model Development Guide in the Deep Learning Toolkit app for more information.
# ## Stage 0 - import libraries
# At stage 0 we define all imports necessary to run our subsequent code depending on various libraries.
# + deletable=false name="mltkc_import"
# this definition exposes all python module imports that should be available in all subsequent commands
import json
import numpy as np
import pandas as pd
from causalnex.structure import DAGRegressor
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold
# ...
# global constants
MODEL_DIRECTORY = "/srv/app/model/data/"
# -
# THIS CELL IS NOT EXPORTED - free notebook cell for testing or development purposes
print("numpy version: " + np.__version__)
print("pandas version: " + pd.__version__)
# ## Stage 1 - get a data sample from Splunk
# In Splunk run a search to pipe a dataset into your notebook environment. Note: mode=stage is used in the | fit command to do this.
# | makeresults count=10<br>
# | streamstats c as i<br>
# | eval s = i%3<br>
# | eval feature_{s}=0<br>
# | foreach feature_* [eval <<FIELD>>=random()/pow(2,31)]<br>
# | fit MLTKContainer mode=stage algo=barebone epochs=10 batch_size=1 s from feature_* into app:barebone_model
# After you run this search your data set sample is available as a csv inside the container to develop your model. The name is taken from the into keyword ("barebone_model" in the example above) or set to "default" if no into keyword is present. This step is intended to work with a subset of your data to create your custom model.
# + deletable=false name="mltkc_stage"
# this cell is not executed from MLTK and should only be used for staging data into the notebook environment
def stage(name):
with open("data/"+name+".csv", 'r') as f:
df = pd.read_csv(f)
with open("data/"+name+".json", 'r') as f:
param = json.load(f)
return df, param
# -
# THIS CELL IS NOT EXPORTED - free notebook cell for testing or development purposes
df, param = stage("causalnex")
print(df.describe())
print(df.head())
# ## Stage 2 - create and initialize a model
# + deletable=false name="mltkc_init"
# initialize your model
# available inputs: data and parameters
# returns the model object which will be used as a reference to call fit, apply and summary subsequently
def init(df,param):
model = DAGRegressor(
alpha=0.1,
beta=0.9,
fit_intercept=True,
hidden_layer_units=None,
dependent_target=True,
enforce_dag=True,
)
return model
# -
# THIS CELL IS NOT EXPORTED - free notebook cell for testing or development purposes
model = init(df,param)
print(init(df,param))
# ## Stage 3 - fit the model
# + deletable=false name="mltkc_fit"
# train your model
# returns a fit info json object and may modify the model object
def fit(model,df,param):
target=param['target_variables'][0]
#Data prep for processing
y_p = df[target]
y = y_p.values
X_p = df[param['feature_variables']]
X = X_p.to_numpy()
X_col = list(X_p.columns)
#Scale the data
ss = StandardScaler()
X_ss = ss.fit_transform(X)
y_ss = (y - y.mean()) / y.std()
scores = cross_val_score(model, X_ss, y_ss, cv=KFold(shuffle=True, random_state=42))
print(f'MEAN R2: {np.mean(scores).mean():.3f}')
X_pd = pd.DataFrame(X_ss, columns=X_col)
y_pd = pd.Series(y_ss, name=target)
model.fit(X_pd, y_pd)
info = pd.Series(model.coef_, index=X_col)
#info = pd.Series(model.coef_, index=list(df.drop(['_time'],axis=1).columns))
return info
# -
# THIS CELL IS NOT EXPORTED - free notebook cell for testing or development purposes
print(param['target_variables'][0])
print(fit(model,df,param))
# ## Stage 4 - apply the model
# + deletable=false name="mltkc_apply"
# apply your model
# returns the calculated results
def apply(model,df,param):
data = []
for col in list(df.columns):
s = model.get_edges_to_node(col)
for i in s.index:
data.append([i,col,s[i]]);
graph = pd.DataFrame(data, columns=['src','dest','weight'])
#results to send back to Splunk
graph_output=graph[graph['weight']>0]
return graph_output
# +
# THIS CELL IS NOT EXPORTED - free notebook cell for testing or development purposes
print(apply(model,df,param))
model.plot_dag(True)
# -
# ## Stage 5 - save the model
# + deletable=false name="mltkc_save"
# save model to name in expected convention "<algo_name>_<model_name>"
def save(model,name):
#with open(MODEL_DIRECTORY + name + ".json", 'w') as file:
# json.dump(model, file)
return model
# -
# ## Stage 6 - load the model
# + deletable=false name="mltkc_load"
# load model from name in expected convention "<algo_name>_<model_name>"
def load(name):
model = {}
#with open(MODEL_DIRECTORY + name + ".json", 'r') as file:
# model = json.load(file)
return model
# -
# ## Stage 7 - provide a summary of the model
# + deletable=false name="mltkc_summary"
# return a model summary
def summary(model=None):
returns = {"version": {"numpy": np.__version__, "pandas": pd.__version__} }
return returns
# -
# After implementing your fit, apply, save and load you can train your model:<br>
# | makeresults count=10<br>
# | streamstats c as i<br>
# | eval s = i%3<br>
# | eval feature_{s}=0<br>
# | foreach feature_* [eval <<FIELD>>=random()/pow(2,31)]<br>
# | fit MLTKContainer algo=barebone s from feature_* into app:barebone_model<br>
# Or apply your model:<br>
# | makeresults count=10<br>
# | streamstats c as i<br>
# | eval s = i%3<br>
# | eval feature_{s}=0<br>
# | foreach feature_* [eval <<FIELD>>=random()/pow(2,31)]<br>
# | apply barebone_model as the_meaning_of_life
# ## End of Stages
# All subsequent cells are not tagged and can be used for further freeform code
|
notebooks/causalnex.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] colab_type="text" id="KMI2k-oBsS08"
# _Lambda School Data Science — Model Validation_
#
# # Classification Metrics & Imbalanced Classes
#
# #### Objectives
# - Classification Metrics: Accuracy, Precision, Recall, F1, ROC AUC
# - Confusion Matrix
# - Imbalanced Classes
#
# #### Pre-reads
# - [Precision and Recall](https://en.wikipedia.org/wiki/Precision_and_recall)
# - [Simple guide to confusion matrix terminology](https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/)
# - [ROC curves and Area Under the Curve explained](https://www.dataschool.io/roc-curves-and-auc-explained/)
#
# + [markdown] colab_type="text" id="rU7RuVcjWdcp"
# ## Preliminary setup
# + [markdown] colab_type="text" id="WIqp4yzdUsf2"
# #### Install [category_encoders](https://github.com/scikit-learn-contrib/categorical-encoding)
# - Google Colab: `pip install category_encoders`
# - Local, Anaconda: `conda install -c conda-forge category_encoders`
#
# #### Install [mlxtend](http://rasbt.github.io/mlxtend/) to plot decision regions
# - Google Colab: Already installed
# - Local, Anaconda: `conda install -c conda-forge mlxtend`
#
# #### Get the Bank Marketing dataset
# - Download from [UCI](https://archive.ics.uci.edu/ml/datasets/Bank+Marketing)
# - Or run this cell:
# + colab={} colab_type="code" id="Ut7wm5_xUqvz"
# !wget https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip
# !unzip bank-additional.zip
# + [markdown] colab_type="text" id="exZrRRC2WObS"
# # Classification Metrics & Confusion Matrix — with Bank Marketing dataset
# -
# !jupyter labextension install @jupyter-widgets/jupyterlab-manager
# + colab={} colab_type="code" id="1FnLW0DjWKaW"
# This code comes from our previous notebook
# Imports
# %matplotlib inline
import ipywidgets as widget
from ipywidgets import interact
import warnings
import category_encoders as ce
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.exceptions import DataConversionWarning
from sklearn.preprocessing import StandardScaler
warnings.filterwarnings(action='ignore', category=DataConversionWarning)
# Load data
bank = pd.read_csv('bank-additional/bank-additional-full.csv', sep=';')
# Assign to X, y
X = bank.drop(columns='y')
y = bank['y'] == 'yes'
# Drop leaky feature
X = X.drop(columns='duration')
# Split Train, Test
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
# Make pipeline
pipeline = make_pipeline(
ce.OneHotEncoder(use_cat_names=True),
StandardScaler(),
LogisticRegression(solver='lbfgs', max_iter=1000)
)
# + [markdown] colab_type="text" id="ktgWzULWW2Z0"
# #### scikit-learn documentation
# - [sklearn.linear_model.LogisticRegression.predict_proba](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.predict_proba)
# - [sklearn.metrics.classification_report](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html)
# - [sklearn.metrics.confusion_matrix](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html)
# - [sklearn.model_selection.cross_val_predict](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_predict.html)
# + colab={} colab_type="code" id="bXN_sDXYWkj4"
from sklearn.model_selection import cross_val_predict
y_pred_proba = cross_val_predict(pipeline, X_train, y_train, cv=3, n_jobs=-1,
method='predict_proba')[:,1]
# -
# #### Change the threshold and re-run this cell
# +
threshold = 0.5
y_pred = y_pred_proba >= threshold
correct = y_pred == y_train
labels = pd.DataFrame({'Ground Truth': y_train,
'Predicted Probability': y_pred_proba,
'Discrete Prediction': y_pred,
'Correct Prediction?': correct})
labels.head(20)
# -
labels['Ground Truth'].value_counts(normalize=True).plot.barh(color='gray');
labels['Discrete Prediction'].value_counts(normalize=True).plot.barh(color='gray')
# +
import seaborn as sns
sns.distplot(labels['Predicted Probability']);
# + [markdown] colab_type="text" id="h01_ZZxcX0hf"
# #### Change the threshold and re-run this cell
# + colab={"base_uri": "https://localhost:8080/", "height": 264} colab_type="code" id="4xRbAMxmXrXw" outputId="e775e009-2ac5-422d-97e2-18c2422d81c5"
from sklearn.metrics import classification_report, confusion_matrix
threshold = 0.5
y_pred = y_pred_proba >= threshold
print(classification_report(y_train, y_pred))
pd.DataFrame(confusion_matrix(y_train, y_pred),
columns=['Predicted Negative', 'Predicted Positive'],
index=['Actual Negative', 'Actual Positive'])
# +
from sklearn.metrics import accuracy_score
accuracy_score(y_train, y_pred)
# + colab={} colab_type="code" id="InBb016HcSef"
#TODO
true_negative = 28786
false_positive = 452
false_negative = 2852
true_positive = 860
predicted_negative = 28786 + 2852
predicted_positive = 452 + 860
actual_positive = 2852 + 860
actual_negative = 28766 + 452
actual_negative = 28766 + 452
accuracy = (true_positive + true_negative) / (predicted_negative + predicted_positive)
precision = true_positive / predicted_positive
recall = true_positive / actual_positive
print('Accuracy', accuracy)
print('Precision', precision)
print('Recall', recall)
# -
# #### F1 Score
# "[The F1 score](https://en.wikipedia.org/wiki/F1_score) is the harmonic average of the precision and recall, where an F1 score reaches its best value at 1 (perfect precision and recall) and worst at 0."
# + [markdown] colab_type="text" id="d50kghfPYk1D"
# ### ROC AUC (Receiver Operating Characteristic, Area Under the Curve)
#
# #### Scikit-Learn docs
# - [User Guide: Receiver operating characteristic (ROC)](https://scikit-learn.org/stable/modules/model_evaluation.html#receiver-operating-characteristic-roc)
# - [sklearn.metrics.roc_curve](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html)
# - [sklearn.metrics.roc_auc_score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html)
#
# #### More links
# - [ROC curves and Area Under the Curve explained](https://www.dataschool.io/roc-curves-and-auc-explained/)
# - [The philosophical argument for using ROC curves](https://lukeoakdenrayner.wordpress.com/2018/01/07/the-philosophical-argument-for-using-roc-curves/)
#
# [Wikipedia explains,](https://en.wikipedia.org/wiki/Receiver_operating_characteristic) "A receiver operating characteristic curve, or ROC curve, is a graphical plot that illustrates the diagnostic ability of a binary classifier system as its discrimination threshold is varied. The ROC curve is created by plotting the true positive rate (TPR) against the false positive rate (FPR) at various threshold settings."
#
# ROC AUC is the area under the ROC curve. [It can be interpreted](https://stats.stackexchange.com/questions/132777/what-does-auc-stand-for-and-what-is-it) as "the expectation that a uniformly drawn random positive is ranked before a uniformly drawn random negative."
#
# ROC AUC measures how well a classifier ranks predicted probabilities. It ranges from 0 to 1. A naive majority class baseline will have an ROC AUC score of 0.5.
# + colab={"base_uri": "https://localhost:8080/", "height": 311} colab_type="code" id="yx5WEweMYBYY" outputId="8ce42a37-5afe-47c5-c4ab-556715da9e3f"
from sklearn.metrics import roc_auc_score, roc_curve
def threshold(thresholds):
fpr, tpr, thresholds = roc_curve(y_train, y_pred_proba)
plt.plot(fpr, tpr)
plt.title('ROC curve')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
print('Area under the Receiver Operating Characteristic curve:',
roc_auc_score(y_train, y_pred_proba))
# When threshold = 0.5
false_positives = 452
true_positives = 860
false_positive_rate = false_positives/actual_negative
true_positive_rate = true_positives/actual_positive
plt.scatter(false_positive_rate, true_positive_rate)
# When threshold = 0.1
false_positives = 5267
true_positives = 2418
false_positive_rate = false_positives/actual_negative
true_positive_rate = true_positives/actual_positive
plt.scatter(false_positive_rate, true_positive_rate);
threshold(thresholds)
# +
dropdown = widget.Dropdown(
options=thresholds,
description='Threshold',
value=0.5006533108523781,
)
dropdown
# +
import numpy as np
from ipywidgets import interactive
def threshold(thresholds):
fpr, tpr, thresholds = roc_curve(y_train, y_pred_proba)
plt.plot(fpr, tpr)
plt.title('ROC curve')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
print('Area under the Receiver Operating Characteristic curve:',
roc_auc_score(y_train, y_pred_proba))
# When threshold = 0.5
false_positives = 452
true_positives = 860
false_positive_rate = false_positives/actual_negative
true_positive_rate = true_positives/actual_positive
plt.scatter(false_positive_rate, true_positive_rate)
# When threshold = 0.1
false_positives = 5267
true_positives = 2418
false_positive_rate = false_positives/actual_negative
true_positive_rate = true_positives/actual_positive
plt.scatter(false_positive_rate, true_positive_rate);
interactive_threshold = interactive(threshold(thresholds), dropdown)
display(interactive_threshold)
# -
pd.DataFrame(dict(fpr=fpr, tpr=tpr, thresholds=thresholds))
# +
import numpy as np
from ipywidgets import interactive
def f(m, b):
plt.figure(2)
x = np.linspace(-10, 10, num=1000)
plt.plot(x, m * x + b)
plt.ylim(-5, 5);
interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
output = interactive_plot.children[-1]
output.layout.height = '350px'
interactive_plot
# -
from ipywidgets import interact, interactive, Layout
def f(x):
plt.plot(range(10))
plt.title(x)
int_widget = interactive(f, x=['AbCd'*10, 1 , 2])
int_widget.children[0].layout = Layout(width='500px')
display(int_widget)
# + [markdown] colab_type="text" id="DMiqiAB_WVPK"
# # Imbalanced Classes — with synthetic data
# + [markdown] colab_type="text" id="OWLBlu5K5kJR"
# ## Fun demo!
#
# The next code cell does five things:
#
# #### 1. Generate data
#
# We use scikit-learn's [make_classification](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_classification.html) function to generate fake data for a binary classification problem, based on several parameters, including:
# - Number of samples
# - Weights, meaning "the proportions of samples assigned to each class."
# - Class separation: "Larger values spread out the clusters/classes and make the classification task easier."
#
# (We are generating fake data so it is easy to visualize.)
#
# #### 2. Split data
#
# We split the data three ways, into train, validation, and test sets. (For this toy example, it's not really necessary to do a three-way split. A two-way split, or even no split, would be ok. But I'm trying to demonstrate good habits, even in toy examples, to avoid confusion.)
#
# #### 3. Fit model
#
# We use scikit-learn to fit a [Logistic Regression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) on the training data.
#
# We use this model parameter:
#
# > **class_weight : _dict or ‘balanced’, default: None_**
#
# > Weights associated with classes in the form `{class_label: weight}`. If not given, all classes are supposed to have weight one.
#
# > The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as `n_samples / (n_classes * np.bincount(y))`.
#
#
# #### 4. Evaluate model
#
# We use our Logistic Regression model, which was fit on the training data, to generate predictions for the validation data.
#
# Then we print [scikit-learn's Classification Report](https://scikit-learn.org/stable/modules/model_evaluation.html#classification-report), with many metrics, and also the accuracy score. We are comparing the correct labels to the Logistic Regression's predicted labels, for the validation set.
#
# #### 5. Visualize decision function
#
# Based on these examples
# - https://imbalanced-learn.readthedocs.io/en/stable/auto_examples/combine/plot_comparison_combine.html
# - http://rasbt.github.io/mlxtend/user_guide/plotting/plot_decision_regions/#example-1-decision-regions-in-2d
# + colab={} colab_type="code" id="PMTjC3vQ7ZNV"
from sklearn.model_selection import train_test_split
def train_validation_test_split(
X, y, train_size=0.8, val_size=0.1, test_size=0.1,
random_state=None, shuffle=True):
assert train_size + val_size + test_size == 1
X_train_val, X_test, y_train_val, y_test = train_test_split(
X, y, test_size=test_size, random_state=random_state, shuffle=shuffle)
X_train, X_val, y_train, y_val = train_test_split(
X_train_val, y_train_val, test_size=val_size/(train_size+val_size),
random_state=random_state, shuffle=shuffle)
return X_train, X_val, X_test, y_train, y_val, y_test
# + colab={"base_uri": "https://localhost:8080/", "height": 638} colab_type="code" id="TcpoWCUq5xNV" outputId="b7cc4074-7e6c-46b5-ed0c-2430e99c9913"
# %matplotlib inline
from IPython.display import display
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.metrics import accuracy_score, classification_report
from sklearn.linear_model import LogisticRegression
from mlxtend.plotting import plot_decision_regions
#1. Generate data
# Try re-running the cell with different values for these parameters
n_samples = 1000
weights = (0.95, 0.05)
class_sep = 0.8
X, y = make_classification(n_samples=n_samples, n_features=2, n_informative=2,
n_redundant=0, n_repeated=0, n_classes=2,
n_clusters_per_class=1, weights=weights,
class_sep=class_sep, random_state=0)
# 2. Split data
# Uses our custom train_validation_test_split function
X_train, X_val, X_test, y_train, y_val, y_test = train_validation_test_split(
X, y, train_size=0.8, val_size=0.1, test_size=0.1, random_state=1)
# 3. Fit model
# Try re-running the cell with different values for this parameter
class_weight = {0: 1, 1: 10000}
model = LogisticRegression(solver='lbfgs', class_weight=class_weight)
model.fit(X_train, y_train)
# 4. Evaluate model
y_pred = model.predict(X_val)
print(classification_report(y_val, y_pred))
print('accuracy', accuracy_score(y_val, y_pred))
display(pd.DataFrame(
confusion_matrix(y_val, y_pred),
columns=['Predicted Negative', 'Predicted Positive'],
index=['Actual Negative', 'Actual Positive']))
# 5. Visualize decision regions
plt.figure(figsize=(10, 6))
plot_decision_regions(X_val, y_val, model, legend=0);
y_pred_proba = model.predict_proba(X_val)[:,1]
print('ROC AUC', roc_auc_score(y_val, y_pred_proba))
# + [markdown] colab_type="text" id="zrllN3yECsEN"
# Try re-running the cell above with different values for these four parameters:
# - `n_samples`
# - `weights`
# - `class_sep`
# - `class_balance`
#
# For example, with a 50% / 50% class distribution:
# ```
# n_samples = 1000
# weights = (0.50, 0.50)
# class_sep = 0.8
# class_balance = None
# ```
#
# With a 95% / 5% class distribution:
# ```
# n_samples = 1000
# weights = (0.95, 0.05)
# class_sep = 0.8
# class_balance = None
# ```
#
# With the same 95% / 5% class distribution, but changing the Logistic Regression's `class_balance` parameter to `'balanced'` (instead of its default `None`)
# ```
# n_samples = 1000
# weights = (0.95, 0.05)
# class_sep = 0.8
# class_balance = 'balanced'
# ```
#
# With the same 95% / 5% class distribution, but with different values for `class_balance`:
# - `{0: 1, 1: 1}` _(equivalent to `None`)_
# - `{0: 1, 1: 2}`
# - `{0: 1, 1: 10}` _(roughly equivalent to `'balanced'` for this dataset)_
# - `{0: 1, 1: 100}`
# - `{0: 1, 1: 10000}`
#
# How do the evaluation metrics and decision region plots change?
# + [markdown] colab_type="text" id="5-3MS-jANssN"
# ## What you can do about imbalanced classes
# + [markdown] colab_type="text" id="2KwgStd-yUUr"
# [Learning from Imbalanced Classes](https://www.svds.com/tbt-learning-imbalanced-classes/) gives "a rough outline of useful approaches" :
#
# - Do nothing. Sometimes you get lucky and nothing needs to be done. You can train on the so-called natural (or stratified) distribution and sometimes it works without need for modification.
# - Balance the training set in some way:
# - Oversample the minority class.
# - Undersample the majority class.
# - Synthesize new minority classes.
# - Throw away minority examples and switch to an anomaly detection framework.
# - At the algorithm level, or after it:
# - Adjust the class weight (misclassification costs).
# - Adjust the decision threshold.
# - Modify an existing algorithm to be more sensitive to rare classes.
# - Construct an entirely new algorithm to perform well on imbalanced data.
#
# + [markdown] colab_type="text" id="iO7kOZ2HN0EA"
# #### We demonstrated two of these options:
#
# - "Adjust the class weight (misclassification costs)" — many scikit-learn classifiers have a `class_balance` parameter
# - "Adjust the decision threshold" — you can lean more about this in a great blog post, [Visualizing Machine Learning Thresholds to Make Better Business Decisions](https://blog.insightdatascience.com/visualizing-machine-learning-thresholds-to-make-better-business-decisions-4ab07f823415).
#
# #### Another option to be aware of:
# - The [imbalance-learn](https://github.com/scikit-learn-contrib/imbalanced-learn) library can be used to "oversample the minority class, undersample the majority class, or synthesize new minority classes."
# + [markdown] colab_type="text" id="P_XjBTW5SBwZ"
# # ASSIGNMENT
#
# #### Bank Marketing
# - Try the `class_weight` parameter.
# - Explore and visualize your data.
# - Wrangle [bad data](https://github.com/Quartz/bad-data-guide), outliers, and missing values.
# - Try engineering more features. You can transform, bin, and combine features.
# - Try selecting fewer features.
#
#
# #### Imbalanced Classes demo with synthetic data
# - Play around with the demo. Change parameter values.
# - Be able to calculate precision, recall, F1, and accuracy "by hand", given a confusion matrix and access to Wikipedia.
#
# # STRETCH
# - Read the blog post, [Visualizing Machine Learning Thresholds to Make Better Business Decisions](https://blog.insightdatascience.com/visualizing-machine-learning-thresholds-to-make-better-business-decisions-4ab07f823415). You can replicate the code as-is, ["the hard way"](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit). Or you can apply it to the Bank Marketing dataset.
# - Try the [imbalance-learn](https://github.com/scikit-learn-contrib/imbalanced-learn) library.
# - Try other [scikit-learn classifiers](https://scikit-learn.org/stable/supervised_learning.html), beyond Logistic Regression.
|
module3-classification-metrics/LS_DS_233_Classification_Metrics_Imbalanced_Classes.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
X
Y=X.cursor()
Y.execute("select * from 'Supermarket_sales'")
new_list=[]
for k in Y.fetchall():
new_list.append(int(k[16]))
new_list
print("Maximum of Unitprice is = ",max(new_list))
print("Minimum of Unitprice is = ",min(new_list))
print("AVG of Unitprice is = ",sum(new_list)/len(new_list))
X.commit()
Y.close()
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
X
Y=X.cursor()
Y.execute("select * from 'Supermarket_sales'")
new_list=[]
for k in Y.fetchall():
new_list.append(int(k[7]))
new_list
print("Maximum of Unitprice is = ",max(new_list))
print("Minimum of Unitprice is = ",min(new_list))
print("AVG of Unitprice is = ",sum(new_list)/len(new_list))
X.commit()
Y.close()
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
X
Y=X.cursor()
Y.execute("SELECT * FROM Supermarket_sales WHERE Productline='Health and beauty'")
new_list=[]
for k in Y.fetchall():
new_list.append(int(k[7]))
new_list
# +
print("Maximum of Quantity with Health and Beauty is = ",max(new_list))
print("Minimum of Quantity with Health and Beauty = ",min(new_list))
print("Average of Quantity with Health and Beauty = ",sum(new_list)/len(new_list))
# -
X.commit()
Y.close()
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
Y=X.cursor()
Y.execute("SELECT * FROM Supermarket_sales WHERE Productline='Health and beauty'")
new_list=[]
for k in Y.fetchall():
new_list.append(int(k[16]))
new_list
# +
print("Maximum of unitprice with Health and Beauty is = ",max(new_list))
print("Minimum of unitprice with Health and Beauty = ",min(new_list))
print("Average of unitprice with Health and Beauty = ",sum(new_list)/len(new_list))
# -
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
Y=X.cursor()
Y.execute("SELECT * FROM Supermarket_sales WHERE Productline='Electronic accessories'")
new_list=[]
for k in Y.fetchall():
new_list.append(int(k[7]))
new_list
# +
print("Maximum of Quantity with Electronic accessories is = ",max(new_list))
print("Minimum of Quantity with Electronic accessories = ",min(new_list))
print("Average of Quantity with Electronic accessories = ",sum(new_list)/len(new_list))
# -
X.commit()
Y.close()
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
Y=X.cursor()
Y.execute("SELECT * FROM Supermarket_sales WHERE Gender = 'Male' AND Productline = 'Health and beauty'")
new_list=[]
for k in Y.fetchall():
new_list.append(int(k[7]))
len(new_list)
X.commit()
Y.close()
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
Y=X.cursor()
Y.execute("SELECT * FROM Supermarket_sales WHERE Gender = 'Female' AND Productline = 'Electronic accessories'")
new_list=[]
for k in Y.fetchall():
new_list.append(int(k[7]))
len(new_list)
X.commit()
Y.close()
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
Y=X.cursor()
Y.execute("SELECT * FROM Supermarket_sales WHERE Gender = 'Female' AND (Productline = 'Electronic accessories'or 'Sports and travel')")
new_list=[]
for k in Y.fetchall():
new_list.append(int(k[7]))
len(new_list)
X.commit()
Y.close()
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
Y=X.cursor()
Y.execute("select * from 'Supermarket_sales'")
tax_value=[]
for k in Y.fetchall():
tax_value.append(int(k[8]))
len(tax_value)
Y.execute("select * from 'Supermarket_sales'")
qt=[]
for k in Y.fetchall():
qt.append(int(k[7]))
len(qt)
import matplotlib.pyplot as plt
plt.scatter(qt,tax_value)
X.commit()
Y.close()
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
Y=X.cursor()
new_list=[]
Y.execute("SELECT * FROM Supermarket_sales WHERE City='Yangon'")
for k in Y.fetchall():
new_list.append(int(k[7]))
sum(new_list)
Y.execute("SELECT * FROM Supermarket_sales WHERE City='Yangon'")
new_data=[]
Y.execute("SELECT * FROM Supermarket_sales WHERE City='Mandalay'")
for k in Y.fetchall():
new_data.append(int(k[7]))
sum(new_data)
X.commit()
Y.close()
import sqlite3
X = sqlite3.connect('SalesDBNEW.db')
Y=X.cursor()
Y.execute("SELECT * FROM Supermarket_sales WHERE City='Yangon'")
new_list=[]
for k in Y.fetchall():
new_list.append(int(k[8]))
sum(new_list)
|
Sales Analysis(SQL).ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Input and output for Onsager transport calculation
#
# The Onsager calculators currently include two computational approaches to determining transport coefficients: an "interstitial" calculation, and a "vacancy-mediated" calculator. Below we describe the
#
# 0. **Assumptions used in transport model** that are necessary to understand the data to be input, and the limitations of the results;
# 1. **Crystal class setup** needed to initiate a calculation;
# 2. **Interstitial calculator setup** needed for an single mobile species calculation, or,
# 3. **Vacancy-mediated calculator setup** needed for a vacancy-mediated substitutional solute calculation;
# 4. the creation of **VASP-style input files** to be run to generate input data;
# 5. proper **Formatting of input data** to be compatible with the calculators; and
# 6. **Interpretation of output** which includes how to convert output into transport coefficients.
#
# This follows the overall structure of a transport coefficient calculation. Broadly speaking, these are the steps necessary to compute transport coefficients:
#
# 1. Identify the crystal to be considered; this requires mapping whatever defects are to be considered mobile onto appropriate Wyckoff sites in the crystal, even if those exact sites are not occupied by true atoms.
# 2. Generate lists of symmetry unrelated "defect states" and "defect state transitions," along with the appropriate "calculator object."
# 3. Construct input files for total energy calculations to be run outside of the Onsager codebase; extract appropriate energy and frequency information from those runs.
# 4. Input the data in a format that the calculator can understand, and transform those energies and frequencies into rates at a given temperature assuming Arrhenius behavior.
# 5. Transform the output into physically relevant quantities (Onsager coefficients, solute diffusivities, mobilities, or drag ratios) with appropriate units.
# ## Assumptions used in Onsager
#
# The `Onsager` code computes transport of defects on an infinite crystalline lattice. Currently, the code requires that the particular defects can be mapped onto Wyckoff positions in a crystal. This does not *require* that the defect be an atom occupying various Wyckoff positions (though that obviously is captured), but merely that the defect have the symmetry and transitions that can be equivalently described by an "object" that occupies Wyckoff positions. Simple examples include vacancies, substitutional solutes, simple interstitial atoms, as well as more complex cases such as split vacancy defects (e.g.: a V-O$_\text{i}$-V split double vacancy with oxygen interstitial in a closed-packed crystal; the entire defect complex can be mapped on to the Wyckoff position of the oxygen interstitial). In order to calculate diffusion, a few assumptions are made:
#
# * **defects are dilute:** we never consider more than one defect at a time in an "infinite" periodic crystal; the vacancy-mediated diffuser uses one vacancy and one solute.
# * **defects diffuse via a Markovian process**: defect states are well-defined, and the transition time from state-to-state is much longer than the equilibration time in a state, so that the evolution of the system is described by the Master equation with time-independent rates.
# * **defects do not alter the underlying symmetry of the crystal**: while the defect itself can have a lower symmetry (according to its Wyckoff position), the presence of a defect does not lead to a global phase transformation to a different crystal; moreover, the crystal maintains translational invariance so that the energy of the system with defect(s) is unchanged under translations.
#
# All of these assumptions are usually good: the dilute limit is valid without strong interactions (such as site blocking), Markovian processes are valid as long as barriers are a few times $k_\text{B}T$, and we are not currently aware of any (simple) defects that induce phase transformations.
#
# Furthermore, relaxation around a defect (or defect cluster) is allowed, but the assumption is that all of the atomic positions can be easily mapped back to "perfect" crystal lattice sites. This is an "off-lattice" model. In some cases, it can be possible to incorporate "new" states, especially metastable states, that are only accessible by a defect.
#
# Finally, the code requires that all diffusion happens on a single sublattice. This sublattice is defined by a single chemical species; it can include multiple Wyckoff positions. But the current algorithms assume that transitions do not result in the creation of *antisite defects* (where a chemical species is on an "incorrect" sublattice).
#
# ## Crystal class setup
#
# The assumption of translational invariance of our defects is captured by the use of a `Crystal` object. Following the standard definition of a crystal, we need to specify (a) three lattice vectors, and (b) at least one basis position, corresponding to at least one site. The crystal needs to contain *at least* the Wyckoff positions on a single sublattice corresponding to the diffusing defects. It can be useful for it to contain *more* atoms that act as "spectator" atoms: they do not participate in diffusion, but define both the underlying symmetry of the crystal, and if atomic-scale calculations will be used to compute configuration and transition-state energies, are necessary to define the energy landscape of diffusion.
#
# The lattice vectors of the underlying crystal set the units of *length* in the transport coefficients. Hence, if the vectors are entered in units of nm, this corresponds to a factor of $10^{-18}\text{ m}^2$ in the transport coefficients. This should also be considered when including factors of volume per atom as well.
#
# * The *lattice vectors* are given by three vectors, $\mathbf{a}_1$, $\mathbf{a}_2$, $\mathbf{a}_3$ in Cartesian coordinates. In python, these are input when creating a Crystal either as a list of three `numpy` vectors, *or* as a square `numpy` matrix. **Note:** if you enter the three vectors as a matrix, remember that **it assumes the vectors are column vectors**. That is, if `amat` is the matrix, then `amat[:,0]` is $\mathbf{a}_1$, `amat[:,1]` is $\mathbf{a}_2$, and `amat[:,2]` is $\mathbf{a}_3$. **This may not be what you're expecting.** The main recommendation is to enter the lattice vectors as a list (or tuple) of three `numpy` vectors.
# * The *atomic basis* is given by a *list* of *lists* of `numpy` vectors of positions in *unit cell coordinates*. For a given `basis`, then `basis[0]` is a list of all positions for the first chemical element in the crystal, `basis[1]` is the second chemical element, and so on. **If you only have a single chemical element, you may enter a list of `numpy` vectors.**
# * An optional *spin* degree of freedom can be included. This is a list of objects, with one for each chemical element. These can be either scalar or vectors, with the assumption that they transform as those objects under group operations. If not included, the spins are all assumed to be equal to 0. Inclusion of these additional degrees of freedom (currently) only impacts the reduction of the unit cell, and the construction of the space group operations.
# * We also take in, strictly for bookkeeping purposes, a list of names for the chemical elements. *This is an optional input*, but recommended for readability.
#
# Once initialized, two main internal operations take place:
#
# 1. The unit cell is *reduced* and *optimized*. Reduction is a process where we try to find the smallest unit cell representation for the `Crystal`. This means that the four-atom "simple cubic" unit cell of face-centered cubic can be input, and the code will reduce it to the standard single-atom primitive cell. The reduction algorithm can end up with "unusual" choices of lattice vectors, so we also optimize the lattice vectors so that they are as close to orthogonal as possible, and ordered from smallest to largest. The atomic basis may be shifted uniformly so that *if* an inversion operation is present, then the inversion center is the origin. Neither choice changes the representation of the crystal; however, the *reduction* operation can be skipped by including the option `noreduce=True`.
# 2. Full symmetry analysis is performed, including: automated construction of space group generator operators, partitioning of basis sites into symmetry related Wyckoff positions, and determination of point group operations for every basis site. All of these operations are automated, and make no reference to crystallographic tables. The algorithm cannot identify which space group it has generated, nor which Wyckoff positions are present. The algorithm respects both *chemistry* and *spin*; this also makes spin a useful manipulation tool to artificially lower symmetry for testing purposes as needed.
#
# **Note**: `Crystal`s can also be constructed by manipulating existing `Crystal` objects. A useful case is for the interstitial diffuser: when working "interactively," it is often easier to first make the underlying "spectator" crystal, and then have that `Crystal` construct the set of Wyckoff positions for a single site in the crystal, and then add that to the basis. `Crystal` objects are intended to be read-only, so these manipulations result in the creation of a new `Crystal` object.
#
# A few quick examples:
import numpy as np
import sys
sys.path.extend(['.', '..'])
from onsager import crystal
# ### Face-centered cubic crystal, vacancy-diffusion
#
# Face-centered cubic crystals could be created either by entering the primitive basis:
a0 = 1.
FCCcrys = crystal.Crystal([a0*np.array([0,0.5,0.5]),
a0*np.array([0.5,0,0.5]),
a0*np.array([0.5,0.5,0])],
[np.array([0.,0.,0.])], chemistry=['fcc'])
print(FCCcrys)
# or by entering the simple cubic unit cell with four atoms:
FCCcrys2 = crystal.Crystal(a0*np.eye(3),
[np.array([0.,0.,0.]), np.array([0,0.5,0.5]),
np.array([0.5,0,0.5]), np.array([0.5,0.5,0])],
chemistry=['fcc'])
print(FCCcrys2)
# The effect of `noreduce` can be seen by regenerating the FCC crystal using the simple cubic unit cell:
FCCcrys3 = crystal.Crystal(a0*np.eye(3),
[np.array([0.,0.,0.]), np.array([0,0.5,0.5]),
np.array([0.5,0,0.5]), np.array([0.5,0.5,0])],
chemistry=['fcc'], noreduce=True)
print(FCCcrys3)
# ### Rocksalt crystal, vacancy-diffusion
# Two chemical species, with interpenetrating FCC lattices. In MgO, we would allow for V$_\text{O}$ (oxygen vacancies) to diffuse, with Mg as a "spectator species":
MgO = crystal.Crystal([a0*np.array([0,0.5,0.5]),
a0*np.array([0.5,0,0.5]),
a0*np.array([0.5,0.5,0])],
[[np.array([0.,0.,0.])], [np.array([0.5,0.5,0.5])]],
chemistry=['Mg', 'O'])
print(MgO)
# ### Face-centered cubic crystal, interstitial diffusion
# Interstitials in FCC crystals usually diffuse through a network of octahedral and tetrahedral sites. We can use the `Wyckoffpos(u)` function in a crystal to generate a list of equivalent sites corresponding to the interstitial positions, and the `addbasis()` function to create a new crystal with these interstitial sites.
octbasis = FCCcrys.Wyckoffpos(np.array([0.5, 0.5, 0.5]))
tetbasis = FCCcrys.Wyckoffpos(np.array([0.25, 0.25, 0.25]))
FCCcrysint = FCCcrys.addbasis(octbasis + tetbasis, ['int'])
print(octbasis)
print(tetbasis)
print(FCCcrysint)
# ## Interstitial calculator setup
# The `Interstitial` calculator is designed for systems where we have a **single defect species** that diffuses throughout the crystal. This includes single vacancy diffusion, and interstitial solute diffusivity. As for any diffusion calculator, we need to define the configurations that the defect will sample, and the transition states of the defect. In the case of a single defect species,
#
# * configurations are simply the Wyckoff positions of the particular sublattice (specified by a `chemistry` index);
# * transition states are pairs of configurations with a displacement vector that connects the initial to the final system.
#
# We use the `sitelist(chemistry)` function to construct a *list* of *lists* of indices for a given `chemistry`; the lists of indices are all symmetrically equivalent crystal basis indices, and each list is symmetrically inequivalent: this is a space group partitioning into equivalent Wyckoff positions.
#
# The transition states are stored as a `jumpnetwork`, which is a *list* of *lists* of *tuples* of transitions: `(initial index, final index, deltax)` where the indices are self-explanatory, and `deltax` is a Cartesian vector corresponding to the translation from the initial state to the final state. The transitions in each list is equivalent by symmetry, and the separate lists are symmetrically inequivalent. Note also that *reverse* transitions are included: `(final index, initial index, -deltax)`. While the jumpnetwork can be constructed "by hand," it is recommended to use the `jumpnetwork()` function inside of a crystal to automate the generation, and then remove "spurious" transitions that are identified.
#
# The algorithm in `jumpnetwork()` is rather simple: a transition is included if
#
# * the distance between the initial and final state is less than a cutoff distance, and
# * the line segment between the initial and final state does not come within a minimum distance of other defect states, and
# * the line segment between the initial and final state does not come within a minimum distance of *any* atomic site in the crystal.
#
# The first criterion identifies "close" jumps, while the second criterion eliminates "long" transitions between states when an intermediate configuration may be possible (i.e., $\text{A}\to\text{B}$ when $\text{A}\to\text{C}\to\text{B}$ would be more likely as the state C is "close" to the line connecting A to B), and the final criterion elimates transitions that takes the defect too close to a "spectator" atom in the crystal.
#
# The interstitial diffuser also identifies unique **tags** for all configurations and transition states. The interstitial tags for *configurations* are strings with `i:` followed by unit cell coordinates of site to three decimal digits. The interstitial tags for *transition states* are strings with `i:` followed by the unit cell coordinates of the initial state, a `^`, and the unit cell coordinates of the final state. When one pretty-prints the interstitial diffuser object, the symmetry unique tags are printed. Note that all of the symmetry equivalent tags are stored in the object, and can be used to identify configurations and transition states, and this is the preferred method for indexing, rather than relying on the particular index into the corresponding lists. The interstitial diffuser calculator contains dictionaries that can be used to convert from tags to indices and vice versa.
#
# Finally, `YAML` interfaces to output the `sitelist` and `jumpnetwork` for an interstitial diffuser are includes; combined with the `YAML` output of the Crystal, this allows for a `YAML` serialized representation of the diffusion object.
from onsager import OnsagerCalc
# ### Face-centered cubic crystal, vacancy-diffusion
#
# We identify the vacancy sites with the crystal sites in the lattice.
chem = 0
FCCsitelist = FCCcrys.sitelist(chem)
print(FCCsitelist)
chem = 0
FCCjumpnetwork = FCCcrys.jumpnetwork(chem, cutoff=a0*0.78)
for n, jn in enumerate(FCCjumpnetwork):
print('Jump type {}'.format(n))
for (i,j), dx in jn:
print(' {} -> {} dx= {}'.format(i,j,dx))
chem = 0
FCCvacancydiffuser = OnsagerCalc.Interstitial(FCCcrys, chem, FCCsitelist, FCCjumpnetwork)
print(FCCvacancydiffuser)
# ### Rocksalt crystal, vacancy-diffusion
# Two chemical species, with interpenetrating FCC lattices. In MgO, we would allow for V$_\text{O}$ (oxygen vacancies) to diffuse, with Mg as a "spectator species".
chem = 1
MgOsitelist = MgO.sitelist(chem)
print(MgOsitelist)
chem = 1
MgOjumpnetwork = MgO.jumpnetwork(chem, cutoff=a0*0.78)
for n, jn in enumerate(MgOjumpnetwork):
print('Jump type {}'.format(n))
for (i,j), dx in jn:
print(' {} -> {} dx= {}'.format(i,j,dx))
chem = 1
MgOdiffuser = OnsagerCalc.Interstitial(MgO, chem, MgOsitelist, MgOjumpnetwork)
print(MgOdiffuser)
# ### Face-centered cubic crystal, interstitial diffusion
# Interstitials in FCC crystals usually diffuse through a network of octahedral and tetrahedral sites. Nominally, diffusion should occur through an octahedral-tetrahedral jumps, but we can extend the cutoff distance to find additinoal jumps between tetrahedrals.
chem = 1
FCCintsitelist = FCCcrysint.sitelist(chem)
print(FCCintsitelist)
chem = 1
FCCintjumpnetwork = FCCcrysint.jumpnetwork(chem, cutoff=a0*0.51)
for n, jn in enumerate(FCCintjumpnetwork):
print('Jump type {}'.format(n))
for (i,j), dx in jn:
print(' {} -> {} dx= {}'.format(i,j,dx))
chem = 1
FCCintdiffuser = OnsagerCalc.Interstitial(FCCcrysint, chem,
FCCintsitelist, FCCintjumpnetwork)
print(FCCintdiffuser)
# The `YAML` representation is intended to combine both the structural information necessary to construct the (1) crystal, (2) chemistry index of the diffusing defect, (3) sitelist, and (4) jumpnetwork; **and** the energies, prefactors, and elastic dipoles (derivative of energy with respect to strain) for the symmetry representatives of configurations and jumps. This will become input for the diffuser when computing transport coefficients as a function of temperature, as well as derivatives with respect to strain (elastodiffusion tensor, activation volume tensor).
print(FCCintdiffuser.crys.simpleYAML() +
'chem: {}\n'.format(FCCintdiffuser.chem) +
FCCintdiffuser.sitelistYAML(FCCintsitelist) +
FCCintdiffuser.jumpnetworkYAML(FCCintjumpnetwork))
# ## Vacancy-mediated calculator setup
# For the vacancy mediated diffuser, the configurations and transition states are more complicated. First, we have three types of configurations:
#
# 1. Vacancy, sufficiently far away from the solute to have zero interaction energy.
# 2. Solute, sufficiently far away from the vacancy to have zero interaction energy.
# 3. Vacancy-solute complexes.
#
# The vacancies and solutes are assumed to be able to occupy the *same* sites in the crystal, and that neither the vacancy or solute lowers the underlying symmetry of the site. This is a rephrasing of our previous assumption that the symmetry of the defect can be mapped onto the symmetry of the crystal Wyckoff position. There are cases where *this is not true*: that is, some solutes, when substituted into a crystal, will relax in a way that *breaks symmetry*. While mathematically this can be treated, we do not currently have an implementation that supports this.
#
# The complexes are only considered out to a finite distance; this is called the "thermodynamic range." It is defined in terms of "shells," which is the number of "jumps" from the solute in order to reach the vacancy. We include one more shell out, called the "kinetic range," which are complexes that include transitions to complexes in the thermodynamic range.
#
# When we consider transition states, we have three types of transition states:
#
# 1. Vacancy transitions, sufficiently far away from the solute to have zero interaction energy.
# 2. Vacancy-solute complex transitions, where only the vacancy changes position (both between complexes in the thermodynamic range, and between the kinetic and thermodynamic range).
# 3. Vacancy-solute complex transitions, where the vacancy and solute exchange place.
#
# These are called, in the "five-frequency framework", omega-0, omega-1, and omega-2 jumps, respectively. The five-frequency model technically identifies omega-1 jumps as *only* between complexes in the thermodynamic range, while the two "additional" jump types, omega-3 and omega-4, connect complexes in the kinetic range to the thermodynamic range. Operationally, we combine omega-1, -3, and -4 into a single set.
#
# To make a diffuser, we need to
#
# 1. Identify the `sitelist` of the vacancies (and hence, solutes),
# 2. Identify the `jumpnetwork` of the vacancies
# 3. Determine the thermodynamic range
#
# then, the diffuser automatically constructs the complexes out to the thermodynamic range, and the full jumpnetworks.
#
# The vacancy-mediated diffuser also identifies unique **tags** for all configurations and transition states. The tags for *configurations* are strings with
#
# * `v:` followed by unit cell coordinates of site to three decimal digits for the vacancy;
# * `s:` followed by unit cell coordinates of site to three decimal digits for the solute;
# * `s:...-v:...` for a solute-vacancy complex.
#
# The *transition states* are strings with
#
# * `omega0:` + (initial vacancy configuration) + `^` + (final vacancy configuration);
# * `omega1:` + (initial solute-vacancy configuration) + `^` + (final vacancy configuration);
# * `omega2:` + (initial solute-vacancy configuration) + `^` + (final solute-vacancy configuration).
#
# When one pretty-prints the vacancy-mediated diffuser object, the symmetry unique tags are printed. Note that all of the symmetry equivalent tags are stored in the object, and can be used to identify configurations and transition states, and this is the preferred method for indexing, rather than relying on the particular index into the corresponding lists. The vacancy-mediated diffuser calculator contains dictionaries that can be used to convert from tags to indices and vice versa.
# ### Face-centered cubic crystal, vacancy mediated-diffusion
#
# We construct the `Onsager` equivalent of the classic five-frequency model. We can use the sitelist and jumpnetwork that we *already constructed for the vacancy by itself*. Note that the omega-1 list contains four jumps: one that is the normally identified "omega-1", and three others that correspond to vacancy "escapes" from the first neighbor complex: to the second, third, and fourth neighbors. In the classic five-frequency model, these rates are all forced to be equal.
chem = 0
fivefreqdiffuser = OnsagerCalc.VacancyMediated(FCCcrys, chem,
FCCsitelist, FCCjumpnetwork, 1)
print(fivefreqdiffuser)
# An `HDF5` representation of the diffusion calculator can be stored for efficient reconstruction of the object, as well as passing between machines. The `HDF5` representation includes *everything*: the underlying `Crystal`, the `sitelist` and `jumpnetwork`s, all of the precalculation and analysis needed for diffusion. This greatly speeds up the construction of the calculator.
# +
import h5py
# replace '/dev/null' with your file of choice, and remove backing_store=False
# to read and write to an HDF5 file.
f = h5py.File('/dev/null', 'w', driver='core', backing_store=False)
fivefreqdiffuser.addhdf5(f) # adds the diffuser to the HDF5 file
# how to read in (after opening `f` as an HDF5 file)
fivefreqcopy = OnsagerCalc.VacancyMediated.loadhdf5(f) # creates a new diffuser from HDF5
f.close() # close up the HDF5 file
print(fivefreqcopy)
# -
# ## VASP-style input files
# At this stage, we have the diffusion "calculator" necessary to compute diffusion, but we need to determine appropriate atomic-scale data to act as input into our calculators. There are two primary steps: (1) constructing appropriate "supercells" containing defect configurations and transition states to be computed, and (2) extracting the appropriate information from those calculations to use in the diffuser. This section deals with the former; the next section will deal with the latter.
#
# The tags are the most straightforward way to identify structures as they are computed, and hence they serve as the mechanism for communicating data into the calculators. To make supercells with defects, we take advantage of the `supercell` module in `Onsager`; both calculators contain a `makesupercell()` function that returns dictionaries of supercells, tags, and appropriate information. Currently, to transform these into usable input files, the `automator` module can convert such dictionaries into tarballs with an appropriate directory structure, files containing information about appropriate tags for the different configurations, a `Makefile` that converts `CONTCAR` output into appropriate `POS` input for the nudged-elastic band calculation.
#
# Both `makesupercell()` commands require an input supercell definition, which is a $3\times3$ integer matrix of column vectors; if `N` is such a matrix, then the supercell vectors are the columns of `A = np.dot(a, N)`, so that $\mathbf A_1$ has components `N[:,0]` in direct coordinates.
from onsager import automator
import tarfile
# ### Face-centered cubic crystal, interstitial diffusion
# We will need to construct (and relax) appropriate intersitial sites, and the transition states between them.
help(FCCintdiffuser.makesupercells)
N = np.array([[-2,2,2],[2,-2,2],[2,2,-2]]) # 32 atom FCC supercell
print(np.dot(FCCcrys.lattice, N))
FCCintsupercells = FCCintdiffuser.makesupercells(N)
help(automator.supercelltar)
with tarfile.open('io-test-int.tar.gz', mode='w:gz') as tar:
automator.supercelltar(tar, FCCintsupercells)
tar = tarfile.open('io-test-int.tar.gz', mode='r:gz')
tar.list()
# Contents of the `Makefile`:
with tar.extractfile('Makefile') as f:
print(f.read().decode('ascii'))
# Contents of the `tags.json` file:
with tar.extractfile('tags.json') as f:
print(f.read().decode('ascii'))
# Contents of one `POSCAR` file for relaxation of a configuration:
with tar.extractfile('relax.00/POSCAR') as f:
print(f.read().decode('ascii'))
tar.close()
# ### Face-centered cubic crystal, vacancy mediated-diffusion
# We will need to construct (and relax) appropriate vacancy, solute, and solute-vacancy complexes, and the transition states between them. The commands are nearly identical to the interstitial diffuser; the primary difference is the larger number of configurations and files.
help(fivefreqdiffuser.makesupercells)
N = np.array([[-3,3,3],[3,-3,3],[3,3,-3]]) # 108 atom FCC supercell
print(np.dot(FCCcrys.lattice, N))
fivefreqsupercells = fivefreqdiffuser.makesupercells(N)
with tarfile.open('io-test-fivefreq.tar.gz', mode='w:gz') as tar:
automator.supercelltar(tar, fivefreqsupercells)
tar = tarfile.open('io-test-fivefreq.tar.gz', mode='r:gz')
tar.list()
# Contents of `Makefile`:
with tar.extractfile('Makefile') as f:
print(f.read().decode('ascii'))
# Contents of the `tags.json` file:
with tar.extractfile('tags.json') as f:
print(f.read().decode('ascii'))
# Contents of one `POSCAR` file for relaxation of a configuration:
with tar.extractfile('relax.01/POSCAR') as f:
print(f.read().decode('ascii'))
tar.close()
# ## Formatting of input data
# Once the atomic-scale data from an appropriate total energy calculation is finished, the data needs to be input into formats that the appropriate diffusion calculator can understand. There are some common definitions between the two, but some differences as well.
#
# In all cases, we work with the assumption that our states are thermally occupied, and our rates are Arrhenius. That means that the (relative) probability of any state can be written as
# $$\rho = Z^{-1}\rho^0 \exp(-E/k_\text{B}T)$$
#
#
# for the partition function $Z$, a site entropic term $\rho^0 = \exp(S/k_\text{B})$, and energy $E$. The transition rate from state A to state B is given by
# $$\lambda(\text{A}\to\text{B}) = \frac{\nu^\text{T}_{\text{A}-\text{B}}}{\rho^0_A} \exp(-(E^\text{T}_{\text{A}-\text{B}} - E_\text{A})/k_\text{B}T)$$
#
#
# where $E^\text{T}_{\text{A}-\text{B}}$ is the energy of the transition state between A and B, and $\nu^\text{T}_{\text{A}-\text{B}}$ is the prefactor for the transition state.
#
# If we assume harmonic transition state theory, then we can write the site entropic term $\rho^0$ as
# $$\rho^0 = \frac{\prod \nu^{\text{perfect-supercell}}}{\prod \nu^{\text{defect-supercell}}}$$
#
#
# where $\nu$ are the vibrational eigenvalues of the corresponding supercells, and the prefactor for the transition state is
# $$\nu^\text{T} = \frac{\prod \nu^{\text{perfect-supercell}}}{\prod_{\nu^2>0} \nu^{\text{transition state}}}$$
#
#
# where we take the product over the real vibrational frequencies in the transition state (there should be one imaginary mode). From a practical point of view, the perfect-supercell cancels out; we will often set $\rho^0$ to 1 for a single state (so that the other $\rho^0$ are relative probabilities), and then $\nu^\text{T}$ becomes more similar to the attempt frequency for the particular jumps. The definitions above map most simply onto a "hopping atom" approximation for the jump rates: the $3\times3$ force-constant matrix is computed for the atom that is moving in the transition, and its eigenvalues are used to determine the modes $\nu$.
#
# Note the units: $\rho^0$ is unitless, while $\nu^\text{T}$ has units of inverse time; this means that the inverse time unit in the computed transport coefficients will come from $\nu^\text{T}$ values. If they are entered in THz, that contributes $10^{12}\text{ s}^{-1}$.
#
# Because we normalize our probabilities, our energies and transition state energies are relative to each other. In all of our calculations, we will multiply energies by $\beta=(k_\text{B}T)^{-1}$ to get a unitless values as inputs for our diffusion calculators. This means that the diffusers *do not have direct information about temperature*; explicit temperature factors that appear in the Onsager coefficients must be included by hand from the output transport coefficients. It also means that the calculators do not have a "unit" of energy; rather, $k_\text{B}T$ and the energies must be in the same units.
#
# ### Face-centered cubic crystal, interstitial diffusion
# We need to compute prefactors and energies for our interstitial diffuser. We can *also* include information about elastic dipoles (derivatives of energy with respect to strain) in order to compute derivatives of diffusivity with respect to strain (elastodiffusion).
help(FCCintdiffuser.diffusivity)
# The ordering in the lists `pre`, `beteene`, `preT` and `betaeneT` corresponds to the `sitelist` and `jumpnetwork` lists. The tags can be used to determine the proper indices. The most straightforward way to store this in python is a dictionary, where the key is the tag, and the value is a list of `[prefactor, energy]`. The advantage of this is that it can be easily transformed to and from `JSON` for simple serialization.
#
# To see a full list of all tags in the dictionary, the `tags` member of a diffuser gives a dictionary of all tags, ordered to match the structure of `sitelist` and `jumpnetwork`.
FCCintdiffuser.tags
# In this example, the energy of the octahedral site is 0, with a base prefactor of 1. The tetrahedral site has an energy of 0.5 (eV) above, with a higher relative vibrational degeneracy of 2. The transition state energy from octahedral to tetrahedral is 1.0 (eV) with a prefactor of 10 (THz); and the transition state energy from tetrahedral to tetrahedral is 2.0 (eV) with a prefactor of 50 (THz).
FCCintdata = {
'i:+0.500,+0.500,+0.500': [1., 0.],
'i:+0.750,+0.750,+0.750': [2., 0.5],
'i:+0.500,+0.500,+0.500^i:+0.750,+0.750,-0.250': [10., 1.0],
'i:+0.750,+0.750,+0.750^i:+1.250,+1.250,+0.250': [50., 2.0]
}
# Conversion from dictionary to lists for a given kBT
# We go through the tags in order, and find one in our data set.
kBT = 0.25 # eV; a rather high temperature
pre = [FCCintdata[t][0] for taglist in FCCintdiffuser.tags['states']
for t in taglist if t in FCCintdata]
betaene = [FCCintdata[t][1]/kBT for taglist in FCCintdiffuser.tags['states']
for t in taglist if t in FCCintdata]
preT = [FCCintdata[t][0] for taglist in FCCintdiffuser.tags['transitions']
for t in taglist if t in FCCintdata]
betaeneT = [FCCintdata[t][1]/kBT for taglist in FCCintdiffuser.tags['transitions']
for t in taglist if t in FCCintdata]
print(pre,betaene,preT,betaeneT,sep='\n')
DFCCint, dDFCCint = FCCintdiffuser.diffusivity(pre, betaene, preT, betaeneT, CalcDeriv=True)
print(DFCCint, dDFCCint, sep='\n')
# The interpretation of this output will be described below.
# ### Face-centered cubic crystal, vacancy mediated-diffusion
# We will need to compute prefactors and energies for our vacancy, solute, and solute-vacancy complexes, and the transition states between them. The difference compared with the interstitial case is that complex prefactors and energies are *excess* quantities. That means for a complex, its $\rho^0$ is the product of $\rho^0$ for the solute state, the vacancy state, *and* the excess; the energy $E$ is the sum of the energy of the solute state, the vacancy state, *and* the excess. **However** for the *transition states*, the prefactors and energies are "absolute".
help(fivefreqdiffuser.Lij)
# The vacancy-mediated diffuser expects combined $\beta F := (E - TS)/k_\text{B}T$, so that our probabilities and rates are proportional to $\exp(-\beta F)$. This is complicated to directly construct, so we have the intermediate function `preene2betafree()`, which is best used by feeding a *dictionary* of arrays:
help(fivefreqdiffuser.preene2betafree)
# Even this is a bit complicated; so we use an additional function that maps the tags into the appropriate lists, `tags2preene()`:
help(fivefreqdiffuser.tags2preene)
# In this example, we have a vacancy-solute binding energy of -0.25 (eV), a vacancy jump barrier of 1.0 (eV) with a prefactor of 10 (THz), an "omega-1" activation barrier of 0.75 (eV) which is a transition state energy of 0.75-0.25 = 0.5, an omega-2 activation barrier of 0.5 (eV) which is a transition state energy of 0.5-0.25 = 0.25, and all of the "omega-3/-4" escape jumps with a transition state energy of 1-0.25/2 = 0.875 (eV).
fivefreqdata = {
'v:+0.000,+0.000,+0.000': [1., 0.],
's:+0.000,+0.000,+0.000': [1., 0.],
's:+0.000,+0.000,+0.000-v:+0.000,-1.000,+0.000': [1., -0.25],
'omega0:v:+0.000,+0.000,+0.000^v:+0.000,+1.000,+0.000': [10., 1.],
'omega1:s:+0.000,+0.000,+0.000-v:+1.000,+0.000,-1.000^v:+1.000,+1.000,-1.000': [10., 0.5],
'omega1:s:+0.000,+0.000,+0.000-v:+1.000,-1.000,+0.000^v:+1.000,+0.000,+0.000': [20., 0.875],
'omega1:s:+0.000,+0.000,+0.000-v:-1.000,+1.000,+0.000^v:-1.000,+2.000,+0.000': [20., 0.875],
'omega1:s:+0.000,+0.000,+0.000-v:+0.000,+1.000,+0.000^v:+0.000,+2.000,+0.000': [20., 0.875],
'omega2:s:+0.000,+0.000,+0.000-v:+0.000,-1.000,+0.000^s:+0.000,+0.000,+0.000-v:+0.000,+1.000,+0.000':
[10., 0.25]
}
# Conversion from dictionary to lists for a given kBT
# note that we can nest the mapping functions.
kBT = 0.25 # eV; a rather high temperature
fivefreqpreene = fivefreqdiffuser.tags2preene(fivefreqdata)
fivefreqbetaF = fivefreqdiffuser.preene2betafree(kBT, **fivefreqpreene)
L0vv, Lss, Lsv, L1vv = fivefreqdiffuser.Lij(*fivefreqbetaF)
print(L0vv, Lss, Lsv, L1vv, sep='\n')
# The interpretation of this output will be described below.
# ## Interpretation of output
# The final step is to take the output from the diffuser calculator, and convert this into physical quantities: solute diffusivity, elastodiffusivity, Onsager coefficients, drag ratios, and so on.
#
# There are two underlying definitions that we use to define our transport coefficients:
# $$\mathbf j = -\underline D \nabla c$$
#
#
# defines the *solute diffusivity* as the tensorial transport coefficient that relates defect concentration gradients to defect fluxes, and
# $$\mathbf j^\text{s} = -\underline L^\text{ss}\nabla\mu^\text{s} - \underline L^\text{sv}\nabla\mu^\text{v}$$
#
#
# $$\mathbf j^\text{v} = -\underline L^\text{vv}\nabla\mu^\text{v} - \underline L^\text{sv}\nabla\mu^\text{s}$$
#
#
# defines the *Onsager coefficients* as the tensorial transport coefficients that relate solute and vacancy chemical potential gradients to solute and vacancy fluxes. We use these equation to also define the *units* of our transport coefficients. Fluxes are in units of (number)/area/time, so with concentration in (number)/volume, diffusivity has units of area/time. If the chemical potential is written in units of energy, the Onsager coefficients have units of (number)/length/energy/time. If the chemical potentials will instead have units of energy/volume, then the corresponding Onsager coefficients have units of area/energy/time.
#
# Below are more specific details about the different calculators and the output available.
# ### Interstitial diffusivity
# The interstitial diffuser outputs a diffusivity tensor that has the units of squared length based on the lengths in the corresponding `Crystal`, and inverse time units corresponding to the rates that are given as input: the ratio of transition state prefactors to configuration prefactors. In a crystalline system, it is typical to specify the lattice vectors in either nm ($10^{-9}\text{ m}$) or Å ($10^{-10}\text{ m}$), and the prefactors of rates are often THz ($10^{12}\text{ s}$), while diffusivity is often reported in either $\text{m}^2/\text{s}$ or $\text{cm}^2/\text{s}$. The conversion factors are
# $$1\text{ nm}^2\cdot\text{THz} = 10^{-6}\text{ m}^2/\text{s} = 10^{-2}\text{ cm}^2/\text{s}$$
#
#
# $$1\text{ A}^2\cdot\text{THz} = 10^{-8}\text{ m}^2/\text{s} = 10^{-4}\text{ cm}^2/\text{s}$$
#
#
#
# It it worth noting that this model of diffusion assumes that the "interstitial" form of the defect is its ground state configuration (or at least *one* of the configurations used in the derivation of the diffusivity is a ground state configuration). This is generally the case for the diffusion of a vacancy, or light interstitial elements; however, the are materials where a solute has a lower energy as a substitutional defect, but can occupy an interstitial site and diffuse from there. This requires knowledge of the *relative occupancy* of the two states. Using Kroger-Vink notation, let [B] be the total solute concentration, and $[\text{B}_\text{A}]$ and $[\text{B}_\text{i}]$ the substitutional and interstitial concentrations, then
# $$D_\text{B} = \left\{[\text{B}_\text{i}]D_\text{int} + [\text{B}_\text{A}]D_\text{sub}\right\}/[\text{B}]$$
#
#
# for interstitial diffusivity $D_\text{int}$ and substitutional diffusivity $D_\text{sub}$. The relative occupancies may be determined by *global thermal equilibrium* or *local thermal equilibrium*. The latter is more complex, and relies on knowledge of local defect processes and conditions, and is not discussed further here. For global thermal equilibrium, if we know the energy of the ground state substitutional defect $E_\text{sub}$ and the lowest energy configuration used by the diffuser $E_\text{int}$, then
# $$[\text{B}_\text{i}]/[\text{B}] = (1 + \exp((E_\text{int}-E_\text{sub})/k_\text{B}T)^{-1} \approx \exp(-(E_\text{int}-E_\text{sub})/k_\text{B}T)$$
#
#
# and
# $$[\text{B}_\text{A}]/[\text{B}] = (1 + \exp(-(E_\text{int}-E_\text{sub})/k_\text{B}T)^{-1} \approx 1$$
#
#
# where the approximations are valid when $E_\text{int}-E_\text{sub}\gg k_\text{B}T$.
# ### Derivatives of diffusivity: activation barrier tensor
# At any given temperature, the temperature dependence of the diffusivity can be taken as an Arrhenius form,
# $$\underline D = \underline D_0 \exp(-\beta \underline E^\text{act})$$
#
#
# for inverse temperature $\beta = (k_\text{B}T)^{-1}$, and the activation barrier, $\underline E^\text{act}$ can also display anisotropy. Note that in this expression, the exponential is taken on a per-component basis, not as a true tensor exponential.
# We can compute $Q$ by taking the per-component logarithmic derivative with respect to inverse temperature,
# $$\underline E^\text{act} = -\underline D^{-1/2}\frac{d\underline D}{d\beta}\underline D^{-1/2}$$
#
#
# The `diffusivity()` function with `CalcDeriv=True` returns a second tensorial quantity, `dD` which when multiplied by $k_\text{B}T$, gives $d\underline D/d\beta$. Hence, to compute the activation barrier tensor, we evaluate:
print(np.dot(np.linalg.inv(DFCCint), kBT*dDFCCint))
# In this case, as the matrices are isotropic, we can use $\underline D^{-1}$ rather than $\underline D^{-1/2}$ which must be computed via diagonalization.
#
# This tensor has the same energy units as the variable `kBT`.
#
# Given the barriers for diffusion, one might have expected that $\underline E^\text{act}$ would be 1, as that is the transition state energy to go from octahedral to tetrahedral. However, the activation barrier is approximately the rate-limiting transition state energy minus the *average configuration energy*. Since we've chosen a large temperature, the tetrahedral sites have non-negligible occupation, which raises the average energy. As the temperature decreases, the activation energy will approach 1.
# ### Derivatives of diffusivity: elastodiffusion and activation volume tensor
# The derivative with respect to strain is the fourth-rank *elastodiffusivity* tensor $\underline d$, where
# $$d_{abcd} = \frac{dD_{ab}}{d\varepsilon_{cd}}$$
#
#
# This is returned by the `elastodiffusion` function, which requires the elastic dipole tensors be included in the function call as well. The elastic dipoles have the same units of energies, and so are input as $\beta\underline P$, which is unitless. The returned tensor has the same units as the diffusivity.
#
# The *activation volume* tensor (logarithmic derivative of diffusivity with respect to stress) can be computed from the elastodiffusivity tensor if the compliance tensor $\underline S$ is known; then,
# $$V^\text{act}_{abcd} = k_\text{B}T \sum_{ijkl=1}^3 (\underline D^{-1/2})_{ai} d_{ijkl} (\underline D^{-1/2})_{bj} S_{klcd}$$
#
#
# The units of this quantity are given by the units of $k_\text{B}T$ (energy) multiplied by the units of $\underline S$ (inverse pressure). Typically, $k_\text{B}T$ will be known in eV and $\underline S$ in GPa$^{-1}$, so the conversion factor
# $$1\text{ eV}\cdot\text{GPa}^{-1} = 1.6022\times10^{-19}\text{ J}\cdot10^{-9}\text{ m}^3/\text{J} = 0.16022\text{ nm}^3 = 160.22\text{ A}^3$$
#
#
# can be useful.
# ### Vacancy-mediated diffusivity
# The interstitial diffuser outputs a diffusivity tensor that has the units of squared length based on the lengths in the corresponding `Crystal`, and inverse time units corresponding to the rates that are given as input: the ratio of transition state prefactors to configuration prefactors. In a crystalline system, it is typical to specify the lattice vectors in either nm ($10^{-9}\text{ m}$) or Å ($10^{-10}\text{ m}$), and the prefactors of rates are often THz ($10^{12}\text{ s}$). The quantities `L0vv`, `Lss`, `Lsv`, and `L1vv` output by the `Lij` function all have the units of area/time, so the the conversion factors below are often useful:
# $$1\text{ nm}^2\cdot\text{THz} = 10^{-6}\text{ m}^2/\text{s} = 10^{-2}\text{ cm}^2/\text{s}$$
#
#
# $$1\text{ A}^2\cdot\text{THz} = 10^{-8}\text{ m}^2/\text{s} = 10^{-4}\text{ cm}^2/\text{s}$$
#
#
# To convert the four quantities into $\underline L^\text{vv}$, $\underline L^\text{ss}$, and $\underline L^\text{sv}$, some additional information is required.
#
# First, in the dilute limit, $\underline L^\text{ss}$ and $\underline L^\text{sv}$ are proportional to $(k_\text{B}T)^{-1}c^\text{v}c^\text{s}$; none of these quantities are known to the diffuser, and the two concentrations are essentially independent variables that must be supplied. The concentrations in these cases are *fractional concentrations*, not per volume. Finally, if the Onsager coefficients are for chemical potential specified as energies (not energies per volume), the quantities need to be *divided by the volume per atom*, and the final quantity has the appropriate units. Hence,
#
# * $\underline L^\text{ss}$ = `Lss*(solute concentration)*(vacancy concentration)/(volume)/kBT`
# * $\underline L^\text{sv}$ = `Lsv*(solute concentration)*(vacancy concentration)/(volume)/kBT`
#
# where the concentration quantities are *fractional*.
#
# The vacancy $\underline L^\text{vv}$ is more complicated, as it has a leading order term that is independent of solute, and a first order correction that is linear in the solute concentration. Hence,
#
# * $\underline L^\text{vv}$ = `(L0vv + L1vv*(solute concentration))*(vacancy concentration)/(volume)/kBT`
# ### Drag ratio
# The *drag ratio* is the unitless (tensorial) quantity $\underline L^\text{sv}(\underline L^\text{ss})^{-1}$. Because of the identical prefactors in front of both terms in the dilute limit, this is given by
print(np.dot(Lsv, np.linalg.inv(Lss)))
# The vacancy wind factor $G=\underline L^\text{As}(\underline L^\text{ss})^{-1}$ is related to the drag ratio by simple transformations.
# ### Solute diffusivity in the dilute limit
# The solute diffusivity can also be computed for the dilute limit as well. The general relation between $\underline D^\text{s}$ and the Onsager transport coefficients is
# $$\underline D^\text{s} = k_\text{B}T\Omega\left\{(c^\text{s})^{-1}\underline L^\text{ss} - (1-c^\text{s}-c^\text{v})^{-1}\underline L^\text{As}\right\}\left(1+\frac{d\ln\gamma^\text{s}}{d\ln c^\text{s}}\right)$$
#
#
# where $\Omega$ is the volume per atom and $\gamma^\text{s}$ is the solute activity:
# $$\mu^\text{s} = \mu^\text{s}_0 + k_\text{B}T\ln\left(\gamma^\text{s}c^\text{s}/c^\text{s}_0\right)$$
#
#
# In the dilute limit, $\gamma^\text{s}\to 1$, and thus
# $$\underline D^\text{s} = k_\text{B}T\Omega(c^\text{s})^{-1}\underline L^\text{ss}$$
#
#
# Conveniently, this cancels most of the "missing" prefactors we put in to compute the Onsager coefficient; hence,
#
# * $\underline D^\text{s}$ = `Lss*(vacancy concentration)`
#
# where the concentration quantities are *fractional*. In the case of *global thermal equilibrium*, the vacancy concentration is the equilibrium concentration $\exp(-(E^\text{v}_\text{form} - TS^\text{v}_\text{form})/k_\text{B}T)$.
#
# A similar argument holds for the vacancy diffusivity in the dilute limit
#
# * $\underline D^\text{v}$ = `L0vv + (solute concentration)*L1vv`
#
# The off-diagonal diffusivity terms are more complex as (1) they are non-symmetric ($\underline D^\text{sv} \ne \underline D^\text{vs}$), and (2) the vacancy-dependency of the solute activity and the solute-dependence of the vacancy activity needs to be known to properly include thermodynamic factors.
|
docs/source/InputOutput.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import os
os.chdir('/home/yash/Desktop/tensorflow-adversarial/tf_example')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn import ModeKeys, Estimator
import _pickle as pickle
from scipy.misc import imread
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from fgsm_cifar import fgsm
from fgsm_cifar_wrt_class import fgsm_wrt_class
import mnist
import sys
img_rows = 32
img_cols = 32
img_chas = 3
input_shape = (img_rows, img_cols, img_chas)
n_classes = 10
def load_CIFAR10(ROOT):
""" load all of cifar """
xs = []
ys = []
for b in range(1,6):
f = os.path.join(ROOT, 'data_batch_%d' % (b, ))
X, Y = load_CIFAR_batch(f)
xs.append(X)
ys.append(Y)
Xtr = np.concatenate(xs)
Ytr = np.concatenate(ys)
del X, Y
Xte, Yte = load_CIFAR_batch(os.path.join(ROOT, 'test_batch'))
return Xtr, Ytr, Xte, Yte
def load_CIFAR_batch(filename):
""" load single batch of cifar """
with open(filename, 'rb') as f:
datadict = pickle.load(f,encoding='latin1')
X = datadict['data']
Y = datadict['labels']
X = X.reshape(10000, 3, 32, 32).transpose(0,2,3,1).astype("float")
Y = np.array(Y)
return X, Y
def find_l2_batch(X_test, X_adv):
ans = np.zeros([X_test.shape[0],n_classes], dtype = np.float32)
for i in range(X_test.shape[0]):
for j in range(n_classes):
ans[i][j] = find_l2(X_test[i], X_adv[i][j])
return ans
# m2 is the grouped flipping
# m1 is the single flipping
#This method returns the distance of each predictions from repective test points calculated by m1 and m2 resp.
def find_m1_m2(X_test,X_adv_one,X_adv_test):
dist_adv_m1 = find_l2(X_test, X_adv_one)
b = find_l2_batch(X_test, X_adv_test)
dist_adv_m2 = np.partition(b,axis=1,kth=1)[:,1]
return np.sqrt(dist_adv_m1), np.sqrt(dist_adv_m2)
# Give this function X_adv_test it gives you the points corresponding to
# each example having min dists and their indices
def give_m2_ans(X_test, X_adv_test):
dists = find_l2_batch(X_test, X_adv_test)
second_min_indices = np.partition(dists, axis=1, kth=1)[:,1]
for i in range(X_test.shape[0]):
second_min_indices[i] = np.where(second_min_indices[i] == dists[i])[0]
return second_min_indices, X_adv_test[second_min_indices.astype(int)]
def random_normal_func(X, n):
X=X.reshape(-1,img_rows*img_cols*img_chas)
print(X.shape)
mean, std = np.mean(X, axis=0), np.std(X,axis=0)
randomX = np.zeros([n,X[0].size])
print(randomX.shape)
for i in range(X[0].size):
randomX[:,i] = np.random.normal(mean[i],std[i],n)
randomX = randomX.reshape(-1,img_rows,img_cols,img_chas)
ans = sess.run(env.ybar, feed_dict={env.x: randomX,env.training: False})
labels = _to_categorical(np.argmax(ans,axis=1), n_classes)
return randomX,labels
def remove_zeroes(X):
indices = np.where(X == 0)[0]
return np.delete(X,indices)
def get_class(X,Y,cls):
Y=np.argmax(Y, axis=1)
indices = np.where(Y==cls)
return X[indices], Y[indices]
def get_flipped_class(X_adv,cls):
return X_adv[:,cls]
# +
print('\nLoading CIFAR10')
ab=sys.getdefaultencoding()
print(ab)
cifar10_dir = 'cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
X_train = X_train.astype('float32') / 255.
X_test = X_test.astype('float32') / 255.
X_train = X_train.reshape(-1, img_rows, img_cols, img_chas)
X_test = X_test.reshape(-1, img_rows, img_cols, img_chas)
# X_train=X_train[:100]
# y_train=y_train[:100]
# +
# one hot encoding, basically creates hte si
def _to_categorical(x, n_classes):
x = np.array(x, dtype=int).ravel()
n = x.shape[0]
ret = np.zeros((n, n_classes))
ret[np.arange(n), x] = 1
return ret
def find_l2(X_test, X_adv):
a=X_test.reshape(-1,32*32*3)
b=X_adv.reshape(-1,32*32*3)
l2_unsquared = np.sum(np.square(a-b),axis=1)
return l2_unsquared
y_train = _to_categorical(y_train, n_classes)
y_test = _to_categorical(y_test, n_classes)
print('\nShuffling training data')
ind = np.random.permutation(X_train.shape[0])
X_train, y_train = X_train[ind], y_train[ind]
# split training/validation dataset
validation_split = 0.1
n_train = int(X_train.shape[0]*(1-validation_split))
X_valid = X_train[n_train:]
X_train = X_train[:n_train]
y_valid = y_train[n_train:]
y_train = y_train[:n_train]
class Dummy:
pass
env = Dummy()
# -
print (X_test.shape)
def model(x, logits=False, training=False):
conv0 = tf.layers.conv2d(x, filters=32, kernel_size=[3, 3],
padding='same', name='conv0',
activation=tf.nn.relu)
pool0 = tf.layers.max_pooling2d(conv0, pool_size=[2, 2],
strides=2, name='pool0')
conv1 = tf.layers.conv2d(pool0, filters=64,
kernel_size=[3, 3], padding='same',
name='conv1', activation=tf.nn.relu)
pool1 = tf.layers.max_pooling2d(conv1, pool_size=[2, 2],
strides=2, name='pool1')
conv2 = tf.layers.conv2d(pool1, filters=128,
kernel_size=[1,1], padding='same',
name='conv2', activation=tf.nn.relu)
flat = tf.reshape(conv2, [-1, 8*8*128], name='flatten')
dense1 = tf.layers.dense(flat, units= 1024, activation=tf.nn.relu,
name='dense1')
dense2 = tf.layers.dense(dense1, units=128, activation=tf.nn.relu,
name='dense2')
logits_ = tf.layers.dense(dense2, units=10, name='logits') #removed dropout
y = tf.nn.softmax(logits_, name='ybar')
if logits:
return y, logits_
return y
# +
# We need a scope since the inference graph will be reused later
with tf.variable_scope('model'):
env.x = tf.placeholder(tf.float32, (None, img_rows, img_cols,
img_chas), name='x')
env.y = tf.placeholder(tf.float32, (None, n_classes), name='y')
env.training = tf.placeholder(bool, (), name='mode')
env.ybar, logits = model(env.x, logits=True,
training=env.training)
z = tf.argmax(env.y, axis=1)
zbar = tf.argmax(env.ybar, axis=1)
env.count = tf.cast(tf.equal(z, zbar), tf.float32)
env.acc = tf.reduce_mean(env.count, name='acc')
xent = tf.nn.softmax_cross_entropy_with_logits(labels=env.y,
logits=logits)
env.loss = tf.reduce_mean(xent, name='loss')
extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(extra_update_ops):
env.optim = tf.train.AdamOptimizer(beta1=0.9, beta2=0.999, epsilon=1e-08,).minimize(env.loss)
# -
with tf.variable_scope('model', reuse=True):
for i in range(n_classes):
if(i==0):
env.x_adv_wrt_class = (fgsm_wrt_class(model, env.x, i, step_size=.05, bbox_semi_side=10))
else:
x = (fgsm_wrt_class(model, env.x, i, step_size=.05, bbox_semi_side=10))
env.x_adv_wrt_class = tf.concat([env.x_adv_wrt_class, x],axis=0)
env.x_adv, env.all_flipped = fgsm(model, env.x, step_size=.05, bbox_semi_side=10) #epochs is redundant now!
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
# +
def save_model(label):
saver = tf.train.Saver()
saver.save(sess, './models/cifar/' + label)
def restore_model(label):
saver = tf.train.Saver()
saver.restore(sess, './models/cifar/' + label)
# -
def _evaluate(X_data, y_data, env):
print('\nEvaluating')
n_sample = X_data.shape[0]
batch_size = 128
n_batch = int(np.ceil(n_sample/batch_size))
loss, acc = 0, 0
ns = 0
for ind in range(n_batch):
print(' batch {0}/{1}'.format(ind+1, n_batch), end='\r')
start = ind*batch_size
end = min(n_sample, start+batch_size)
batch_loss, batch_count, batch_acc = sess.run(
[env.loss, env.count, env.acc],
feed_dict={env.x: X_data[start:end],
env.y: y_data[start:end],
env.training: False})
loss += batch_loss*batch_size
print('batch count: {0}'.format(np.sum(batch_count)))
ns+=batch_size
acc += batch_acc*batch_size
loss /= ns
acc /= ns
# print (ns)
# print (n_sample)
print(' loss: {0:.4f} acc: {1:.4f}'.format(loss, acc))
return loss, acc
# +
def _predict(X_data, env):
print('\nPredicting')
n_sample = X_data.shape[0]
batch_size = 128
n_batch = int(np.ceil(n_sample/batch_size))
yval = np.empty((X_data.shape[0], n_classes))
for ind in range(n_batch):
print(' batch {0}/{1}'.format(ind+1, n_batch), end='\r')
start = ind*batch_size
end = min(n_sample, start+batch_size)
batch_y = sess.run(env.ybar, feed_dict={
env.x: X_data[start:end], env.training: False})
yval[start:end] = batch_y
return yval
def train(label):
print('\nTraining')
n_sample = X_train.shape[0]
batch_size = 128
n_batch = int(np.ceil(n_sample/batch_size))
n_epoch = 50
for epoch in range(n_epoch):
print('Epoch {0}/{1}'.format(epoch+1, n_epoch))
for ind in range(n_batch):
print(' batch {0}/{1}'.format(ind+1, n_batch), end='\r')
start = ind*batch_size
end = min(n_sample, start+batch_size)
sess.run(env.optim, feed_dict={env.x: X_train[start:end],
env.y: y_train[start:end],
env.training: True})
if(epoch%5 == 0):
model_label = label+ '{0}'.format(epoch)
print("saving model " + model_label)
save_model(model_label)
save_model(label)
# -
def create_adv_wrt_class(X, Y, label):
print('\nCrafting adversarial')
n_sample = X.shape[0]
pred = np.argmax(Y,axis=1)
batch_size = 1
n_batch = int(np.ceil(n_sample/batch_size))
n_epoch = 20
x_adv_shape = list(X.shape)[1:]
x_adv_shape = np.append(np.append(n_sample,n_classes),x_adv_shape)
X_adv = np.empty(x_adv_shape)
for ind in range(n_batch):
print(' batch {0}/{1}'.format(ind+1, n_batch), end='\r')
start = ind*batch_size
end = min(n_sample, start+batch_size)
tmp = sess.run(env.x_adv_wrt_class, feed_dict={env.x: X[start:end],
env.y: Y[start:end],
env.training: False})
# _evaluate(tmp, Y[start:end],env)
# print (tmp.shape)
tmp[pred[start]] = X[start]
X_adv[start:end] = tmp
# print(all_flipped)
print('\nSaving adversarial')
# os.makedirs('data', exist_ok=True)
# np.save('data/cifar/' + label + '.npy', X_adv)
return X_adv
def create_adv(X, Y, label):
print('\nCrafting adversarial')
n_sample = X.shape[0]
batch_size = 1
n_batch = int(np.ceil(n_sample/batch_size))
n_epoch = 20
X_adv = np.empty_like(X)
for ind in range(n_batch):
print(' batch {0}/{1}'.format(ind+1, n_batch), end='\r')
start = ind*batch_size
end = min(n_sample, start+batch_size)
tmp, all_flipped = sess.run([env.x_adv, env.all_flipped], feed_dict={env.x: X[start:end],
env.y: Y[start:end],
env.training: False})
# _evaluate(tmp, Y[start:end],env)
X_adv[start:end] = tmp
# print(all_flipped)
print('\nSaving adversarial')
# os.makedirs('data', exist_ok=True)
# np.save('data/cifar/' + label + '.npy', X_adv)
return X_adv
label="cifar_with_cnn"
# train(label) # else
#Assuming that you've started a session already else do that first!
restore_model(label + '45')
# _evaluate(X_train, y_train, env)
# +
# test = "test"
# train = "train"
# random = "random"
# X_adv_test = np.load('data/' + test + '.npy')
# X_adv_train = np.load('data/' + train + '.npy')
# X_adv_random = np.load('data/' + random + '.npy')
# -
# X_random = np.random.rand(10000,img_rows,img_cols,1)
# X_train_sub = X_train[:10000]
# X_random = X_random[:10000]
# +
test_m1 = "test_fs_m1"
test_m2 = "test_fs_m2"
train_m1 = "train_fs_m1"
train_m2 = "train_fs_m2"
random_m1 = "random_fs_m1"
random_m2 = "random_fs_m2"
random_normal_m1= "random_normal_fs_m1"
random_normal_m2 = "random_normal_fs_m2"
n = 1000
X_test_sub = X_test[:n]
X_train_sub = X_train[:n]
y_train_sub = sess.run(env.ybar, feed_dict={env.x: X_train_sub,env.training: False})
y_train_sub = _to_categorical(np.argmax(y_train_sub, axis=1), n_classes)
y_test_sub = sess.run(env.ybar, feed_dict={env.x:X_test_sub ,env.training: False})
y_test_sub = _to_categorical(np.argmax(y_test_sub, axis=1), n_classes)
X_random = np.random.rand(n,img_rows,img_cols,img_chas)
X_random = X_random[:n]
y_random = sess.run(env.ybar, feed_dict={env.x: X_random,env.training: False})
y_random = _to_categorical(np.argmax(y_random, axis=1), n_classes)
X_random_normal, y_random_normal = random_normal_func(X_train,n)
X_adv_test_m1 = create_adv(X_test_sub, y_test_sub, test_m1)
X_adv_train_m1 = create_adv(X_train_sub, y_train_sub, train_m1)
X_adv_random_m1 = create_adv(X_random,y_random, random_m1)
X_adv_random_normal_m1 = create_adv(X_random_normal, y_random_normal, random_normal_m1)
# _, X_adv_test_m2 = give_m2_ans(X_test_sub, create_adv_wrt_class(X_test_sub, y_test_sub, test_m2))
# _, X_adv_train_m2 = give_m2_ans(X_train_sub, create_adv_wrt_class(X_train_sub, y_train_sub, train_m2))
# _, X_adv_random_m2 = give_m2_ans(X_random, create_adv_wrt_class(X_random, y_random, random_m2))
# _, X_adv_random_normal_m2 = give_m2_ans(X_random_normal, create_adv_wrt_class(X_random_normal, y_random_normal, random_normal_m2))
# X_adv_test_m1 = np.load('data/' + test_m1 + '.npy')
# X_adv_test_m2 = np.load('data/' + test_m2 + '.npy')
# X_adv_train = np.load('data/' + train + '.npy')
# X_adv_random = np.load('data/' + random + '.npy')
# X_adv_random_normal = np.load('data/' + random_normal + '.npy')
# +
# for i in range(n):
# y_adv_pred = sess.run(env.ybar, feed_dict={env.x: X_adv_test[i],env.training: False})
# print (np.argmax(y_adv_pred, axis=1))
# print (np.argmax(sess.run(env.ybar, feed_dict={env.x: X_adv_one, env.training: False}), axis=1))
# a=find_l2_batch(X_test[:n],X_adv_test)
# c=find_l2_batch(X_adv_one,X_adv_test)
# b=find_l2(X_test[:n], X_adv_one)
# # a,b = find_m1_m2(X_test[:n], X_adv_one, X_adv_test)
# # print(a-b)
# x= (np.partition(a,axis=1,kth=1)[:,1])
# k= (np.partition(c,axis=1,kth=0)[:,0])
# for i in range(n):
# x[i]=(np.where(a[i] == x[i])[0])
# k[i]=(np.where(c[i] == k[i])[0])
# print (x)
# print (k)
# +
l2_test_m1 = find_l2(X_adv_test_m1,X_test_sub)
l2_train_m1 = find_l2(X_adv_train_m1, X_train_sub)
l2_random_m1 = find_l2(X_adv_random_m1,X_random)
l2_random_normal_m1 = find_l2(X_adv_random_normal_m1,X_random_normal)
# l2_test_m2 = find_l2(X_adv_test_m2,X_test_sub)
# l2_train_m2 = find_l2(X_adv_train_m2, X_train_sub)
# l2_random_m2 = find_l2(X_adv_random_m2,X_random)
# l2_random_normal_m2 = find_l2(X_adv_random_normal_m2,X_random_normal)
# +
nz_test = np.count_nonzero(l2_test_m1)
nz_train = np.count_nonzero(l2_train_m1)
nz_random = np.count_nonzero(l2_random_m1)
nz_random_normal = np.count_nonzero(l2_random_normal_m1)
print (nz_test)
print (nz_train)
print (nz_random)
print (nz_random_normal)
l2_test_m1 = remove_zeroes(l2_test_m1)
l2_random_m1 = remove_zeroes(l2_random_m1)
l2_random_normal_m1 = remove_zeroes(l2_random_normal_m1)
l2_test_m1 = remove_zeroes(l2_test_m1)
min_no = min(nz_test, nz_train)
l2_train_m1 = np.sqrt(l2_train_m1[:min_no])
l2_test_m1 = np.sqrt(l2_test_m1[:min_no])
l2_random_m1 = np.sqrt(l2_random_m1[:min_no])
l2_random_normal_m1 = np.sqrt(l2_random_normal_m1[:min_no])
# np.count_nonzero(l2_test_m2)
# np.count_nonzero(l2_train_m2)
# np.count_nonzero(l2_random_m2)
# np.count_nonzero(l2_random_normal_m2)
# -
# +
# %matplotlib inline
# evenly sampled time at 200ms intervals
t = np.arange(1,min_no+1, 1)
# red dashes, blue squares and green triangles
plt.plot(t, l2_test_m1, 'r--', t, l2_train_m1, 'b--', t, l2_random_m1, 'y--', l2_random_normal_m1, 'g--')
plt.show()
# +
import matplotlib.patches as mpatches
# %matplotlib inline
# evenly sampled time at 200ms intervals
t = np.arange(1,101, 1)
# red dashes, blue squares and green triangles
plt.plot(t, l2_test_m1[:100], 'r--', t, l2_train_m1[:100], t, l2_random_m1[:100], 'y--', l2_random_normal_m1[:100], 'g--')
blue_patch = mpatches.Patch(color='blue', label='Train Data')
plt.legend(handles=[blue_patch])
plt.show()
# -
# %matplotlib inline
plt.hist(l2_test_m1,150, range = (0,2))
plt.title("L2 distance of test data")
plt.xlabel("Distance")
plt.ylabel("Frequency")
plt.show()
# %matplotlib inline
plt.hist(l2_train_m1,150, range = (0,2))
plt.title("L2 distance of train data")
plt.xlabel("Distance")
plt.ylabel("Frequency")
plt.show()
# %matplotlib inline
plt.hist(l2_random_m1,100)
plt.title("L2 distance of random data")
plt.xlabel("Distance")
plt.ylabel("Frequency")
plt.show()
# %matplotlib inline
plt.hist(l2_random_normal_m1,100)
plt.title("L2 distance of random normal data")
plt.xlabel("Distance")
plt.ylabel("Frequency")
plt.show()
|
CIFAR/.ipynb_checkpoints/ex_lass_signum_no_fixed-step-length-CIFAR10-M1-epoch100-checkpoint.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.7 (RAPIDS)
# language: python
# name: rapids
# ---
# + [markdown] colab_type="text" id="PH-b-S2fC8q6"
# # Tutorial: Visualizing the Silk Road Blockchain with Graphistry and Neo4j
#
# Investigating large datasets becomes easier by directly visualizing cypher (BOLT) query results with Graphistry. This tutorial walks through querying Neo4j, visualizing the results, and additional configurations and queries.
#
# This analysis is based on a blockchain data extract the Graphistry team performed around court proceedings from when **<NAME>**, the key DEA agent in the Silk Road bust, was sentenced for embezzling money from **<NAME>** (Dread Pirate Roberts). We explore to how to recreate the analysis, and determine where Carl's money went after he performed the initial embezzling.
#
# **Instructions**
# * Read along the various cells
# * Click the prebuilt visualizations to start them, and interact with them just like Google Maps
# * To try on your own, setup your own Neo4j instance & get a Graphistry API key, and run the data loading cells
#
#
# **Further reading**
#
# * UI Guide: https://labs.graphistry.com/graphistry/ui.html
# * Python client tutorials & demos: https://github.com/graphistry/pygraphistry
# * Graphistry API Key: https://www.graphistry.com/api-request
# * Neo4j-as-a-service: http://graphstory.com
# * DEA incident: https://arstechnica.com/tech-policy/2016/08/stealing-bitcoins-with-badges-how-silk-roads-dirty-cops-got-caught/
# + [markdown] colab_type="text" id="3_k-GZjJDO1I"
# ## Config
# -
# **Install dependencies**
#
# * On first run of a non-Graphistry notebook server:
# 1. Uncomment and run the first two lines
# 2. Restart your Python kernel runtime from the top menue
# * For advanced alternate installs, see subsequent commented lines
# +
# #!pip install --user pandas
# #!pip install --user graphistry[bolt]
### ADVANCED:
### If you already have the neo4j python driver, you can leave out '[bolt]':
# ### !pip install --user graphistry
### If you already have graphistry but not neo4j, you can reuse your existing graphistry:
# ### !pip install --user neo4j
# -
# **Import & test**
import pandas as pd
import neo4j # just for testing
from neo4j import GraphDatabase # for data loader
import graphistry
print('neo4j', neo4j.__version__)
print('graphistry', graphistry.__version__)
# **Connect**
#
# * You may need to reconnect if your Neo4j connection closes
# * Uncomment the below section for non-Graphistry notebook servers
# + colab={} colab_type="code" id="kSJfTLxNDQi5"
NEO4J = {
'uri': "bolt://my.site.COM:7687",
'auth': ("neo4j", "<PASSWORD>")
}
graphistry.register(bolt=NEO4J)
## If not using the local Graphistry server
#GRAPHISTRY = {
# 'server': 'MY.GRAPHISTRY.COM',
# 'api': 2,
# 'key': 'MY_GRAPHISTRY_API_KEY'
#}
#graphistry.register(bolt=NEO4J, **GRAPHISTRY)
# + [markdown] colab_type="text" id="sRQ-M4Q4sq-8"
# ## Optional: Load tainted transactions into your own Neo4j DB
# To populate your own Neo4j instance, set one or both of the top commands to True
# + colab={} colab_type="code" id="qIk1pGXzsvxr"
DELETE_EXISTING_DATABASE=False
POPULATE_DATABASE=False
if DELETE_EXISTING_DATABASE:
driver = GraphDatabase.driver(**NEO4J)
with driver.session() as session:
# split into 2 transancations case of memory limit errors
print('Deleting existing transactions')
tx = session.begin_transaction()
tx.run("""MATCH (a:Account)-[r]->(b) DELETE r""")
tx.commit()
print('Deleting existing accounts')
tx = session.begin_transaction()
tx.run("""MATCH (a:Account) DELETE a""")
tx.commit()
print('Delete successful')
if POPULATE_DATABASE:
edges = pd.read_csv('https://www.dropbox.com/s/q1daa707y99ind9/edges.csv?dl=1')
edges = edges.rename(columns={'Amount $': "USD", 'Transaction ID': 'Transaction'})[['USD', 'Date', 'Source', 'Destination', 'Transaction']]
id_len = len(edges['Source'][0].split('...')[0]) #truncate IDs (dirty data)
edges = edges.assign(
Source=edges['Source'].apply(lambda id: id[:id_len]),
Destination=edges['Destination'].apply(lambda id: id[:id_len]))
ROSS_FULL='2a37b3bdca935152335c2097e5da367db24209cc'
ROSS = ROSS_FULL[:32]
CARL_FULL = 'b2233dd22ade4c9978ec1fd1fbb36eb7f9b4609e'
CARL = CARL_FULL[:32]
CARL_NICK = 'Carl Force (DEA)'
ROSS_NICK = 'Ro<NAME>bricht (SilkRoad)'
nodes = pd.read_csv('https://www.dropbox.com/s/nf796f1asow8tx7/nodes.csv?dl=1')
nodes = nodes.rename(columns={'Balance $': 'USD', 'Balance (avg) $': 'USD_avg', 'Balance (max) $': 'USD_max', 'Tainted Coins': 'Tainted_Coins'})[['Account', 'USD', 'USD_avg', 'USD_max', 'Tainted_Coins']]
nodes['Account'] = nodes['Account'].apply(lambda id: id[:id_len])
nodes['Account'] = nodes['Account'].apply(lambda id: CARL_NICK if id == CARL else ROSS_NICK if id == ROSS else id)
driver = GraphDatabase.driver(**NEO4J)
with driver.session() as session:
tx = session.begin_transaction()
print('Loading', len(nodes), 'accounts')
for index, row in nodes.iterrows():
if index % 2000 == 0:
print('Committing', index - 2000, '...', index)
tx.commit()
tx = session.begin_transaction()
tx.run("""
CREATE (a:Account {
Account: $Account,
USD: $USD, USD_avg: $USD_avg, USD_max: $USD_max, Tainted_Coins: $Tainted_Coins
})
RETURN id(a)
""", **row)
if index % 2000 == 0:
print(index)
print('Committing rest')
tx.commit()
tx = session.begin_transaction()
print('Creating index on Account')
tx.run(""" CREATE INDEX ON :Account(Account) """)
tx.commit()
STATUS=1000
BATCH=2000
driver = GraphDatabase.driver(**NEO4J)
with driver.session() as session:
tx = session.begin_transaction()
print('Loading', len(edges), 'transactions')
for index, row in edges.iterrows():
tx.run("""MATCH (a:Account),(b:Account)
WHERE a.Account = $Source AND b.Account = $Destination
CREATE (a)-[r:PAYMENT {
Source: $Source, Destination: $Destination, USD: $USD, Date: $Date, Transaction: $Transaction
}]->(b)
""", **row)
if index % STATUS == 0:
print(index)
if index % BATCH == 0 and index > 0:
print('sending batch out')
tx.commit()
print('... done')
tx = session.begin_transaction()
tx.commit()
# + [markdown] colab_type="text" id="mqbo_o0RMmkI"
# ## Cypher Demos
#
# ### 1a. Warmup: Visualize all $7K - $10K transactions
# Try panning and zooming (same touchpad/mouse controls as Google Maps), and clicking on individual wallets and transactions.
# + colab={} colab_type="code" id="fRXlWQvtycCM"
g = graphistry.cypher("""
MATCH (a)-[r:PAYMENT]->(b) WHERE r.USD > 7000 AND r.USD < 10000 RETURN a, r, b ORDER BY r.USD DESC
""")
# + colab={"base_uri": "https://localhost:8080/", "height": 543} colab_type="code" id="OrRqdkK4GhJl" outputId="2fc30291-063b-4a21-a704-2cde524b85e2"
g.plot()
# + [markdown] colab_type="text" id="RkrYDjcYl6g2"
# Screenshot
# 
# + [markdown] colab_type="text" id="TQzLQog09sjJ"
# ### 1b. Cleanup: Configure node and edge titles to use amount fields
# * **Static config**: We can preconfigure the visualization from directly within the notebook
# * **Dynamic config**: Try dynamically improving the visualization on-the-fly within the tool by
# * Do `add histogram for...` on `edge:USD` and `point:USD_MAX`
# * Set edge/point coloring using them, and selecting a "Gradient (Spectral7 7)" blend, and toggling to reverse order (so cold to hot).
# * For `point:USD_MAX`, toggle it to controling point size, and in the `Scene settings`, increase the point size slider
# + colab={"base_uri": "https://localhost:8080/", "height": 543} colab_type="code" id="B2Im4KZsDCLv" outputId="f2965600-2b14-421b-b780-6e8a0da7ca11"
g = g\
.bind(point_title='Account')\
.bind(edge_title='USD')
g.plot()
# + [markdown] colab_type="text" id="m4YvIWNP-fCe"
# ### 2. Look for all transactions 1-5 hops from embezzling DEA Agent Carl Force
#
# #### 2a. Downstream
# Where did most of Carl's money go?
# * Try setting up filters on `edge:USD` to separate out small vs big money flows.
# + colab={"base_uri": "https://localhost:8080/", "height": 543} colab_type="code" id="Uywc60Xq-slC" outputId="3c593d83-c824-4a78-ca7c-a04a9c04b059"
g.cypher("""
match (a)-[r:PAYMENT*1..20]->(b)
where a.Account = $root and ALL(transfer IN r WHERE transfer.USD > $min_amount and transfer.USD < $max_amount )
return a, r, b
""",
{'root': "Carl Force (DEA)",
'min_amount': 999,
'max_amount': 99999}).plot()
# + [markdown] colab_type="text" id="XaHKnft9cOf_"
# Screenshot:
#
# 
# + [markdown] colab_type="text" id="Kg5oaTufWqe6"
# #### 2b. Upstream
# From where did Carl get most of his money?
# + colab={"base_uri": "https://localhost:8080/", "height": 543} colab_type="code" id="hzv-tNMc_bZP" outputId="1462c06b-318f-4229-c4db-b265bdc4f868"
g.cypher("""
match (a)-[r:PAYMENT*1..10]->(b)
where b.Account=$sink and ALL(transfer IN r WHERE transfer.USD > $min_amount and transfer.USD < $max_amount )
return r, a, b
""",
{'sink': "Carl Force (DEA)",
'min_amount': 1999,
'max_amount': 99999}).plot()
# + [markdown] colab_type="text" id="OhglbPE7gAhq"
# Screenshot:
#
# 
# + [markdown] colab_type="text" id="gusmhJvHbvbh"
# ## 3. Paths between Silk Road and Carl Force
# + colab={"base_uri": "https://localhost:8080/", "height": 543} colab_type="code" id="kAnSUoJVWuQn" outputId="d31d0070-5eea-4a5c-b8c6-8915a2665f70"
g.cypher("match (a)-[r:PAYMENT*1..10]->(b) where a.Account=$silk and b.Account=$dea return r, a, b",
{'dea': "Carl Force (DEA)", "silk": "Ross Ulbricht (SilkRoad)"}).plot()
# + [markdown] colab_type="text" id="MvcNGnYIsgff"
# ## Further Reading
#
# * UI Guide: https://labs.graphistry.com/graphistry/ui.html
# * Python client tutorials & demos: https://github.com/graphistry/pygraphistry
# * DEA incident: https://arstechnica.com/tech-policy/2016/08/stealing-bitcoins-with-badges-how-silk-roads-dirty-cops-got-caught/
|
demos/demos_databases_apis/neo4j/official/graphistry_bolt_tutorial_public.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # GLM: Model Selection
# +
# %matplotlib inline
import pymc3 as pm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from collections import OrderedDict
from ipywidgets import interactive, fixed
plt.style.use('seaborn-darkgrid')
print('Runing on PyMC3 v{}'.format(pm.__version__))
rndst = np.random.RandomState(0)
# -
# A fairly minimal reproducable example of Model Selection using WAIC, and LOO as currently implemented in PyMC3.
#
# This example creates two toy datasets under linear and quadratic models, and then tests the fit of a range of polynomial linear models upon those datasets by using Widely Applicable Information Criterion (WAIC), and leave-one-out (LOO) cross-validation using Pareto-smoothed importance sampling (PSIS).
#
# The example was inspired by <NAME>' [blogpost](https://jakevdp.github.io/blog/2015/08/07/frequentism-and-bayesianism-5-model-selection/) on model selection, although Cross-Validation and Bayes Factor comparison are not implemented. The datasets are tiny and generated within this Notebook. They contain errors in the measured value (y) only.
#
# ### Local Functions
# +
def generate_data(n=20, p=0, a=1, b=1, c=0, latent_sigma_y=20):
'''
Create a toy dataset based on a very simple model that we might
imagine is a noisy physical process:
1. random x values within a range
2. latent error aka inherent noise in y
3. optionally create labelled outliers with larger noise
Model form: y ~ a + bx + cx^2 + e
NOTE: latent_sigma_y is used to create a normally distributed,
'latent error' aka 'inherent noise' in the 'physical' generating
process, rather than experimental measurement error.
Please don't use the returned `latent_error` values in inferential
models, it's returned in the dataframe for interest only.
'''
df = pd.DataFrame({'x':rndst.choice(np.arange(100), n, replace=False)})
## create linear or quadratic model
df['y'] = a + b*(df['x']) + c*(df['x'])**2
## create latent noise and marked outliers
df['latent_error'] = rndst.normal(0, latent_sigma_y, n)
df['outlier_error'] = rndst.normal(0, latent_sigma_y*10, n)
df['outlier'] = rndst.binomial(1, p, n)
## add noise, with extreme noise for marked outliers
df['y'] += ((1-df['outlier']) * df['latent_error'])
df['y'] += (df['outlier'] * df['outlier_error'])
## round
for col in ['y','latent_error','outlier_error','x']:
df[col] = np.round(df[col],3)
## add label
df['source'] = 'linear' if c == 0 else 'quadratic'
## create simple linspace for plotting true model
plotx = np.linspace(df['x'].min() - np.ptp(df['x'])*.1,
df['x'].max() + np.ptp(df['x'])*.1, 100)
ploty = a + b * plotx + c * plotx ** 2
dfp = pd.DataFrame({'x':plotx, 'y':ploty})
return df, dfp
def interact_dataset(n=20, p=0, a=-30, b=5, c=0, latent_sigma_y=20):
'''
Convenience function:
Interactively generate dataset and plot
'''
df, dfp = generate_data(n, p, a, b, c, latent_sigma_y)
g = sns.FacetGrid(df, size=8, hue='outlier', hue_order=[True,False]
,palette=sns.color_palette('Set1'), legend_out=False)
g.map(plt.errorbar, 'x', 'y', 'latent_error', marker="o",
ms=10, mec='w', mew=2, ls='', elinewidth=0.7).add_legend()
plt.plot(dfp['x'], dfp['y'], '--', alpha=0.8)
plt.subplots_adjust(top=0.92)
g.fig.suptitle('Sketch of Data Generation ({})'.format(df['source'][0]), fontsize=16)
def plot_datasets(df_lin, df_quad, dfp_lin, dfp_quad):
'''
Convenience function:
Plot the two generated datasets in facets with generative model
'''
df = pd.concat((df_lin, df_quad), axis=0)
g = sns.FacetGrid(col='source', hue='source', data=df, size=6,
sharey=False, legend_out=False)
g.map(plt.scatter, 'x', 'y', alpha=0.7, s=100, lw=2, edgecolor='w')
g.axes[0][0].plot(dfp_lin['x'], dfp_lin['y'], '--', alpha=0.6)
g.axes[0][1].plot(dfp_quad['x'], dfp_quad['y'], '--', alpha=0.6)
def plot_traces(traces, retain=1000):
'''
Convenience function:
Plot traces with overlaid means and values
'''
ax = pm.traceplot(traces[-retain:], figsize=(12,len(traces.varnames)*1.5),
lines={k: v['mean'] for k, v in pm.summary(traces[-retain:]).iterrows()})
for i, mn in enumerate(pm.summary(traces[-retain:])['mean']):
ax[i,0].annotate('{:.2f}'.format(mn), xy=(mn,0), xycoords='data',
xytext=(5,10), textcoords='offset points', rotation=90,
va='bottom', fontsize='large', color='#AA0022')
def create_poly_modelspec(k=1):
'''
Convenience function:
Create a polynomial modelspec string for patsy
'''
return ('y ~ 1 + x ' + ' '.join(['+ np.power(x,{})'.format(j)
for j in range(2, k+1)])).strip()
def run_models(df, upper_order=5):
'''
Convenience function:
Fit a range of pymc3 models of increasing polynomial complexity.
Suggest limit to max order 5 since calculation time is exponential.
'''
models, traces = OrderedDict(), OrderedDict()
for k in range(1, upper_order+1):
nm = 'k{}'.format(k)
fml = create_poly_modelspec(k)
with pm.Model() as models[nm]:
print('\nRunning: {}'.format(nm))
pm.glm.GLM.from_formula(fml, df,
priors={'Intercept':pm.Normal.dist(mu=0, sd=100)},
family=pm.glm.families.Normal())
traces[nm] = pm.sample(2000)
return models, traces
def plot_posterior_cr(models, traces, rawdata, xlims,
datamodelnm='linear', modelnm='k1'):
'''
Convenience function:
Plot posterior predictions with credible regions shown as filled areas.
'''
## Get traces and calc posterior prediction for npoints in x
npoints = 100
mdl = models[modelnm]
trc = pm.trace_to_dataframe(traces[modelnm][-1000:])
trc = trc[[str(v) for v in mdl.cont_vars[:-1]]]
ordr = int(modelnm[-1:])
x = np.linspace(xlims[0], xlims[1], npoints).reshape((npoints,1))
pwrs = np.ones((npoints,ordr+1)) * np.arange(ordr+1)
X = x ** pwrs
cr = np.dot(X, trc.T)
## Calculate credible regions and plot over the datapoints
dfp = pd.DataFrame(np.percentile(cr,[2.5, 25, 50, 75, 97.5], axis=1).T,
columns=['025','250','500','750','975'])
dfp['x'] = x
pal = sns.color_palette('Greens')
f, ax1d = plt.subplots(1,1, figsize=(7,7))
f.suptitle('Posterior Predictive Fit -- Data: {} -- Model: {}'.format(datamodelnm,
modelnm), fontsize=16)
plt.subplots_adjust(top=0.95)
ax1d.fill_between(dfp['x'], dfp['025'], dfp['975'], alpha=0.5,
color=pal[1], label='CR 95%')
ax1d.fill_between(dfp['x'], dfp['250'], dfp['750'], alpha=0.5,
color=pal[4], label='CR 50%')
ax1d.plot(dfp['x'], dfp['500'], alpha=0.6, color=pal[5], label='Median')
plt.legend()
ax1d.set_xlim(xlims)
sns.regplot(x='x', y='y', data=rawdata, fit_reg=False,
scatter_kws={'alpha':0.7,'s':100, 'lw':2,'edgecolor':'w'}, ax=ax1d)
# -
# ## Generate toy datasets
#
# ### Interactively draft data
#
# Throughout the rest of the Notebook, we'll use two toy datasets created by a linear and a quadratic model respectively, so that we can better evaluate the fit of the model selection.
#
# Right now, lets use an interactive session to play around with the data generation function in this Notebook, and get a feel for the possibilities of data we could generate.
#
#
# $$y_{i} = a + bx_{i} + cx_{i}^{2} + \epsilon_{i}$$
#
# where:
# $i \in n$ datapoints
#
# $\epsilon \sim \mathcal{N}(0,latent\_sigma\_y)$
#
#
# **NOTE on outliers:**
#
# + We can use value `p` to set the (approximate) proportion of 'outliers' under a bernoulli distribution.
# + These outliers have a 10x larger `latent_sigma_y`
# + These outliers are labelled in the returned datasets and may be useful for other modelling, see another example Notebook `GLM-robust-with-outlier-detection.ipynb`
interactive(interact_dataset, n=[5,50,5], p=[0,.5,.05], a=[-50,50],
b=[-10,10], c=[-3,3], latent_sigma_y=[0,1000,50])
# **Observe:**
#
# + I've shown the `latent_error` in errorbars, but this is for interest only, since this shows the _inherent noise_ in whatever 'physical process' we imagine created the data.
# + There is no _measurement error_.
# + Datapoints created as outliers are shown in **red**, again for interest only.
# ### Create datasets for modelling
# We can use the above interactive plot to get a feel for the effect of the params. Now we'll create 2 fixed datasets to use for the remainder of the Notebook.
#
# 1. For a start, we'll create a linear model with small noise. Keep it simple.
# 2. Secondly, a quadratic model with small noise
n = 12
df_lin, dfp_lin = generate_data(n=n, p=0, a=-30, b=5, c=0, latent_sigma_y=40)
df_quad, dfp_quad = generate_data(n=n, p=0, a=-200, b=2, c=3, latent_sigma_y=500)
# Scatterplot against model line
plot_datasets(df_lin, df_quad, dfp_lin, dfp_quad)
# **Observe:**
#
# + We now have two datasets `df_lin` and `df_quad` created by a linear model and quadratic model respectively.
# + You can see this raw data, the ideal model fit and the effect of the latent noise in the scatterplots above
# + In the folowing plots in this Notebook, the linear-generated data will be shown in Blue and the quadratic in Green.
#
# ### Standardize
# +
dfs_lin = df_lin.copy()
dfs_lin['x'] = (df_lin['x'] - df_lin['x'].mean()) / df_lin['x'].std()
dfs_quad = df_quad.copy()
dfs_quad['x'] = (df_quad['x'] - df_quad['x'].mean()) / df_quad['x'].std()
# -
# Create ranges for later ylim xim
# +
dfs_lin_xlims = (dfs_lin['x'].min() - np.ptp(dfs_lin['x'])/10,
dfs_lin['x'].max() + np.ptp(dfs_lin['x'])/10)
dfs_lin_ylims = (dfs_lin['y'].min() - np.ptp(dfs_lin['y'])/10,
dfs_lin['y'].max() + np.ptp(dfs_lin['y'])/10)
dfs_quad_ylims = (dfs_quad['y'].min() - np.ptp(dfs_quad['y'])/10,
dfs_quad['y'].max() + np.ptp(dfs_quad['y'])/10)
# -
# ## Demonstrate simple linear model
#
# This *linear model* is really simple and conventional, an OLS with L2 constraints (Ridge Regression):
#
# $$y = a + bx + \epsilon$$
# ### Define model using explicit PyMC3 method
with pm.Model() as mdl_ols:
## define Normal priors to give Ridge regression
b0 = pm.Normal('b0', mu=0, sd=100)
b1 = pm.Normal('b1', mu=0, sd=100)
## define Linear model
yest = b0 + b1 * df_lin['x']
## define Normal likelihood with HalfCauchy noise (fat tails, equiv to HalfT 1DoF)
sigma_y = pm.HalfCauchy('sigma_y', beta=10)
likelihood = pm.Normal('likelihood', mu=yest, sd=sigma_y, observed=df_lin['y'])
traces_ols = pm.sample(2000)
plot_traces(traces_ols, retain=1000)
# **Observe:**
#
# + This simple OLS manages to make fairly good guesses on the model parameters - the data has been generated fairly simply after all - but it does appear to have been fooled slightly by the inherent noise.
#
# ### Define model using PyMC3 GLM method
#
# PyMC3 has a module - `glm` - for defining models using a `patsy`-style formula syntax. This seems really useful, especially for defining simple regression models in fewer lines of code.
#
# Here's the same OLS model as above, defined using `glm`.
with pm.Model() as mdl_ols_glm:
# setup model with Normal likelihood (which uses HalfCauchy for error prior)
pm.glm.GLM.from_formula('y ~ 1 + x', df_lin, family=pm.glm.families.Normal())
traces_ols_glm = pm.sample(2000)
plot_traces(traces_ols_glm, retain=1000)
# **Observe:**
#
# + The output parameters are of course named differently to the custom naming before. Now we have:
#
# `b0 == Intercept`
# `b1 == x`
# `sigma_y == sd`
#
#
# + However, naming aside, this `glm`-defined model appears to behave in a very similar way, and finds the same parameter values as the conventionally-defined model - any differences are due to the random nature of the sampling.
# + We can quite happily use the `glm` syntax for further models below, since it allows us to create a small model factory very easily.
# ## Create higher-order linear models
#
# Back to the real purpose of this Notebook, to demonstrate model selection.
#
# First, let's create and run a set of polynomial models on each of our toy datasets. By default this is for models of order 1 to 5.
#
# ### Create and run polynomial models
#
# Please see `run_models()` above for details. Generally, we're creating 5 polynomial models and fitting each to the chosen dataset
models_lin, traces_lin = run_models(dfs_lin, 5)
models_quad, traces_quad = run_models(dfs_quad, 5)
# ## A really bad method for model selection: compare likelihoods
#
# Evaluate log likelihoods straight from model.logp
# +
dfll = pd.DataFrame(index=['k1','k2','k3','k4','k5'], columns=['lin','quad'])
dfll.index.name = 'model'
for nm in dfll.index:
dfll.loc[nm,'lin'] = - models_lin[nm].logp(pm.summary(traces_lin[nm],
traces_lin[nm].varnames)['mean'].to_dict())
dfll.loc[nm,'quad'] = - models_quad[nm].logp(pm.summary(traces_quad[nm],
traces_quad[nm].varnames)['mean'].to_dict())
dfll = pd.melt(dfll.reset_index(), id_vars=['model'],
var_name='poly', value_name='log_likelihood')
# -
# Plot log-likelihoods
g = sns.factorplot(x='model', y='log_likelihood', col='poly',
hue='poly', data=dfll, size=6)
# **Observe:**
#
# + Again we're showing the linear-generated data at left (Blue) and the quadratic-generated data on the right (Green)
# + For both datasets, as the models get more complex, the likelhood increases monotonically
# + This is expected, since the models are more flexible and thus able to (over)fit more easily.
# + This overfitting makes it a terrible idea to simply use the likelihood to evaluate the model fits.
# ### View posterior predictive fit
#
# Just for the linear, generated data, lets take an interactive look at the posterior predictive fit for the models k1 through k5.
#
# As indicated by the likelhood plots above, the higher-order polynomial models exhibit some quite wild swings in the function in order to (over)fit the data
interactive(plot_posterior_cr, models=fixed(models_lin), traces=fixed(traces_lin),
rawdata=fixed(dfs_lin), xlims=fixed(dfs_lin_xlims), datamodelnm=fixed('linear'),
modelnm = ['k1','k2','k3','k4','k5'])
# ## Compare models using WAIC
#
# The Widely Applicable Information Criterion (WAIC) can be used to calculate the goodness-of-fit of a model using numerical techniques. See [(Watanabe 2013)](http://www.jmlr.org/papers/volume14/watanabe13a/watanabe13a.pdf) for details.
# **Observe:**
#
# + We get three different measurements:
# - waic: widely available information criterion
# - waic_se: standard error of waic
# - p_waic: effective number parameters
#
# In this case we are interested in the WAIC score. We also plot error bars for the standard error of the estimated scores. This gives us a more accurate view of how much they might differ.
#
# Now loop through all the models and calculate the WAIC
# +
dfwaic = pd.DataFrame(index=['k1','k2','k3','k4','k5'], columns=['lin','quad'])
dfwaic.index.name = 'model'
for nm in dfwaic.index:
dfwaic.loc[nm, 'lin'] = pm.waic(traces_lin[nm], models_lin[nm])[:2]
dfwaic.loc[nm, 'quad'] = pm.waic(traces_quad[nm], models_quad[nm])[:2]
dfwaic = pd.melt(dfwaic.reset_index(), id_vars=['model'], var_name='poly', value_name='waic_')
dfwaic[['waic', 'waic_se']] = dfwaic['waic_'].apply(pd.Series)
# Define a wrapper function for plt.errorbar
def errorbar(x, y, se, order, color, **kws):
xnum = [order.index(x_i) for x_i in x]
plt.errorbar(xnum, y, yerr=se, color='k', ls='None')
g = sns.factorplot(x='model', y='waic', col='poly', hue='poly', data=dfwaic, size=6)
order = sns.utils.categorical_order(dfwaic['model'])
g.map(errorbar,'model', 'waic', 'waic_se', order=order);
# -
# **Observe**
#
# + We should prefer the model(s) with lower WAIC
#
#
# + Linear-generated data (lhs):
# + The WAIC seems quite flat across models
# + The WAIC seems best (lowest) for simpler models.
#
#
# + Quadratic-generated data (rhs):
# + The WAIC is also quite flat across the models
# + The lowest WAIC is model **k4**, but **k3** - **k5** are more or less the same.
# ## Compare leave-one-out Cross-Validation [LOO]
#
# Leave-One-Out Cross-Validation or K-fold Cross-Validation is another quite universal approach for model selection. However, to implement K-fold cross-validation we need to paritition the data repeatly and fit the model on every partition. It can be very time consumming (computation time increase roughly as a factor of K). Here we are applying the numerical approach using the posterier trace as suggested in Vehtari et al 2015.
# +
dfloo = pd.DataFrame(index=['k1','k2','k3','k4','k5'], columns=['lin','quad'])
dfloo.index.name = 'model'
for nm in dfloo.index:
dfloo.loc[nm, 'lin'] = pm.loo(traces_lin[nm], models_lin[nm])[:2]
dfloo.loc[nm, 'quad'] = pm.loo(traces_quad[nm], models_quad[nm])[:2]
dfloo = pd.melt(dfloo.reset_index(), id_vars=['model'], var_name='poly', value_name='loo_')
dfloo[['loo', 'loo_se']] = dfloo['loo_'].apply(pd.Series)
g = sns.factorplot(x='model', y='loo', col='poly', hue='poly', data=dfloo, size=6)
order = sns.utils.categorical_order(dfloo['model'])
g.map(errorbar,'model', 'loo', 'loo_se', order=order);
# -
# **Observe**
#
# + We should prefer the model(s) with lower LOO. You can see that LOO is nearly identical with WAIC. That's because WAIC is asymptotically equal to LOO. However, PSIS-LOO is supposedly more robust than WAIC in the finite case (under weak priors or influential observation).
#
#
# + Linear-generated data (lhs):
# + The LOO is also quite flat across models
# + The LOO is also seems best (lowest) for simpler models.
#
#
# + Quadratic-generated data (rhs):
# + The same pattern as the WAIC
#
# ## Final remarks and tips
#
# It is important to keep in mind that, with more data points, the real underlying model (one that we used to generate the data) should outperform other models.
#
# There is some agreement that PSIS-LOO offers the best indication of a model's quality. To quote from [avehtari's comment](https://github.com/pymc-devs/pymc3/issues/938#issuecomment-313425552): "I also recommend using PSIS-LOO instead of WAIC, because it's more reliable and has better diagnostics as discussed in http://link.springer.com/article/10.1007/s11222-016-9696-4 (preprint https://arxiv.org/abs/1507.04544), but if you insist to have one information criterion then leave WAIC".
#
# Alternatively, Watanabe [says](http://watanabe-www.math.dis.titech.ac.jp/users/swatanab/index.html) "WAIC is a better approximator of the generalization error than the pareto smoothing importance sampling cross validation. The Pareto smoothing cross validation may be the better approximator of the cross validation than WAIC, however, it is not of the generalization error".
# ## Reference
#
#
# For more information on Model Selection in PyMC3, and about Bayesian model selection, you could start with:
#
# + <NAME>'s [detailed response](https://stats.stackexchange.com/questions/161082/bayesian-model-selection-in-pymc3/166383#166383) to a question on Cross Validated
# + The Deviance Information Criterion: 12 Years On [(Speigelhalter et al 2014)](http://onlinelibrary.wiley.com/doi/10.1111/rssb.12062/abstract)
# + Bayesian predictive information criterion for the evaluation of hierarchical Bayesian and empirical Bayes models [(Ando 2007)](https://doi.org/10.1093/biomet/asm017)
# + A Widely Applicable Bayesian Information Criterion [(Watanabe 2013)](http://www.jmlr.org/papers/volume14/watanabe13a/watanabe13a.pdf)
# + Efficient Implementation of Leave-One-Out Cross-Validation and WAIC for Evaluating Fitted Bayesian Models [(Vehtari et al 2015)](http://arxiv.org/abs/1507.04544)
# Example originally contributed by <NAME> 2016-01-09 [github.com/jonsedar](https://github.com/jonsedar). Edited by <NAME> 2017-07-6 [github.com/junpenglao](https://github.com/junpenglao)
|
docs/source/notebooks/GLM-model-selection.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# Before you start creating custom scorers, make sure you have created and configured a Solr cluster and trained a ranker by either following the steps on the notebook "Answer-Retrieval.ipynb" or by using some other tooling.
#
# If you used the python notebook mentioned above, you are ready to start. Otherwise, please make sure you enter the needed information into the file credentials.json present in the same directory of this notebook. This will allow the exercise performed here to read and write needed credentials and constant values for all the steps ahead.
# ## 1. Create a Custom Scorer
#
# Custom Scorers should be defined and configured within custom-scorer folder.
#
# In this step, you will create a custom feature to improve the ranking phase. In general, there can be multiple custom features that can be engineered depending upon the use case.
#
# The custom scorer on this tutorial adds a feature related to the number of up votes an answer received on Stack Exchange. This feature is related to the content of a document. You can also create scorers that work on the content of the query or on both (query and document).
#
# The class that implements your scorer can be added to the corresponding package (one of document, query, query_document) in the rr_custom_scorers project. This is how the class for the Up votes scorer looks like:
#
# --------------------------------------------------------------------------
# from document_scorer import DocumentScorer
#
# class UpVoteScorer(DocumentScorer):
#
# def __init__(self, name='DocumentScorer', short_name='ds', description='Description of the scorer',
# include_stop=False):
# """ Base class for any scorers that consume a Solr document and extract
# a specific signal from a Solr document
#
# Args:
# name (str): Name of the Scorer
# short_name (str): Used for the header which is sent to ranker
# description (str): Description of the scorer
# """
# super(UpVoteScorer, self).__init__(name=name, short_name=short_name, description=description)
#
# def score(self, document):
# upVote = document['upModVotes']
#
# if upVote is not None:
# if upVote == 0:
# return 0
# elif 0 < upVote <= 3:
# return 0.15
# elif 3 < upVote <= 5:
# return 0.35
# elif 5 < upVote <= 8:
# return 0.55
# elif 8 < upVote <= 11:
# return 0.75
# elif 11 < upVote <= 14:
# return 0.85
# elif upVote > 14:
# return 1
# else:
# return 0
#
# ----------------------------------------------------------------------------
#
# Notice that the scorer uses the information stored in document (upModVotes). Make sure the data you need to use in the scorer is stored in your solr documents.
#
# Some preprocessing might be required in order to define the logic of the scorer (the normalization criteria, for example). For this example, a histogram of up votes was analyzed in order to define the normalization ranges.
#
# Once you have created the class that implements the custom socrer, edit the file features.json within the config directory of the project rr_custom_scorers_proxy_app to add the custom feature information. It should look like this:
#
# {
# "scorers":[
# {
# "init_args":{
# "name":"UpVoteScorer",
# "short_name":"uvs1",
# "description":"Score based on the number of up votes a document received"
# },
# "type":"document",
# "module":"document_upvote_scorer",
# "class":"UpVoteScorer"
# }
# ]
# }
#
# If you write more than one scorer, just add them to the scorers:[] list.
#
# ## 2. Install Dependencies and Compile Custom Scorers
# +
import subprocess
import shlex
import os
from shutil import copyfile
#getting current directory
curdir = os.getcwd()
CUSTOM_SCORERS_PATH=curdir+'/../custom-scorer'
#creating wheel in /custom-scorer/ and copying it using pip install
#Note: Wheel is a packaging framework for Python and is used
#for packaging the custom scorer project
try:
os.system("cd "+CUSTOM_SCORERS_PATH+"; pip wheel .")
os.system("pip install retrieve_and_rank_scorer-0.0.1-py2-none-any.whl")
print('Successfully installed retrieve_and_rank_scorer-0.0.1-py2-none-any.whl package.')
except:
print ('Command to install custom scorer whl file failed.')
# -
# ## 3. Create service.cfg File
#
# This step writes your RR credentials to the service.cfg file, expected by the proxy app.
# To create the file, run the code below
#
# +
import os
import json
#getting current directory
curdir = os.getcwd()
#loading credentials
credFilePath = curdir+'/../config/credentials.json'
with open(credFilePath) as credFile:
credentials = json.load(credFile)
SERVICE_CFG_PATH=curdir+'/../config'
#creating service.cfg file
serviceCfgPath = SERVICE_CFG_PATH+'/service.cfg'
with open(serviceCfgPath, 'w') as serviceCfgFile:
serviceCfgFile.write('SOLR_CLUSTER_ID='+credentials['cluster_id']+'\n')
serviceCfgFile.write('SOLR_COLLECTION_NAME='+credentials['collection_name']+'\n')
serviceCfgFile.write('RETRIEVE_AND_RANK_BASE_URL=https://gateway.watsonplatform.net/retrieve-and-rank/api'+'\n')
serviceCfgFile.write('RETRIEVE_AND_RANK_USERNAME='+credentials['username']+'\n')
serviceCfgFile.write('RETRIEVE_AND_RANK_PASSWORD='+credentials['password']+'\n')
# -
# ## 4. Start the Server
#
# Start the python flask server by using your command line or terminal as shown below.
#
# $ python server.py
# ## 5. Generate Training Data
#
# Once the training ground truth file is ready, a file which contains the feature vectors for each questions needs to be generated. This file will also contain the new features added by your custom scorers.
#
# To generate the traingdata.csv file:
#
# 0. Make sure the proxy app is running
# 1. Edit bin/python/trainproxy.py - fl (fields) in lines 83, 95 to consider the fields used by the added custom scorers
# 2. Run the code below (this is composed of two phase: generation of a trainingdata.csv file and sending the
# request to create a ranker to the service). You know the request has been sent when the output shows something
# like: {"ranker_id":"3b140ax15-rank-2018", "name":"rr_ask_ranker_cs", "created":"2016-05-19T14:51:50.635Z",
# "url":"https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/rankers/3b140ax15-
# rank-2018","status":"Training","status_description":"The ranker instance is in its training phase"}
# 3. Validate trainingdata.csv has the new feature
# (e.g. question_id,f0,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,r1,r2,s,newfeature,ground_truth)
#
# ### NOTE : THIS STEP COULD TAKE A LONG TIME!
# +
import subprocess
import json
import shlex
import os
#getting current directory
curdir = os.getcwd()
#loading credentials
credFilePath = curdir+'/../config/credentials.json'
with open(credFilePath) as credFile:
credentials = json.load(credFile)
USERNAME=credentials['username']
PASSWORD=credentials['password']
SOLR_CLUSTER_ID=credentials['cluster_id']
COLLECTION_NAME=credentials['collection_name']
TRAIN_FILE_PATH=curdir+'/../bin/python'
GROUND_TRUTH_FILE=curdir+"/../data/groundtruth/answerGT_train.csv"
#Running command that trains a ranker
cmd = 'python %s/trainproxy.py -u %s:%s -i %s -c %s -x %s -n %s' %\
(TRAIN_FILE_PATH, USERNAME, PASSWORD, GROUND_TRUTH_FILE, SOLR_CLUSTER_ID, COLLECTION_NAME, "ranker")
try:
process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
output = process.communicate()[0]
except:
print ('Command:')
print (cmd)
print ('Response:')
print (output)
# -
# ## 6. Train a New Ranker with Custom Scorer(s)
#
# To train a ranker which will consider the added features:
#
# 0. Make sure the proxy app is running
# 1. Run the code below
#
# NOTE: In this step you will need to provide the value for the RANKER_NAME constant.
#
# ### NOTE : THIS STEP COULD TAKE A LONG TIME!
# +
import subprocess
import json
import shlex
import os
#getting current directory
curdir = os.getcwd()
#loading credentials
credFilePath = curdir+'/../config/credentials.json'
with open(credFilePath) as credFile:
credentials = json.load(credFile)
BASEURL=credentials['url']
RANKER_URL=BASEURL+"rankers"
USERNAME=credentials['username']
PASSWORD=credentials['password']
TRAINING_DATA=curdir+'/../data/groundtruth/trainingdata.csv'
#please provide the ranker name
RANKER_NAME="rr_ask_cs_ranker"
#Checking if ranker with same name already exists
curl_cmd = 'curl -u "%s":"%s" "%s"' %(USERNAME, PASSWORD, RANKER_URL)
process = subprocess.Popen(shlex.split(curl_cmd), stdout=subprocess.PIPE)
output = process.communicate()[0]
found = False
ranker_id = ''
try:
parsed_json = json.loads(output)
rankers = parsed_json['rankers']
for i in range(len(rankers)):
ranker_json = rankers[i]
if ranker_json['name'] == RANKER_NAME:
found = True
ranker_id = ranker_json['ranker_id']
except:
print ('Command:')
print (curl_cmd)
print ('Response:')
print (output)
if found:
print "Ranker "+RANKER_NAME+" already exists with ID "+ranker_id+"."
print json.dumps(parsed_json, sort_keys=True, indent=4)
else:
#Running command that trains a ranker
cmd = 'curl -k -X POST -u %s:%s -F training_data=@%s -F training_metadata="{\\"name\\":\\"%s\\"}" %s' %\
(USERNAME, PASSWORD, TRAINING_DATA, RANKER_NAME, RANKER_URL)
process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
output = process.communicate()[0]
print cmd
try:
parsed_json = json.loads(output)
print json.dumps(parsed_json, sort_keys=True, indent=4)
credentials['cs_ranker_id'] = parsed_json['ranker_id']
with open(credFilePath, 'w') as credFileUpdated:
json.dump(credentials, credFileUpdated)
except:
print ('Command:')
print (cmd)
print ('Response:')
print (output)
# -
# ## 7. Check Status of a Ranker with Custom Scorers
#
# If the generation of training data finished succesfully and the output was that a new ranker has been created and it is on its training phase, you can query the status to check when it becomes "Available" by running the code below.
# +
import subprocess
import json
import shlex
import os
#getting current directory
curdir = os.getcwd()
#loading credentials
credFilePath = curdir+'/../config/credentials.json'
with open(credFilePath) as credFile:
credentials = json.load(credFile)
BASEURL=credentials['url']
RANKER_URL=BASEURL+"rankers"
USERNAME=credentials['username']
PASSWORD=credentials['password']
RANKER_ID=credentials['cs_ranker_id']
#Running command that checks the status of a ranker
curl_cmd = 'curl -u %s:%s %s/%s' % (USERNAME, PASSWORD, RANKER_URL, RANKER_ID)
process = subprocess.Popen(shlex.split(curl_cmd), stdout=subprocess.PIPE)
output = process.communicate()[0]
try:
parsed_json = json.loads(output)
print json.dumps(parsed_json, sort_keys=True, indent=4)
except:
print ('Command:')
print (curl_cmd)
print ('Response:')
print (output)
# -
# ### Note : Before running experiments, you should update the .env file with the ranker id of the trained ranker and restart the plython flask application
# ## 8. Run Experiments with New Ranker using Custom Scorer(s)
#
# To test a ranker using custom scorers:
#
# 0. Make sure the proxy app is running
# 1. Edit bin/python/testproxy.py
# 2. Edit fl (fields) in lines 85, 178 to consider the fields used by the added custom scorers
# 3. Run the code below to:
# - Edit service.cfg
# - Create experiments folder in /data (if you run these multiple times, rename the folder to keep all of the
# wanted results otherwise it will be overwritten)
# - Run experiment_with_custom_scorers.sh to run the test experiment. This step will generate the files needed
# for analysis of the custom scorers performance
#
# ### NOTE : THIS STEP COULD TAKE A LONG TIME!
#
# +
import subprocess
import json
import shlex
import os
#getting current directory
curdir = os.getcwd()
#please provide the full path to the file answerGT_test.csv
TEST_FILE=curdir+"/../data/groundtruth/answerGT_test.csv"
#loading credentials
credFilePath = curdir+'/../config/credentials.json'
with open(credFilePath) as credFile:
credentials = json.load(credFile)
#editing service.cfg file
SERVICE_CFG_PATH=curdir+'/../config'
SERVICE_CFG_PATH = SERVICE_CFG_PATH+'/service.cfg'
#adding ranker and test file
with open(SERVICE_CFG_PATH, 'w') as serviceCfgFile:
serviceCfgFile.write('SOLR_CLUSTER_ID='+credentials['cluster_id']+'\n')
serviceCfgFile.write('SOLR_COLLECTION_NAME='+credentials['collection_name']+'\n')
serviceCfgFile.write('RETRIEVE_AND_RANK_BASE_URL=https://gateway.watsonplatform.net/retrieve-and-rank/api'+'\n')
serviceCfgFile.write('RETRIEVE_AND_RANK_USERNAME='+credentials['username']+'\n')
serviceCfgFile.write('RETRIEVE_AND_RANK_PASSWORD='+credentials['password']+'\n')
serviceCfgFile.write('RANKER_ID='+credentials['ranker_id']+'\n')
serviceCfgFile.write('TEST_RELEVANCE_FILE='+TEST_FILE+'\n')
#creating experiments directory
curdir = os.getcwd()
DATA_PATH=curdir+'/../data'
cmd1 = 'mkdir '+DATA_PATH+'/experiments'
try:
process = subprocess.Popen(shlex.split(cmd1), stdout=subprocess.PIPE)
output = process.communicate()[0]
except:
print ('Command to create experiments directory failed:')
print (cmd1)
#running experiment script
try:
os.system("cd "+curdir+"/../; ./bin/bash/experiment.sh "+SERVICE_CFG_PATH\
+" "+DATA_PATH+"/experiments")
except:
print ('Command to run experiment failed.')
#changing ranker id to reflect custom scorer ranker
with open(SERVICE_CFG_PATH, 'w') as serviceCfgFile:
serviceCfgFile.write('SOLR_CLUSTER_ID='+credentials['cluster_id']+'\n')
serviceCfgFile.write('SOLR_COLLECTION_NAME='+credentials['collection_name']+'\n')
serviceCfgFile.write('RETRIEVE_AND_RANK_BASE_URL=https://gateway.watsonplatform.net/retrieve-and-rank/api'+'\n')
serviceCfgFile.write('RETRIEVE_AND_RANK_USERNAME='+credentials['username']+'\n')
serviceCfgFile.write('RETRIEVE_AND_RANK_PASSWORD='+credentials['password']+'\n')
serviceCfgFile.write('RANKER_ID='+credentials['cs_ranker_id']+'\n')
serviceCfgFile.write('TEST_RELEVANCE_FILE='+TEST_FILE+'\n')
#running experiment with custom scorers script
try:
os.system("cd "+curdir+"/../; ./bin/bash/experiment_with_custom_scorers.sh "+SERVICE_CFG_PATH\
+" "+DATA_PATH+"/experiments/")
except:
print ('Command to run experiment with custom scorers failed.')
# -
# ## 9. Test Ranker with Custom Scorer(s)
#
# To test the ranker, submit a query and observe the results returned by running the command below
#
# NOTE: In this step you should provide the value for the QUESTION constant.
# +
import subprocess
import json
import shlex
import os
#getting current directory
curdir = os.getcwd()
#loading credentials
credFilePath = curdir+'/../config/credentials.json'
with open(credFilePath) as credFile:
credentials = json.load(credFile)
USERNAME=credentials['username']
PASSWORD=credentials['password']
RANKER_ID=credentials['cs_ranker_id']
#please provide the query to test
QUESTION="what is the best city to visit in brazil"
#Running command that queries Solr
QUESTION = QUESTION.replace(" ","%20")
curl_cmd = 'curl GET "http://localhost:3000/api/custom_ranker?&q=%s&wt=json&fl=id,title,subtitle,answer,\
answerScore,userReputation,views,upModVotes,downModVotes,userId,username,tags,userId,username,authorUsername,authorUserId&\
wt=json&ranker_id=%s&fq=\'\'"' %(QUESTION, RANKER_ID)
print curl_cmd
process = subprocess.Popen(shlex.split(curl_cmd), stdout=subprocess.PIPE)
output = process.communicate()[0]
try:
parsed_json = json.loads(output)
print json.dumps(parsed_json, sort_keys=True, indent=4)
except:
print ('Command:')
print (curl_cmd)
print ('Response:')
print (output)
# -
# ## 10. Analyze Experiment Results
#
# Using the iPython notebook launched in Step 2 (testing step), repeat iPython notebook analysis from Step 2. You will need to add a new experiment variable to add the experiment with custom features included in the analysis charts or calculating NDCG scores.
import os
import pandas as pd
import numpy as np
import json
import matplotlib.pyplot as plt
# %matplotlib inline
import functools
import requests
import random
import seaborn as sns
import analysis_utils as au
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
sns.set_style('darkgrid')
from collections import defaultdict, Counter
# Parameters
#getting current directory
curdir = os.getcwd()
base_directory=curdir+'/../data'
experiments_directory = os.path.join(base_directory, 'experiments')
# +
# Solr experiment
solr_experiment_path = os.path.join(experiments_directory, 'exp_solr_only.json')
solr_experiment = au.RetrieveAndRankExperiment(experiment_file_path=solr_experiment_path)
solr_entries = solr_experiment.experiment_entries
# RR experiment
rr_experiment_path = os.path.join(experiments_directory, 'exp_retrieve_and_rank.json')
rr_experiment = au.RetrieveAndRankExperiment(experiment_file_path=rr_experiment_path)
rr_entries = rr_experiment.experiment_entries
# RR experiment with custom scorers
rr_experiment_path_scorer = os.path.join(experiments_directory, 'exp_retrieve_and_rank_scorers.json')
rr_experiment_scorer = au.RetrieveAndRankExperiment(experiment_file_path=rr_experiment_path_scorer)
rr_entries_scorer = rr_experiment_scorer.experiment_entries
# +
def query_solr(query, fq=None, wt='json', fl='id,title,subtitle,answer,answerScore,upModVotes', num_rows=10):
" Query standalone Solr "
params = dict(q=query, wt=wt, fl=fl, rows=num_rows)
if fq is not None:
params['fq'] = fq
return solr_experiment.rr_service.select(params)
def query_retrieve_and_rank(query, fq=None, wt='json', fl='id,title,subtitle,answer,answerScore,upModVotes', num_rows=10):
" Query the retrieve and rank API "
ranker_id = rr_experiment.ranker_id
params = dict(q=query, ranker_id=ranker_id, wt=wt, fl=fl, rows=num_rows)
if fq is not None:
params['fq'] = fq
return rr_experiment.rr_service.fcselect(params)
def get_doc_by_id(doc_id, query=None):
" Get the solr document, if we have the id"
query = '*:*' if query is None else query
resp = query_solr(query='*:*', fq='id:%s' % doc_id, fl='id,title,subtitle,answer,answerScore,upModVotes')
if resp.ok:
docs = resp.json().get('response', {}).get('docs', [])
if len(docs) > 0 and docs[0]['id'] == doc_id:
return docs[0]
elif len(docs) == 0:
raise ValueError('No docs returned. Response json : %r' % resp.json())
else:
raise ValueError('ID of top document does not match. Response json : %r' % resp.json())
else:
raise resp.raise_for_status()
# -
# ## 11. Experiment Analysis
#
# ### Total Relevance
#
# Total Relevance measures, for each query sent to the ranker, the % of answers in the top X documents that were relevant.
#
# For example, let query X have 8 relevant documents. The first 5 documents in the response from the ranker are relevant but the next 5 documents are all irrelevant. Total Relevance would be calculated as follows:
#
# Total Relevance@001 = 1 relevant document in top 1 / 1 possible relevant document in top 1 = 1.00
# ...
# Total Relevance@005 = 5 relevant documents in top 5 / 5 possible relevant documents in top 5 = 1.00
# ...
# Total Relevance@008 = 5 relevant documents in top 8 / 8 possible relevant documents in top 8 = 0.625
# ...
# Total Relevance@010 = 5 relevant documents in top 10 / 8 possible relevant documents in top 10 = 0.625
#
# Thus total relevance measures the % of documents in the top X documents that are relevant, as compared to the maximum number of relevant documents that could be returned in the top X.
#
# This concludes the custom features section. The proxy app is probably still running on a session. To interrupt the process, just do Ctrl+C.
# Define the function
plot_total_relevance_at_n = functools.partial(au.plot_relevance_results, func=au.total_relevance_at_n,
xlabel='Documents@00N Index', ylabel='Relevance %',
title='Avg. % of Documents in Top N that are Relevant')
plot_total_relevance_at_n([solr_entries, rr_entries,rr_entries_scorer],
legend=['Solr','RR','RR with Custom Scorer'],
title='Total relevance with UpVote scorer')
# ### Normalized Discounted Cumulative Gain (NDCG)
# Discounted Cumulative Gain is an Information Retrieval Metric that takes into account the position and relevance of documents at different positions. Normalized Discounted Cumulative Gain normalizes the metric based on what the optimal ranking of results would be.
#
# Notation:
# rel_i = relevance of ith document
#
# DCG@00N = rel_1 + sum(rel_i / log2(i + 1) for i in range(1,n))
#
# NDCG@00N = DCG@00N / IDCG@00N
#
# IDCG@00N = "DCG of the optimal ordering of a result set"
#
# For example, consider a query that has 3 relevant documents. 1 of these 3 documents has relevance 2 and the other 2 have relevance 1, (and naturally all other documents have relevance 0). Assume the relevance of the documents in the result set is as follows
#
# RS = [1, 0, 2, 1, 0, ...] (first retrieved document has relevance 1, second has relevance 0, etc.)
#
# The optimal result set would have most relevant documents first. Here is the ideal ordering for this problem:
# IRS = [2, 1, 1, 0, 0, ...]
#
# After doing the math, we get:
# DCG@005 = 2.43
# IDCG@005 = 3.13
# NDCG@005 = 0.77
absolute_strategy_ndcg = functools.partial(au.experiment_average_ndcg, method='absolute')
relative_strategy_ndcg = functools.partial(au.experiment_average_ndcg, method='relative')
plot_absolute_ndcg = functools.partial(au.plot_relevance_results, func=absolute_strategy_ndcg,
xlabel='Documents@00N Index', ylabel='NDCG',
title='Absolute NDCG@00N')
plot_relative_ndcg = functools.partial(au.plot_relevance_results, func=relative_strategy_ndcg,
xlabel='Documents@00N Index', ylabel='NDCG',
title='Relative NDCG@00N')
plot_absolute_ndcg([solr_entries, rr_entries,rr_entries_scorer],
legend=['Solr', 'RR','RR with custom scorer'],
title='Absolute NDCG')
plot_relative_ndcg([solr_entries, rr_entries,rr_entries_scorer],
legend=['Solr', 'RR'],
title='Relative NDCG')
# ## Cleanup and Shutdown
# +
import os
import subprocess
import shlex
#getting current directory
curdir = os.getcwd()
CUSTOM_SCORERS_ANSWERS_PATH=curdir+'/../data/groundtruth/'
#Remove temporary answers csv files generated by custom scorers
cmd1 = 'rm '+CUSTOM_SCORERS_ANSWERS_PATH+'answer_*.csv'
try:
os.system(cmd1)
print (cmd1)
except:
print ('Removal of .csv file from answers directory failed:')
print (cmd1)
|
notebooks/Custom Scorer.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Numpy
# ## Mengingat list
# - *powerfull*
# - Koleksi dari nilai
# - Menampung berbagai macam tipe data
# - Mengganti, Menambah, Mengurangi
# - Kebutuhan untuk Data Science: Operasi Matematika antar list, *speed*
tinggi = [1.73, 1.68, 1.71, 1.89, 1.69]
tinggi
berat = [65.4, 59.2, 63.6, 88.4, 68.7]
berat / tinggi ** 2
# ## Solusi? Numpy, horray
# - Python Numerik
# - Alternatif dari list python: NumPy Array
# - Kalkulasi semua elemen array
# - Mudah dan Cepat
import numpy as np
np_tinggi = np.array(tinggi)
np_tinggi
np_berat = np.array(berat)
np_berat
bmi = np_berat / np_tinggi ** 2
bmi
# ## Numpy remarks
np.array([1.0, 'is', True]) # Numpy hanya dapat menampung satu tipe
python_list = [1,2,3]
numpy_array = np.array([1,2,3])
python_list + python_list
numpy_array + numpy_array
# ## Numpy subsetting
bmi
bmi[1]
bmi > 23
bmi[bmi > 23]
# ## 2D Numpy arrays
import numpy as np
np_tinggi = np.array([1.73, 1.68, 1.71, 1.89, 1.69])
np_berat = np.array([ 65.4, 59.2, 63.6, 88.4, 68.7])
type(np_tinggi)
type(np_berat)
np_2d = np.array([[1.73, 1.68, 1.71, 1.89, 1.69], [ 65.4, 59.2, 63.6, 88.4, 68.7]])
np_2d
np_2d.shape
np_2d = np.array([[1.73, 1.68, 1.71, 1.89, 1.69], [ 65.4, 59.2, 63.6, 88.4, "68.7"]])
np_2d # Ingat hanya bisa satu tipe
# ## Nubsetting Numpy 2D
np_2d[0]
np_2d[0][2]
np_2d[0,2]
np_2d[:,1:3]
np_2d[1,:]
# ## NumPy dan Statistika Dasar
# +
tinggi = np.round(np.random.normal(1.75, 0.20, 5000), 2)
berat = np.round(np.random.normal(60.32, 15, 5000), 2)
# np.random.normal(distribution_mean, distribution_standard_deviation, jumlah_sample)
# -
np_city = np.column_stack((tinggi, berat))
np_city
np.mean(np_city[:,0])
np.median(np_city[:,0])
np.corrcoef(np_city[:,0], np_city[:,1])
np.std(np_city[:,0])
|
Bagian 1 - Pengenalan Python untuk Data Science/4. Numpy.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Optimization Methods
#
# Until now, you've always used Gradient Descent to update the parameters and minimize the cost. In this notebook, you will learn more advanced optimization methods that can speed up learning and perhaps even get you to a better final value for the cost function. Having a good optimization algorithm can be the difference between waiting days vs. just a few hours to get a good result.
#
# By completing this assignment you will:
#
# - Understand the intuition between Adam and RMS prop
#
# - Recognize the importance of mini-batch gradient descent
#
# - Learn the effects of momentum on the overall performance of your model
#
# Gradient descent goes "downhill" on a cost function $J$. Think of it as trying to do this:
# <img src="images/cost.jpg" style="width:650px;height:300px;">
# <caption><center> <u> **Figure 1** </u>: **Minimizing the cost is like finding the lowest point in a hilly landscape**<br> At each step of the training, you update your parameters following a certain direction to try to get to the lowest possible point. </center></caption>
#
# **Notations**: As usual, $\frac{\partial J}{\partial a } = $ `da` for any variable `a`.
#
# To get started, run the following code to import the libraries you will need.
# +
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
import math
import sklearn
import sklearn.datasets
from opt_utils_v1a import load_params_and_grads, initialize_parameters, forward_propagation, backward_propagation
from opt_utils_v1a import compute_cost, predict, predict_dec, plot_decision_boundary, load_dataset, update_parameters_with_gd, random_mini_batches
from testCases import *
# %matplotlib inline
plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# -
# ## 1 - Momentum
#
# Because mini-batch gradient descent makes a parameter update after seeing just a subset of examples, the direction of the update has some variance, and so the path taken by mini-batch gradient descent will "oscillate" toward convergence. Using momentum can reduce these oscillations.
#
# Momentum takes into account the past gradients to smooth out the update. We will store the 'direction' of the previous gradients in the variable $v$. Formally, this will be the exponentially weighted average of the gradient on previous steps. You can also think of $v$ as the "velocity" of a ball rolling downhill, building up speed (and momentum) according to the direction of the gradient/slope of the hill.
#
# <img src="images/opt_momentum.png" style="width:400px;height:250px;">
# <caption><center> <u><font color='purple'>**Figure 3**</u><font color='purple'>: The red arrows shows the direction taken by one step of mini-batch gradient descent with momentum. The blue points show the direction of the gradient (with respect to the current mini-batch) on each step. Rather than just following the gradient, we let the gradient influence $v$ and then take a step in the direction of $v$.<br> <font color='black'> </center>
#
#
# **Exercise**: Initialize the velocity. The velocity, $v$, is a python dictionary that needs to be initialized with arrays of zeros. Its keys are the same as those in the `grads` dictionary, that is:
# for $l =1,...,L$:
# ```python
# v["dW" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters["W" + str(l+1)])
# v["db" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters["b" + str(l+1)])
# ```
# **Note** that the iterator l starts at 0 in the for loop while the first parameters are v["dW1"] and v["db1"] (that's a "one" on the superscript). This is why we are shifting l to l+1 in the `for` loop.
# +
# GRADED FUNCTION: initialize_velocity
def initialize_velocity(parameters):
"""
Initializes the velocity as a python dictionary with:
- keys: "dW1", "db1", ..., "dWL", "dbL"
- values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters.
Arguments:
parameters -- python dictionary containing your parameters.
parameters['W' + str(l)] = Wl
parameters['b' + str(l)] = bl
Returns:
v -- python dictionary containing the current velocity.
v['dW' + str(l)] = velocity of dWl
v['db' + str(l)] = velocity of dbl
"""
L = len(parameters) // 2 # number of layers in the neural networks
v = {}
# Initialize velocity
for l in range(L):
### START CODE HERE ### (approx. 2 lines)
v["dW" + str(l+1)] = np.zeros((parameters["W" + str(l+1)].shape))
v["db" + str(l+1)] = np.zeros((parameters["b" + str(l+1)].shape))
### END CODE HERE ###
return v
# +
parameters = initialize_velocity_test_case()
v = initialize_velocity(parameters)
print("v[\"dW1\"] =\n" + str(v["dW1"]))
print("v[\"db1\"] =\n" + str(v["db1"]))
print("v[\"dW2\"] =\n" + str(v["dW2"]))
print("v[\"db2\"] =\n" + str(v["db2"]))
# -
# **Expected Output**:
#
# ```
# v["dW1"] =
# [[ 0. 0. 0.]
# [ 0. 0. 0.]]
# v["db1"] =
# [[ 0.]
# [ 0.]]
# v["dW2"] =
# [[ 0. 0. 0.]
# [ 0. 0. 0.]
# [ 0. 0. 0.]]
# v["db2"] =
# [[ 0.]
# [ 0.]
# [ 0.]]
# ```
# **Exercise**: Now, implement the parameters update with momentum. The momentum update rule is, for $l = 1, ..., L$:
#
# $$ \begin{cases}
# v_{dW^{[l]}} = \beta v_{dW^{[l]}} + (1 - \beta) dW^{[l]} \\
# W^{[l]} = W^{[l]} - \alpha v_{dW^{[l]}}
# \end{cases}\tag{3}$$
#
# $$\begin{cases}
# v_{db^{[l]}} = \beta v_{db^{[l]}} + (1 - \beta) db^{[l]} \\
# b^{[l]} = b^{[l]} - \alpha v_{db^{[l]}}
# \end{cases}\tag{4}$$
#
# where L is the number of layers, $\beta$ is the momentum and $\alpha$ is the learning rate. All parameters should be stored in the `parameters` dictionary. Note that the iterator `l` starts at 0 in the `for` loop while the first parameters are $W^{[1]}$ and $b^{[1]}$ (that's a "one" on the superscript). So you will need to shift `l` to `l+1` when coding.
# +
# GRADED FUNCTION: update_parameters_with_momentum
def update_parameters_with_momentum(parameters, grads, v, beta, learning_rate):
"""
Update parameters using Momentum
Arguments:
parameters -- python dictionary containing your parameters:
parameters['W' + str(l)] = Wl
parameters['b' + str(l)] = bl
grads -- python dictionary containing your gradients for each parameters:
grads['dW' + str(l)] = dWl
grads['db' + str(l)] = dbl
v -- python dictionary containing the current velocity:
v['dW' + str(l)] = ...
v['db' + str(l)] = ...
beta -- the momentum hyperparameter, scalar
learning_rate -- the learning rate, scalar
Returns:
parameters -- python dictionary containing your updated parameters
v -- python dictionary containing your updated velocities
"""
L = len(parameters) // 2 # number of layers in the neural networks
# Momentum update for each parameter
for l in range(L):
### START CODE HERE ### (approx. 4 lines)
# compute velocities
v["dW" + str(l+1)] = beta*v["dW" + str(l+1)]+(1-beta)*grads['dW' + str(l+1)]
v["db" + str(l+1)] = beta*v["db" + str(l+1)]+(1-beta)*grads['db' + str(l+1)]
# update parameters
parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate*v["dW" + str(l+1)]
parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate*v["db" + str(l+1)]
### END CODE HERE ###
return parameters, v
# +
parameters, grads, v = update_parameters_with_momentum_test_case()
parameters, v = update_parameters_with_momentum(parameters, grads, v, beta = 0.9, learning_rate = 0.01)
print("W1 = \n" + str(parameters["W1"]))
print("b1 = \n" + str(parameters["b1"]))
print("W2 = \n" + str(parameters["W2"]))
print("b2 = \n" + str(parameters["b2"]))
print("v[\"dW1\"] = \n" + str(v["dW1"]))
print("v[\"db1\"] = \n" + str(v["db1"]))
print("v[\"dW2\"] = \n" + str(v["dW2"]))
print("v[\"db2\"] = v" + str(v["db2"]))
# -
# **Expected Output**:
#
# ```
# W1 =
# [[ 1.62544598 -0.61290114 -0.52907334]
# [-1.07347112 0.86450677 -2.30085497]]
# b1 =
# [[ 1.74493465]
# [-0.76027113]]
# W2 =
# [[ 0.31930698 -0.24990073 1.4627996 ]
# [-2.05974396 -0.32173003 -0.38320915]
# [ 1.13444069 -1.0998786 -0.1713109 ]]
# b2 =
# [[-0.87809283]
# [ 0.04055394]
# [ 0.58207317]]
# v["dW1"] =
# [[-0.11006192 0.11447237 0.09015907]
# [ 0.05024943 0.09008559 -0.06837279]]
# v["db1"] =
# [[-0.01228902]
# [-0.09357694]]
# v["dW2"] =
# [[-0.02678881 0.05303555 -0.06916608]
# [-0.03967535 -0.06871727 -0.08452056]
# [-0.06712461 -0.00126646 -0.11173103]]
# v["db2"] = v[[ 0.02344157]
# [ 0.16598022]
# [ 0.07420442]]
# ```
# **Note** that:
# - The velocity is initialized with zeros. So the algorithm will take a few iterations to "build up" velocity and start to take bigger steps.
# - If $\beta = 0$, then this just becomes standard gradient descent without momentum.
#
# **How do you choose $\beta$?**
#
# - The larger the momentum $\beta$ is, the smoother the update because the more we take the past gradients into account. But if $\beta$ is too big, it could also smooth out the updates too much.
# - Common values for $\beta$ range from 0.8 to 0.999. If you don't feel inclined to tune this, $\beta = 0.9$ is often a reasonable default.
# - Tuning the optimal $\beta$ for your model might need trying several values to see what works best in term of reducing the value of the cost function $J$.
# <font color='blue'>
# **What you should remember**:
# - Momentum takes past gradients into account to smooth out the steps of gradient descent. It can be applied with batch gradient descent, mini-batch gradient descent or stochastic gradient descent.
# - You have to tune a momentum hyperparameter $\beta$ and a learning rate $\alpha$.
# ## 2 - Adam
#
# Adam is one of the most effective optimization algorithms for training neural networks. It combines ideas from RMSProp (described in lecture) and Momentum.
#
# **How does Adam work?**
# 1. It calculates an exponentially weighted average of past gradients, and stores it in variables $v$ (before bias correction) and $v^{corrected}$ (with bias correction).
# 2. It calculates an exponentially weighted average of the squares of the past gradients, and stores it in variables $s$ (before bias correction) and $s^{corrected}$ (with bias correction).
# 3. It updates parameters in a direction based on combining information from "1" and "2".
#
# The update rule is, for $l = 1, ..., L$:
#
# $$\begin{cases}
# v_{dW^{[l]}} = \beta_1 v_{dW^{[l]}} + (1 - \beta_1) \frac{\partial \mathcal{J} }{ \partial W^{[l]} } \\
# v^{corrected}_{dW^{[l]}} = \frac{v_{dW^{[l]}}}{1 - (\beta_1)^t} \\
# s_{dW^{[l]}} = \beta_2 s_{dW^{[l]}} + (1 - \beta_2) (\frac{\partial \mathcal{J} }{\partial W^{[l]} })^2 \\
# s^{corrected}_{dW^{[l]}} = \frac{s_{dW^{[l]}}}{1 - (\beta_2)^t} \\
# W^{[l]} = W^{[l]} - \alpha \frac{v^{corrected}_{dW^{[l]}}}{\sqrt{s^{corrected}_{dW^{[l]}}} + \varepsilon}
# \end{cases}$$
# where:
# - t counts the number of steps taken of Adam
# - L is the number of layers
# - $\beta_1$ and $\beta_2$ are hyperparameters that control the two exponentially weighted averages.
# - $\alpha$ is the learning rate
# - $\varepsilon$ is a very small number to avoid dividing by zero
#
# As usual, we will store all parameters in the `parameters` dictionary
# **Exercise**: Initialize the Adam variables $v, s$ which keep track of the past information.
#
# **Instruction**: The variables $v, s$ are python dictionaries that need to be initialized with arrays of zeros. Their keys are the same as for `grads`, that is:
# for $l = 1, ..., L$:
# ```python
# v["dW" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters["W" + str(l+1)])
# v["db" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters["b" + str(l+1)])
# s["dW" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters["W" + str(l+1)])
# s["db" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters["b" + str(l+1)])
#
# ```
# +
# GRADED FUNCTION: initialize_adam
def initialize_adam(parameters) :
"""
Initializes v and s as two python dictionaries with:
- keys: "dW1", "db1", ..., "dWL", "dbL"
- values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters.
Arguments:
parameters -- python dictionary containing your parameters.
parameters["W" + str(l)] = Wl
parameters["b" + str(l)] = bl
Returns:
v -- python dictionary that will contain the exponentially weighted average of the gradient.
v["dW" + str(l)] = ...
v["db" + str(l)] = ...
s -- python dictionary that will contain the exponentially weighted average of the squared gradient.
s["dW" + str(l)] = ...
s["db" + str(l)] = ...
"""
L = len(parameters) // 2 # number of layers in the neural networks
v = {}
s = {}
# Initialize v, s. Input: "parameters". Outputs: "v, s".
for l in range(L):
### START CODE HERE ### (approx. 4 lines)
v["dW" + str(l+1)] = np.zeros((parameters["W" + str(l+1)].shape))
v["db" + str(l+1)] = np.zeros((parameters["b" + str(l+1)].shape))
s["dW" + str(l+1)] = np.zeros((parameters["W" + str(l+1)].shape))
s["db" + str(l+1)] = np.zeros((parameters["b" + str(l+1)].shape))
### END CODE HERE ###
return v, s
# +
parameters = initialize_adam_test_case()
v, s = initialize_adam(parameters)
print("v[\"dW1\"] = \n" + str(v["dW1"]))
print("v[\"db1\"] = \n" + str(v["db1"]))
print("v[\"dW2\"] = \n" + str(v["dW2"]))
print("v[\"db2\"] = \n" + str(v["db2"]))
print("s[\"dW1\"] = \n" + str(s["dW1"]))
print("s[\"db1\"] = \n" + str(s["db1"]))
print("s[\"dW2\"] = \n" + str(s["dW2"]))
print("s[\"db2\"] = \n" + str(s["db2"]))
# -
# **Expected Output**:
#
# ```
# v["dW1"] =
# [[ 0. 0. 0.]
# [ 0. 0. 0.]]
# v["db1"] =
# [[ 0.]
# [ 0.]]
# v["dW2"] =
# [[ 0. 0. 0.]
# [ 0. 0. 0.]
# [ 0. 0. 0.]]
# v["db2"] =
# [[ 0.]
# [ 0.]
# [ 0.]]
# s["dW1"] =
# [[ 0. 0. 0.]
# [ 0. 0. 0.]]
# s["db1"] =
# [[ 0.]
# [ 0.]]
# s["dW2"] =
# [[ 0. 0. 0.]
# [ 0. 0. 0.]
# [ 0. 0. 0.]]
# s["db2"] =
# [[ 0.]
# [ 0.]
# [ 0.]]
# ```
# **Exercise**: Now, implement the parameters update with Adam. Recall the general update rule is, for $l = 1, ..., L$:
#
# $$\begin{cases}
# v_{W^{[l]}} = \beta_1 v_{W^{[l]}} + (1 - \beta_1) \frac{\partial J }{ \partial W^{[l]} } \\
# v^{corrected}_{W^{[l]}} = \frac{v_{W^{[l]}}}{1 - (\beta_1)^t} \\
# s_{W^{[l]}} = \beta_2 s_{W^{[l]}} + (1 - \beta_2) (\frac{\partial J }{\partial W^{[l]} })^2 \\
# s^{corrected}_{W^{[l]}} = \frac{s_{W^{[l]}}}{1 - (\beta_2)^t} \\
# W^{[l]} = W^{[l]} - \alpha \frac{v^{corrected}_{W^{[l]}}}{\sqrt{s^{corrected}_{W^{[l]}}}+\varepsilon}
# \end{cases}$$
#
#
# **Note** that the iterator `l` starts at 0 in the `for` loop while the first parameters are $W^{[1]}$ and $b^{[1]}$. You need to shift `l` to `l+1` when coding.
# +
# GRADED FUNCTION: update_parameters_with_adam
def update_parameters_with_adam(parameters, grads, v, s, t, learning_rate = 0.01,
beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8):
"""
Update parameters using Adam
Arguments:
parameters -- python dictionary containing your parameters:
parameters['W' + str(l)] = Wl
parameters['b' + str(l)] = bl
grads -- python dictionary containing your gradients for each parameters:
grads['dW' + str(l)] = dWl
grads['db' + str(l)] = dbl
v -- Adam variable, moving average of the first gradient, python dictionary
s -- Adam variable, moving average of the squared gradient, python dictionary
learning_rate -- the learning rate, scalar.
beta1 -- Exponential decay hyperparameter for the first moment estimates
beta2 -- Exponential decay hyperparameter for the second moment estimates
epsilon -- hyperparameter preventing division by zero in Adam updates
Returns:
parameters -- python dictionary containing your updated parameters
v -- Adam variable, moving average of the first gradient, python dictionary
s -- Adam variable, moving average of the squared gradient, python dictionary
"""
L = len(parameters) // 2 # number of layers in the neural networks
v_corrected = {} # Initializing first moment estimate, python dictionary
s_corrected = {} # Initializing second moment estimate, python dictionary
# Perform Adam update on all parameters
for l in range(L):
# Moving average of the gradients. Inputs: "v, grads, beta1". Output: "v".
### START CODE HERE ### (approx. 2 lines)
v["dW" + str(l+1)] = beta1*v["dW" + str(l+1)] +(1-beta1)*grads['dW' + str(l+1)]
v["db" + str(l+1)] = beta1*v["db" + str(l+1)] +(1-beta1)*grads['db' + str(l+1)]
### END CODE HERE ###
# Compute bias-corrected first moment estimate. Inputs: "v, beta1, t". Output: "v_corrected".
### START CODE HERE ### (approx. 2 lines)
v_corrected["dW" + str(l+1)] = v["dW" + str(l+1)]/(1-np.power(beta1,t))
v_corrected["db" + str(l+1)] = v["db" + str(l+1)]/(1-np.power(beta1,t))
### END CODE HERE ###
# Moving average of the squared gradients. Inputs: "s, grads, beta2". Output: "s".
### START CODE HERE ### (approx. 2 lines)
s["dW" + str(l+1)] = beta2*s["dW" + str(l+1)] +(1-beta2)*np.power(grads['dW' + str(l+1)],2)
s["db" + str(l+1)] = beta2*s["db" + str(l+1)] +(1-beta2)*np.power(grads['db' + str(l+1)],2)
### END CODE HERE ###
# Compute bias-corrected second raw moment estimate. Inputs: "s, beta2, t". Output: "s_corrected".
### START CODE HERE ### (approx. 2 lines)
s_corrected["dW" + str(l+1)] = s["dW" + str(l+1)]/(1-np.power(beta2,t))
s_corrected["db" + str(l+1)] = s["db" + str(l+1)]/(1-np.power(beta2,t))
### END CODE HERE ###
# Update parameters. Inputs: "parameters, learning_rate, v_corrected, s_corrected, epsilon". Output: "parameters".
### START CODE HERE ### (approx. 2 lines)
parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate*(v_corrected["dW" + str(l+1)]/np.sqrt(s_corrected["dW" + str(l+1)]+epsilon))
parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate*(v_corrected["db" + str(l+1)]/np.sqrt(s_corrected["db" + str(l+1)]+epsilon))
### END CODE HERE ###
return parameters, v, s
# +
parameters, grads, v, s = update_parameters_with_adam_test_case()
parameters, v, s = update_parameters_with_adam(parameters, grads, v, s, t = 2)
print("W1 = \n" + str(parameters["W1"]))
print("b1 = \n" + str(parameters["b1"]))
print("W2 = \n" + str(parameters["W2"]))
print("b2 = \n" + str(parameters["b2"]))
print("v[\"dW1\"] = \n" + str(v["dW1"]))
print("v[\"db1\"] = \n" + str(v["db1"]))
print("v[\"dW2\"] = \n" + str(v["dW2"]))
print("v[\"db2\"] = \n" + str(v["db2"]))
print("s[\"dW1\"] = \n" + str(s["dW1"]))
print("s[\"db1\"] = \n" + str(s["db1"]))
print("s[\"dW2\"] = \n" + str(s["dW2"]))
print("s[\"db2\"] = \n" + str(s["db2"]))
# -
# **Expected Output**:
#
# ```
# W1 =
# [[ 1.63178673 -0.61919778 -0.53561312]
# [-1.08040999 0.85796626 -2.29409733]]
# b1 =
# [[ 1.75225313]
# [-0.75376553]]
# W2 =
# [[ 0.32648046 -0.25681174 1.46954931]
# [-2.05269934 -0.31497584 -0.37661299]
# [ 1.14121081 -1.09245036 -0.16498684]]
# b2 =
# [[-0.88529978]
# [ 0.03477238]
# [ 0.57537385]]
# v["dW1"] =
# [[-0.11006192 0.11447237 0.09015907]
# [ 0.05024943 0.09008559 -0.06837279]]
# v["db1"] =
# [[-0.01228902]
# [-0.09357694]]
# v["dW2"] =
# [[-0.02678881 0.05303555 -0.06916608]
# [-0.03967535 -0.06871727 -0.08452056]
# [-0.06712461 -0.00126646 -0.11173103]]
# v["db2"] =
# [[ 0.02344157]
# [ 0.16598022]
# [ 0.07420442]]
# s["dW1"] =
# [[ 0.00121136 0.00131039 0.00081287]
# [ 0.0002525 0.00081154 0.00046748]]
# s["db1"] =
# [[ 1.51020075e-05]
# [ 8.75664434e-04]]
# s["dW2"] =
# [[ 7.17640232e-05 2.81276921e-04 4.78394595e-04]
# [ 1.57413361e-04 4.72206320e-04 7.14372576e-04]
# [ 4.50571368e-04 1.60392066e-07 1.24838242e-03]]
# s["db2"] =
# [[ 5.49507194e-05]
# [ 2.75494327e-03]
# [ 5.50629536e-04]]
# ```
# You now have three working optimization algorithms (mini-batch gradient descent, Momentum, Adam). Let's implement a model with each of these optimizers and observe the difference.
# ## 3 - Model with different optimization algorithms
#
# Lets use the following "moons" dataset to test the different optimization methods. (The dataset is named "moons" because the data from each of the two classes looks a bit like a crescent-shaped moon.)
train_X, train_Y = load_dataset()
# We have already implemented a 3-layer neural network. You will train it with:
# - Mini-batch **Gradient Descent**: it will call your function:
# - `update_parameters_with_gd()`
# - Mini-batch **Momentum**: it will call your functions:
# - `initialize_velocity()` and `update_parameters_with_momentum()`
# - Mini-batch **Adam**: it will call your functions:
# - `initialize_adam()` and `update_parameters_with_adam()`
def model(X, Y, layers_dims, optimizer, learning_rate = 0.0007, mini_batch_size = 64, beta = 0.9,
beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8, num_epochs = 10000, print_cost = True):
"""
3-layer neural network model which can be run in different optimizer modes.
Arguments:
X -- input data, of shape (2, number of examples)
Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (1, number of examples)
layers_dims -- python list, containing the size of each layer
learning_rate -- the learning rate, scalar.
mini_batch_size -- the size of a mini batch
beta -- Momentum hyperparameter
beta1 -- Exponential decay hyperparameter for the past gradients estimates
beta2 -- Exponential decay hyperparameter for the past squared gradients estimates
epsilon -- hyperparameter preventing division by zero in Adam updates
num_epochs -- number of epochs
print_cost -- True to print the cost every 1000 epochs
Returns:
parameters -- python dictionary containing your updated parameters
"""
L = len(layers_dims) # number of layers in the neural networks
costs = [] # to keep track of the cost
t = 0 # initializing the counter required for Adam update
seed = 10 # For grading purposes, so that your "random" minibatches are the same as ours
m = X.shape[1] # number of training examples
# Initialize parameters
parameters = initialize_parameters(layers_dims)
# Initialize the optimizer
if optimizer == "gd":
pass # no initialization required for gradient descent
elif optimizer == "momentum":
v = initialize_velocity(parameters)
elif optimizer == "adam":
v, s = initialize_adam(parameters)
# Optimization loop
for i in range(num_epochs):
# Define the random minibatches. We increment the seed to reshuffle differently the dataset after each epoch
seed = seed + 1
minibatches = random_mini_batches(X, Y, mini_batch_size, seed)
cost_total = 0
for minibatch in minibatches:
# Select a minibatch
(minibatch_X, minibatch_Y) = minibatch
# Forward propagation
a3, caches = forward_propagation(minibatch_X, parameters)
# Compute cost and add to the cost total
cost_total += compute_cost(a3, minibatch_Y)
# Backward propagation
grads = backward_propagation(minibatch_X, minibatch_Y, caches)
# Update parameters
if optimizer == "gd":
parameters = update_parameters_with_gd(parameters, grads, learning_rate)
elif optimizer == "momentum":
parameters, v = update_parameters_with_momentum(parameters, grads, v, beta, learning_rate)
elif optimizer == "adam":
t = t + 1 # Adam counter
parameters, v, s = update_parameters_with_adam(parameters, grads, v, s,
t, learning_rate, beta1, beta2, epsilon)
cost_avg = cost_total / m
# Print the cost every 1000 epoch
if print_cost and i % 1000 == 0:
print ("Cost after epoch %i: %f" %(i, cost_avg))
if print_cost and i % 100 == 0:
costs.append(cost_avg)
# plot the cost
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('epochs (per 100)')
plt.title("Learning rate = " + str(learning_rate))
plt.show()
return parameters
# +
X_assess, Y_assess, mini_batch_size = random_mini_batches_test_case()
mini_batches = random_mini_batches(X_assess, Y_assess, mini_batch_size)
print ("shape of the 1st mini_batch_X: " + str(mini_batches[0][0].shape))
print ("shape of the 2nd mini_batch_X: " + str(mini_batches[1][0].shape))
print ("shape of the 3rd mini_batch_X: " + str(mini_batches[2][0].shape))
print ("shape of the 1st mini_batch_Y: " + str(mini_batches[0][1].shape))
print ("shape of the 2nd mini_batch_Y: " + str(mini_batches[1][1].shape))
print ("shape of the 3rd mini_batch_Y: " + str(mini_batches[2][1].shape))
print ("mini batch sanity check: " + str(mini_batches[0][0][0][0:3]))
# -
# **Expected Output**:
#
# <table style="width:50%">
# <tr>
# <td > **shape of the 1st mini_batch_X** </td>
# <td > (12288, 64) </td>
# </tr>
#
# <tr>
# <td > **shape of the 2nd mini_batch_X** </td>
# <td > (12288, 64) </td>
# </tr>
#
# <tr>
# <td > **shape of the 3rd mini_batch_X** </td>
# <td > (12288, 20) </td>
# </tr>
# <tr>
# <td > **shape of the 1st mini_batch_Y** </td>
# <td > (1, 64) </td>
# </tr>
# <tr>
# <td > **shape of the 2nd mini_batch_Y** </td>
# <td > (1, 64) </td>
# </tr>
# <tr>
# <td > **shape of the 3rd mini_batch_Y** </td>
# <td > (1, 20) </td>
# </tr>
# <tr>
# <td > **mini batch sanity check** </td>
# <td > [ 0.90085595 -0.7612069 0.2344157 ] </td>
# </tr>
#
# </table>
# You will now run this 3 layer neural network with each of the 3 optimization methods.
#
# ### 3.1 - Mini-batch Gradient descent
#
# Run the following code to see how the model does with mini-batch gradient descent.
# +
# train 3-layer model
layers_dims = [train_X.shape[0], 5, 2, 1]
parameters = model(train_X, train_Y, layers_dims, optimizer = "gd")
# Predict
predictions = predict(train_X, train_Y, parameters)
# Plot decision boundary
plt.title("Model with Gradient Descent optimization")
axes = plt.gca()
axes.set_xlim([-1.5,2.5])
axes.set_ylim([-1,1.5])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
# -
# ### 3.2 - Mini-batch gradient descent with momentum
#
# Run the following code to see how the model does with momentum. Because this example is relatively simple, the gains from using momemtum are small; but for more complex problems you might see bigger gains.
# +
# train 3-layer model
layers_dims = [train_X.shape[0], 5, 2, 1]
parameters = model(train_X, train_Y, layers_dims, beta = 0.9, optimizer = "momentum")
# Predict
predictions = predict(train_X, train_Y, parameters)
# Plot decision boundary
plt.title("Model with Momentum optimization")
axes = plt.gca()
axes.set_xlim([-1.5,2.5])
axes.set_ylim([-1,1.5])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
# -
# ### 3.3 - Mini-batch with Adam mode
#
# Run the following code to see how the model does with Adam.
# +
# train 3-layer model
layers_dims = [train_X.shape[0], 5, 2, 1]
parameters = model(train_X, train_Y, layers_dims, optimizer = "adam")
# Predict
predictions = predict(train_X, train_Y, parameters)
# Plot decision boundary
plt.title("Model with Adam optimization")
axes = plt.gca()
axes.set_xlim([-1.5,2.5])
axes.set_ylim([-1,1.5])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
# -
# ### 3.4 - Summary
#
# <table>
# <tr>
# <td>
# **optimization method**
# </td>
# <td>
# **accuracy**
# </td>
# <td>
# **cost shape**
# </td>
#
# </tr>
# <td>
# Gradient descent
# </td>
# <td>
# 79.7%
# </td>
# <td>
# oscillations
# </td>
# <tr>
# <td>
# Momentum
# </td>
# <td>
# 79.7%
# </td>
# <td>
# oscillations
# </td>
# </tr>
# <tr>
# <td>
# Adam
# </td>
# <td>
# 94%
# </td>
# <td>
# smoother
# </td>
# </tr>
# </table>
#
# Momentum usually helps, but given the small learning rate and the simplistic dataset, its impact is almost negligeable. Also, the huge oscillations you see in the cost come from the fact that some minibatches are more difficult thans others for the optimization algorithm.
#
# Adam on the other hand, clearly outperforms mini-batch gradient descent and Momentum. If you run the model for more epochs on this simple dataset, all three methods will lead to very good results. However, you've seen that Adam converges a lot faster.
#
# Some advantages of Adam include:
# - Relatively low memory requirements (though higher than gradient descent and gradient descent with momentum)
# - Usually works well even with little tuning of hyperparameters (except $\alpha$)
# **References**:
#
# - Adam paper: https://arxiv.org/pdf/1412.6980.pdf
|
01_advanced_topics_machine_learning/assignments/notebooks/2_Training/HW02_Sol_Optimization_methods.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
df = pd.read_csv("amazonreview.csv")
df.info()
# +
file = open('1234.txt', 'r')
book = file.read()
def tokenize():
if book is not None:
words = book.lower().split()
return words
else:
return None
def map_book(tokens):
hash_map = {}
if tokens is not None:
for element in tokens:
word = element.replace(",","")
word = word.replace(".","")
if word in hash_map:
hash_map[word] = hash_map[word] + 1
else:
hash_map[word] = 1
return hash_map
else:
return None
words = tokenize()
word_list = ["display", "screen","notch","resolution","camera", "picture", "video", "recording", "selfie", "potrait", "rear" , "flash", "pixel", "front","music", "speaker", "sound","battery", "charge", "power","lithium-ion","money","budget","phone", "device", "model","design", "look","color","ram","glass","temper","os","android" ,"nougat","processor", "cpu", "snapdragon","hardware","heat","warm","game", "gpu","sensor", "navigation","compass","magnetometer","accelerometer", "ambient","temperature","network","connectivity","4g","lte","volte","wifi","hotspot","usb","jack","gps","bluetooth","signal","location","standards", "nfc", "infrared", "sim", "3g", "4g", "charger", "dash", "usb", "turbo", "memory", "storage","rom","internal", "expandable", "gb","warranty","google","notification", "gesture"]
map = map_book(words)
for word in word_list:
print('Word: [' + word + '] Frequency: ' + str(map[word]))
# -
display=["display", "screen","notch","resolution"]
camera=["camera", "picture", "video", "recording", "selfie", "potrait","rear" ,"flash", "megapixel", "front" ]
music=["music", "song", "speaker", "sound"]
battery=["battery", "charge", "power","lithium-ion","standbytime"]
money=["money","budget"]
phone=["phone", "device", "model"]
design=["design", "look"]
color=["color"]
ram=["ram"]
glass=["glass" "temper"]
os=["os","android" ,"nougat", "oxygen", "operating system"]
processor=["processor", "cpu", "snapdragon","hardware"]
heat=["heat","warm"]
game=["game", "gpu"]
sensor=["sensor", "navigation", "finegerprint","face-reconigation","voice-reconigation","voice-reconigation","compass","magnetometer","proximity","accelerometer", "ambient", "gyroscope" "barometer" ,"temperature"]
network=["network","connectivity","4g","lte","volte","wifi","hotspot","usb","jack","gps","bluetooth","signal","location","standards","b/g", "nfc", "infrared", "sim", "fmgsm", "cdma", "gsm", "3g", "4g", "bands"]
charger=["charger", "c-type", "dash", "usb", "turbo"]
harddisk=["harddisk", "memory", "storage","rom","internal", "expandable", "microsd", "gb", "tb", "mb"]
launcher=["launcher"]
warranty=["warranty", "guarantee"]
assisstant=["assisstant", "siri", "google"]
notification=["notification", "alert", "gesture"]
dict={"display":0,"camera":0,"music":0,"battery":0,"notification":0,"warranty":0,"harddisk":0,"charger":0,"network":0,"sensor":0,"game":0,"heat":0,"processor":0,"os":0,"glass":0,"ram":0,"color":0,"design":0,"phone":0,"money":0}
for token in word_list:
if(map[token]<=0):
continue;
for token in display:
dict["display"]+=map[token];
break;
for token in camera:
dict["camera"]+=map[token];
break;
for token in music:
dict["music"]+=map[token];
break;
for token in battery:
dict["battery"]+=map[token];
break;
for token in notification:
dict["notification"]+=map[token];
break;
for token in warranty:
dict["warranty"]+=map[token];
break;
for token in harddisk:
dict["harddisk"]+=map[token];
break;
for token in charger:
dict["charger"]+=map[token];
break;
for token in network:
dict["network"]+=map[token];
break;
for token in sensor:
dict["sensor"]+=map[token];
break;
for token in game:
dict["game"]+=map[token];
break;
for token in heat:
dict["heat"]+=map[token];
break;
for token in processor:
dict["processor"]+=map[token];
break;
for token in os:
dict["os"]+=map[token];
break;
for token in glass:
dict["glass"]+=map[token];
break;
for token in ram:
dict["ram"]+=map[token];
break;
for token in color:
dict["color"]+=map[token];
break;
for token in design:
dict["design"]+=map[token];
break;
for token in phone:
dict["phone"]+=map[token];
break;
for token in money:
dict["money"]+=map[token];
break;
for val in dict:
print(val,dict[val])
|
Frequency_analysis/frequency_of_word.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.8.8 64-bit (''torch_x86'': conda)'
# language: python
# name: python38864bittorchx86condad5999c8bd9c4485a99dbef96feddd77f
# ---
import numpy as np
# ## 1D with numpy
t = np.array([0.,1.,2.,3.,4.,5.,6.])
print(t)
print('Rank of t : ', t.ndim)
print('Shape of t : ', t.shape)
# .ndim : numpy의 차원을 출력
# .shape : numpy의 크기를 출력 (7,)은 (1,7)을 의미함.
f't[0] t[1] t[-1] = {t[0]} {t[1]} {t[-1]}'
# numpy에서는 범위를 지정하여 원소를 가져올 수 있습니다. 이를 slicing이라고 합니다. "배열\[시작번호 : 끝번호\]"를 지정하면 끝번호를 제외한 범위의 원소를 가져옵니다.
print(t[2:5])
print(t[4:-1])
print(f't[:2] t[3:] = {t[:2]} {t[3:]}')
# ## 2D with numpy
t = np.array([ [(j+1.0)*(i+1.0) for j in range(3)] for i in range(4)])
print(t)
print('Rank of t: ', t.ndim)
print('Shape of t: ', t.shape)
# # 파이토치 텐서
#
# 파이토치의 텐서는 numpy와 매우 유사하지만 더 좋습니다.
import torch
t = torch.FloatTensor([float(i) for i in range(7)])
print(t)
print(t.dim()) # 차원
print(t.shape) # 크기
print(t.size()) # 크기
# 파이토치에서도 슬라이싱을 제공합니다. 사용은 numpy와 동일합니다.
print(t[0], t[1], t[-1])
print(t[2:5], t[4:-1])
print(t[:2],t[3:])
# ## 2D with PyTorch
t = torch.FloatTensor([ [(j+1.0)*(i+1.0) for j in range(3)] for i in range(4)])
print(t)
print(t.dim())
print(t.size())
print(t[:,1]) # 모든 첫번째 차원에서 두번째 차원의 첫번째 원소만 가져온다.
print(t[:,1].size())
print(t[:,:-1]) # 모든 첫번째 차원에서 두번째 차원의 마지막 원소를 제외하고 모두 가져온다.
# ## 브로드캐스팅
#
# 두 행렬 A, B가 있습니다. 행렬의 덧셈과 뺄셈을 할 때는 두 행렬 A, B의 크기가 동일해야 된다고 배웠습니다. 하지만 딥러닝에서는 그렇지 못한 경우가 발생합니다. 이때 자동으로 크기를 맞춰서 연산해주는 것이 브로드캐스팅입니다.
m1 = torch.FloatTensor([[3, 3]])
m2 = torch.FloatTensor([[2, 2]])
print(m1 + m2)
# m1과 m2의 크기는 둘다 (1,2)이므로 문제 없이 덧셈 연산이 가능합니다. 이번에는 크기가 다른 텐서들 간의 연산을 해보겠습니다.
m1 = torch.FloatTensor([[1,2]]) # vector
m2 = torch.FloatTensor([3]) # scalar
print(m1 + m2)
print(m1.size() , m2.size())
# 결과를 보듯이 m2가 (1,2) 차원으로 변경되어 연산이 수행된 것을 알 수 있습니다.
m1 = torch.FloatTensor([[1, 2]]) # 2,1 vector
m2 = torch.FloatTensor([[3], [4]]) # 1,2 vector
print(m1 + m2)
# 두 벡터는 수학적으로 연산이 불가능합니다. 파이토치에서는 두 벡터를 (2,2) 크기로 변경하여 연산되었습니다.
#
# ```
# [1, 2]
# ==> [[1, 2],
# [1, 2]]
# [3],[4]
# ==> [[3, 3],
# [4, 4]]
# ```
#
# 브로드캐스팅은 이처럼 크기가 다른 두 텐서를 연산할 수 있다는 점에서 좋지만, 반대로 두 텐서의 크기가 다른지 모른 상태로 어떠한 에러가 없다면 의도치 않은 결과를 낼 것입니다. 그리고 이러한 오류가 어디서 발생했는지 알 수 없을 것 입니다.
# # 주요 사용되는 기능
#
# ## 행렬 곱셈과 곱셈의 차이
#
# 행렬로 곱셈을 하는 방법은 크게 두가지가 있습니다. 행렬 곱셈과 원소 별 곱셈입니다. 파이토치 텐서의 행렬 곱셈을 보겠습니다. 이를 matmul()을 통해 수행합니다.
m1 = torch.FloatTensor([[1, 2], [3, 4]])
m2 = torch.FloatTensor([[1], [2]])
print('Shape of Matrix 1: ', m1.shape) # 2 x 2
print('Shape of Matrix 2: ', m2.shape) # 2 x 1
print(m1.matmul(m2)) # 2 x 1
# 행렬 곱셈 이외에도 element-wise 곱셈이 있습니다. 이는 동일한 크기의 행렬이 동일한 위치에 있는 원소끼리 곱하는 것을 말합니다. 여기서는 브로드캐스팅이 된후에 element-wise 곱셈이 수행되는 것을 보여줍니다. 이를 * 또는 mat()을 통해 수행합니다.
m1 = torch.FloatTensor([[1, 2], [3, 4]])
m2 = torch.FloatTensor([[1], [2]])
print('Shape of Matrix 1: ', m1.shape) # 2 x 2
print('Shape of Matrix 2: ', m2.shape) # 2 x 1
print(m1 * m2) # 2 x 2
print(m1.mul(m2))
# m1 행렬의 크기는 (2,2) 였습니다. m2 행렬의 크기는 (2,1)였습니다. 이때 element-wise 곱세을 수행하면, 두 행렬의 크기는 브로드캐스팅된 후에 곱셈이 수행됩니다.
#
# ```
# [1]
# [2]
# ==> [[1, 1],
# [2, 2]]
# ```
# ## 평균
#
# 평균을 구하는 방법은 쉽습니다. .mean()을 사용하여 원소의 평균을 구합니다.
t = torch.FloatTensor([1,2])
print(t.mean())
t = torch.FloatTensor([[1,2],[3,4]])
print(t.mean())
print(t.mean(dim=0))
print(t.mean(dim=-1), t.mean(dim=1))
# ## 덧셈
#
# 덧셈은 평균 연산과 연산 방법이나 인자가 의미하는 바는 정확히 동일합니다. 다만 평균이 아니라 덧셈을 할 뿐입니다.
t = torch.FloatTensor([[1,2,],[3,4]])
print(t.sum())
print(t.sum(dim =0))
print(t.sum(dim =1))
print(t.sum(dim =-1))
# ## 최대와 아그맥스(ArgMax)
#
# 최대는 원소의 최대값을 리턴하고, 아그맥스는(ArgMax)는 최대값을 가진 인덱스를 리턴합니다.
t = torch.FloatTensor([[1,2],[3,4]])
print(t)
print(t.max())
print(t.max(dim=0))
print(t.max(dim=1))
print(t.max(dim=-1))
print(f"max : {t.max(dim=0)[0]}")
print(f"arg max : {t.max(dim=0)[1]}")
|
01 Tensor.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: cv
# language: python
# name: cv
# ---
# # Computer Vision Nanodegree
#
# ## Project: Image Captioning
#
# ---
#
# In this notebook, you will use your trained model to generate captions for images in the test dataset.
#
# This notebook **will be graded**.
#
# Feel free to use the links below to navigate the notebook:
# - [Step 1](#step1): Get Data Loader for Test Dataset
# - [Step 2](#step2): Load Trained Models
# - [Step 3](#step3): Finish the Sampler
# - [Step 4](#step4): Clean up Captions
# - [Step 5](#step5): Generate Predictions!
# <a id='step1'></a>
# ## Step 1: Get Data Loader for Test Dataset
#
# Before running the code cell below, define the transform in `transform_test` that you would like to use to pre-process the test images.
#
# Make sure that the transform that you define here agrees with the transform that you used to pre-process the training images (in **2_Training.ipynb**). For instance, if you normalized the training images, you should also apply the same normalization procedure to the test images.
# +
import sys
sys.path.append('/opt/cocoapi/PythonAPI')
from pycocotools.coco import COCO
from data_loader import get_loader
from torchvision import transforms
# TODO #1: Define a transform to pre-process the testing images.
transform_test = transforms.Compose([
transforms.Resize((224,224)), # smaller edge of image resized to 224
transforms.ToTensor(), # convert the PIL Image to a tensor
transforms.Normalize((0.485, 0.456, 0.406), # normalize image for pre-trained model
(0.229, 0.224, 0.225))])
#-#-#-# Do NOT modify the code below this line. #-#-#-#
# Create the data loader.
data_loader = get_loader(transform=transform_test,
mode='test',
cocoapi_loc='/home/jupyter/')
# -
# Run the code cell below to visualize an example test image, before pre-processing is applied.
# +
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
# Obtain sample image before and after pre-processing.
orig_image, image = next(iter(data_loader))
# Visualize sample image, before pre-processing.
plt.imshow(np.squeeze(orig_image))
plt.title('example image')
plt.show()
# -
print(orig_image.shape)
print(image.shape)
# +
# Visualize sample image, before pre-processing.
# plt.imshow(np.squeeze(image))
# plt.title('transformed image')
# plt.show()
# -
# <a id='step2'></a>
# ## Step 2: Load Trained Models
#
# In the next code cell we define a `device` that you will use move PyTorch tensors to GPU (if CUDA is available). Run this code cell before continuing.
# +
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# -
# Before running the code cell below, complete the following tasks.
#
# ### Task #1
#
# In the next code cell, you will load the trained encoder and decoder from the previous notebook (**2_Training.ipynb**). To accomplish this, you must specify the names of the saved encoder and decoder files in the `models/` folder (e.g., these names should be `encoder-5.pkl` and `decoder-5.pkl`, if you trained the model for 5 epochs and saved the weights after each epoch).
#
# ### Task #2
#
# Plug in both the embedding size and the size of the hidden layer of the decoder corresponding to the selected pickle file in `decoder_file`.
# +
# Watch for any changes in model.py, and re-load it automatically.
# %load_ext autoreload
# %autoreload 2
import os
import torch
from model import EncoderCNN, DecoderRNN
# +
# TODO #2: Specify the saved models to load.
encoder_file = 'encoder-3.pkl'
decoder_file = 'decoder-3.pkl'
# TODO #3: Select appropriate values for the Python variables below.
embed_size = 512
hidden_size = 256
# The size of the vocabulary.
vocab_size = len(data_loader.dataset.vocab)
# Initialize the encoder and decoder, and set each to inference mode.
encoder = EncoderCNN(embed_size)
encoder.eval()
decoder = DecoderRNN(embed_size, hidden_size, vocab_size, debug=True)
decoder.eval()
# Load the trained weights.
encoder.load_state_dict(torch.load(os.path.join('./models', encoder_file)))
decoder.load_state_dict(torch.load(os.path.join('./models', decoder_file)))
# Move models to GPU if CUDA is available.
encoder.to(device)
decoder.to(device)
# -
# <a id='step3'></a>
# ## Step 3: Finish the Sampler
#
# Before executing the next code cell, you must write the `sample` method in the `DecoderRNN` class in **model.py**. This method should accept as input a PyTorch tensor `features` containing the embedded input features corresponding to a single image.
#
# It should return as output a Python list `output`, indicating the predicted sentence. `output[i]` is a nonnegative integer that identifies the predicted `i`-th token in the sentence. The correspondence between integers and tokens can be explored by examining either `data_loader.dataset.vocab.word2idx` (or `data_loader.dataset.vocab.idx2word`).
#
# After implementing the `sample` method, run the code cell below. If the cell returns an assertion error, then please follow the instructions to modify your code before proceeding. Do **not** modify the code in the cell below.
# +
# import torch.utils.data as data
# # (Optional) TODO #2: Amend the image transform below.
# transform_train = transforms.Compose([
# transforms.Resize(256), # smaller edge of image resized to 256
# transforms.RandomAffine(degrees=15, translate=(.1,.1), shear=(10,10)),
# transforms.RandomCrop(224), # get 224x224 crop from random location
# transforms.RandomHorizontalFlip(), # horizontally flip image with probability=0.5
# transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1,
# hue=0.1), # randomly change the brightness, contrast and saturation of an image
# transforms.ToTensor(), # convert the PIL Image to a tensor
# transforms.Normalize((0.485, 0.456, 0.406), # normalize image for pre-trained model
# (0.229, 0.224, 0.225))])
# # Build data loader.
# data_loader = get_loader(transform=transform_train,
# mode='train',
# batch_size=1,
# vocab_from_file=True)
# indices = data_loader.dataset.get_train_indices()
# # Create and assign a batch sampler to retrieve a batch with the sampled indices.
# new_sampler = data.sampler.SubsetRandomSampler(indices=indices)
# data_loader.batch_sampler.sampler = new_sampler
# # Obtain the batch.
# images, captions = next(iter(data_loader))
# images.shape
# captions.shape
# images = images.to(device)
# captions = captions.to(device)
# # Obtain the embedded image features.
# features = encoder(images) #.unsqueeze(1)
# output = decoder(features,captions)
# features.shape
# +
# output.view(-1, vocab_size)
# +
# torch.cat((captions,captions), dim=0 ).view(-1)
# +
# Move image Pytorch Tensor to GPU if CUDA is available.
image = image.to(device)
print(image.shape)
# Obtain the embedded image features.
features = encoder(image).unsqueeze(1)
print(features.shape)
# Pass the embedded image features through the model to get a predicted caption.
output = decoder.sample(features)
print('example output:', output)
assert (type(output)==list), "Output needs to be a Python list"
assert all([type(x)==int for x in output]), "Output should be a list of integers."
assert all([x in data_loader.dataset.vocab.idx2word for x in output]), "Each entry in the output needs to correspond to an integer that indicates a token in the vocabulary."
# -
# <a id='step4'></a>
# ## Step 4: Clean up the Captions
#
# In the code cell below, complete the `clean_sentence` function. It should take a list of integers (corresponding to the variable `output` in **Step 3**) as input and return the corresponding predicted sentence (as a single Python string).
idx2word = data_loader.dataset.vocab.idx2word
# TODO #4: Complete the function.
def clean_sentence(output):
sentence = ''
for i in output:
word = idx2word[i]
if i not in [0,1]:
sentence += word + ' '
return sentence
# After completing the `clean_sentence` function above, run the code cell below. If the cell returns an assertion error, then please follow the instructions to modify your code before proceeding.
# +
sentence = clean_sentence(output)
print('example sentence:', sentence)
assert type(sentence)==str, 'Sentence needs to be a Python string!'
# -
# <a id='step5'></a>
# ## Step 5: Generate Predictions!
#
# In the code cell below, we have written a function (`get_prediction`) that you can use to use to loop over images in the test dataset and print your model's predicted caption.
def get_prediction():
orig_image, image = next(iter(data_loader))
plt.imshow(np.squeeze(orig_image))
plt.title('Sample Image')
plt.show()
image = image.to(device)
features = encoder(image).unsqueeze(1)
output = decoder.sample(features)
sentence = clean_sentence(output)
print(sentence)
# Run the code cell below (multiple times, if you like!) to test how this function works.
get_prediction()
# As the last task in this project, you will loop over the images until you find four image-caption pairs of interest:
# - Two should include image-caption pairs that show instances when the model performed well.
# - Two should highlight image-caption pairs that highlight instances where the model did not perform well.
#
# Use the four code cells below to complete this task.
# ### The model performed well!
#
# Use the next two code cells to loop over captions. Save the notebook when you encounter two images with relatively accurate captions.
get_prediction()
get_prediction()
# ### The model could have performed better ...
#
# Use the next two code cells to loop over captions. Save the notebook when you encounter two images with relatively inaccurate captions.
get_prediction()
get_prediction()
# ### Plotting loss and perplexity
# +
import pandas as pd
# find out where the log file is
# !ls
# +
log_fn = 'training_log_1572788319.txt'
with open(log_fn, 'r') as f:
log = f.readlines()
log = [l.replace('\n','').split(',') for l in log]
log = [[l.replace(' [', ': ').split('/',1)[0] for l in lo] for lo in log]
log_dict = [{l.split(':')[0].strip():float(l.split(':')[1]) for l in lo} for lo in log]
df = pd.DataFrame(log_dict)
# -
df[['Loss']].plot()
# ignore the outliers at the beginning
df[['Perplexity']][100:].plot()
# +
class Attention(nn.Module):
def __init__(self, encoder_dim, decoder_dim, attention_dim):
super(Attention, self).__init__()
self.encoder_att = nn.Linear(encoder_dim, attention_dim) # linear layer to transform encoded image
self.decoder_att = nn.Linear(decoder_dim, attention_dim) # linear layer to transform decoder's output
self.full_att = nn.Linear(attention_dim, 1) # linear layer to calculate values to be softmax-ed
self.relu = nn.ReLU()
self.softmax = nn.Softmax(dim=1) # softmax layer to calculate weights
def forward(self, encoder_out, decoder_hidden):
att1 = self.encoder_att(encoder_out) # (batch_size, num_pixels, attention_dim)
att2 = self.decoder_att(decoder_hidden) # (batch_size, attention_dim)
att = self.full_att(self.relu(att1 + att2.unsqueeze(1))).squeeze(2) # (batch_size, num_pixels)
alpha = self.softmax(att) # (batch_size, num_pixels)
attention_weighted_encoding = (encoder_out * alpha.unsqueeze(2)).sum(dim=1) # (batch_size, encoder_dim)
return attention_weighted_encoding, alpha
class AttentionDecoderRNN(nn.Module):
def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1, pretrained_embeds=None, debug=False):
super(DecoderRNN, self).__init__()
self.hidden_size = hidden_size
self.word_embeddings = nn.Embedding(vocab_size, embed_size)
if pretrained_embeds is not None:
# torch.from_numpy(pretrained_embeds)
self.word_embeddings = self.word_embeddings.weight.data.copy_(pretrained_embeds)
self.word_embeddings.weight.requires_grad = False
self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)
self.dec = nn.Linear(hidden_size, vocab_size)
self.debug = debug
def forward(self, features, captions):
if self.debug:
print('features: ', features.shape)
print('captions: ', captions.shape)
embeds = self.word_embeddings(captions[:,:-1])
if self.debug:
print('embeds: ', embeds.shape)
features = features.unsqueeze(1)
if self.debug:
print('unsq feats: ', features.shape)
inputs = (features, embeds)
inputs = torch.cat(inputs,1)
if self.debug:
print('inputs: ', inputs.shape)
# inputs = inputs.view(len(inputs), 1, -1)
# print('inputs.view', inputs.shape)
h_shape = (1, inputs.shape[0], self.hidden_size)
if self.debug:
print('h-shape: ', h_shape)
hidden = (torch.randn(h_shape).cuda(),
torch.randn(h_shape).cuda()) # clean out hidden state
out, hidden = self.lstm(inputs, hidden)
if self.debug:
print('out: ', out.shape)
print('hidden: ', hidden[0].shape)
token_space = self.dec(out)
if self.debug:
print('token_space: ', token_space.shape)
# token_scores = F.log_softmax(x, dim=1) # nn.CrossEntory takes care of this
# if self.debug:
# print('token_scores: ', token_scores.shape)
return token_space
def sample(self, inputs, states=None, max_len=20):
" accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) "
output = []
# clear hidden state
h_shape = (1, inputs.shape[0], self.hidden_size)
hidden = (torch.randn(h_shape).cuda(), torch.randn(h_shape).cuda())
# loop until <end> token is sampled or maximum length is reached
# out, hidden = self.lstm()
for i in range(max_len):
out, hidden = self.lstm(inputs, hidden)
if self.debug:
print('out: ', out.shape)
x = self.dec(out)
if self.debug:
print('x: ', x.shape)
values, tokens = torch.max(x, dim=-1)
if self.debug:
print('tokens: ',tokens)
token = tokens.item()
output.append(token)
if token==1:
break
inputs = self.word_embeddings(tokens)
return output
# -
|
3_Inference.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ___
#
# <a href='http://www.pieriandata.com'><img src='../Pierian_Data_Logo.png'/></a>
# ___
# <center><em>Copyright <NAME></em></center>
# <center><em>For more information, visit us at <a href='http://www.pieriandata.com'>www.pieriandata.com</a></em></center>
# # Time Series with Pandas Project Exercise
#
# For this exercise, answer the questions below given the dataset: https://fred.stlouisfed.org/series/UMTMVS
#
# This dataset is the Value of Manufacturers' Shipments for All Manufacturing Industries.
# **Import any necessary libraries.**
# +
# CODE HERE
# -
# **Read in the data UMTMVS.csv file from the Data folder**
# +
# CODE HERE
# -
# **Check the head of the data**
# +
# CODE HERE
# -
# **Set the DATE column as the index.**
# +
# CODE HERE
# -
# **Check the data type of the index.**
# +
# CODE HERE
# -
# **Convert the index to be a datetime index. Note, there are many, many correct ways to do this!**
# +
# CODE HERE
# -
# **Plot out the data, choose a reasonable figure size**
# +
# CODE HERE
# -
# **What was the percent increase in value from Jan 2009 to Jan 2019?**
# +
#CODE HERE
# -
# **What was the percent decrease from Jan 2008 to Jan 2009?**
# +
#CODE HERE
# -
# **What is the month with the least value after 2005?** [HINT](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.idxmin.html)
# +
#CODE HERE
# -
# **What 6 months have the highest value?**
# +
# CODE HERE
# -
# **How many millions of dollars in value was lost in 2008? (Another way of posing this question is what was the value difference between Jan 2008 and Jan 2009)**
# +
# CODE HERE
# -
# **Create a bar plot showing the average value in millions of dollars per year**
# +
# CODE HERE
# -
# **What year had the biggest increase in mean value from the previous year's mean value? (Lots of ways to get this answer!)**
#
# [HINT for a useful method](https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.idxmax.html)
# +
# CODE HERE
# -
# **Plot out the yearly rolling mean on top of the original data. Recall that this is monthly data and there are 12 months in a year!**
# +
# CODE HERE
# -
# **BONUS QUESTION (HARD).**
#
# **Some month in 2008 the value peaked for that year. How many months did it take to surpass that 2008 peak? (Since it crashed immediately after this peak) There are many ways to get this answer. NOTE: I get 70 months as my answer, you may get 69 or 68, depending on whether or not you count the start and end months. Refer to the video solutions for full explanation on this.**
# +
#CODE HERE
# -
# # GREAT JOB!
|
tsa/jose/TSA_COURSE_NOTEBOOKS/04-Time-Series-with-Pandas/.ipynb_checkpoints/07-Time-Series-with-Pandas-Project-Exercise-SET-TWO-checkpoint.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import csv
import random
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
labels = []
headlines = []
loweredHeadlines = []
tokenizedHeadlines = []
filteredHeadlines = []
all_words = []
documents = []
manualStopWords = ['(', ')','#',',',';',"'s",'?']
stop_words = (stopwords.words('english'))
for m in manualStopWords:
stop_words.append(m)
# print(stop_words)
with open('datasetNew.csv') as file:
reader = csv.DictReader(file)
for row in reader:
labels.append(row['label'])
headlines.append(row['headline'])
# print(labels)
# print(headlines)
# Lower case headlines
for h in headlines:
loweredHeadlines.append(h.lower())
# print(loweredHeadlines)
# Tokenize lower-cased headlines and remove stop words
for low in loweredHeadlines:
words = []
filtered_words = []
words = word_tokenize(low)
for w in words:
if w not in stop_words:
filtered_words.append(w)
all_words.append(w)
tokenizedHeadlines.append(filtered_words)
i=0
l=len(headlines)
while(i<l):
documents.append((tokenizedHeadlines[i],labels[i]))
i=i+1
# print(documents)
all_words = nltk.FreqDist(all_words)
# print(all_words.most_common(20))
# print(tokenizedHeadlines)
word_feature = list(all_words.keys())[:5000]
# print(word_feature)
# print(all_words)
def find_features(document):
words=set(document)
features = {}
for w in word_feature:
features[w]=(w in words)
return features
featuresets = [(find_features(headlines),labels) for (headlines,labels) in documents]
# print(featuresets)
training_set = featuresets[:6000]
testing_set = featuresets[6000:]
# print(training_set)
# print(testing_set)
import nltk
classifier = nltk.NaiveBayesClassifier.train(training_set)
print("Naive Bayes:",(nltk.classify.accuracy(classifier,testing_set))*100)
# -
|
text_classification_nltk.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# # Metric Learning with the Shogun Machine Learning Toolbox
# #### *By <NAME> (GitHub ID: [iglesias](https://github.com/iglesias)) as project report for GSoC 2013 ([project details](http://www.google-melange.com/gsoc/project/google/gsoc2013/iglesias/62013)).*
# This notebook illustrates <a href="http://en.wikipedia.org/wiki/Statistical_classification">classification</a> and <a href="http://en.wikipedia.org/wiki/Feature_selection">feature selection</a> using <a href="http://en.wikipedia.org/wiki/Similarity_learning#Metric_learning">metric learning</a> in Shogun. To overcome the limitations of <a href="http://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm">knn</a> with Euclidean distance as the distance measure, <a href="http://en.wikipedia.org/wiki/Large_margin_nearest_neighbor">Large Margin Nearest Neighbour</a>(LMNN) is discussed. This is consolidated by applying LMNN over the metagenomics data set.
# ## Building up the intuition to understand LMNN
# First of all, let us introduce LMNN through a simple example. For this purpose, we will be using the following two-dimensional toy data set:
# +
import numpy
import os
import shogun as sg
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
x = numpy.array([[0,0],[-1,0.1],[0.3,-0.05],[0.7,0.3],[-0.2,-0.6],[-0.15,-0.63],[-0.25,0.55],[-0.28,0.67]])
y = numpy.array([0,0,0,0,1,1,2,2])
# -
# That is, there are eight feature vectors where each of them belongs to one out of three different classes (identified by either 0, 1, or 2). Let us have a look at this data:
# +
import matplotlib.pyplot as pyplot
# %matplotlib inline
def plot_data(feats,labels,axis,alpha=1.0):
# separate features according to their class
X0,X1,X2 = feats[labels==0], feats[labels==1], feats[labels==2]
# class 0 data
axis.plot(X0[:,0], X0[:,1], 'o', color='green', markersize=12, alpha=alpha)
# class 1 data
axis.plot(X1[:,0], X1[:,1], 'o', color='red', markersize=12, alpha=alpha)
# class 2 data
axis.plot(X2[:,0], X2[:,1], 'o', color='blue', markersize=12, alpha=alpha)
# set axes limits
axis.set_xlim(-1.5,1.5)
axis.set_ylim(-1.5,1.5)
axis.set_aspect('equal')
axis.set_xlabel('x')
axis.set_ylabel('y')
figure,axis = pyplot.subplots(1,1)
plot_data(x,y,axis)
axis.set_title('Toy data set')
pyplot.show()
# -
# In the figure above, we can see that two of the classes are represented by two points that are, for each of these classes, very close to each other. The third class, however, has four points that are close to each other with respect to the y-axis, but spread along the x-axis.
# If we were to apply kNN (*k-nearest neighbors*) in a data set like this, we would expect quite some errors using the standard Euclidean distance. This is due to the fact that the spread of the data is not similar amongst the feature dimensions. The following piece of code plots an ellipse on top of the data set. The ellipse in this case is in fact a circunference that helps to visualize how the Euclidean distance weights equally both feature dimensions.
# +
def make_covariance_ellipse(covariance):
import matplotlib.patches as patches
import scipy.linalg as linalg
# the ellipse is centered at (0,0)
mean = numpy.array([0,0])
# eigenvalue decomposition of the covariance matrix (w are eigenvalues and v eigenvectors),
# keeping only the real part
w,v = linalg.eigh(covariance)
# normalize the eigenvector corresponding to the largest eigenvalue
u = v[0]/linalg.norm(v[0])
# angle in degrees
angle = 180.0/numpy.pi*numpy.arctan(u[1]/u[0])
# fill Gaussian ellipse at 2 standard deviation
ellipse = patches.Ellipse(mean, 2*w[0]**0.5, 2*w[1]**0.5, 180+angle, color='orange', alpha=0.3)
return ellipse
# represent the Euclidean distance
figure,axis = pyplot.subplots(1,1)
plot_data(x,y,axis)
ellipse = make_covariance_ellipse(numpy.eye(2))
axis.add_artist(ellipse)
axis.set_title('Euclidean distance')
pyplot.show()
# -
# A possible workaround to improve the performance of kNN in a data set like this would be to input to the kNN routine a distance measure. For instance, in the example above a good distance measure would give more weight to the y-direction than to the x-direction to account for the large spread along the x-axis. Nonetheless, it would be nicer (and, in fact, much more useful in practice) if this distance could be learnt automatically from the data at hand. Actually, LMNN is based upon this principle: given a number of neighbours *k*, find the Mahalanobis distance measure which maximizes kNN accuracy (using the given value for *k*) in a training data set. As we usually do in machine learning, under the assumption that the training data is an accurate enough representation of the underlying process, the distance learnt will not only perform well in the training data, but also have good generalization properties.
# Now, let us use the [LMNN class](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1LMNN.html) implemented in Shogun to find the distance and plot its associated ellipse. If everything goes well, we will see that the new ellipse only overlaps with the data points of the green class.
# First, we need to wrap the data into Shogun's feature and label objects:
# +
from shogun import features, MulticlassLabels
feats = features(x.T)
labels = MulticlassLabels(y.astype(numpy.float64))
# -
# Secondly, perform LMNN training:
# +
from shogun import LMNN
# number of target neighbours per example
k = 1
lmnn = LMNN(feats,labels,k)
# set an initial transform as a start point of the optimization
init_transform = numpy.eye(2)
lmnn.put('maxiter', 2000)
lmnn.train(init_transform)
# -
# LMNN is an iterative algorithm. The argument given to [`train`](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1LMNN.html#ab1b8bbdb8390415ac3ae7dc655cb512d) represents the initial state of the solution. By default, if no argument is given, then LMNN uses [PCA](http://en.wikipedia.org/wiki/Principal_component_analysis) to obtain this initial value.
# Finally, we retrieve the distance measure learnt by LMNN during training and visualize it together with the data:
# +
# get the linear transform from LMNN
L = lmnn.get_real_matrix('linear_transform')
# square the linear transform to obtain the Mahalanobis distance matrix
M = numpy.matrix(numpy.dot(L.T,L))
# represent the distance given by LMNN
figure,axis = pyplot.subplots(1,1)
plot_data(x,y,axis)
ellipse = make_covariance_ellipse(M.I)
axis.add_artist(ellipse)
axis.set_title('LMNN distance')
pyplot.show()
# -
# ## Beyond the main idea
# LMNN is one of the so-called linear metric learning methods. What this means is that we can understand LMNN's output in two different ways: on the one hand, as a distance measure, this was explained above; on the other hand, as a linear transformation of the input data. Like any other linear transformation, LMNN's output can be written as a matrix, that we will call $L$. In other words, if the input data is represented by the matrix $X$, then LMNN can be understood as the data transformation expressed by $X'=L X$. We use the convention that each column is a feature vector; thus, the number of rows of $X$ is equal to the input dimension of the data, and the number of columns is equal to the number of vectors.
#
# So far, so good. But, if the output of the same method can be interpreted in two different ways, then there must be a relation between them! And that is precisely the case! As mentioned above, the ellipses that were plotted in the previous section represent a distance measure. This distance measure can be thought of as a matrix $M$, being the distance between two vectors $\vec{x_i}$ and $\vec{x_j}$ equal to $d(\vec{x_i},\vec{x_j})=(\vec{x_i}-\vec{x_j})^T M (\vec{x_i}-\vec{x_j})$. In general, this type of matrices are known as *Mahalanobis* matrices. In LMNN, the matrix $M$ is precisely the 'square' of the linear transformation $L$, i.e. $M=L^T L$. Note that a direct consequence of this is that $M$ is guaranteed to be positive semi-definite (PSD), and therefore define a valid metric.
#
# This distance measure/linear transform duality in LMNN has its own advantages. An important one is that the optimization problem can go back and forth between the $L$ and the $M$ representations, giving raise to a very efficient solution.
# Let us now visualize LMNN using the linear transform interpretation. In the following figure we have taken our original toy data, transform it using $L$ and plot both the before and after versions of the data together.
# +
# project original data using L
lx = numpy.dot(L,x.T)
# represent the data in the projected space
figure,axis = pyplot.subplots(1,1)
plot_data(lx.T,y,axis)
plot_data(x,y,axis,0.3)
ellipse = make_covariance_ellipse(numpy.eye(2))
axis.add_artist(ellipse)
axis.set_title('LMNN\'s linear transform')
pyplot.show()
# -
# In the figure above, the transparent points represent the original data and are shown to ease the visualization of the LMNN transformation. Note also that the ellipse plotted is the one corresponding to the common Euclidean distance. This is actually an important consideration: if we think of LMNN as a linear transformation, the distance considered in the projected space is the Euclidean distance, and no any Mahalanobis distance given by M. To sum up, we can think of LMNN as a linear transform of the input space, or as method to obtain a distance measure to be used in the input space. It is an error to apply **both** the projection **and** the learnt Mahalanobis distance.
# ### Neighbourhood graphs
# An alternative way to visualize the effect of using the distance found by LMNN together with kNN consists of using neighbourhood graphs. Despite the fancy name, these are actually pretty simple. The idea is just to construct a graph in the Euclidean space, where the points in the data set are the nodes of the graph, and a directed edge from one point to another denotes that the destination node is the 1-nearest neighbour of the origin node. Of course, it is also possible to work with neighbourhood graphs where $k \gt 1$. Here we have taken the simplification of $k = 1$ so that the forthcoming plots are not too cluttered.
# Let us define a data set for which the Euclidean distance performs considerably bad. In this data set there are several levels or layers in the y-direction. Each layer is populated by points that belong to the same class spread along the x-direction. The layers are close to each other in pairs, whereas the spread along x is larger. Let us define a function to generate such a data set and have a look at it.
# +
import numpy
import matplotlib.pyplot as pyplot
# %matplotlib inline
def sandwich_data():
from numpy.random import normal
# number of distinct classes
num_classes = 6
# number of points per class
num_points = 9
# distance between layers, the points of each class are in a layer
dist = 0.7
# memory pre-allocation
x = numpy.zeros((num_classes*num_points, 2))
y = numpy.zeros(num_classes*num_points)
for i,j in zip(range(num_classes), range(-num_classes//2, num_classes//2 + 1)):
for k,l in zip(range(num_points), range(-num_points//2, num_points//2 + 1)):
x[i*num_points + k, :] = numpy.array([normal(l, 0.1), normal(dist*j, 0.1)])
y[i*num_points:i*num_points + num_points] = i
return x,y
def plot_sandwich_data(x, y, axis=pyplot, cols=['r', 'b', 'g', 'm', 'k', 'y']):
for idx,val in enumerate(numpy.unique(y)):
xi = x[y==val]
axis.scatter(xi[:,0], xi[:,1], s=50, facecolors='none', edgecolors=cols[idx])
x, y = sandwich_data()
figure, axis = pyplot.subplots(1, 1, figsize=(5,5))
plot_sandwich_data(x, y, axis)
axis.set_aspect('equal')
axis.set_title('"Sandwich" toy data set')
axis.set_xlabel('x')
axis.set_ylabel('y')
pyplot.show()
# -
# Let the fun begin now! In the following block of code, we create an instance of a kNN classifier, compute the nearest neighbours using the Euclidean distance and, afterwards, using the distance computed by LMNN. The data set in the space result of the linear transformation given by LMNN is also shown.
# +
from shogun import KNN, LMNN, features, MulticlassLabels
def plot_neighborhood_graph(x, nn, axis=pyplot, cols=['r', 'b', 'g', 'm', 'k', 'y']):
for i in range(x.shape[0]):
xs = [x[i,0], x[nn[1,i], 0]]
ys = [x[i,1], x[nn[1,i], 1]]
axis.plot(xs, ys, cols[int(y[i])])
feats = features(x.T)
labels = MulticlassLabels(y)
fig, axes = pyplot.subplots(1, 3, figsize=(15, 10))
# use k = 2 instead of 1 because otherwise the method nearest_neighbors just returns the same
# points as their own 1-nearest neighbours
k = 2
distance = sg.distance('EuclideanDistance')
distance.init(feats, feats)
knn = KNN(k, distance, labels)
plot_sandwich_data(x, y, axes[0])
plot_neighborhood_graph(x, knn.nearest_neighbors(), axes[0])
axes[0].set_title('Euclidean neighbourhood in the input space')
lmnn = LMNN(feats, labels, k)
# set a large number of iterations. The data set is small so it does not cost a lot, and this way
# we ensure a robust solution
lmnn.put('maxiter', 3000)
lmnn.train()
knn.put('distance', lmnn.get_distance())
plot_sandwich_data(x, y, axes[1])
plot_neighborhood_graph(x, knn.nearest_neighbors(), axes[1])
axes[1].set_title('LMNN neighbourhood in the input space')
# plot features in the transformed space, with the neighbourhood graph computed using the Euclidean distance
L = lmnn.get_real_matrix('linear_transform')
xl = numpy.dot(x, L.T)
feats = features(xl.T)
dist = sg.distance('EuclideanDistance')
dist.init(feats, feats)
knn.put('distance', dist)
plot_sandwich_data(xl, y, axes[2])
plot_neighborhood_graph(xl, knn.nearest_neighbors(), axes[2])
axes[2].set_ylim(-3, 2.5)
axes[2].set_title('Euclidean neighbourhood in the transformed space')
[axes[i].set_xlabel('x') for i in range(len(axes))]
[axes[i].set_ylabel('y') for i in range(len(axes))]
[axes[i].set_aspect('equal') for i in range(len(axes))]
pyplot.show()
# -
# Notice how all the lines that go across the different layers in the left hand side figure have disappeared in the figure in the middle. Indeed, LMNN did a pretty good job here. The figure in the right hand side shows the disposition of the points in the transformed space; from which the neighbourhoods in the middle figure should be clear. In any case, this toy example is just an illustration to give an idea of the power of LMNN. In the next section we will see how after applying a couple methods for feature normalization (e.g. scaling, whitening) the Euclidean distance is not so sensitive against different feature scales.
# ## Real data sets
# ### Feature selection in metagenomics
# Metagenomics is a modern field in charge of the study of the DNA of microorganisms. The data set we have chosen for this section contains information about three different types of apes; in particular, gorillas, chimpanzees, and bonobos. Taking an approach based on metagenomics, the main idea is to study the DNA of the microorganisms (e.g. bacteria) which live inside the body of the apes. Owing to the many chemical reactions produced by these microorganisms, it is not only the DNA of the host itself important when studying, for instance, sickness or health, but also the DNA of the microorganisms inhabitants.
# First of all, let us load the ape data set. This data set contains features taken from the bacteria inhabitant in the gut of the apes.
# +
from shogun import CSVFile, features, MulticlassLabels
ape_features = features(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'multiclass/fm_ape_gut.dat')))
ape_labels = MulticlassLabels(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'multiclass/label_ape_gut.dat')))
# -
# It is of course important to have a good insight of the data we are dealing with. For instance, how many examples and different features do we have?
print('Number of examples = %d, number of features = %d.' % (ape_features.get_num_vectors(), ape_features.get_num_features()))
# So, 1472 features! Those are quite many features indeed. In other words, the feature vectors at hand lie on a 1472-dimensional space. We cannot visualize in the input feature space how the feature vectors look like. However, in order to gain a little bit more of understanding of the data, we can apply dimension reduction, embed the feature vectors in a two-dimensional space, and plot the vectors in the embedded space. To this end, we are going to use one of the [many](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1EmbeddingConverter.html) methods for dimension reduction included in Shogun. In this case, we are using t-distributed stochastic neighbour embedding (or [t-dsne](http://jmlr.org/papers/v9/vandermaaten08a.html)). This method is particularly suited to produce low-dimensional embeddings (two or three dimensions) that are straightforward to visualize.
# +
def visualize_tdsne(features, labels):
from shogun import TDistributedStochasticNeighborEmbedding
converter = TDistributedStochasticNeighborEmbedding()
converter.put('target_dim', 2)
converter.put('perplexity', 25)
embedding = converter.embed(features)
import matplotlib.pyplot as pyplot
% matplotlib inline
x = embedding.get_real_matrix('feature_matrix')
y = labels.get_real_vector('labels')
pyplot.scatter(x[0, y==0], x[1, y==0], color='green')
pyplot.scatter(x[0, y==1], x[1, y==1], color='red')
pyplot.scatter(x[0, y==2], x[1, y==2], color='blue')
pyplot.show()
visualize_tdsne(ape_features, ape_labels)
# -
# In the figure above, the green points represent chimpanzees, the red ones bonobos, and the blue points gorillas. Providing the results in the figure, we can rapidly draw the conclusion that the three classes of apes are somewhat easy to discriminate in the data set since the classes are more or less well separated in two dimensions. Note that t-dsne use randomness in the embedding process. Thus, the figure result of the experiment in the previous block of code will be different after different executions. Feel free to play around and observe the results after different runs! After this, it should be clear that the bonobos form most of the times a very compact cluster, whereas the chimpanzee and gorillas clusters are more spread. Also, there tends to be a chimpanzee (a green point) closer to the gorillas' cluster. This is probably a outlier in the data set.
# Even before applying LMNN to the ape gut data set, let us apply kNN classification and study how it performs using the typical Euclidean distance. Furthermore, since this data set is rather small in terms of number of examples, the kNN error above may vary considerably (I have observed variation of almost 20% a few times) across different runs. To get a robust estimate of how kNN performs in the data set, we will perform cross-validation using [Shogun's framework](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CrossValidation.html) for evaluation. This will give us a reliable result regarding how well kNN performs in this data set.
# +
from shogun import KNN
from shogun import StratifiedCrossValidationSplitting, CrossValidation
from shogun import CrossValidationResult, MulticlassAccuracy
# set up the classifier
knn = KNN()
knn.put('k', 3)
knn.put('distance', sg.distance('EuclideanDistance'))
# set up 5-fold cross-validation
splitting = StratifiedCrossValidationSplitting(ape_labels, 5)
# evaluation method
evaluator = MulticlassAccuracy()
cross_validation = CrossValidation(knn, ape_features, ape_labels, splitting, evaluator)
# locking is not supported for kNN, deactivate it to avoid an inoffensive warning
cross_validation.put('m_autolock', False)
# number of experiments, the more we do, the less variance in the result
num_runs = 200
cross_validation.put('num_runs', num_runs)
# perform cross-validation and print the result!
result = cross_validation.evaluate()
result = CrossValidationResult.obtain_from_generic(result)
print('kNN mean accuracy in a total of %d runs is %.4f.' % (num_runs, result.get_real('mean')))
# -
# Finally, we can say that KNN performs actually pretty well in this data set. The average test classification error is less than between 2%. This error rate is already low and we should not really expect a significant improvement applying LMNN. This ought not be a surprise. Recall that the points in this data set have more than one thousand features and, as we saw before in the dimension reduction experiment, only two dimensions in an embedded space were enough to discern arguably well the chimpanzees, gorillas and bonobos.
# Note that we have used stratified splitting for cross-validation. Stratified splitting divides the folds used during cross-validation so that the proportion of the classes in the initial data set is approximately maintained for each of the folds. This is particular useful in *skewed* data sets, where the number of examples among classes varies significantly.
# Nonetheless, LMNN may still turn out to be very useful in a data set like this one. Making a small modification of the vanilla LMNN algorithm, we can enforce that the linear transform found by LMNN is diagonal. This means that LMNN can be used to weight each of the features and, once the training is performed, read from these weights which features are relevant to apply kNN and which ones are not. This is indeed a form of *feature selection*. Using Shogun, it is extremely easy to switch to this so-called *diagonal* mode for LMNN: just call the method [`set_diagonal(use_diagonal)`](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1LMNN.html#ad2f03dbad3ad08ab76aecbb656a486e6) with `use_diagonal` set to `True`.
# The following experiment takes about five minutes until it is completed (using Shogun Release, i.e. compiled with optimizations enabled). This is mostly due to the high dimension of the data (1492 features) and the fact that, during training, LMNN has to compute many outer products of feature vectors, which is a computation whose time complexity is proportional to the square of the number of features. For the illustration purposes of this notebook, in the following cell we are just going to use a small subset of all the features so that the training finishes faster.
# +
from shogun import LMNN
import numpy
# to make training faster, use a portion of the features
fm = ape_features.get_real_matrix('feature_matrix')
ape_features_subset = features(fm[:150, :])
# number of targer neighbours in LMNN, here we just use the same value that was used for KNN before
k = 3
lmnn = LMNN(ape_features_subset, ape_labels, k)
lmnn.put('m_diagonal', True)
lmnn.put('maxiter', 1000)
init_transform = numpy.eye(ape_features_subset.get_num_features())
lmnn.train(init_transform)
diagonal = numpy.diag(lmnn.get_real_matrix('linear_transform'))
print('%d out of %d elements are non-zero.' % (numpy.sum(diagonal != 0), diagonal.size))
# -
# So only 64 out of the 150 first features are important according to the result transform! The rest of them have been given a weight exactly equal to zero, even if all of the features were weighted equally with a value of one at the beginnning of the training. In fact, if all the 1472 features were used, only about 158 would have received a non-zero weight. Please, feel free to experiment using all the features!
# It is a fair question to ask how did we know that the maximum number of iterations in this experiment should be around 1200 iterations. Well, the truth is that we know this only because we have run this experiment with this same data beforehand, and we know that after this number of iterations the algorithm has converged. This is not something nice, and the ideal case would be if one could completely forget about this parameter, so that LMNN uses as many iterations as it needs until it converges. Nevertheless, this is not practical at least because of two reasons:
#
# - If you are dealing with many examples or with very high dimensional feature vectors, you might not want to wait until the algorithm converges and have a look at what LMNN has found before it has completely converged.
# - As with any other algorithm based on gradient descent, the termination criteria can be tricky. Let us illustrate this further:
# +
import matplotlib.pyplot as pyplot
# %matplotlib inline
statistics = lmnn.get_statistics()
pyplot.plot(statistics.obj.get())
pyplot.grid(True)
pyplot.xlabel('Number of iterations')
pyplot.ylabel('LMNN objective')
pyplot.show()
# -
# Along approximately the first three hundred iterations, there is not much variation in the objective. In other words, the objective curve is pretty much flat. If we are not careful and use termination criteria that are not demanding enough, training could be stopped at this point. This would be wrong, and might have terrible results as the training had not clearly converged yet at that moment.
# In order to avoid disastrous situations, in Shogun we have implemented LMNN with really demanding criteria for automatic termination of the training process. Albeit, it is possible to tune the termination criteria using the methods [`set_stepsize_threshold`](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1LMNN.html#a76b6914cf9d1a53b0c9ecd828c7edbcb) and [`set_obj_threshold`](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1LMNN.html#af78c7dd9ed2307c0d53e7383cdc01a24). These methods can be used to modify the lower bound required in the step size and the increment in the objective (relative to its absolute value), respectively, to stop training. Also, it is possible to set a hard upper bound on the number of iterations using [`set_maxiter`](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1LMNN.html#afcf319806eb710a0d9535fbeddf93795) as we have done above. In case the internal termination criteria did not fire before the maximum number of iterations was reached, you will receive a warning message, similar to the one shown above. This is not a synonym that the training went wrong; but it is strongly recommended at this event to have a look at the objective plot as we have done in the previous block of code.
# ### Multiclass classification
# In addition to feature selection, LMNN can be of course used for multiclass classification. I like to think about LMNN in multiclass classification as a way to empower kNN. That is, the idea is basically to apply kNN using the distance found by LMNN $-$ in contrast with using one of the other most common distances, such as the Euclidean one. To this end we will use the wine data set from the [UCI Machine Learning repository](http://archive.ics.uci.edu/ml/datasets/Wine "Wine data set").
# +
from shogun import CSVFile, features, MulticlassLabels
wine_features = features(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'uci/wine/fm_wine.dat')))
wine_labels = MulticlassLabels(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'uci/wine/label_wine.dat')))
assert(wine_features.get_num_vectors() == wine_labels.get_num_labels())
print('%d feature vectors with %d features from %d different classes.' % (wine_features.get_num_vectors(), \
wine_features.get_num_features(), wine_labels.get_num_classes()))
# -
# First, let us evaluate the performance of kNN in this data set using the same cross-validation setting used in the previous section:
# +
from shogun import KNN, EuclideanDistance
from shogun import StratifiedCrossValidationSplitting, CrossValidation
from shogun import CrossValidationResult, MulticlassAccuracy
import numpy
# kNN classifier
k = 5
knn = KNN()
knn.put('k', k)
knn.put('distance', EuclideanDistance())
splitting = StratifiedCrossValidationSplitting(wine_labels, 5)
evaluator = MulticlassAccuracy()
cross_validation = CrossValidation(knn, wine_features, wine_labels, splitting, evaluator)
cross_validation.put('m_autolock', False)
num_runs = 200
cross_validation.put('num_runs', num_runs)
result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate())
euclidean_means = numpy.zeros(3)
euclidean_means[0] = result.get_real('mean')
print('kNN accuracy with the Euclidean distance %.4f.' % result.get_real('mean'))
# -
# Seconly, we will use LMNN to find a distance measure and use it with kNN:
# +
from shogun import LMNN
# train LMNN
lmnn = LMNN(wine_features, wine_labels, k)
lmnn.put('maxiter', 1500)
lmnn.train()
# evaluate kNN using the distance learnt by LMNN
knn.set_distance(lmnn.get_distance())
result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate())
lmnn_means = numpy.zeros(3)
lmnn_means[0] = result.get_real('mean')
print('kNN accuracy with the distance obtained by LMNN %.4f.' % result.get_real('mean'))
# -
# The warning is fine in this case, we have made sure that the objective variation was really small after 1500 iterations. In any case, do not hesitate to check it yourself studying the objective plot as it was shown in the previous section.
# As the results point out, LMNN really helps here to achieve better classification performance. However, this comparison is not entirely fair since the Euclidean distance is very sensitive to the scaling that different feature dimensions may have, whereas LMNN can adjust to this during training. Let us have a closer look to this fact. Next, we are going to retrieve the feature matrix and see what are the maxima and minima for every dimension.
print('minima = ' + str(numpy.min(wine_features, axis=1)))
print('maxima = ' + str(numpy.max(wine_features, axis=1)))
# Examine the second and the last dimensions, for instance. The second dimension has values ranging from 0.74 to 5.8, while the values of the last dimension range from 278 to 1680. This will cause that the Euclidean distance works specially wrong in this data set. You can realize of this considering that the total distance between two points will almost certainly just take into account the contributions of the dimensions with largest range.
# In order to produce a more fair comparison, we will rescale the data so that all the feature dimensions are within the interval [0,1]. Luckily, there is a [preprocessor](http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1Preprocessor.html) class in Shogun that makes this straightforward.
# +
from shogun import RescaleFeatures
# preprocess features so that all of them vary within [0,1]
preprocessor = RescaleFeatures()
preprocessor.init(wine_features)
wine_features.add_preprocessor(preprocessor)
wine_features.apply_preprocessor()
# sanity check
assert(numpy.min(wine_features) >= 0.0 and numpy.max(wine_features) <= 1.0)
# perform kNN classification after the feature rescaling
knn.put('distance', EuclideanDistance())
result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate())
euclidean_means[1] = result.get_real('mean')
print('kNN accuracy with the Euclidean distance after feature rescaling %.4f.' % result.get_real('mean'))
# train kNN in the new features and classify with kNN
lmnn.train()
knn.put('distance', lmnn.get_distance())
result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate())
lmnn_means[1] = result.get_real('mean')
print('kNN accuracy with the distance obtained by LMNN after feature rescaling %.4f.' % result.get_real('mean'))
# -
# Another different preprocessing that can be applied to the data is called *whitening*. Whitening, which is explained in an [article in wikipedia](http://en.wikipedia.org/wiki/Whitening_transformation "Whitening transform"), transforms the covariance matrix of the data into the identity matrix.
# +
import scipy.linalg as linalg
# shorthand for the feature matrix -- this makes a copy of the feature matrix
data = wine_features.get_real_matrix('feature_matrix')
# remove mean
data = data.T
data-= numpy.mean(data, axis=0)
# compute the square of the covariance matrix and its inverse
M = linalg.sqrtm(numpy.cov(data.T))
# keep only the real part, although the imaginary that pops up in the sqrtm operation should be equal to zero
N = linalg.inv(M).real
# apply whitening transform
white_data = numpy.dot(N, data.T)
wine_white_features = features(white_data)
# -
# The covariance matrices before and after the transformation can be compared to see that the covariance really becomes the identity matrix.
# +
import matplotlib.pyplot as pyplot
# %matplotlib inline
fig, axarr = pyplot.subplots(1,2)
axarr[0].matshow(numpy.cov(wine_features))
axarr[1].matshow(numpy.cov(wine_white_features))
pyplot.show()
# -
# Finally, we evaluate again the performance obtained with kNN using the Euclidean distance and the distance found by LMNN using the whitened features.
# +
wine_features = wine_white_features
# perform kNN classification after whitening
knn.set_distance(EuclideanDistance())
result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate())
euclidean_means[2] = result.get_real('mean')
print('kNN accuracy with the Euclidean distance after whitening %.4f.' % result.get_real('mean'))
# train kNN in the new features and classify with kNN
lmnn.train()
knn.put('distance', lmnn.get_distance())
result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate())
lmnn_means[2] = result.get_real('mean')
print('kNN accuracy with the distance obtained by LMNN after whitening %.4f.' % result.get_real('mean'))
# -
# As it can be seen, it did not really help to whiten the features in this data set with respect to only applying feature rescaling; the accuracy was already rather large after rescaling. In any case, it is good to know that this transformation exists, as it can become useful with other data sets, or before applying other machine learning algorithms.
# Let us summarize the results obtained in this section with a bar chart grouping the accuracy results by distance (Euclidean or the one found by LMNN), and feature preprocessing:
# +
assert(euclidean_means.shape[0] == lmnn_means.shape[0])
N = euclidean_means.shape[0]
# the x locations for the groups
ind = 0.5*numpy.arange(N)
# bar width
width = 0.15
figure, axes = pyplot.subplots()
figure.set_size_inches(6, 5)
euclidean_rects = axes.bar(ind, euclidean_means, width, color='y')
lmnn_rects = axes.bar(ind+width, lmnn_means, width, color='r')
# attach information to chart
axes.set_ylabel('Accuracies')
axes.set_ylim(top=1.4)
axes.set_title('kNN accuracy by distance and feature preprocessing')
axes.set_xticks(ind+width)
axes.set_xticklabels(('Raw', 'Rescaling', 'Whitening'))
axes.legend(( euclidean_rects[0], lmnn_rects[0]), ('Euclidean', 'LMNN'), loc='upper right')
def autolabel(rects):
# attach text labels to bars
for rect in rects:
height = rect.get_height()
axes.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%.3f' % height,
ha='center', va='bottom')
autolabel(euclidean_rects)
autolabel(lmnn_rects)
pyplot.show()
# -
# ## References
# - <NAME>., <NAME>. Distance Metric Learning for Large Margin Nearest Neighbor Classification. [(Link to paper in JMLR)](http://jmlr.org/papers/v10/weinberger09a.html).
|
doc/ipython-notebooks/metric/LMNN.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Building a matrix for numerical methods using a Landlab grid
#
# (<NAME>, University of Colorado Boulder, July 2020)
#
# *This notebook explains how to use the matrix-building functions to construct a matrix for a finite-volume or finite-difference solution on a Landlab grid.*
#
# ## Introduction
#
# Numerical solutions to differential equations often involve matrices. With grid-based numerical models, like those that Landlab is designed to support, the problem is *discretized* in space: we solve for one or more state variables of interest at a series of discrete spatial locations, such as a grid node or the cell that surrounds it. That process of discretization converts a partial differential equation into a set of ordinary differential equations, with one equation per point. Consider, for example, the one-dimensional diffusion equation:
#
# $$\frac{\partial \eta}{\partial t} = D\frac{\partial^2 \eta}{\partial x^2}$$
#
# where $t$ is time, $x$ is distance, $D$ is a transport coefficient, and $\eta$ could be concentration of a dissolved chemical (classic chemical diffusion), the temperature in a solid (heat diffusion), the velocity of flow in a viscous liquid (viscous momentum diffusion), or the height of the land on a hillslope (soil diffusion). If the domain is discretized such that we seek the value of $\eta$ at a series of discrete points, then the above equation for a given point $i$ becomes:
#
# $$\frac{d \eta_i}{d t} = D\frac{d^2 \eta}{d x^2}\bigg\rvert_i$$
#
# where the subscript at the right means "evaluated at $i$". Once the right side has been cast in terms of values of $\eta$ at particular points, you end up with a linear system of equations, and matrix methods provide a natural way to solve them. One example among many is an implicit finite-difference solution to the one-dimensional form of the diffusion equation, which involves constructing a matrix and a "right-hand side" vector, inverting the matrix, and multiplying it by the vector to obtain a solution for the state variable at each grid node (for more on that particular example, see *Mathematical Modeling of Earth's Dynamical Systems* by Slingerland and Kump, or *Numerical Recipes* by Press et al.).
#
# When using matrix methods to solve a set of equation at discrete points, whether in 2D or 1D (or even 3D), you typically have an $MxM$ matrix, where $M$ is the number of solution points. Each row in the matrix represents the equation for one of the points. If the equation for a given point includes terms that represent, say, two of its immediately neighboring points, then the columns representing those two points contain non-zero entries. More generally, finite-volume and finite-difference matrices tend be sparse, with only a few non-zero entries in each row: the column that represents the point itself, and the columns representing its immediate neighbors.
#
# Building the matrix therefore requires knowledge of which points are connected to which other points in the grid. In 1D, this is easy. In 2D, it's a bit more complicated. Fortunately, the structure of a Landlab grid lends itself to this task. In particular, we know the connectivity for the *nodes* in the grid. It also turns out that when nodes are the solution points (as is typical), the number of equations---and thus $M$---corresponds exactly to the number of *core nodes* in the grid.
#
# In the following, we first work through the mathematics in a simple example: a finite-volume matrix solution to a steady diffusion equation with a source term, also known as a Poisson equation. We then show some worked examples of the Landlab matrix tools in action.
# ## Example: steady diffusion with a source term
#
# Consider the diffusion model for hillslope evolution in two dimensions. The equation describes the time evolution of land surface height, $z$, given a transport coefficient $D$ $[L^2/T]$, and relative uplift rate $U$ $[L/T]$ as:
#
# $$\frac{\partial z}{\partial t} = U - \nabla \cdot (-D \nabla z)$$
#
# Here $\nabla z$ is the gradient of $z$, which here is a two-element vector (components in the $x$ and $y$ directions, respectively), and $\nabla\cdot$ is the divergence operator. We'll use a matrix method to solve for $z(x)$ when the time derivative is zero. So the equation we want to solve is:
#
# $$U \nabla \cdot (-D \nabla z) = 0$$
#
# If $D$ is spatially uniform, we can write this as:
#
# $$\boxed{\nabla^2 z = -U/D}$$
#
# This is the equation we're going to discretize and solve. Here $\nabla^2$ is understood to be the divergence-of-the-gradient, and in 1D would just be a second derivative:
#
# $$\frac{d^2z}{dx^2} = -\frac{U}{D}$$
#
# The minus sign is important: it indicates upward convexity of the solution when $U$ and $D$ are positive (which they always are in this case).
#
#
#
#
# ### Finite-volume discretization
#
# Let's take a step back in the derivation of the diffusion equation to note that it is composed of two parts together. One part is mass conservation:
#
# $$\frac{\partial z}{\partial t} = U - \nabla \cdot \mathbf{q}$$
#
# where $\mathbf{q}$ is soil volume flux per unit width $[L^2/T]$. The other part is the flux law:
#
# $$\mathbf{q} = -D\nabla z$$
#
# For this example, we'll set the time derivative to zero, meaning we are looking for a steady solution.
#
# Next, we integrate the conservation law over a 2D region $R$. In general, $R$ is a simply connected region. Ultimately for us, it will be a grid cell, which could be a square, a rectangle, a hexagon, or even an irregular polygon.
#
# $$\int\int_R \nabla\cdot \mathbf{q} dR = \int\int_R U dR$$
#
# Because $U$ is constant inside the region $R$,
#
# $$\int\int_R \nabla\cdot \mathbf{q} dR = U A_r$$
#
# Now we apply Green's theorem, which basically says that an area integral over the divergence of a vector field is equivalent to a line integral of the surface-normal component of that vector around the perimeter of the region. Intuitively, if we consider $\mathbf{q}$ to be a flux in this case, what we're saying is that we can obtain the net total flux over the region (grid cell!) by integrating the flux all around the perimeter. Think of it as keeping track of all the people who enter or leave the perimeter of a playing field.
#
# $$\oint_S \mathbf{q} \cdot\mathbf{n} dS = U A_r$$
#
# where $\mathbf{n}$ is an (outward-facing) unit vector perpendicular to the perimeter $S$ that encloses region $R$. For us, again the perimeter is just the perimeter of the grid cell: the four sides of a square or rectangle, or the six side of a hexagon, the $N$ sides of a Voronoi polygon, or whatever. Then the line integral becomes a summation.
#
# We will define a quantity $q$ that represents the face-normal component of $\mathbf{q}$. The sign convention is as follows:
#
# - $q$ is positive if the vector orientation is toward the upper-right half space (including "right" and "up")
#
# - $q$ is negative if the vector orientation is toward the lower-left half space (including "left" and "down")
#
# We will also define a binary variable $\delta$, which is negative if the outward surface-normal points toward the lower-left half space, and positive if it points toward the upper-right half space.
#
# Here's where Landlab grids come into the picture. The two definitions represent the use of *links* in a Landlab grid: when $q$ is positive when it oriented in the link's direction, and negative when oriented in the opposite direction. In a simple raster grid, where the links are all horizontal or vertical, the interpretation is very simple: flow to the right (increasing $x$) is positive, and to the left is negative; flow upward (increasing $y$) is positive, and downward is negative.
#
# More generally, whatever the grid type, links by convention always "point" toward the upper-right half space; hence the general definition of $q$ above. The variable $\delta$ represents the link orientation relative to the cell: positive when the link points out of the cell, negative when it points into the cell. The variable is represented in a Landlab grid by the array `link_dirs_at_node`: one for each link, starting from the "east" (or "right") direction and going counter-clockwise.
#
# Suppose $R$ is a square grid cell of width $\Delta x$. Then:
#
# $$\oint_S \mathbf{f} \cdot\mathbf{n} dR = \sum_{k=1}^4 q_k \delta_k \Delta x$$
#
# where $q_k$ is the magnitude of the vector field at face $k$, and $\delta = -1$ if the link at face $k$ points inward, and $+1$ if the link points outward.
#
# For this Poisson problem (i.e., diffusion with zero time derivative), the flux between the two nodes at either end of a link is approximated as the difference in $z$ divided by the distance, which here is $\Delta x$. For each of the four directions:
#
# $q_e = -(D/\Delta x) (z_e - z_i)$
#
# $q_n = -(D/\Delta x) (z_n - z_i)$
#
# $q_e = -(D/\Delta x) (z_i - z_w)$
#
# $q_s = -(D/\Delta x) (z_i - z_s)$
#
# Here the subscript refers to the four cardinal directions. When you work out the summation above, you get:
#
# $$\sum_{k=1}^4 q_k \delta_k \Delta x = -D (z_e + z_n - + z_w + z_s - 4z_i)$$.
#
# Now plug this back into our governing equation, and divide both sides by $A_r = \Delta x^2$:
#
# $$-D (z_e + z_n - + z_w + z_s - 4z_i) = U$$
#
# or
#
# $$\boxed{z_e + z_n - + z_w + z_s - 4z_i = -U/D}$$
#
# So the above represents a system of equations: one equation per core node in a Landlab grid. For any given core node, $z_i$ is the elevation of the node itself, and the other four are the elevations of its four neighbors. By the way, for a regular raster grid, this finite-volume setup turns out to be the same as the finite-difference version. Here the directional subscripts will ultimately be replaced with indices of the particular neighboring nodes.
# ### Example of a finite-volume setup
#
# Suppose we have a raster model grid with 4 rows and 5 columns, so that there are 6 interior nodes. To make it interesting, let's assume that one of the interior nodes is actually a fixed-value boundary. We will also assume that the perimeter nodes are fixed-value boundaries. Fixed-value boundary simply means that we will keep the elevation constant at these nodes. In total, then, there are 5 core nodes at which we wish to solve for $z$. An illustration of the grid, with the lower-left node being node number 0, looks like:
#
# `o---o---o---o---o
# | | | | |
# o---.---.---o---o
# | | | | |
# o---.---.---.---o
# | | | | |
# o---o---o---o---o`
#
# In the illustration, `.` is a core node, and `o` is a fixed-value boundary node. The numbering of *nodes* looks like this:
#
# `15---16---17---18---19
# | | | | |
# 10---11---12---13---14
# | | | | |
# 5--- 6--- 7--- 8--- 9
# | | | | |
# 0--- 1--- 2--- 3--- 4`
#
# Here's a version where we number the *core nodes* consecutively:
#
# `o---o---o---o---o
# | | | | |
# o---3---4---o---o
# | | | | |
# o---0---1---2---o
# | | | | |
# o---o---o---o---o`
#
# These numbers correspond to rows in a matrix that we will construct. For each row, the column representing the node itself gets a -4, corresponding to the boxed equation above. For each of its neighboring **core** nodes, the corresponding column gets a +1. For example, the first row in the matrix, representing core node 0 in the above sketch, will have a -4 in column 0. It will have a +1 in column 1, representing the neighbor to its east, and a +1 in column 3, representing the neighbor to its north. Here's what the matrix should look like:
#
# \begin{vmatrix}
# -4 & 1 & 0 & 1 & 0 \\
# 1 & -4 & 1 & 0 & 1 \\
# 0 & 1 & -4 & 0 & 0 \\
# 1 & 0 & 0 & -4 & 1 \\
# 0 & 1 & 0 & 1 & -4 \\
# \end{vmatrix}
#
# But what happens when one or more of the four neighbors is not another core node, but rather a fixed-value boundary? That's actually the case for *all* of the core nodes in the above example. To appreciate how this works, recall that we're going to put all the constant terms on the right-hand side of the equation. To write this out, we need a way to notate both core nodes and fixed-value nodes. Here, we'll use a subscript to index by *core node ID* (for the core nodes), and parentheses to index by *node ID* (for the boundary nodes). With that notation in mind, the equations for the example grid above are:
#
# \begin{eqnarray}
# z_1 + z_3 + z(5) + z(1) - 4z_0 = -U/D \\
# z_2 + z_4 + z_0 + z(2) - 4z_1 = -U/D \\
# z(9) + z(13) + z_1 + z(3) - 4z_2 = -U/D \\
# z_4 + z(16) + z(10) + z_0 - 4z_3 = -U/D \\
# z(13) + z(17) + z_3 + z_1 - 4z_4 = -U/D \\
# \end{eqnarray}
#
# With this notation, it's easy to spot the fixed-value boundary nodes, whose entries we'll move to the right-side:
#
# \begin{eqnarray}
# - 4z_0 + z_1 + z_3 = -U/D - (z(5) + z(1)) \\
# z_0 - 4z_1 + z_2 + z_4 = -U/D - z(2) \\
# z_1 - 4z_2 = -U/D - (z(9) + z(13) + z_1 + z(3)) \\
# z_0 - 4z_3 + z_4 = -U/D - (z(16) + z(10)) \\
# z_1 + z_3 - 4z_4 = -U/D - (z(13) + z(17)) \\
# \end{eqnarray}
#
# The above set of equations is represented by the following matrix equation:
#
# \begin{gather}
# \begin{bmatrix}
# -4 & 1 & 0 & 1 & 0 \\
# 1 & -4 & 1 & 0 & 1 \\
# 0 & 1 & -4 & 0 & 0 \\
# 1 & 0 & 0 & -4 & 1 \\
# 0 & 1 & 0 & 1 & -4 \\
# \end{bmatrix}
# \begin{bmatrix}
# z_0 \\
# z_1 \\
# z_2 \\
# z_3 \\
# z_4
# \end{bmatrix} =
# \begin{bmatrix}
# -U/D - (z(5) + z(1)) \\
# -U/D - z(2) \\
# -U/D - (z(9) + z(13) + z_1 + z(3)) \\
# -U/D - (z(16) + z(10)) \\
# -U/D - (z(13) + z(17))
# \end{bmatrix}
# \end{gather}
#
# or more succinctly,
#
# $$A\mathbf{z} = \mathbf{b}$$
#
# for which the solution is
#
# $$\mathbf{z} = A^{-1} \mathbf{b}$$
#
# In other words this is the equation that we need to solve by inverting the matrix $A$, which we can do using `numpy.linalg.inv()`. Here's an example:
# +
import numpy as np
mat = np.array([[-4, 1, 0, 1, 0],
[ 1, -4, 1, 0, 1],
[ 0, 1, -4, 0, 0],
[ 1, 0, 0, -4, 1],
[ 0, 1, 0, 1, -4],])
print(np.linalg.inv(mat))
# -
# Let's assume for the sake of this example that $U=10^{-4}$ m/yr, $D=10^{-2}$ m$^2$/yr, and all the nodes around the perimeter have zero elevation. What does the solution look like in terms of numbers?
U = 0.0001
D = 0.01
rhs = -(U / D) + np.zeros((5, 1))
solution = np.dot(np.linalg.inv(mat), rhs) # dot product for matrix-vector multiplication
print(solution)
# You can see from this example that once you have your matrix and right-hand side vector, numpy's linear algebra functions make it straightforward to solve the system. The tricky part is building the matrix and the right-side vector in the first place. This is where Landlab's matrix-building utility comes in.
# ## Landlab's matrix-building functions
#
# To facilitate matrix-based numerical solutions, Landlab's collection of utilities includes two helper functions:
#
# - `get_core_node_matrix(grid, value, rhs=None)` creates and returns a matrix like $A$ above for a Landlab grid, as well as a right-hand-side vector. The matrix is returned as an M x M numpy array, where M is the number of core nodes in the grid. The right-hand-side vector is an M x 1 array. Each row in the matrix represents one core node. The rules for building a row, and the corresponding row in the right-hand-side vector, are:
# - For every *active link* connected to the node, if the link connects to another core node, the corresponding column in the matrix is assigned the value $+1$. For example, in the tiny grid presented earlier, core node 0 is connected to two other core nodes, 1 and 3. Therefore, columns 1 and 3 in row 0 of the matrix are each set to $+1$.
# - The matrix column representing the node itself is assigned a value equal to $-1$ times the number of active links that connect to the node, which represents the number of neighboring nodes that are not closed-boundary nodes. In the example grid above, core node 0 is connected for four active links, and so row 0, column 0 is set to -4.
# - All other matrix entries are zero.
# - For every neighboring *fixed-value boundary* node adjacent to core node $i$, the value at the neighbor node is subtracted from column $i$ of the right-hand side vector. This is how a fixed-value boundary condition is handled. In the example grid above, core node 0 is bordered by two fixed-value boundary nodes (node IDs 1 and 5). The values of $z$ at these two fixed-value nodes are subtracted from row 0 of the right-hand-side boundary vector.
#
# - `get_core_node_matrix_var_coef(grid, value, coef_at_link=coef, rhs=None)` does basically the same thing, but allows for a spatially variable coefficient ($D$, or its equivalent in your particular problem). In the example above, we assumed that $D$ was constant, and were therefore able to move it to the right side of the equation. But there are plenty of cases where you might want to allow $D$ to vary in space. This function allows that by taking as an input a 1D array containing a value of $D$ for each grid link. The function ensures that $D$ is factored in appropropriately. (Exercise to the reader: use the example above, but with a spatially variable $D$, to work out what "appropriately" means here). Note that when $D$ varies in space, it is included on the left side of the equation (i.e., in the matrix $A$) and **not** in the right-side vector.
#
# Both functions return two items: an M x M array (the matrix) and an M x 1 array (for the right-hand-side vector). With both functions, however, it is your job as the user to properly set up your right-hand-side vector. You have two options. The first is to pass in an array as the `rhs` argument. It should be a 1D array of length equal to the number of core nodes. The function will then add the boundary condition information to whatever values you have already put there. The second option is to omit the `rhs` argument. In this case the function will create a "preliminary" version that contains **only** the values needed to handle fixed-value boundary conditions; you must then add the rest of your right-side information to this before solving. For example, in the sample problem above, you would need to add $-U/D$ to each element of your right-hand-side vector, while the function would take care of adding the various boundary $z$ values.
#
# Both functions take either a `RasterModelGrid` or a `HexModelGrid` as the first argument. The matrix-creation functions work for both grid types. Note however that if you have a hex grid, you must multiply your right-hand-side vector by 3/2 (exercise: modify the derivation above, accounting for the area and side length of a hexagon, to demonstrate why this is the case). In principle, the same finite-volume solution method should work for other grid types too, but with modifications to handle spatial variation in cell area, face width, and link length. (If irregular-grid functionality is something you need for your application, we encourage you to develop it and submit a pull request!)
#
# Both functions also take a `value` array containing the node-based values of interest (e.g., $z$ in the sample problem above). This should by a 1D numpy array of length equal to the total number of grid nodes.
#
# ## Examples using Landlab matrix functions
#
# ### Constant coefficient
#
# The example below uses Landlab to solve the tiny sample problem described above.
# +
from landlab import RasterModelGrid, imshow_grid
from landlab.utils import get_core_node_matrix
import numpy as np
# Define parameter values
U = 0.0001 # uplift rate of material, relative to baselevel, m/yr
D = 0.01 # soil transport coefficient ("diffusivity"), m2/yr
# Create a simple grid
grid = RasterModelGrid((4, 5), xy_spacing=1.0)
# Add a field for topographic elevation
z = grid.add_zeros('topographic__elevation', at='node')
# Convert one of the interior nodes to boundary
grid.status_at_node[13] = grid.BC_NODE_IS_FIXED_VALUE
# Build the matrix and right-hand-side vector
mat, rhs = get_core_node_matrix(grid, z)
# Add the correct data to the right-hand-side vector
rhs -= U / D
# Let's take a look at them
print('Matrix:')
print(mat)
print('Right-side vector:')
print(rhs)
# Solve: invert the matrix using numpy's linalg.inv() function, then take dot product
z_core = np.dot(np.linalg.inv(mat.toarray()), rhs)
print('Solution:')
print(z_core)
# Insert the solution into the elevation field
z[grid.core_nodes] = z_core.flatten() # flatten because z is a 1D array
# Plot
imshow_grid(grid, z)
# -
# Note that the solution for our tiny test grid is the same as before, as it should be.
# ### Version with a variable coefficient
#
# Next, we repeat the above, but for a case of a spatially variable $D$. We'll first do it with an array of $D$ values, one per link, where the $D$ values are the same as above, just to demonstrate that the solution is the same.
# +
from landlab.utils import get_core_node_matrix
# Define an array of D values
D = 0.01 + np.zeros(grid.number_of_links) # we could also make this a grid field if desired
# Build the matrix and right-hand-side vector
mat, rhs = get_core_node_matrix(grid, z, coef_at_link=D)
# Add the correct data to the right-hand-side vector: this time D is on the left side, so
# we don't incorporate it in the right-side vector
rhs -= U
# Let's take a look at them
print('Matrix:')
print(mat)
print('Right-side vector:')
print(rhs)
# Solve: invert the matrix using numpy's linalg.inv() function, then take dot product
z_core = np.dot(np.linalg.inv(mat.toarray()), rhs)
print('Solution:')
print(z_core)
# Insert the solution into the elevation field
z[grid.core_nodes] = z_core.flatten() # flatten because z is a 1D array
# Plot
imshow_grid(grid, z)
# -
# Here, the matrix and RHS vector are different, but the solution is the same. We've simply factored $D$ into the left side instead of the right side.
#
# Now let's try making $D$ actually vary in space. For the sake of illustration, we'll assign a high value to the links on the left, and a 100x lower value to the links on the right. What do you think this will do to the topography?
# +
# Define an array of D values
D = np.zeros(grid.number_of_links) # we could also make this a grid field if desired
D[grid.x_of_node[grid.node_at_link_head] > 2.0] = 0.001
D[grid.x_of_node[grid.node_at_link_head] <= 2.0] = 0.1
print('D values:')
print(D)
# Build the matrix and right-hand-side vector
mat, rhs = get_core_node_matrix(grid, z, coef_at_link=D)
# Add the correct data to the right-hand-side vector: this time D is on the left side, so
# we don't incorporate it in the right-side vector
rhs -= U
# Let's take a look at them
print('Matrix:')
print(mat)
print('Right-side vector:')
print(rhs)
# Solve: invert the matrix using numpy's linalg.inv() function, then take dot product
z_core = np.dot(np.linalg.inv(mat.toarray()), rhs)
print('Solution:')
print(z_core)
# Insert the solution into the elevation field
z[grid.core_nodes] = z_core.flatten() # flatten because z is a 1D array
# Plot
imshow_grid(grid, z)
# -
# Here the lone core cell on the right is surrounded by links at which transport is inefficient; in other words, $D$ is small. Therefore, the cell needs steep slopes on all sides in order to transport out the incoming soil. The other cells are all bordered by at least one link with a high $D$ value, so they don't need much gradient to transport out the incoming material.
#
#
# ### Comparison with 1D analytical solution
#
#
# In the next example, we'll set up an effectively 1D domain, and compare it with the known analytical solution. We can produce a quasi-1D grid by giving it just 3 rows, two of which are boundary rows, and setting the status of those boundaries to *closed*.
#
# The expected analytical solution is a parabola:
#
# $$z = \frac{UL^2}{D}\left(\frac{x}{L} - \frac{1}{2}\left[\frac{x}{L}\right]^2\right)$$
#
# +
from landlab import RasterModelGrid, imshow_grid
from landlab.utils import get_core_node_matrix
import numpy as np
# Define parameter values
U = 0.0001 # uplift rate of material, relative to baselevel, m/yr
D = 0.01 # soil transport coefficient ("diffusivity"), m2/yr
# Create a simple grid
grid = RasterModelGrid((3, 101), xy_spacing=1.0)
# Add a field for topographic elevation
z = grid.add_zeros('topographic__elevation', at='node')
# Set closed boundaries on north and south
grid.set_closed_boundaries_at_grid_edges(False, True, False, True)
# Build the matrix and right-hand-side vector
mat, rhs = get_core_node_matrix(grid, z)
# Add the correct data to the right-hand-side vector
rhs -= U / D
# Solve: invert the matrix using numpy's linalg.inv() function, then take dot product
z_core = np.dot(np.linalg.inv(mat.toarray()), rhs)
# Insert the solution into the elevation field
z[grid.core_nodes] = z_core.flatten() # flatten because z is a 1D array
# Calculate the analytical solution
middle_row = np.arange(101, 202, dtype=int) # middle row of grid nodes
x = grid.x_of_node[middle_row] # x coordinates: 0, 1, ... 100
L = 50.0 # half-length of domain
za = (U/D) * (x * L - 0.5 * x * x) # analytical solution
# Plot
import matplotlib.pyplot as plt
plt.plot(x, z[middle_row], 'b.')
plt.plot(x, za, 'r')
plt.xlabel('Distance (m)')
plt.ylabel('Height (m)')
plt.legend(['numerical', 'analytical'])
# -
# ### Hexagonal grid
#
# One advantage of the finite-volume method is that it isn't limited to rectilinear grids. The next example demonstrates this with a tiny hex grid. This wee little grid has just two core nodes, so our matrix will be 2x2. One change is that we need to multiply the RHS values by 3/2 to account for the hex geometry.
# +
from landlab import HexModelGrid
# Instantiate the grid: here 3 rows, with 3 columns top and bottom and 4 in the middle
hg = HexModelGrid((3, 3))
# Add the elevation field
z = hg.add_zeros('topographic__elevation', at='node')
# Constants, as before
U = 0.0001
D = 0.01
dx = 1.0 # this is the spacing between nodes
# Create the matrix and RHS
mat, rhs = get_core_node_matrix(hg, z)
# Fill in the rest of the RHS vector, including a factor of 3/2 for the hex grid.
rhs[:] += -1.5 * U * dx * dx / D
# Solve
soln = np.dot(np.linalg.inv(mat.toarray()), rhs)
z[hg.core_nodes] = soln.flatten()
print(mat)
print(rhs)
print(z)
# -
# We can test this. The uplift rate times the cell area represents the volume rate in. Because this is a steady problem, it should equal the volume rate out. The volume rate out across any outer cell face is equal to the gradient across the face times $D$ times the width of the face. The face width in this case is $3^{-1/2}$. Here, the boundaries are all at zero and the distance between nodes is unity, so the gradient is equal to the elevation value. Hence, the flux out across any one face is:
#
# $$3^{-1/2} Dz$$
#
# and the total flux equals the flux of one face times the number of outer faces, of which there happen to be 10. Here's the calculation:
# Test: area times 2 cells times uplift rate should equal number of exposed sides times elevation
area = 0.5 * 3.0**0.5
influx = 2 * area * U
outflux = 10 * D * (1.0 / 3.0**0.5) * z[4]
print(influx)
print(outflux)
# So, we have successfully balanced mass.
#
# These examples have used a simple steady diffusion (Poisson) equation, cast in terms of hillslope evolution. The same equation could be used, for example, for a steady 2D heat conduction problem, or a solute injection-and-diffusion problem. And although these examples focus on the steady problem, a similar matrix-based approach can be used for implicit solutions to the time-evolving problem.
#
# ### Appendix 1: deriving a finite-element discretization for a hexagonal grid
#
# In a regular hexagonal grid, the summation should look as derived in the following:
#
# $$\oint_S \mathbf{f} \cdot\mathbf{n} dR = U A_r$$,
#
# where $A_r$ is now the area of a regular hexagon. In terms of the side length, $a$, area is:
#
# $A_r = \frac{3\sqrt{3}}{2}a^2$.
#
# The side length relates to the height, $\Delta x$, (midpoint of one face to midpoint of the opposite face) as:
#
# $\Delta x = \frac{3}{\sqrt{3}}a$, or
#
# $a = \frac{\sqrt{3}}{3}\Delta x = \frac{1}{\sqrt{3}}\Delta x$.
#
# Plugging this in for area,
#
# $A_r = \frac{3\sqrt{3}}{2}\left( \frac{1}{\sqrt{3}} \right)^2 = \frac{\sqrt{3}}{2}\Delta x^2$.
#
#
# So then our summation looks like:
#
# $$\oint_S \mathbf{f} \cdot\mathbf{n} dR = \sum_{k=1}^6 \mathbf{q_k}\delta_k \frac{1}{\sqrt{3}}\Delta x = U \frac{\sqrt{3}}{2}\Delta x^2$$
#
# which simplifies to
#
# $$\sum_{k=1}^6 \mathbf{q_k}\delta_k = U \frac{3}{2}\Delta x$$
#
# Then put in the 6 fluxes (here assuming a "horizontal" arrangement):
#
# $q_e \delta_e = -D(1/\Delta x) (\eta_e - \eta_i)$
#
# $q_{nne} \delta_{nne} = -D(1/\Delta x) (\eta_{nne} - \eta_i)$
#
# $q_{nnw} \delta_{nne} = -D(1/\Delta x) (\eta_{nnw} - \eta_i)$
#
# $q_w \delta_w = -D(1/\Delta x) (\eta_w - \eta_i)$
#
# $q_{ssw} \delta_{ssw} = -D(1/\Delta x) (\eta_{ssw} - \eta_i)$
#
# $q_{sse} \delta_{sse} = -D(1/\Delta x) (\eta_{ssw} - \eta_i)$
#
# and so you get:
#
# $$\eta_e + \eta_{nne} + \eta_{nnw} + \eta_w + \eta_{ssw} + \eta_{sse} - 6\eta_i = -\frac{3U}{2D} \Delta x^2$$
#
# Conclusion: the only difference between a raster and a hex grid is the factor of 3/2 on the RHS, and of course the fact that you are adding up 6 neighbors instead of 4.
#
# ### Appendix 2: Deriving the analytical solution
#
# Let $s = dz/dx$, then
#
# $$\frac{ds}{dx} = -\frac{U}{D}$$
#
# Assume we have a linear domain of length $2L$, in which $s(L)=0$. Integrate:
#
# $$s = -\frac{U}{D}x + C_1$$
#
# Evaluate the constant of integration:
#
# $$0 = -\frac{U}{D}L + C_1$$
#
# and therefore
#
# $$s = \frac{dz}{dx} = \frac{U}{D}(L-x)$$
#
# The above implies that gradient is positive when $x<L$, zero when $x=L$, and negative when $x>L$, as expected.
#
# Now integrate again:
#
# $$z = \frac{U}{D}\left(Lx - \frac{x^2}{2}\right) + C_2$$
#
# Given $z(x)=z(2L)=0$, $C_2=0$, thus (and factoring out $L^2$):
#
# $$\boxed{z = \frac{UL^2}{D}\left(\frac{x}{L} - \frac{1}{2}\left[\frac{x}{L}\right]^2\right)}$$
#
#
#
#
|
notebooks/tutorials/matrix_creation/numerical_matrix_building_tools.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Deep research of electrocardiograms
# In previous tutorials you have learned about batches, pipelines and models. All those concepts are essential components of deep learning research, and CardIO provides convenient implementations of them for all users.
# But in order to perform real research, you need to conduct well-described, reproducible experiments and keep track on the results.
#
# For this task `research` module of `batchflow` comes in handy. In this tutorial we will use `research` to train and test multiple variations of ResNet architecture in the task of atrial fibrillation classification.
#
# In this tutorial we will cover part of the functionality of `research`, but we strongly recommend to go through [BatchFlow's Research tutorial](https://github.com/analysiscenter/batchflow/blob/master/examples/tutorials/08_research.ipynb) and to take a look at [documentation for Research](https://analysiscenter.github.io/batchflow/intro/research.html).
# # Table of contents
#
#
# * [Experimental design](#Experimetal-design)
# * [Describing model variations](#Describing-model-variations)
# * [Creating dataset](#Creating-dataset)
# * [Setting up model configuration](#Setting-up-model-configuration)
# * [Setting up training parameters](#Setting-up-training-parameters)
# * [Defining pipelines](#Defining-pipelines)
# * [Running the experiment](#Running-the-experiment)
# * [Summary](#Summary)
# # Experimental design
# When you are starting an experiment, the very first thing you should do is to write down the experimental design. Clear and explicit design of experiment makes it easier to reproduce the results, because it helps to make sure that all important conditions are accounted.
#
# We will now follow this rule and step by step generate experimental desing, which later will be used as configuration for our experiments.
# ## Describing model variations
# First, we shall define which variations of ResNet architecture we are going to test.
# `ResNet` class from `batchflow.models` has following configuration parameters:
# * number of filters after first convolution
# * layout in ResNet blocks
# * number of filters in ResNet blocks' convolutions
# * number of ResNet blocks between poolings
#
# We are going to tweak all of them! And, we suppose that you are already familiar with models from `batchflow.models`.
#
#
# Along with custom architectures, let's try some classics, like `ResNet18` and `ResNet34`. To do this, we define "model" option of our experiment:
# +
import sys
sys.path.append("..")
from cardio.batchflow.models.tf import ResNet, ResNet18, ResNet34
from cardio.batchflow.research import Option, Grid, Research
model_op1 = Option('model', [ResNet18, ResNet34])
model_op2 = Option('model', [ResNet])
# -
# As you can see, we have defined custom and classic ResNets in different options. Have some patience, in a few moments we will explain this move.
#
# Next, let's define options for input filters:
input_filters_op1 = Option('input_filters', [64])
input_filters_op2 = Option('input_filters', [32, 8])
# And now just follow the same procedure for the rest of the parameters:
# +
layout_op1 = Option('layout', ['cnacna'])
layout_op2 = Option('layout', ['cna', 'cnacna'])
blocks_op1= Option('blocks', [[2, 2, 2, 2], [3, 4, 6, 3]])
blocks_op2 = Option('blocks', [[2, 3, 4, 5, 4, 3, 2], [2, 2, 2, 2, 2, 2, 2],
[1, 1, 1, 1, 1, 1, 1]])
filters_op1 = Option('filters', [[64, 128, 256, 512], [64, 128, 256, 512]])
filters_op2 = Option('filters', [[4, 8, 16, 32, 64, 128, 256], [4, 4, 8, 8, 16, 16, 20]])
# -
# This is just the time to explain why we define two options for each parameter.
#
# We have defined options for different parameters, but what are we going to do with them now? We will use them to generate a single grid of parameters, that will include all the combinations we want to test.
#
# Here, take a look at this simple example to get the intuition about grid generation:
# +
op1 = Option('p1', [1, 2])
op2 = Option('p2', ['v1', 'v2'])
op3 = Option('p1', [4])
op4 = Option('p2', ['v3'])
grid = (op1 * op2 + op3 * op4)
grid
# -
# You can perform multipliction and addition of options. But, as far as `Grid` object is not very intuitive, we can generate all configurations from this grid and take a look at them:
list(grid.gen_configs())
# This form is much simpler to understand!
#
# Also, there is a method `Option.product` that implements element-wise multiplication - see an example below.
# +
grid = Option.product(op1, op2)
list(grid.gen_configs())
# -
# Now we are ready to generate the grid for our experiment:
grid = (Option.product(model_op1, blocks_op1, filters_op1) * layout_op1 * input_filters_op1 +
model_op2 * layout_op2 * input_filters_op2 * blocks_op2 * filters_op2)
# Great, we're done with model variations. Now we shall move to the next part - the data.
# ## Creating dataset
# Here we just follow familiar procedure: setting up paths to the signals and the labels, then creating dataset instance and splitting data into train and test subsets.
# +
import os
from cardio import batchflow as bf
from cardio import EcgDataset
PATH = "/notebooks/data/ECG/training2017" # Change this path for your data dicrectory
SIGNALS_MASK = os.path.join(PATH, "A*.hea")
LABELS_PATH = os.path.join(PATH, "REFERENCE.csv")
# -
eds = EcgDataset(path=SIGNALS_MASK, no_ext=True, sort=True)
eds.split(0.8, shuffle=False)
# ## Setting up model configuration
# Now, here comes the interesting part! When we define `model_config`, we use `C('parameter_name')` for all the parameters we want to vary:
# +
import tensorflow as tf
from cardio.batchflow import F, B, C, V
model_config = {
'inputs': dict(signals={'shape': F(lambda batch: batch.signal[0].shape[1:])},
labels={'classes': ['A', 'NO'], 'transform': 'ohe', 'name': 'targets'}),
'initial_block/inputs': 'signals',
"loss": "ce",
"input_block/filters": C('input_filters'),
"body/block/layout": C('layout'),
"body/filters": C('filters'),
"body/num_blocks": C('blocks'),
"session/config": tf.ConfigProto(allow_soft_placement=True),
"device": C("device"),
"optimizer": "Adam",
}
# -
# Corresponding values from configuration will be inserted instead of those templates.
# ## Setting up training parameters
# This part is pretty short and simple - just setting up batch size and number of epochs.
BATCH_SIZE = 32
EPOCHS = 300
# ## Defining pipelines
# At first we define root pipelines, wich contain only signal processing. Also, we will define a function to flip signals whose R peaks are turned down.
# +
import numpy as np
from numba import njit
@njit(nogil=True)
def center_flip(signal):
"""
Center signal and flip signals with R peaks turned down.
"""
return np.random.choice(np.array([1, -1])) * (signal - np.mean(signal))
# +
root_train = (
bf.Pipeline()
.load(components=["signal", "meta"], fmt="wfdb")
.load(components="target", fmt="csv", src=LABELS_PATH)
.drop_labels(["~"])
.rename_labels({"N": "NO", "O": "NO"})
.apply_to_each_channel(center_flip)
.random_resample_signals("normal", loc=300, scale=10)
.random_split_signals(3000, {"A": 6, "NO": 2})
.apply_transform(func=np.transpose, src='signal', dst='signal', axes=[0, 2, 1])
).run(BATCH_SIZE, shuffle=True, drop_last=True, n_epochs=None, lazy=True)
root_test = (
bf.Pipeline()
.load(components=["signal", "meta"], fmt="wfdb")
.load(components="target", fmt="csv", src=LABELS_PATH)
.drop_labels(["~"])
.rename_labels({"N": "NO", "O": "NO"})
.apply_to_each_channel(center_flip)
.split_signals(3000, 3000)
.apply_transform(func=np.transpose, src='signal', dst='signal', axes=[0, 2, 1])
).run(BATCH_SIZE, shuffle=True, drop_last=True, n_epochs=1, lazy=True)
# -
# Next, we define main pipelines. Training pipeline is pretty simlpe - we just train the model and save loss to pipeline variable.
# Again, we need to define simple function - this one prepares data from batch to be fed into a model.
def make_data(batch, **kwagrs):
"""
Prepare data from `signal` and `target` component of batch to be fed into network.
Separates each crop as individual signal and makes a corresponding label.
"""
n_reps = [signal.shape[0] for signal in batch.signal]
signals = np.array([segment for signal in batch.signal for segment in signal])
targets = np.repeat(batch.target, n_reps, axis=0)
return {"feed_dict": {'signals': signals, 'labels': targets}}
model_train = (
bf.Pipeline()
.init_variable('loss', init_on_each_run=list)
.init_model('dynamic', C('model'), 'model', config=model_config)
.train_model('model',
make_data=make_data,
fetches=["loss"],
save_to=[V("loss")], mode="w")
)
# Testing pipeline is a bit more complex. At first, we initialize a variable to store metrics and save number of splits for each signal in batch component `splits`. Then, as usual, import model, make predictions and save predictions and targets into the batch components.
#
# As far as we make predictions for splits, we need to aggrageate them to obtain prediction for the whole signal. To do so, we will use `aggregate_crop_predictions` and update corresponding batch components.
# Then, pipeline method `gather_metrics` accumulates targets and predictions from batch and allows to calculate metrics afterwards.
def aggregate_crops(arr, splits, agg_func, predictions=True, **kwargs):
"""
Aggregates predictions or labels from separate crops for whole signal.
If predictions is True, applies softmax function before aggreagation.
"""
if predictions:
arr -= np.max(arr, axis=1, keepdims=True)
arr_exp = np.exp(arr)
arr = (arr_exp / np.sum(arr_exp, axis=1, keepdims=True))
arr = np.split(arr, np.cumsum(splits)[:-1])
return np.array([agg_func(sig[:, 0]) for sig in arr])
model_test = (
bf.Pipeline()
.init_variable("metrics", init_on_each_run=None)
.apply_transform(src="signal", dst="splits", func=lambda x: [x.shape[0]])
.import_model("model", C("import_from"))
.predict_model("model", make_data=make_data,
fetches=["predictions", "targets"],
save_to=[B('predictions'), B("targets")])
.apply_transform_all(func=aggregate_crops, predictions=True,
src='predictions', dst='predictions',
splits=B('splits'), agg_func=np.mean)
.apply_transform_all(func=aggregate_crops, predictions=False,
src='targets', dst='targets',
splits=B('splits'), agg_func=np.max)
.gather_metrics('class', targets=B('targets'), predictions=B('predictions'),
fmt='proba', save_to=V('metrics'), mode='a')
)
# # Running the experiment
# Before starting the experiment, we have to set how often to run test pipeline. Calculation of this value is not very strainghtforward because it should be stated in a number of iterations, not epochs.
TEST_EACH_EPOCH = 20
TRAIN_SIZE = len(eds.train)
ITERATIONS = ((TRAIN_SIZE // BATCH_SIZE) + 1) * EPOCHS
TEST_EXEC_FOR = ITERATIONS // EPOCHS * TEST_EACH_EPOCH
STR_EXEC = '%{}'.format(TEST_EXEC_FOR)
# Also, we will set a few constants for research:
N_REPS = 5
N_BRANCHES = 2
N_WORKERS = 3
GPU = [1, 2, 3, 4, 5, 6]
# At the end of run of any pipeline we can execute some function. So let's write two functions to save number of trainable parameters and F1 score:
# +
def get_trainable_variables(iteration, experiment, ppl, model_name="model"):
"""
Returns a number of trainable variables in the model.
"""
return experiment[ppl].pipeline.get_model_by_name(model_name).get_number_of_trainable_vars()
def calc_metrics(iteration, experiment, ppl, var_name):
"""
Gets variable with metrics class from the pipeline and
calculates F1 score.
"""
metrics = experiment[ppl].pipeline.get_variable(var_name)
f1 = metrics.evaluate('f1_score')
return f1
# -
# Now, define the whole research pipeline and run it:
mr = (
Research()
.pipeline(root_train << eds, model_train,
variables=["loss"], name="train", dump=STR_EXEC)
.pipeline(root_test << eds, model_test,
name="test", execute=STR_EXEC, dump=STR_EXEC,
import_from="train", run=True)
.function(calc_metrics, returns='metrics_f1', name='metrics_f1',
execute=STR_EXEC, dump=STR_EXEC, ppl='test', var_name='metrics')
.function(get_trainable_variables, returns='trainable_variables',
name='trainable_variables', execute=1, dump=1, ppl='train')
.grid(grid)
)
mr.run(n_reps=N_REPS, n_iters=ITERATIONS, workers=N_WORKERS, gpu=GPU,
branches=N_BRANCHES, name='ResNet_research', progress_bar=True)
# Now in folder ResNet_research you can find the results: loss, saved after each iteration, f1 score on the whole test set calculated each 20 epochs and number of trainable variables in each model.
# # Summary
# In this notebook we have learned about research and experiments and now you know how to:
# * define research grid
# * use metrics in the pipeline
# * run research experiments
|
tutorials/IV.Research.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] id="0S96dkjmRR_j" colab_type="text"
# [](http://rpi.analyticsdojo.com)
# <center><h1>Introduction to Text Mining in Python</h1></center>
# <center><h3><a href = 'http://rpi.analyticsdojo.com'>rpi.analyticsdojo.com</a></h3></center>
# + [markdown] id="Cqiaxyr8RJ-7" colab_type="text"
#
# These exercises were adapted from Mining the Social Web, 2nd Edition [See origional here](https://github.com/ptwobrussell/Mining-the-Social-Web-2nd-Edition/)
# Simplified BSD License that governs its use.
#
# + [markdown] id="5v9HdaIKRJ-9" colab_type="text"
# ### Key Terms for Text Mining
# - A collection of documents – corpus
# - Document – a piece of text
# - Terms/tokens – a word in a document
# - Entity – Some type of person, place, or organization
#
# + id="yXoFPKuRRJ-_" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 812} outputId="a42537d1-fda0-4b6c-ad45-c5818e2583b7"
corpus = {
'a' : "Mr. Green killed <NAME> in the study with the candlestick. \
Mr. Green is not a very nice fellow.",
'b' : "<NAME> has a green plant in his study.",
'c' : "<NAME> watered <NAME>'s green plant while he was away \
from his office last week."
}
#This will separate the documents (sentences) into terms/tokins/words.
terms = {
'a' : [ i.lower() for i in corpus['a'].split() ],
'b' : [ i.lower() for i in corpus['b'].split() ],
'c' : [ i.lower() for i in corpus['c'].split() ]
}
terms
# + [markdown] id="DCv3qrYmRJ_P" colab_type="text"
# ### Term Frequency
# - A very common factor is to determine how frequently a word or term occurs with a document.
# - This is how early web search engines worked. (Not very well).
# - A common basic standarization method is to control for the number of words in the document.
#
# + id="uWYPzCUjRJ_S" colab_type="code" colab={}
from math import log
#This is our terms we would like to use.
QUERY_TERMS = ['mr.', 'green']
#This calculates the term frequency normalized by the length.
def tf(term, doc, normalize):
doc = doc.lower().split()
if normalize:
return doc.count(term.lower()) / float(len(doc))
else:
return doc.count(term.lower()) / 1.0
# + id="7loOhwuHRJ_Y" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 133} outputId="ca94cbbe-0741-44fd-dfd7-c25531e9a48a"
#This prints the basic documents. We can see that Mr. Green is in the first document.
for (k, v) in sorted(corpus.items()):
print (k, ':', v)
print('\n')
# + id="xWpeMzguRJ_i" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 301} outputId="96e9797d-2fb9-45f8-9025-30940d186c1a"
# Score queries by calculating cumulative tf (normalized and unnormalized).
query_scores = {'a': 0, 'b': 0, 'c': 0}
#This starts the search for each query
for term in [t.lower() for t in QUERY_TERMS]:
#This starts the search for each document in the corpus
for doc in sorted(corpus):
print ('TF(%s): %s' % (doc, term), tf(term, corpus[doc], True))
print('\n') #Let's skip a line.
print ("This does the same thing but unnormalized.")
for term in [t.lower() for t in QUERY_TERMS]:
#This starts the search for each document in the corpus
for doc in sorted(corpus):
print ('TF(%s): %s' % (doc, term), tf(term, corpus[doc], False))
# + [markdown] id="amnZbUC3RJ_o" colab_type="text"
# ### TF-IDF
# - TF-IDF incorporates the inverse document frequency in the analysis. This type of factor would limit the impact of *frequent words* that would show up in a large number of documents.
# - The tf-idf calc involves multiplying against a tf value less than 0, so it's necessary to return a value greater than 1 for consistent scoring. (Multiplying two values less than 1 returns a value less than each of them.)
# + id="cKuRv-nuRJ_p" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 72} outputId="02459252-f9c6-4a7f-f7f5-56f9ed884ab4"
def idf(term, corpus):
num_texts_with_term = len([True for text in corpus if term.lower()
in text.lower().split()])
try:
return 1.0 + log(float(len(corpus)) / num_texts_with_term)
except ZeroDivisionError:
return 1.0
for term in [t.lower() for t in QUERY_TERMS]:
print ('IDF: %s' % (term, ), idf(term, corpus.values()))
# + id="n3EAJ-gXRJ_v" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 636} outputId="a773c3f1-4280-4e04-886b-9df89d0aac43"
#TF-IDF Just multiplies the two together
def tf_idf(term, doc, corpus):
return tf(term, doc, True) * idf(term, corpus)
query_scores = {'a': 0, 'b': 0, 'c': 0}
for term in [t.lower() for t in QUERY_TERMS]:
for doc in sorted(corpus):
print ('TF(%s): %s' % (doc, term), tf(term, corpus[doc], True))
print ('IDF: %s' % (term, ), idf(term, corpus.values()))
print('\n')
for doc in sorted(corpus):
score = tf_idf(term, corpus[doc], corpus.values())
print ('TF-IDF(%s): %s' % (doc, term), score)
query_scores[doc] += score
print('\n')
print ("Overall TF-IDF scores for query '%s'" % (' '.join(QUERY_TERMS), ))
for (doc, score) in sorted(query_scores.items()):
print (doc, score)
# + id="JgzEv5DoRJ_2" colab_type="code" colab={}
# + id="0B1_bACORJ_4" colab_type="code" colab={}
|
files/spring2020/16-intro-nlp/02-corpus-simple.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: MLenv3
# language: python
# name: mlenv3
# ---
# # WS2332 - Project 7 - Lecture 2
# <NAME>
# <div>
# <img src=docs/tudelft_logo.jpg width=300px></div>
# **What:** Lab Session 1 of course WS2332 (Project 7): Introduction to Machine Learning
#
# * Today's lecture focuses on **regression via supervised learning in 1D**
#
# **How:** Jointly workout this notebook
# * GitHub: https://github.com/mabessa/Intro2ML
# 1. You can do this locally in your computer (but you have to have the Python packages installed):
# * clone the repository to your computer: git clone https://github.com/mabessa/Intro2ML
# * load jupyter notebook (it will open in your internet browser): jupyter notebook
# * search for this notebook in your computer and open it
# 2. Or you can use Google's Colab (no installation required, but times out if idle):
# * go to https://colab.research.google.com
# * login
# * File > Open notebook
# * click on Github (no need to login or authorize anything)
# * paste the git link: https://github.com/mabessa/Intro2ML
# * click search and then click on the notebook.
#
# This simple tutorial is based on a script I created for this article: https://imechanica.org/node/23957
#
# It follows from some examples provided by the scikit-learn user guide, which seem to have originated from <NAME>, <NAME>, <NAME>, and <NAME>.
#
# License: BSD 3 clause
# **Let's start by importing basic modules into Python**
# This is a comment
import numpy as np # fundamental scientific computing module
import matplotlib.pyplot as plt # plotting module
# ## Outline for today
#
# 1. Quick introduction to Python
# 2. Polynomial approximations (global & noiseless)
# 3. Polynomial approximations for noisy datasets
# ## 1. Quick introduction to Python
#
# Let's plot the function $x\sin(x)$ in the domain $x\in[0,10]$.
#
# 1. Define the function $f(x) = x\sin(x)$
def f(x):
return x * np.sin(x)
# 2. Create a vector of 50 points that are uniformly spaced between 0 and 10
n_data = 50 # number of points for plotting the function
x_data = np.linspace(0, 10, n_data) # uniformly spaced points
# You can see the vector by doing:
print(x_data)
# 3. Let's calculate the values of $f(x)=x \sin(x)$ for each of the 50 points of vector x_data
#
# ### Exercise 1
#
# Compute f(x) for the points we created and save these values in y_data.
# +
# Exercise 1.
# Write your code here:
# until here.
# -
# 4. Now let's plot the function from the 50 points we know
# +
fig1, ax1 = plt.subplots() # This opens a new figure
# Plot points and interpolate them:
ax1.plot(x_data, y_data, 'ro:', markersize=6, linewidth=2,
label=u'ground truth: $f(x) = x\,\sin(x)$')
ax1.set_xlabel('$x$') # label of the x axis
ax1.set_ylabel('$f(x)$') # label of the y axis
ax1.legend(loc='upper left') # plot legend in the upper left corner
# -
# As we can see, if we have lots of points, even linear interpolation between the points can approximate the function very well.
#
# However, what if we use just a few points from our dataset x_data?
# +
n_train = 5 # points to train the algorithm
x_train = np.linspace(0, 10, n_train) # 5 points uniformly distributed
y_train = f(x_train)
ax1.plot(x_train, y_train, 'k*', markersize=12,
label="Training points") # Markers locating training points
ax1.plot(x_train, y_train, 'g-', linewidth=2,
label=u'local linear interpolation') # linear interpolation
# plotted
ax1.legend(loc='upper left') # replot legend
fig1 # replot fig1 now overlaying the plot in the previous cell
# -
# This is called local interpolation because each line only depends on the two points it is connecting (not on the other points).
#
# * Next, we are going to look into global interpolation with polynomials.
# ## 2. Polynomial approximations (global & noiseless)
# +
# We start by importing the polynomial predictor from scikit-learn
from sklearn.preprocessing import PolynomialFeatures # For Polynomial fit
from sklearn.linear_model import LinearRegression # For Least Squares
from sklearn.pipeline import make_pipeline # to link different objects
degree = 4 # degree of polynomial we want to fit
poly_model = make_pipeline(PolynomialFeatures(degree),
LinearRegression())
poly_model.fit(x_train,y_train) # fit the polynomial to our 5 points
# in x_train
# -
# **But that gives an error!**
#
# Scikit-learn models expect the input, i.e. x_train, to be a 2D array (a matrix) where each line corresponds to one point and each column corresponds to a **FEATURE** of that point.
#
# So, instead of expecting an array like:
print(x_train)
# It expects this:
# +
X_train = np.reshape(x_train, (-1, 1)) # convert vector to 2d array
# Other way of doing this would be:
# X_train = x_train[:, np.newaxis]
print(X_train)
# -
# Note that in this case, each point has only one feature: the $x$ coordinate of that point.
#
# * Let's try again to fit the polynomial to the data, but now using X_train instead of x_train:
poly_model.fit(X_train,y_train) # fit the polynomial to our 5 points
# in X_train which is a 2D array
# Now it works!
#
# This means that scikit-learn has fit the polynomial model to our 5 training points.
#
# We can then use this model to predict all 50 points we defined in x_data:
# In scikit-learn, predicting from a model is a one-liner:
y_pred = poly_model.predict(x_data)
# **Something went wrong again**. What happened?
#
# ### Exercise 2
#
# Use our polynomial model to predict all 50 points we defined in x_data
# +
# Exercise 2.
# Write your code here:
# until here.
# -
# Let's see if you got it right by plotting the polynomial prediction on top of fig1.
# +
# Plot x_data and prediction as a blue line:
ax1.plot(x_data, y_pred, 'b-', linewidth=2,
label="Polynomial of degree %d prediction" % degree)
# Replot figure and legend:
ax1.legend(loc='upper left')
fig1
# -
# Nice.
#
# Yet, our polynomial (blue) is clearly different to the function we want to "learn", i.e. $x \sin(x)$.
#
# How do we evaluate the quality of our approximation?
#
# * By evaluating the error of our polynomial model in the points that we didn't use in the fit.
#
# Two common metrics are $R^2$ and $MSE$ (you will have to search for them and explain them!)
# +
# Import error metrics:
from sklearn.metrics import mean_squared_error, r2_score
# Compute MSE and R2 for the polynomial model we fitted
mse_value = mean_squared_error(y_data, y_pred)
r2_value = r2_score(y_data, y_pred)
print('MSE for polynomial = ', mse_value)
print('R2 score for polynomial = ', r2_value)
# -
# As expected, these predictions are not great because:
#
# * We want $MSE$ to be as low as possible
#
# * The closer $R^2$ is to 1.0 the better
#
# You will dive deeper in this when solving the Lab Assignment.
# ## 3. Polynomial approximations for noisy datasets
# Let's consider a different case now.
#
# Imagine that your data is imperfect.
#
# This is very common in practice because usually data comes from experimental measurements.
#
# For comparison purposes, let's "fabricate" such dataset based on the dataset we considered in the previous sections.
# +
seed = 1987 # set a random seed so that everyone gets the same result
np.random.seed(seed)
# Let's perturb every y_data point with Gaussian noise
random_std = 0.5 + 1.0 * np.random.random(y_data.shape)
# Then, take the random value for STD from 0.5 to 1.5 for each
# data point and create noise following a Gaussian distribution with
# that STD at that point:
noise = np.random.normal(0, random_std)
# The perturbed data becomes:
y_noisy_data = y_data + noise
# -
# For comparison, we plot the noisy data with the noiseless function that we would like to discover $x \sin(x)$:
# +
fig2, ax2 = plt.subplots() # This opens a new figure
# Plot the noiseless function ("the ground thruth")
ax2.plot(x_data, y_data, 'r:', linewidth=2,
label=u'ground truth: $f(x) = x\,\sin(x)$')
# Plot the noisy dataset that we are given:
plt.errorbar(x_data, y_noisy_data, random_std, fmt='kx',
markersize=6, label=u'noisy dataset')
ax2.set_xlabel('$x$') # label of the x axis
ax2.set_ylabel('$f(x)$') # label of the y axis
ax2.legend(loc='upper left') # plot legend in the upper left corner
# -
# Note a couple of things:
#
# * The black "x" marks the average value if we were to measure many times the same property.
#
# * The black bars indicate the noise in each data point (each data point has a different noise value). Formally, we call this aleatoric uncertainty because if we were to measure many times the output for a given input we would obtain that average and standard deviation.
# ### 3.1. Data preprocessing
# In Section 1 we decided to have two different datasets: one with 50 points and the other with 5 new points (not within the original 50).
#
# This does not reflect usual practice.
#
# In data science we are usually given a dataset, and then we need to train and test our algorithms with the **same** dataset.
#
# However, to test the algorithm we have to use data that we have not used in training, otherwise we would be cheating!
#
# This is done by splitting the dataset (in this case x_data) into two sets:
#
# 1. **Training** set (for example: 75% of the dataset)
#
#
# 2. **Test** set with the remaining points of the dataset
#
# Scikit-learn has a very easy way of doing this:
# +
from sklearn.model_selection import train_test_split
X_data = np.reshape(x_data,(-1,1)) # a 2D array that scikit-learn likes
# Let's split the data points into 10% for the training set (5 points)
# and the rest for the test set:
X_train, X_test, y_train, y_test = train_test_split(X_data,
y_noisy_data, test_size=0.90,
random_state=seed)
# -
# Note that the train_test_split module of scikit-learn picks points pseudo-randomly according to the random_state seed value.
#
# Let's visualize the training and testing sets:
# +
# If you want, you can convert back to 1D array for plotting.
x_train = X_train.ravel() # THIS IS NOT NECESSARY, PYTHON CAN ALSO PLOT from the 2D array
x_test = X_test.ravel() # THIS IS NOT NECESSARY, PYTHON CAN ALSO PLOT from the 2D array
# Plot the noisy training dataset:
ax2.plot(x_train, y_train, 'g*', markersize=18,
label="Training points") # Markers locating training points
ax2.plot(x_test, y_test, 'bs', markersize=6,
label="Testing points") # Markers locating training points
ax2.set_xlabel('$x$') # label of the x axis
ax2.set_ylabel('$f(x)$') # label of the y axis
ax2.legend(loc='upper left') # plot legend in the upper left corner
fig2
# -
# Let's create a new figure with less clutter by just plotting the ground truth function and the training points.
# +
fig3, ax3 = plt.subplots() # This opens a new figure
# Plot the noiseless function ("the ground thruth")
ax3.plot(x_data, y_data, 'r:', linewidth=2,
label=u'ground truth: $f(x) = x\,\sin(x)$')
ax3.plot(x_train, y_train, 'g*', markersize=18,
label="Training points") # Markers locating training points
ax3.set_xlabel('$x$') # label of the x axis
ax3.set_ylabel('$f(x)$') # label of the y axis
ax3.legend(loc='upper left') # plot legend in the upper left corner
# -
# ### Exercise 3
#
# Fit a polynomial of degree 4 to this training data and calculate the $R^2$ and $MSE$ metrics for the testing data.
# +
# Exercise 3.
# Write your code here:
# until here.
# -
# Well done...
#
# Yet, this does not seem like a great result, does it?
#
# The $R^2$ value is so bad that it is even negative!
#
# * What explains this result?
#
# * Can we do something to fix this while still using polynomials?
#
# * If we used more points would that help?
#
# * What if we increased the degree of the polynomial?
# ### You will explore these and other things in Part 1 of Lab Assignment...
#
# Have fun!
#
#
|
LabSession_1_Intro2ML.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Generative Adversarial Networks with MedNIST Dataset
#
# ## Introduction
#
# This notebook illustrates the use of MONAI for training a network to generate images from a random input tensor. A simple GAN is employed to do with with a separate Generator and Discriminator networks.
#
# This will go through the steps of:
# * Loading the data from a remote source
# * Constructing a dataset from this data and transforms
# * Defining the networks
# * Training and evaluation
#
# ### Get the dataset
#
# The MedNIST dataset was gathered from several sets from [TCIA](https://wiki.cancerimagingarchive.net/display/Public/Data+Usage+Policies+and+Restrictions), [the RSNA Bone Age Challenge](http://rsnachallenges.cloudapp.net/competitions/4), and [the NIH Chest X-ray dataset](https://cloud.google.com/healthcare/docs/resources/public-datasets/nih-chest).
#
# The dataset is kindly made available by [Dr. <NAME>., Ph.D.](https://www.mayo.edu/research/labs/radiology-informatics/overview) (Department of Radiology, Mayo Clinic)
# under the Creative Commons [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/).
# If you use the MedNIST dataset, please acknowledge the source, e.g.
#
# https://github.com/Project-MONAI/MONAI/blob/master/examples/notebooks/mednist_tutorial.ipynb.
#
# First step is to import libraries and define some parameters:
# +
# %matplotlib inline
import os
import sys
import tarfile
from urllib.request import urlopen
from io import BytesIO
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from IPython.display import clear_output
from tqdm.notebook import tqdm
sys.path.append('/home/localek10/workspace/MONAI/')
import torch
from torch.utils.data import DataLoader
import monai
from monai.transforms import \
Transform, Compose, AddChannel, ScaleIntensity, ToTensor, RandRotate, RandFlip, RandZoom
from monai.networks.nets import Generator, Discriminator
from monai.networks.utils import normal_init
np.random.seed(0)
mednist_url = 'https://www.dropbox.com/s/5wwskxctvcxiuea/MedNIST.tar.gz?dl=1'
disc_train_interval = 1
disc_train_steps = 5
batch_size = 300
latent_size = 64
num_epochs = 50
real_label = 1
gen_label = 0
learning_rate = 2e-4
betas = (0.5, 0.999)
device = torch.device('cuda:0')
# -
# The method for loading the data from the remote source differs here to demonstrate how to download and read from a tar file without using the filesystem, and because we only want the images of hand X-rays. This isn't a classification example so the category data isn't needed, so we'll download the tarball, open it using the standard library, and recall all of the file names for hands:
# +
remote_file = urlopen(mednist_url)
dat=BytesIO(remote_file.read())
tar=tarfile.open('MedNIST.tar.gz',fileobj=dat)
hands = [n for n in tar.getnames() if 'Hand' in n and '.jpeg' in n]
# -
# To load the actual image data from the tarfile, we define a transform type to do this using Matplotlib. This is used with other transforms for preparing the data followed by randomized augmentation transforms. The `CacheDataset` class is used here to cache all of the prepared images from the tarball, so we will have in memory all of the prepared images ready to be augmented with randomized rotation, flip, and zoom operations:
# +
class LoadTarJpeg(Transform):
def __call__(self, data):
return plt.imread(tar.extractfile(data))
train_transforms = Compose([
LoadTarJpeg(),
AddChannel(),
ScaleIntensity(),
RandRotate(range_x=15, prob=0.5, keep_size=True),
RandFlip(spatial_axis=0, prob=0.5),
RandZoom(min_zoom=0.9, max_zoom=1.1, prob=0.5),
ToTensor()
])
train_ds = monai.data.CacheDataset(hands, train_transforms)
train_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True, num_workers=10)
# -
# We now define out generator and discriminator networks. The parameters are carefully chosen to suit the image size of `(1, 64, 64)` as loaded from the tar file. Input images to the discriminator are downsampled four times to produce very small images which are flattened and passed as input to a fully-connected layer. The input latent vectors to the generator are passed through a fully-connected layer to produce an output of shape `(64, 8, 8)`, this is then upsampled three times to produce a final output which is the same shape as the real images. The networks are initialized with a normalization scheme to improve results:
# +
disc_net=Discriminator(
in_shape=(1, 64, 64),
channels=(8, 16, 32, 64, 1),
strides=(2, 2, 2, 2, 1),
num_res_units=1,
kernel_size=5
).to(device)
gen_net = Generator(
latent_shape=latent_size,
start_shape=(64, 8, 8),
channels=[32, 16, 8, 1],
strides=[2, 2, 2, 1]
)
# initialize both networks
disc_net.apply(normal_init)
gen_net.apply(normal_init)
# input images are scaled to [0,1] so enforce the same of generated outputs
gen_net.conv.add_module('activation', torch.nn.Sigmoid())
gen_net = gen_net.to(device)
# -
# Now we define the loss functions to use with helper functions to wrap the loss calculation process for the generator and the discriminator. We also define our optimizers:
# +
disc_loss = torch.nn.BCELoss()
gen_loss = torch.nn.BCELoss()
disc_opt = torch.optim.Adam(disc_net.parameters(), learning_rate, betas=betas)
gen_opt = torch.optim.Adam(gen_net.parameters(), learning_rate, betas=betas)
def discriminator_loss(gen_images, real_images):
"""
The discriminator loss if calculated by comparing its prediction for real and generated images.
"""
real = real_images.new_full((real_images.shape[0], 1), real_label)
gen = gen_images.new_full((gen_images.shape[0], 1), gen_label)
realloss = disc_loss(disc_net(real_images), real)
genloss = disc_loss(disc_net(gen_images.detach()), gen)
return (realloss + genloss) / 2
def generator_loss(input):
"""
The generator loss is calculated by determining how well the discriminator was fooled by the generated images.
"""
output = disc_net(input)
cats = output.new_full(output.shape, real_label)
return gen_loss(output, cats)
# -
# We now train by iterating over the dataset for a number of epochs. At certain after the generator training stage for each batch, the discriminator is trained for a number of steps on the same real and generated images.
# +
best_metric = -1
best_metric_epoch = -1
epoch_loss_values = [(0, 0)]
gen_step_loss = []
disc_step_loss = []
step = 0
for epoch in range(num_epochs):
gen_net.train()
disc_net.train()
epoch_loss = 0
for batch_data in tqdm(train_loader, f'Epoch {epoch + 1}, avg loss: {epoch_loss_values[-1][1]:.4f}'):
real_images = batch_data.to(device)
latent = torch.randn(real_images.shape[0], latent_size).to(device)
gen_opt.zero_grad()
gen_images = gen_net(latent)
loss = generator_loss(gen_images)
loss.backward()
gen_opt.step()
epoch_loss += loss.item()
gen_step_loss.append((step,loss.item()))
if step % disc_train_interval == 0:
disc_total_loss = 0
for _ in range(disc_train_steps):
disc_opt.zero_grad()
dloss = discriminator_loss(gen_images, real_images)
dloss.backward()
disc_opt.step()
disc_total_loss += dloss.item()
disc_step_loss.append((step, disc_total_loss / disc_train_steps))
step += 1
epoch_loss /= step
epoch_loss_values.append((step, epoch_loss))
clear_output(True)
# -
# The separate loss values for the generator and discriminator can be graphed together. These should reach an equilibrium as the generator's ability to fool the discriminator balances with that networks ability to discriminate accurately between real and fake images.
plt.figure(figsize=(12,5))
plt.semilogy(*zip(*gen_step_loss), label='Generator Loss')
plt.semilogy(*zip(*disc_step_loss), label='Discriminator Loss')
plt.grid(True,'both','both')
plt.legend()
# Finally we show a few randomly generated images. Hopefully most images will have four fingers and a thumb as expected (assuming polydactyl examples were not present in large numbers in the dataset). This demonstrative notebook doesn't train the networks for long, training beyond the default 50 epochs should improve results.
# +
test_size = 10
test_latent = torch.randn(test_size, latent_size).to(device)
test_images = gen_net(test_latent)
fig, axs = plt.subplots(1,test_size,figsize=(20,4))
for i, ax in enumerate(axs):
ax.axis('off')
ax.imshow(test_images[i, 0].cpu().data.numpy(), cmap='gray')
|
examples/notebooks/mednist_GAN_tutorial.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
import os
import pandas
# +
#input_file_name = 'data/massey_2018/rankings_through_20180304.csv'
input_file_name = 'data/massey_2018/rankings_through_20180311.csv'
chunks = list()
current_chunk = list()
with open(input_file_name, 'r') as input_file:
for line in input_file:
if line.strip() == '':
chunks.append(current_chunk)
current_chunk = list()
else:
current_chunk.append(line.strip())
chunks.append(current_chunk)
# +
# chunk 0 = metadata
# chunk 1 = blank
# chunk 2 = ranker list
# chunk 3 = rankings header
# chunk 4 = rankings
#output_file_name = 'data/massey_2018/rankings_through_20180304.clean.csv'
output_file_name = 'data/massey_2018/rankings_through_20180311.clean.csv'
with open(output_file_name, 'w') as output_file:
for line in chunks[3]:
data = map(lambda s: s.strip(), line.split(','))
print >> output_file, ','.join(data)
for line in chunks[4]:
data = map(lambda s: s.strip(), line.split(','))
print >> output_file, ','.join(data)
#df = pandas.read_csv(output_file_name).drop('Unnamed: 74', axis=1)
df = pandas.read_csv(output_file_name).drop('Unnamed: 75', axis=1)
# +
# For missing ranks, use the median of all other rankers
# This happens, e.g., for rankers that only rank the top 25 or in other rare cases
# The median rank is helpfully provided in the data already
basic_cols = ['Team', 'Conf', 'WL', 'Rank', 'Mean', 'Trimmed', 'Median', 'StDev']
ranker_cols = list(set(df.columns) - set(basic_cols))
for ranker in ranker_cols:
df[ranker] = df[ranker].fillna(df['Median'])
# -
df.to_csv(output_file_name)
|
prepare_latest_rankings.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Homework: Multilingual Embedding-based Machine Translation (7 points)
# **In this homework** **<font color='red'>YOU</font>** will make machine translation system without using parallel corpora, alignment, attention, 100500 depth super-cool recurrent neural network and all that kind superstuff.
#
# But even without parallel corpora this system can be good enough (hopefully).
#
# For our system we choose two kindred Slavic languages: Ukrainian and Russian.
# ### Feel the difference!
#
# (_синій кіт_ vs. _синій кит_)
# 
# ### Frament of the Swadesh list for some slavic languages
#
# The Swadesh list is a lexicostatistical stuff. It's named after American linguist Morris Swadesh and contains basic lexis. This list are used to define subgroupings of languages, its relatedness.
#
# So we can see some kind of word invariance for different Slavic languages.
#
#
# | Russian | Belorussian | Ukrainian | Polish | Czech | Bulgarian |
# |-----------------|--------------------------|-------------------------|--------------------|-------------------------------|-----------------------|
# | женщина | жанчына, кабета, баба | жінка | kobieta | žena | жена |
# | мужчина | мужчына | чоловік, мужчина | mężczyzna | muž | мъж |
# | человек | чалавек | людина, чоловік | człowiek | člověk | човек |
# | ребёнок, дитя | дзіця, дзіцёнак, немаўля | дитина, дитя | dziecko | dítě | дете |
# | жена | жонка | дружина, жінка | żona | žena, manželka, choť | съпруга, жена |
# | муж | муж, гаспадар | чоловiк, муж | mąż | muž, manžel, choť | съпруг, мъж |
# | мать, мама | маці, матка | мати, матір, неня, мама | matka | matka, máma, 'стар.' mateř | майка |
# | отец, тятя | бацька, тата | батько, тато, татусь | ojciec | otec | баща, татко |
# | много | шмат, багата | багато | wiele | mnoho, hodně | много |
# | несколько | некалькі, колькі | декілька, кілька | kilka | několik, pár, trocha | няколко |
# | другой, иной | іншы | інший | inny | druhý, jiný | друг |
# | зверь, животное | жывёла, звер, істота | тварина, звір | zwierzę | zvíře | животно |
# | рыба | рыба | риба | ryba | ryba | риба |
# | птица | птушка | птах, птиця | ptak | pták | птица |
# | собака, пёс | сабака | собака, пес | pies | pes | куче, пес |
# | вошь | вош | воша | wesz | veš | въшка |
# | змея, гад | змяя | змія, гад | wąż | had | змия |
# | червь, червяк | чарвяк | хробак, черв'як | robak | červ | червей |
# | дерево | дрэва | дерево | drzewo | strom, dřevo | дърво |
# | лес | лес | ліс | las | les | гора, лес |
# | палка | кій, палка | палиця | patyk, pręt, pałka | hůl, klacek, prut, kůl, pálka | палка, пръчка, бастун |
# But the context distribution of these languages demonstrates even more invariance. And we can use this fact for our for our purposes.
# ## Data
import gensim
import numpy as np
from gensim.models import KeyedVectors
# Download embeddings here:
# * [cc.uk.300.vec.zip](https://yadi.sk/d/9CAeNsJiInoyUA)
# * [cc.ru.300.vec.zip](https://yadi.sk/d/3yG0-M4M8fypeQ)
# Load embeddings for ukrainian and russian.
uk_emb = KeyedVectors.load_word2vec_format("cc.uk.300.vec")
ru_emb = KeyedVectors.load_word2vec_format("cc.ru.300.vec")
ru_emb.most_similar([ru_emb["август"]], topn=10)
uk_emb.most_similar([uk_emb["серпень"]])
ru_emb.most_similar([uk_emb["серпень"]])
# Load small dictionaries for correspoinding words pairs as trainset and testset.
def load_word_pairs(filename):
uk_ru_pairs = []
uk_vectors = []
ru_vectors = []
with open(filename, "r") as inpf:
for line in inpf:
uk, ru = line.rstrip().split("\t")
if uk not in uk_emb or ru not in ru_emb:
continue
uk_ru_pairs.append((uk, ru))
uk_vectors.append(uk_emb[uk])
ru_vectors.append(ru_emb[ru])
return uk_ru_pairs, np.array(uk_vectors), np.array(ru_vectors)
uk_ru_train, X_train, Y_train = load_word_pairs("ukr_rus.train.txt")
uk_ru_test, X_test, Y_test = load_word_pairs("ukr_rus.test.txt")
# ## Embedding space mapping
# Let $x_i \in \mathrm{R}^d$ be the distributed representation of word $i$ in the source language, and $y_i \in \mathrm{R}^d$ is the vector representation of its translation. Our purpose is to learn such linear transform $W$ that minimizes euclidian distance between $Wx_i$ and $y_i$ for some subset of word embeddings. Thus we can formulate so-called Procrustes problem:
#
# $$W^*= \arg\min_W \sum_{i=1}^n||Wx_i - y_i||_2$$
# or
# $$W^*= \arg\min_W ||WX - Y||_F$$
#
# where $||*||_F$ - Frobenius norm.
#
# In Greek mythology, Procrustes or "the stretcher" was a rogue smith and bandit from Attica who attacked people by stretching them or cutting off their legs, so as to force them to fit the size of an iron bed. We make same bad things with source embedding space. Our Procrustean bed is target embedding space.
# 
# 
# But wait...$W^*= \arg\min_W \sum_{i=1}^n||Wx_i - y_i||_2$ looks like simple multiple linear regression (without intercept fit). So let's code.
# +
from sklearn.linear_model import LinearRegression
# YOUR CODE HERE
mapping = LinearRegression(fit_intercept=False)
mapping.fit(X_train, Y_train)
# -
# Let's take a look at neigbours of the vector of word _"серпень"_ (_"август"_ in Russian) after linear transform.
august = mapping.predict(uk_emb["серпень"].reshape(1, -1))
ru_emb.most_similar(august)
# We can see that neighbourhood of this embedding cosists of different months, but right variant is on the ninth place.
# As quality measure we will use precision top-1, top-5 and top-10 (for each transformed Ukrainian embedding we count how many right target pairs are found in top N nearest neighbours in Russian embedding space).
def precision(pairs, mapped_vectors, topn=1):
"""
:args:
pairs = list of right word pairs [(uk_word_0, ru_word_0), ...]
mapped_vectors = list of embeddings after mapping from source embedding space to destination embedding space
topn = the number of nearest neighbours in destination embedding space to choose from
:returns:
precision_val, float number, total number of words for those we can find right translation at top K.
"""
assert len(pairs) == len(mapped_vectors)
num_matches = 0
for i, (_, ru) in enumerate(pairs):
most_similar_words = [x[0] for x in ru_emb.most_similar([mapped_vectors[i]], topn=topn)]
if ru in most_similar_words:
num_matches += 1
precision_val = num_matches / len(pairs)
return precision_val
assert precision([("серпень", "август")], august, topn=5) == 0.0
assert precision([("серпень", "август")], august, topn=9) == 1.0
assert precision([("серпень", "август")], august, topn=10) == 1.0
assert precision(uk_ru_test, X_test) == 0.0
assert precision(uk_ru_test, Y_test) == 1.0
# +
precision_top1 = precision(uk_ru_test, mapping.predict(X_test), 1)
precision_top5 = precision(uk_ru_test, mapping.predict(X_test), 5)
assert precision_top1 >= 0.635
assert precision_top5 >= 0.813
# -
# ## Making it better (orthogonal Procrustean problem)
# .It can be shown (see original paper) that a self-consistent linear mapping between semantic spaces should be orthogonal.
# We can restrict transform $W$ to be orthogonal. Then we will solve next problem:
#
# $$W^*= \arg\min_W ||WX - Y||_F \text{, where: } W^TW = I$$
#
# $$I \text{- identity matrix}$$
#
# Instead of making yet another regression problem we can find optimal orthogonal transformation using singular value decomposition. It turns out that optimal transformation $W^*$ can be expressed via SVD components:
# $$X^TY=U\Sigma V^T\text{, singular value decompostion}$$
# $$W^*=UV^T$$
def learn_transform(X_train, Y_train):
"""
:returns: W* : float matrix[emb_dim x emb_dim] as defined in formulae above
"""
# YOU CODE HERE
U, S, V_t = np.linalg.svd(X_train.T@Y_train)
W = U@V_t
return W
W = learn_transform(X_train, Y_train)
ru_emb.most_similar([np.matmul(uk_emb["серпень"], W)])
assert precision(uk_ru_test, np.matmul(X_test, W), 1) >= 0.653
assert precision(uk_ru_test, np.matmul(X_test, W), 5) >= 0.824
# ## UK-RU Translator
# Now we are ready to make simple word-based translator: for earch word in source language in shared embedding space we find the nearest in target language.
#
with open("fairy_tale.txt", "r") as inpf:
uk_sentences = [line.rstrip().lower() for line in inpf]
def translate(sentence):
"""
:args:
sentence - sentence in Ukrainian (str)
:returns:
translation - sentence in Russian (str)
* find ukrainian embedding for each word in sentence
* transform ukrainian embedding vector
* find nearest russian word and replace
"""
# YOUR CODE HERE
sentence_tokens = sentence.split(' ')
result = []
for word in sentence_tokens:
try:
word_transl = ru_emb.most_similar([np.matmul(uk_emb[word], W)], topn=1)[0][0]
except:
word_transl = word
result.append(word_transl)
return ' '.join(result)
assert translate(".") == "."
assert translate("1 , 3") == "1 , 3"
assert translate("кіт зловив мишу") == "кот поймал мышку"
for sentence in uk_sentences:
print("src: {}\ndst: {}\n".format(sentence, translate(sentence)))
# Not so bad, right? We can easily improve translation using language model and not one but several nearest neighbours in shared embedding space. But next time.
# ## Would you like to learn more?
#
# ### Articles:
# * [Exploiting Similarities among Languages for Machine Translation](https://arxiv.org/pdf/1309.4168) - entry point for multilingual embedding studies by <NAME> (the author of W2V)
# * [Offline bilingual word vectors, orthogonal transformations and the inverted softmax](https://arxiv.org/pdf/1702.03859) - orthogonal transform for unsupervised MT
# * [Word Translation Without Parallel Data](https://arxiv.org/pdf/1710.04087)
# * [Loss in Translation: Learning Bilingual Word Mapping with a Retrieval Criterion](https://arxiv.org/pdf/1804.07745)
# * [Unsupervised Alignment of Embeddings with Wasserstein Procrustes](https://arxiv.org/pdf/1805.11222)
#
# ### Repos (with ready-to-use multilingual embeddings):
# * https://github.com/facebookresearch/MUSE
#
# * https://github.com/Babylonpartners/fastText_multilingual -
|
week01_embeddings/homework.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
SOLUTION = """
- - - - 1 - - 2 - -
1 2 - 1 2 - 1 - - 1
- 1 - - - - - 1 3 -
- - 1 - 9 3 1 3 - -
- 1 - - - - - - - 1
1 - - - - - - - 1 -
- - 3 1 3 9 - 1 - -
- 3 1 - - - - - 1 -
1 - - 1 - 2 1 - 2 1
- - 2 - - 1 - - - -
""".replace('\t', '').strip()
def flip(src):
for line in src.split('\n'):
print(str(''.join(reversed(line))))
flip(SOLUTION)
|
src/puzzle/examples/gph/Make Your Own Fillomino.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# %load_ext autoreload
# %autoreload 2
# %matplotlib inline
# -
#export
from exp.nb_02 import *
import torch.nn.functional as F
# ## Initial setup
# ### Data
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=1786)
mpl.rcParams['image.cmap'] = 'gray'
x_train,y_train,x_valid,y_valid = get_data()
n,m = x_train.shape
c = y_train.max()+1
nh = 50
class Model(nn.Module):
def __init__(self, n_in, nh, n_out):
super().__init__()
self.layers = [nn.Linear(n_in,nh), nn.ReLU(), nn.Linear(nh,n_out)]
def __call__(self, x):
for l in self.layers: x = l(x)
return x
model = Model(m, nh, 10)
pred = model(x_train)
# ### Cross entropy loss
# First, we will need to compute the softmax of our activations. This is defined by:
#
# $$\hbox{softmax(x)}_{i} = \frac{e^{x_{i}}}{e^{x_{0}} + e^{x_{1}} + \cdots + e^{x_{n-1}}}$$
#
# or more concisely:
#
# $$\hbox{softmax(x)}_{i} = \frac{e^{x_{i}}}{\sum_{0 \leq j \leq n-1} e^{x_{j}}}$$
#
# In practice, we will need the log of the softmax when we calculate the loss.
def log_softmax(x): return (x.exp()/(x.exp().sum(-1,keepdim=True))).log()
sm_pred = log_softmax(pred)
# The cross entropy loss for some target $x$ and some prediction $p(x)$ is given by:
#
# $$ -\sum x\, \log p(x) $$
#
# But since our $x$s are 1-hot encoded, this can be rewritten as $-\log(p_{i})$ where i is the index of the desired target.
# This can be done using numpy-style [integer array indexing](https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#integer-array-indexing). Note that PyTorch supports all the tricks in the advanced indexing methods discussed in that link.
y_train[:3]
sm_pred[[0,1,2], [5,0,4]]
y_train.shape[0]
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=2081)
def nll(input, target): return -input[range(target.shape[0]), target].mean()
loss = nll(sm_pred, y_train)
loss
# Note that the formula
#
# $$\log \left ( \frac{a}{b} \right ) = \log(a) - \log(b)$$
#
# gives a simplification when we compute the log softmax, which was previously defined as `(x.exp()/(x.exp().sum(-1,keepdim=True))).log()`
def log_softmax(x): return x - x.exp().sum(-1,keepdim=True).log()
test_near(nll(log_softmax(pred), y_train), loss)
# Then, there is a way to compute the log of the sum of exponentials in a more stable way, called the [LogSumExp trick](https://en.wikipedia.org/wiki/LogSumExp). The idea is to use the following formula:
#
# $$\log \left ( \sum_{j=1}^{n} e^{x_{j}} \right ) = \log \left ( e^{a} \sum_{j=1}^{n} e^{x_{j}-a} \right ) = a + \log \left ( \sum_{j=1}^{n} e^{x_{j}-a} \right )$$
#
# where a is the maximum of the $x_{j}$.
def logsumexp(x):
m = x.max(-1)[0]
return m + (x-m[:,None]).exp().sum(-1).log()
# This way, we will avoid an overflow when taking the exponential of a big activation. In PyTorch, this is already implemented for us.
test_near(logsumexp(pred), pred.logsumexp(-1))
# So we can use it for our `log_softmax` function.
def log_softmax(x): return x - x.logsumexp(-1,keepdim=True)
test_near(nll(log_softmax(pred), y_train), loss)
# Then use PyTorch's implementation.
test_near(F.nll_loss(F.log_softmax(pred, -1), y_train), loss)
# In PyTorch, `F.log_softmax` and `F.nll_loss` are combined in one optimized function, `F.cross_entropy`.
test_near(F.cross_entropy(pred, y_train), loss)
# ## Basic training loop
# Basically the training loop repeats over the following steps:
# - get the output of the model on a batch of inputs
# - compare the output to the labels we have and compute a loss
# - calculate the gradients of the loss with respect to every parameter of the model
# - update said parameters with those gradients to make them a little bit better
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=2542)
loss_func = F.cross_entropy
#export
def accuracy(out, yb): return (torch.argmax(out, dim=1)==yb).float().mean()
# +
bs=64 # batch size
xb = x_train[0:bs] # a mini-batch from x
preds = model(xb) # predictions
preds[0], preds.shape
# -
yb = y_train[0:bs]
loss_func(preds, yb)
accuracy(preds, yb)
lr = 0.5 # learning rate
epochs = 1 # how many epochs to train for
for epoch in range(epochs):
for i in range((n-1)//bs + 1):
# set_trace()
start_i = i*bs
end_i = start_i+bs
xb = x_train[start_i:end_i]
yb = y_train[start_i:end_i]
loss = loss_func(model(xb), yb)
loss.backward()
with torch.no_grad():
for l in model.layers:
if hasattr(l, 'weight'):
l.weight -= l.weight.grad * lr
l.bias -= l.bias.grad * lr
l.weight.grad.zero_()
l.bias .grad.zero_()
loss_func(model(xb), yb), accuracy(model(xb), yb)
# ## Using parameters and optim
# ### Parameters
# Use `nn.Module.__setattr__` and move relu to functional:
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=2818)
class Model(nn.Module):
def __init__(self, n_in, nh, n_out):
super().__init__()
self.l1 = nn.Linear(n_in,nh)
self.l2 = nn.Linear(nh,n_out)
def __call__(self, x): return self.l2(F.relu(self.l1(x)))
model = Model(m, nh, 10)
for name,l in model.named_children(): print(f"{name}: {l}")
model
model.l1
def fit():
for epoch in range(epochs):
for i in range((n-1)//bs + 1):
start_i = i*bs
end_i = start_i+bs
xb = x_train[start_i:end_i]
yb = y_train[start_i:end_i]
loss = loss_func(model(xb), yb)
loss.backward()
with torch.no_grad():
for p in model.parameters(): p -= p.grad * lr
model.zero_grad()
fit()
loss_func(model(xb), yb), accuracy(model(xb), yb)
# Behind the scenes, PyTorch overrides the `__setattr__` function in `nn.Module` so that the submodules you define are properly registered as parameters of the model.
class DummyModule():
def __init__(self, n_in, nh, n_out):
self._modules = {}
self.l1 = nn.Linear(n_in,nh)
self.l2 = nn.Linear(nh,n_out)
def __setattr__(self,k,v):
if not k.startswith("_"): self._modules[k] = v
super().__setattr__(k,v)
def __repr__(self): return f'{self._modules}'
def parameters(self):
for l in self._modules.values():
for p in l.parameters(): yield p
mdl = DummyModule(m,nh,10)
mdl
[o.shape for o in mdl.parameters()]
# ### Registering modules
# We can use the original `layers` approach, but we have to register the modules.
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=2997)
layers = [nn.Linear(m,nh), nn.ReLU(), nn.Linear(nh,10)]
class Model(nn.Module):
def __init__(self, layers):
super().__init__()
self.layers = layers
for i,l in enumerate(self.layers): self.add_module(f'layer_{i}', l)
def __call__(self, x):
for l in self.layers: x = l(x)
return x
model = Model(layers)
model
# ### nn.ModuleList
# `nn.ModuleList` does this for us.
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=3173)
class SequentialModel(nn.Module):
def __init__(self, layers):
super().__init__()
self.layers = nn.ModuleList(layers)
def __call__(self, x):
for l in self.layers: x = l(x)
return x
model = SequentialModel(layers)
model
fit()
loss_func(model(xb), yb), accuracy(model(xb), yb)
# ### nn.Sequential
# `nn.Sequential` is a convenient class which does the same as the above:
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=3199)
model = nn.Sequential(nn.Linear(m,nh), nn.ReLU(), nn.Linear(nh,10))
fit()
loss_func(model(xb), yb), accuracy(model(xb), yb)
# +
# nn.Sequential??
# -
model
# ### optim
# Let's replace our previous manually coded optimization step:
#
# ```python
# with torch.no_grad():
# for p in model.parameters(): p -= p.grad * lr
# model.zero_grad()
# ```
#
# and instead use just:
#
# ```python
# opt.step()
# opt.zero_grad()
# ```
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=3278)
class Optimizer():
def __init__(self, params, lr=0.5): self.params,self.lr=list(params),lr
def step(self):
with torch.no_grad():
for p in self.params: p -= p.grad * lr
def zero_grad(self):
for p in self.params: p.grad.data.zero_()
model = nn.Sequential(nn.Linear(m,nh), nn.ReLU(), nn.Linear(nh,10))
opt = Optimizer(model.parameters())
for epoch in range(epochs):
for i in range((n-1)//bs + 1):
start_i = i*bs
end_i = start_i+bs
xb = x_train[start_i:end_i]
yb = y_train[start_i:end_i]
pred = model(xb)
loss = loss_func(pred, yb)
loss.backward()
opt.step()
opt.zero_grad()
loss,acc = loss_func(model(xb), yb), accuracy(model(xb), yb)
loss,acc
# PyTorch already provides this exact functionality in `optim.SGD` (it also handles stuff like momentum, which we'll look at later - except we'll be doing it in a more flexible way!)
#export
from torch import optim
# +
# optim.SGD.step??
# -
def get_model():
model = nn.Sequential(nn.Linear(m,nh), nn.ReLU(), nn.Linear(nh,10))
return model, optim.SGD(model.parameters(), lr=lr)
model,opt = get_model()
loss_func(model(xb), yb)
for epoch in range(epochs):
for i in range((n-1)//bs + 1):
start_i = i*bs
end_i = start_i+bs
xb = x_train[start_i:end_i]
yb = y_train[start_i:end_i]
pred = model(xb)
loss = loss_func(pred, yb)
loss.backward()
opt.step()
opt.zero_grad()
loss,acc = loss_func(model(xb), yb), accuracy(model(xb), yb)
loss,acc
# Randomized tests can be very useful.
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=3442)
assert acc>0.7
# ## Dataset and DataLoader
# ### Dataset
# It's clunky to iterate through minibatches of x and y values separately:
#
# ```python
# xb = x_train[start_i:end_i]
# yb = y_train[start_i:end_i]
# ```
#
# Instead, let's do these two steps together, by introducing a `Dataset` class:
#
# ```python
# xb,yb = train_ds[i*bs : i*bs+bs]
# ```
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=3578)
#export
class Dataset():
def __init__(self, x, y): self.x,self.y = x,y
def __len__(self): return len(self.x)
def __getitem__(self, i): return self.x[i],self.y[i]
train_ds,valid_ds = Dataset(x_train, y_train),Dataset(x_valid, y_valid)
assert len(train_ds)==len(x_train)
assert len(valid_ds)==len(x_valid)
xb,yb = train_ds[0:5]
assert xb.shape==(5,28*28)
assert yb.shape==(5,)
xb,yb
model,opt = get_model()
for epoch in range(epochs):
for i in range((n-1)//bs + 1):
xb,yb = train_ds[i*bs : i*bs+bs]
pred = model(xb)
loss = loss_func(pred, yb)
loss.backward()
opt.step()
opt.zero_grad()
loss,acc = loss_func(model(xb), yb), accuracy(model(xb), yb)
assert acc>0.7
loss,acc
# ### DataLoader
# Previously, our loop iterated over batches (xb, yb) like this:
#
# ```python
# for i in range((n-1)//bs + 1):
# xb,yb = train_ds[i*bs : i*bs+bs]
# ...
# ```
#
# Let's make our loop much cleaner, using a data loader:
#
# ```python
# for xb,yb in train_dl:
# ...
# ```
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=3674)
class DataLoader():
def __init__(self, ds, bs): self.ds,self.bs = ds,bs
def __iter__(self):
for i in range(0, len(self.ds), self.bs): yield self.ds[i:i+self.bs]
train_dl = DataLoader(train_ds, bs)
valid_dl = DataLoader(valid_ds, bs)
xb,yb = next(iter(valid_dl))
assert xb.shape==(bs,28*28)
assert yb.shape==(bs,)
plt.imshow(xb[0].view(28,28))
yb[0]
model,opt = get_model()
def fit():
for epoch in range(epochs):
for xb,yb in train_dl:
pred = model(xb)
loss = loss_func(pred, yb)
loss.backward()
opt.step()
opt.zero_grad()
fit()
loss,acc = loss_func(model(xb), yb), accuracy(model(xb), yb)
assert acc>0.7
loss,acc
# ### Random sampling
# We want our training set to be in a random order, and that order should differ each iteration. But the validation set shouldn't be randomized.
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=3942)
class Sampler():
def __init__(self, ds, bs, shuffle=False):
self.n,self.bs,self.shuffle = len(ds),bs,shuffle
def __iter__(self):
self.idxs = torch.randperm(self.n) if self.shuffle else torch.arange(self.n)
for i in range(0, self.n, self.bs): yield self.idxs[i:i+self.bs]
small_ds = Dataset(*train_ds[:10])
s = Sampler(small_ds,3,False)
[o for o in s]
s = Sampler(small_ds,3,True)
[o for o in s]
# +
def collate(b):
xs,ys = zip(*b)
return torch.stack(xs),torch.stack(ys)
class DataLoader():
def __init__(self, ds, sampler, collate_fn=collate):
self.ds,self.sampler,self.collate_fn = ds,sampler,collate_fn
def __iter__(self):
for s in self.sampler: yield self.collate_fn([self.ds[i] for i in s])
# -
train_samp = Sampler(train_ds, bs, shuffle=True)
valid_samp = Sampler(valid_ds, bs, shuffle=False)
train_dl = DataLoader(train_ds, sampler=train_samp, collate_fn=collate)
valid_dl = DataLoader(valid_ds, sampler=valid_samp, collate_fn=collate)
xb,yb = next(iter(valid_dl))
plt.imshow(xb[0].view(28,28))
yb[0]
xb,yb = next(iter(train_dl))
plt.imshow(xb[0].view(28,28))
yb[0]
xb,yb = next(iter(train_dl))
plt.imshow(xb[0].view(28,28))
yb[0]
# +
model,opt = get_model()
fit()
loss,acc = loss_func(model(xb), yb), accuracy(model(xb), yb)
assert acc>0.7
loss,acc
# -
# ### PyTorch DataLoader
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=4171)
#export
from torch.utils.data import DataLoader, SequentialSampler, RandomSampler
train_dl = DataLoader(train_ds, bs, sampler=RandomSampler(train_ds), collate_fn=collate)
valid_dl = DataLoader(valid_ds, bs, sampler=SequentialSampler(valid_ds), collate_fn=collate)
model,opt = get_model()
fit()
loss_func(model(xb), yb), accuracy(model(xb), yb)
# PyTorch's defaults work fine for most things however:
train_dl = DataLoader(train_ds, bs, shuffle=True, drop_last=True)
valid_dl = DataLoader(valid_ds, bs, shuffle=False)
# +
model,opt = get_model()
fit()
loss,acc = loss_func(model(xb), yb), accuracy(model(xb), yb)
assert acc>0.7
loss,acc
# -
# Note that PyTorch's `DataLoader`, if you pass `num_workers`, will use multiple threads to call your `Dataset`.
# ## Validation
# You **always** should also have a [validation set](http://www.fast.ai/2017/11/13/validation-sets/), in order to identify if you are overfitting.
#
# We will calculate and print the validation loss at the end of each epoch.
#
# (Note that we always call `model.train()` before training, and `model.eval()` before inference, because these are used by layers such as `nn.BatchNorm2d` and `nn.Dropout` to ensure appropriate behaviour for these different phases.)
# [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=4260)
def fit(epochs, model, loss_func, opt, train_dl, valid_dl):
for epoch in range(epochs):
# Handle batchnorm / dropout
model.train()
# print(model.training)
for xb,yb in train_dl:
loss = loss_func(model(xb), yb)
loss.backward()
opt.step()
opt.zero_grad()
model.eval()
# print(model.training)
with torch.no_grad():
tot_loss,tot_acc = 0.,0.
for xb,yb in valid_dl:
pred = model(xb)
tot_loss += loss_func(pred, yb)
tot_acc += accuracy (pred,yb)
nv = len(valid_dl)
print(epoch, tot_loss/nv, tot_acc/nv)
return tot_loss/nv, tot_acc/nv
# *Question*: Are these validation results correct if batch size varies?
# `get_dls` returns dataloaders for the training and validation sets:
#export
def get_dls(train_ds, valid_ds, bs, **kwargs):
return (DataLoader(train_ds, batch_size=bs, shuffle=True, **kwargs),
DataLoader(valid_ds, batch_size=bs*2, **kwargs))
# Now, our whole process of obtaining the data loaders and fitting the model can be run in 3 lines of code:
train_dl,valid_dl = get_dls(train_ds, valid_ds, bs)
model,opt = get_model()
loss,acc = fit(5, model, loss_func, opt, train_dl, valid_dl)
assert acc>0.9
# ## Export
# !python notebook2script.py 03_minibatch_training.ipynb
|
nbs/dl2/03_minibatch_training.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
#
# ## Basics of Computation in Python
#
# ### Python
# - Programming language
# - High-level
# - Interpreted
# - Data science and machine learning
# ### Expressions
# - The Python interpreter can evaluate an expression
# - An expression alone doesn’t do anything
# - `3 + 2`
# - `8 + 2 * 3`
# - An expression alone is not a line of code (instruction)
# - Useful for testing
# - Bad for maintainability
#
#
# +
# Did you know? The command for commenting a block of code in Jupyter notebook is CTRL-/
# Highlight some lines of code and type CTRL-/ to comment or uncomment them all
# Try some expressions
3 + 2
# 3 + 2 * 8
# 8 - 4
# -
# ### Arithmetic Operators
# - Python’s basic arithmetic operators:
#
#
# | Operator | Meaning | Example |
# |----------|---------|---------|
# |`+`|add|`3+2`|
# |`-`|subtract|`5-2`|
# |`*`|multiply|`6*2`|
# |`\`|divide|`8/2`|
# |`**`|raise to the power|`2**3`|
# |`%`|modulus (remainder)|`7%3`|
# |`//`|floor division (integer division)|`7//3`|
#
#
# - The order of precedence among the arithmetic operators is:
# - First: expressions in parentheses
# - Second: exponentiation
# - Third: multiplication and division operators
# - Last: addition and subtraction operators
# +
# Try some arithmetic operators
# Notice how Python only outputs the value of the expression on the last line
2 + 3 * (8 + 2**3)
8%3
# -
# ### Comparison and Logical Operators
# - Evaluate to a Boolean value
# - Comparison operators
#
# | Operator | Meaning | Example |
# |----------|---------|---------|
# |`<`|add|`3 < 2`|
# |`>`|greater than|`3 > 2`|
# |`<=`|less than or equal to|`3 <= 3`|
# |`>=`|greater than or equal to|`5 >= 3`|
# |`==`|equal to|`4 == 2`|
# |`%`|not equal to|`4 != 2`|
#
# - Logical operators
#
# | Operator | Meaning | Example |
# |----------|---------|---------|
# |`and`|True if both operands are True|`3 > 2 and 4 != 2`|
# |`or`|True if at least one operand is True|`3 < 2 and 4 != 2`|
# |`not`|True if the operand is False|`not 4 == 3`|
#
# Try some logical operators
3 < 2 and 4 != 2
# ### Python Data Types
# - Every piece of data has a type
# - Basic Data Types
# | Name | Type | Example |
# |------|------|---------|
# |`int`|integer|`-27`|
# |`float`|floating point (decimal)|`27.1`|
# |`bool`|Boolean|`True`|
# |`str`|character string|`"hello"`|
#
# - There are many more built-in data types
# - Programmers can define their own custom data types
#
# ### Variables
# - A variable is a name for a memory area where data is stored
# - it allows data values to *change* rather than remain *constant*
# - Defined by initial assignment to a value
# - Variable names
# - should be meaningful, for readability
# - can contain letters, digits and underscore character
# - may not start with a digit
# - may not be a Python *reserved word*
# - The same variable can refer to values of any data type
# ### Assignment Operators
# - Assigns a value to a variable
# - Example: `val = 4`
# - Read it as: set `val` to `4`
# - Interpret it as: Put `4` into the memory area that `val` refers to
# - Operators
# - Simple assignment
#
# `size = 17.5`
# - The assignment expression evaluates to the assigned value
#
# `size := 17.5`
# - Shorthand (`+=`, `-=`, `*=`, etc.)
#
# `size += 2` is shorthand for `size = size + 2`
# Demonstrate some assignment operations
width = 4
#length := width
#length += 2
# area = length * width
# ### Data Type Conversions
# - A variable can refer to values of different types
# - Check the data type of a variable's value: `type(length)`
# - Convert a value to a different type (if legal)
#
# `val = 4
# fval = float(val)
# sval = str(fval)`
# - Note: a conversion function does not change the data type of the input parameter
# +
# Try conversions
val = 4
type(val)
# fval = float(val)
# type(fval)
# type(val)
# bval = bool(val) # what does this mean? what number is False?
# bval
# sval = str(fval)
# type(sval)
# sval
# sval = "hello"
# int(sval)
# -
# ### Input and Output
# - *Useful* programs take inoput and generate output
# - Command-line interface
# - Graphical user interface (GUI)
# - Files
# - Network sources
# - Databases
# ### Command-line input
# - Function `input(prompt)`
# - prints the *optional* prompt on the command line
# - waits for the user to type something
# - the text is sent to the program only after the user types enter/return
# - the entered data is always interpreted as text, *even if it's numeric*
# +
# Try getting some input
value = input( "Please enter a value: ")
value
# type(value)
# input()
# -
# ### Command-line output
# - Function `print()`
# - prints the value(s) passed to it
# - automatically converts data values to strings
# - goes to the next line by default
# - separates values with space by default
# - optional arguments can set different separator and end of line values
# - Format output using string formatting functions
# # Examples of output
#
# print( "Here is a message." )
# print( "Here is a value:", val ) # where did val come from?
# print( "Don't go to next line.", end = ' ' )
# print("more text")
# print("more text")
#
# ### Strings
# - A string is a complex data type
# - a *sequence* of characters that is *immutable*
# - individual characters are identified using indexing syntax: `s[position]`
# 
# - the general `len()` function returns the length of a string
#
# Experiment with indexing syntax
s = "birds"
print(s[3])
print(s[-1])
print(len(s))
type(s[3])
# ### String Operators
# - `+`
# - concatenate strings
# - `==` `!=`
# - test the equality of strings
# - `<` `<=` `>` `>=`
# - compare strings alphabetically
# String operators
s1 = "cat"
s2 = "dog"
s3 = "cat"
print(s1 + s2)
print(s1 == s3)
print(s2 < s1)
print("Dog" < "cat")
# ### Special and unprintable characters
# - Represented with *escape* sequences
# - preceded by backslash `\`
# - Common special characters
# |Character|Escape Sequence|
# |---------|---------------|
# |newline|`\n`|
# |tab|`\t`|
# |backslash|`\\`|
# |quotes|`\'` `\"`|
# Escape sequences
print("hello\n")
print("1\t2")
print("\xEA")
# ### String slicing
# - expanded indexing
# - a slice of a string is a new string, composed of characters from the initial string
# |Syntax|Result|
# |------|------|
# |`s[start]`|a single character|
# |`s[start:end]`|a substring|
# |`s[start:end:step]`|a selection of characters|
# - the end position is not inclusive (up to but not including *end*)
# - the step can be positive or negative
# - a negative step proceeds backwards through the string
#
# ### Empty and default values in slicing
# - the default step is `1`
# - the default end is `start+1`
# - an empty value for end means the end of the string (in the *step* direction)
# - an empty value for start means the start of the string (in the *step* direction)
# +
# What will this do?
# s[-1::-1]
# -
# ### String functions
# |Name|Behavior|
# |----|--------|
# |s.split()|Split a string into pieces based on a delimiter|
# |s.strip()|Remove leading/trailing whitespace or other characters|
# |s.upper()|Convert a string to uppercase|
# |s.lower()|Convert a string to lowercase|
# |s.isnumeric()|Return True if a string is numeric|
# |s.find()|Return the index of a substring|
# |s.replace()|Replace one substring with another|
# |*Many, many, more ...*|Look them up as needed|
# some string functions
s = "hello"
print(s.upper())
print(s)
str = s.upper()
print(str)
str = "I am a string."
print(str.replace("am", "am not"))
"222".isnumeric()
s = "Fox. Socks. Box. Knox. Knox in box. Fox in socks."
print(s[1])
print(s[-1])
print(s[:3])
print(s.replace("ocks", "ox"))
print(s[0] + s[5] + s[12])
|
.ipynb_checkpoints/ComputationBasics-checkpoint.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Entrainement - Set vins
# ## Abstract
# L'analyse conduite sur les outliers et la suppression des colonnes idoines d'une part et la définition d'une nouvelle variable par clustering d'autre part permet de maximiser le score d'algortihme de ML et DL
# The analysis conducted on the outliers and the deletion of the appropriate columns on the one hand and the definition of a new variable by clustering on the other hand makes it possible to maximize the algorithm score of ML and DL
# # Table: <a class="anchor" id="chapter0"></a>
# * [Bibliothèques utilisées](#chapter1)
# * [Setup & exploration statistique](#chapter2)
# * [Essai de modèles](#chapter3)
# * [Clustering et prédictions](#chapter4)
#
# # -----------------------------------------------------------------------------------------------------------
# ### Bibliothèqes utilisées <a class="anchor" id="chapter1"></a>
# * [retour Table](#chapter0)
# +
#Generique
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# reduction dimension
from sklearn.feature_selection import VarianceThreshold,RFE,RFECV,SelectKBest,f_regression
# ML
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import neighbors
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
from sklearn.model_selection import GridSearchCV
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score
# DL
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense,Dropout
import tensorflow as tf
import warnings
warnings.filterwarnings("ignore")
# -
# # -----------------------------------------------------------------------------------------------------------
# ### Setup & exploration statistique <a class="anchor" id="chapter2"></a>
# * [retour Table](#chapter0)
df = pd.read_csv('WineQT.csv')
# #### Revue de base:
# - Revue sur variables
# - Revue des doublons
# - Visibilité NAN
#
# Une vue d'ensemble des données
df
df.info()
# Que représente la variable Id ?
df.Id.value_counts()
# Il y a autant d'ID que d'entrée -> Il apparait ainsi que cette variable n'apporte pas d'info pertinente sur le jeu de donnée, il convient de la supprimer
df = df.drop(['Id'],axis = 1)
# A ce stade, il ne parait pas opportun de supprimer davantage de variable
# Présence de doublons ?
df.duplicated().sum()
# Note : il est intéressant de constater qu'il ya présence de doublons et que l'on vient de supprimer une variable pour laquelle chaque entrée présente une valeur distincte. Ainsi, si nous avions pratiqué l'analyse des doublons en amont, nous serions passé à côté de cette info dans la mesure où aucun doublon n'aurait été détecté.
# On procède à l'élimination des doublons et l'on confirme
df = df.drop_duplicates()
df.duplicated().sum()
# Présence de NaN ?
NAN = pd.DataFrame({'Count':df.isna().sum()})
NAN
# #### Revue statistique:
stat = round(df.describe(),3)
stat
# On affiche la distribution en diagramme boite à moustache afin de vérifier la présence de valeurs aberrantes:
# +
plt.figure(figsize=(20,20))
for k in range(0,len(df.columns)):
plt.subplot(4,3,k+1)
plt.boxplot(df[df.columns[k]])
plt.title(f'{df.columns[k]}')
Q3 = stat.loc['75%',df.columns[k]]
Q1 = stat.loc['25%',df.columns[k]]
borne_sup = Q3+1.5*(Q3-Q1)
borne_inf = Q1-1.5*(Q3-Q1)
plt.axhline(y=borne_sup)
plt.axhline(y=borne_inf)
plt.show()
# -
# On considère qu'une valeur est abérrante si elle est au delà ou en deça, respectivement de Q3 + 1.5 x (Q3-Q1) et Q1 - 1.5 x (Q3 - Q1), matérialisé sur les graphes précédants par les deux lignes horizontales bleues.
# On propose de créer un dataset miroir où chaque outlier sera codé à 1 de façon à pouvoir par la suite statuer sur les actions à entreprendre vis-à-vis des données.
miroir = df.copy()
# On crée une fonction qui permet de présenter l'information outlier
def outlier(x,i):
Q3 = stat.loc['75%',df.columns[i]]
Q1 = stat.loc['25%',df.columns[i]]
borne_sup = Q3+1.5*(Q3-Q1)
borne_inf = Q1-1.5*(Q3-Q1)
if x > borne_sup or x < borne_inf:
return 1
else:
return 0
# On applique cette fonction à l'ensemble du dataframe
for i in range(len(df.columns)):
miroir[df.columns[i]] = miroir[df.columns[i]].apply(lambda x: outlier(x,i))
miroir
# On présente les résultats dans un dataframe
# +
liste_0 =[]
liste_1 =[]
for i in range(len(df.columns)):
liste_0.append(miroir[df.columns[i]].value_counts()[0])
liste_1.append(miroir[df.columns[i]].value_counts()[1])
visu = pd.DataFrame({0:liste_0,1:liste_1},index = df.columns)
visu['%'] = round(100*visu[1]/(visu[1]+visu[0]),2)
visu
# -
# La proportion de valeur aberrante est plutot faible à l'exception des variables 'residual sugar' et 'chlorides'
# On cherche à présent à savoir comment sont distribuées ces valeurs abérrantes dans le dataset
miroir['somme'] = miroir.sum(axis = 1)
miroir.somme.value_counts()
# On apprend ainsi que 731 entrées ne présentent aucune valeurs abérrantes et 205 entrées seulement 1 valeur aberrante
miroir_bis = miroir.drop(['residual sugar','chlorides','somme'],axis = 1)
miroir_bis['somme'] = miroir_bis.sum(axis = 1)
miroir_bis.somme.value_counts()
# On constate qu'en supprimant les variables à relativement "forte" présence de valeurs abérrantes,i.e "Chloride" et residual sugar" ainsi que les lignes présentant au moins 1 valeur abérrante, on dispose d'un jeu de donnée représentant 81% du jeu de donnée initiale sans valeurs abérrantes contre 71% si on garde toutes les variables
# - Afin de tendre vers un modèle statistiquement robuste, les choix suivants sont réalisés:
# - suppression des variables "Chlorides" et "residual sugar"
# - suppression de toute entrée présentant au moins une valeur abérrante
to_suppr = miroir_bis[miroir_bis['somme']>=1].index
df = df.drop(['residual sugar','chlorides'],axis = 1)
df = df.drop(to_suppr)
df
# +
plt.figure(figsize=(20,20))
for k in range(0,len(df.columns)):
plt.subplot(4,3,k+1)
plt.boxplot(df[df.columns[k]])
plt.title(f'{df.columns[k]}')
plt.show()
# -
# # -----------------------------------------------------------------------------------------------------------
# ### Essai de modèles: <a class="anchor" id="chapter3"></a>
# * [retour Table](#chapter0)
# Définition des features / target
# On imagine que la variable pertinente à prédire ici est la qualité
features = df.drop(['quality'],axis = 1)
target = df['quality']
# Préparation / normalisation des données
# +
X_train,X_test,y_train,y_test = train_test_split(features,target,test_size = 0.2)
scaler = preprocessing.StandardScaler().fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
# -
# MODEL N°1 - REGRESSION LOGISTIQUE
logreg = LogisticRegression()
logreg.fit(X_train_scaled,y_train)
logreg.score(X_test_scaled,y_test)
# MODEL N°1_bis - REGRESSION LOGISTIQUE - optimisé
# +
clf_lr = LogisticRegression()
params_lr = {'solver':['liblinear','lbfgs','newton-cg','saga'],'C' :[10**(i) for i in range(-4,5)]}
gridcv = GridSearchCV(clf_lr,param_grid =params_lr,scoring = 'accuracy',cv = 5)
grille = gridcv.fit(X_train_scaled,y_train)
grille.score(X_test_scaled,y_test)
# -
# MODEL N°2 - KNN
K7NN = neighbors.KNeighborsClassifier(n_neighbors=7,metric ='minkowski')
K7NN.fit(X_train_scaled,y_train)
K7NN.score(X_test_scaled,y_test)
# MODEL N°2_bis - KNN optimisé
# +
score_minko = []
score_man =[]
score_cheb =[]
meta = [score_minko,score_man,score_cheb]
termes =['minkowski','manhattan','chebyshev']
for i,terme in enumerate(termes):
for k in range(1,40):
knn = neighbors.KNeighborsClassifier(n_neighbors=k,metric =terme)
knn.fit(X_train_scaled,y_train)
y_pred = knn.predict(X_test)
score =accuracy_score(y_test,y_pred)
meta[i].append(score)
k = [i for i in range(1,40)]
plt.plot(k,score_minko,label ='minko')
plt.plot(k,score_man,label ='man')
plt.plot(k,score_cheb,label = 'cheb')
plt.legend()
plt.show()
# -
np.argmax(score_man)
K6NN = neighbors.KNeighborsClassifier(n_neighbors=np.argmax(score_man),metric ='manhattan')
K6NN.fit(X_train_scaled,y_train)
K6NN.score(X_test_scaled,y_test)
# La démarche d'optimisation n'est pas fructueuse
# MODEL N°x - RESEAU NEURONNE DENSE
# +
model = Sequential()
model.add(tf.keras.Input(shape =(9)))
model.add(Dense(124,activation = 'relu'))
model.add(Dropout(0.2))
model.add(Dense(124,activation = 'relu'))
model.add(Dropout(0.2))
model.add(Dense(528,activation = 'relu'))
model.add(Dropout(0.2))
model.add(Dense(124,activation = 'relu'))
model.add(Dropout(0.2))
model.add(Dense(10,activation ='softmax'))
model.compile(loss =tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=False, reduction="auto", name="sparse_categorical_crossentropy"
),optimizer ='adam',metrics = 'accuracy')
epok = 50
training_history = model.fit(X_train_scaled,y_train,validation_data=(X_test_scaled,y_test),batch_size =10,epochs = epok)
# +
train_acc = training_history.history['accuracy']
val_acc = training_history.history['val_accuracy']
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.plot(np.arange(1,epok +1,1),training_history.history['accuracy'], label='Training Accuracy', color='blue')
plt.plot(np.arange(1,epok +1,1),training_history.history['val_accuracy'], label='Validation Accuracy', color='red')
plt.legend()
plt.show()
# -
# Un score si bas s'explique peut-être par la mauvaise définition de la variable "quality" ?
# # -----------------------------------------------------------------------------------------------------------
# ## Clustering et prédictions <a class="anchor" id="chapter4"></a>
# * [retour Table](#chapter0)
# On va " laisser " le jeu de donnée définir le nombre de catégorie pertinente, par clustering
# Il nous faut en premier lieu déterminer le nombre optimal de cluster
# +
range_n_clusters =[2,3,4,5,6,7]
s_scores =[]
for n_cluster in range_n_clusters:
cluster = AgglomerativeClustering(n_clusters = n_cluster)
cluster.fit(features)
labels = cluster.labels_
s_score = silhouette_score(df,labels,metric ='euclidean')
s_scores.append(s_score)
# -
plt.plot(range_n_clusters,s_scores)
# Il apparait que 2 semble un nombre optimal de classe pour ce problème.
# On procède à une classification non supervisée de sorte à produire une nouvelle variable 'LABEL' que l'on associera au jeu de donnée
# +
cluster = AgglomerativeClustering(n_clusters = 2)
cluster.fit(features)
labels = cluster.labels_
LABEL = pd.Series(labels)
df_new = pd.concat([df.reset_index().drop(['index'],axis = 1),LABEL],axis= 1).rename(columns={0:'LABEL'})
df_new
# -
# On prépare à nouveau le jeu de donnée
# +
FEATURES = df_new.drop(['LABEL','quality'],axis = 1)
TARGET = df_new['LABEL']
X_TRAIN,X_TEST,Y_TRAIN,Y_TEST = train_test_split(FEATURES,TARGET,test_size = 0.2)
scaler = preprocessing.StandardScaler().fit(X_TRAIN)
X_TRAIN_SCALED = scaler.transform(X_TRAIN)
X_TEST_SCALED = scaler.transform(X_TEST)
# -
FEATURES
# On essaie à nouveau un modèle de régression logistique
LOGREG = LogisticRegression()
LOGREG.fit(X_TRAIN_SCALED,Y_TRAIN)
LOGREG.score(X_TEST_SCALED,Y_TEST)
# +
MODEL = Sequential()
MODEL.add(tf.keras.Input(shape =(9)))
MODEL.add(Dense(124,activation = 'relu'))
MODEL.add(Dropout(0.2))
MODEL.add(Dense(124,activation = 'relu'))
MODEL.add(Dropout(0.2))
MODEL.add(Dense(528,activation = 'relu'))
MODEL.add(Dropout(0.2))
MODEL.add(Dense(124,activation = 'relu'))
MODEL.add(Dropout(0.2))
MODEL.add(Dense(1,activation ='sigmoid'))
MODEL.compile(loss ="binary_crossentropy",optimizer ='adam',metrics = 'binary_accuracy')
epok = 50
training_history = MODEL.fit(X_TRAIN_SCALED,Y_TRAIN,validation_data=(X_TEST_SCALED,Y_TEST),batch_size =10,epochs = epok)
# +
train_acc = training_history.history['binary_accuracy']
val_acc = training_history.history['val_binary_accuracy']
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.plot(np.arange(1,epok +1,1),training_history.history['binary_accuracy'], label='Training Accuracy', color='blue')
plt.plot(np.arange(1,epok +1,1),training_history.history['val_binary_accuracy'], label='Validation Accuracy', color='red')
plt.legend()
plt.show()
# -
# Il semble que l'on a gagné à utiliser une nouvelle variable LABEL avec seulement deux classes. Il pourrait être objecté que cette variable LABEL ne se base sur rien de concret mais ce serait occulter le fait que:
# - d'une part la variable 'quality' ne présente elle aussi pas de justification à priori
# - d'autre part la variable 'LABEL' a été générée à partir du jeu de donnée, suite à la recherche du meilleur nombre de classe.
# Si l'on fait varier le nombre de classe de LABEL, on baisse invariablement en score ce qui tend à démontrer la pertinence de la démarche
# +
score =[]
for i in range(2,10):
cluster = AgglomerativeClustering(n_clusters = i)
cluster.fit(features)
labels = cluster.labels_
LABEL = pd.Series(labels)
df_new = pd.concat([df.reset_index().drop(['index'],axis = 1),LABEL],axis= 1).rename(columns={0:'LABEL'})
FEATURES = df_new.drop(['LABEL','quality'],axis = 1)
TARGET = df_new['LABEL']
X_TRAIN,X_TEST,Y_TRAIN,Y_TEST = train_test_split(FEATURES,TARGET,test_size = 0.2)
scaler = preprocessing.StandardScaler().fit(X_TRAIN)
X_TRAIN_SCALED = scaler.transform(X_TRAIN)
X_TEST_SCALED = scaler.transform(X_TEST)
LOGREG = LogisticRegression()
LOGREG.fit(X_TRAIN_SCALED,Y_TRAIN)
score.append(LOGREG.score(X_TEST_SCALED,Y_TEST))
# -
plt.plot([i for i in range(2,10)],score,label ='Score')
plt.title('Evolution du score de precision en fonction du nombre de cluster')
plt.xlabel('Nombre de cluster')
plt.ylabel('Score')
plt.show()
# Il est possible de tolérer moins de précision, via l'augmentation du nombre de classe si cela se traduit par une amélioration du chiffre de vente, eu égard à la proposition de fourchette de prix par label correspondant à plusieurs types de consommateurs.
# In fine, les classes de "LABEL" vont regrouper des vins dont le gout va dépendre de l'ensemble des variables proposées. Il est attendu que le fait d'avoir regroupé les vins en utilisant l'algorithme est plus pertinent en terme de gout et de variabilité de gout que si cela avait été réalisé manuellement sur la base d'une ou deux variables.
# Il eut été intéressant de fournir les noms des vins de façon à soumettre à des connaisseurs les regroupements proposés.
# * [retour Table](#chapter0)
|
Exploration statistique - ML - Grid search - DNN - Clustering.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python (rl)
# language: python
# name: rl
# ---
# # Debug trained MCTS agent
# +
# %matplotlib inline
import numpy as np
import sys
import logging
from matplotlib import pyplot as plt
import torch
sys.path.append("../../")
from ginkgo_rl import GinkgoLikelihood1DEnv, MCTSAgent
# +
logging.basicConfig(
format='%(message)s',
datefmt='%H:%M',
level=logging.DEBUG
)
for key in logging.Logger.manager.loggerDict:
if "ginkgo_rl" not in key:
logging.getLogger(key).setLevel(logging.ERROR)
# -
env = GinkgoLikelihood1DEnv()
agent = MCTSAgent(env, verbose=1)
agent.load_state_dict(torch.load("../data/runs/mcts_20200901_174303/model.pty"))
# ## Let's play an episode
# +
# Initialize episode
state = env.reset()
done = False
log_likelihood = 0.
errors = 0
reward = 0.0
agent.set_env(env)
agent.eval()
# Render initial state
env.render()
while not done:
# Agent step
action, agent_info = agent.predict(state)
# Environment step
next_state, next_reward, done, info = env.step(action)
env.render()
# Book keeping
log_likelihood += next_reward
errors += int(info["legal"])
agent.update(state, reward, action, done, next_state, next_reward=reward, num_episode=0, **agent_info)
reward, state = next_reward, next_state
# -
|
experiments/debug/debug_mcts.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Matplotlib Tutorial
# Have you ever thought what reports would be like without visualizations to represent and understand the data with which you work?
#
# Reading articles would be tedious and unfriendly to readers. Visualizations are very important, in the world of Machine Learning, where few people understand how the data is being processed, it is important to communicate them in a friendly way, where anyone, even non-technical people, can understand what is being done.
#
# The visualizations play a very important role, with them we can observe trends, even before applying any algorithm.
# In this tutorial we will learn how to perform the following visualization step by step, understanding each line of code.
#
# <img src="./Sample-english.jpg">
#
#
# We will use the [Matplotlib](https://matplotlib.org/) library along with its `pyplot` module.
#
# According to the documentation, matplotlib is a library for creating static and animated displays with Python. Matplotlib makes things easy even if they seem hard. This library helps us:
#
# * Create quality visualizations.
# * Make graphs and interactive figures in which you can zoom, scroll and update them.
# * Custom views.
# * Export them to different formats.
#
# And much more, all available in the [Documentation](https://matplotlib.org/).
#
# ## IImporting the libraries.
import numpy as np
import matplotlib.pyplot as plt
# For this tutorial we will not need to import datasets, with the help of `Numpy` we will generate the necessary data for the graph.
# We create 300 numbers ranging from the range -pi to pi
x = np.linspace(-np.pi, np.pi, 300, endpoint=True)
# We will use the function sine and cosine
sine, cosine = np.sin(x), np.cos(x)
# ## Begining with the tutorial
# ### Understanding the figure and plot methods
# In matplotlib we work with figures, to start with the tutorial, we will create the one that is going to be needed for the project. If you want to read more about it, I invite you to visit the documentation. [matplotlib.pyplot.figure](https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.figure.html).
#
# Likewise, we will create the sine and cosine plot with the data that was generated using the `plot` method. For more information you can visit [matplotlib.pyplot.plot](https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.plot.html)
#
# > **Note:** We will use the `show` method to prevent matplotlib from printing a series of information related to the plot stored in memory.
# Creating the figure
plt.figure(figsize=(10,8))
plt.plot(x, sine)
plt.plot(x, cosine)
plt.show()
# We start with some graphs that seem simple, but this is where your imagination has no limits, we can format the plots, for this matplotlib offers us a series of parameters that we can configure to our liking, such as:
#
# - **Color:** Choose the color of the graph.
# - **Linewidth:** Choose the thickness of the line.
# - **Linestyle:** We can choose whether to use solid, dotted, dashed lines, among others available [Here](https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D.set_linestyle)
# - **Label:** Assign a name or description to the line.
# - For more parameters, visit the documentation.
#
# If we look at our example, the sine line is Red, and the cosine line is Blue, and the lines are thicker and each graph has a label assigned to it. Let's add this.
plt.figure(figsize=(10,8))
plt.plot(x, sine, color='red', linewidth=1.5, linestyle='-', label='Sine')
plt.plot(x, cosine, color='blue', linewidth=1.5, linestyle='-', label='Cosine')
plt.show()
# ### Working with the axes.
# Note that the example has no axes, we have to remove them from our graph. To do this, we can access them with the `gca` method of `pyplot`.
#
# A figure is made up of 4 axes. Top, Bottom, Left and Right. In the example, the right axis and the one Top are not used, in addition the left and the one below are found in a different position.
#
# We will proceed to apply these changes with the `spines` method by accessing the axes of the figure with the `gca` method of `pyplot`. `Spines` provides us with a series of parameters that we can add using the `set` function, and the `set_color` subfunction, we will rely on this to assign the axes that we are going to remove a `set_color` none.
# +
plt.figure(figsize=(10,8))
plt.plot(x, sine, color='red', linewidth=1.5, linestyle='-', label='Sine')
plt.plot(x, cosine, color='blue', linewidth=1.5, linestyle='-', label='Cosine')
axes = plt.gca()
# Deleting the right axe
axes.spines['right'].set_color('none')
# Deleting the top axe
axes.spines['top'].set_color('none')
plt.show()
# -
# We have eliminated two axes, the other two if we are going to need them, but in a different position, for this, with the same `spines` method and with the `set_position` parameter we will achieve this result. Find more information [Here](https://matplotlib.org/3.5.1/api/spines_api.html#matplotlib.spines.Spine.set_position)
# +
plt.figure(figsize=(10,8))
plt.plot(x, sine, color='red', linewidth=1.5, linestyle='-', label='Sine')
plt.plot(x, cosine, color='blue', linewidth=1.5, linestyle='-', label='Cosine')
axes = plt.gca()
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
# We position the axis according to the data and centered on zero
axes.spines['bottom'].set_position(('data', 0))
axes.spines['left'].set_position(('data', 0))
plt.show()
# -
# ### Changing axis data $x$ and $y$
# The axes data is different from the one shown in the example, we have to show them the same. The `xticks` and `yticks` method will help us.
#
# In addition, thanks to a `for` loop we can go through that data and give it the format we want.
# +
plt.figure(figsize=(10,8))
plt.plot(x, sine, color='red', linewidth=1.5, linestyle='-', label='Sine')
plt.plot(x, cosine, color='blue', linewidth=1.5, linestyle='-', label='Cosine')
axes = plt.gca()
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
axes.spines['bottom'].set_position(('data', 0))
axes.spines['left'].set_position(('data', 0))
# We add the information we want to appear on the axes
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$'])
plt.yticks(np.linspace(-1,1,3, endpoint=True),
['-1', '', '+1'])
for label in axes.get_xticklabels() + axes.get_yticklabels():
label.set_fontsize(16)
plt.show()
# -
# ### Visual aid, the legend method
# We see that the example graph provides us with a visual aid to identify which line corresponds to which function.
#
# To add this help we can use the `legend` method, giving it a location specified by us or simply letting matplotlib decide which is best for the example.
# +
plt.figure(figsize=(10,8))
plt.plot(x, sine, color='red', linewidth=1.5, linestyle='-', label='Sine')
plt.plot(x, cosine, color='blue', linewidth=1.5, linestyle='-', label='Cosine')
axes = plt.gca()
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
axes.spines['bottom'].set_position(('data', 0))
axes.spines['left'].set_position(('data', 0))
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$'])
plt.yticks(np.linspace(-1,1,3, endpoint=True),
['-1', '', '+1'])
for label in axes.get_xticklabels() + axes.get_yticklabels():
label.set_fontsize(16)
# Adding the legend visual aid
plt.legend(loc='upper left')
plt.show()
# -
# ### Multigraphics, Scatter and Plot together in one figure.
# Now let's add the blue and red point that appears on the graph. We will use a chart type called `scatter`. The points are at $\frac{2}{3}$ of $\pi$ in X, and at $y$ the corresponding sine and cosine value for that $\frac{2}{3}$ of $\pi$.
#
# The dotted lines can be added with the `plot` method used earlier to plot the graph of the sine and cosine function. The coordinates we will use are the same ones that will be used for the points added with `scatter`. We have to indicate two coordinates, point where the line starts, point where it ends. In our example:
#
# * Starts at $(x=\frac{2\pi}{3}, y=0)$.
# * Ends in $(x=\frac{2\pi}{3}, y=sin/cos(x))$.
# +
plt.figure(figsize=(10,8))
plt.plot(x, sine, color='red', linewidth=1.5, linestyle='-', label='Sine')
plt.plot(x, cosine, color='blue', linewidth=1.5, linestyle='-', label='Cosine')
axes = plt.gca()
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
axes.spines['bottom'].set_position(('data', 0))
axes.spines['left'].set_position(('data', 0))
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$'])
plt.yticks(np.linspace(-1,1,3, endpoint=True),
['-1', '', '+1'])
for label in axes.get_xticklabels() + axes.get_yticklabels():
label.set_fontsize(16)
plt.legend(loc='upper left')
# We calculate the value of 2/3 of pi
x_0 = 2*np.pi/3
# We paint the red dotted line
plt.plot([x_0,x_0], [0, np.sin(x_0)], color='red', linewidth=2.5, linestyle='--')
# We paint the blue dotted line
plt.plot([x_0,x_0], [0, np.cos(x_0)], color='blue', linewidth=2.5, linestyle='--')
# We paint the red point of size 50
plt.scatter(x_0, np.sin(x_0), 50, color='red')
# We paint the blue point of size 50
plt.scatter(x_0, np.cos(x_0), 50, color='blue')
plt.show()
# -
# ### Add value to your visualizations by placing annotations.
# We only have to add some annotations, for this we use the `annotate` method, with which, with the help of coordinates, we can indicate a certain point with an arrow.
#
# * First parameter: Annotation.
# * Second parameter: Coordinates
# * Rest of parameters are configurable and according to the style that each user wants to give it.
# +
plt.figure(figsize=(10,8))
plt.plot(x, sine, color='red', linewidth=1.5, linestyle='-', label='Sine')
plt.plot(x, cosine, color='blue', linewidth=1.5, linestyle='-', label='Cosine')
axes = plt.gca()
axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
axes.spines['bottom'].set_position(('data', 0))
axes.spines['left'].set_position(('data', 0))
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$'])
plt.yticks(np.linspace(-1,1,3, endpoint=True),
['-1', '', '+1'])
for label in axes.get_xticklabels() + axes.get_yticklabels():
label.set_fontsize(16)
plt.legend(loc='upper left')
x_0 = 2*np.pi/3
plt.plot([x_0,x_0], [0, np.sin(x_0)], color='red', linewidth=2.5, linestyle='--')
plt.plot([x_0,x_0], [0, np.cos(x_0)], color='blue', linewidth=2.5, linestyle='--')
plt.scatter(x_0, np.sin(x_0), 50, color='red')
plt.scatter(x_0, np.cos(x_0), 50, color='blue')
#Annotation for the point of sine
plt.annotate(r'$\sin(\frac{2\pi}{3}) = \frac{\sqrt{3}}{2}$',
xy = (x_0, np.sin(x_0)),
xycoords = 'data',
xytext = (+10,+30),
textcoords= 'offset points',
fontsize = 16,
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=.2'))
# Annotation for the point of cosine
plt.annotate(r'$\cos(\frac{2\pi}{3}) = -\frac{1}{2}$',
xy = (x_0, np.cos(x_0)),
xycoords = 'data',
xytext = (-100,-50),
textcoords= 'offset points',
fontsize = 16,
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=.2'))
plt.show()
# -
# With this we have finished our tutorial, and I hope you have learned a lot about how visualizations are handled with `matplotlib`.
#
# Finally, a tip that can be very useful, save your visualizations, you can do this with a simple line of code.
#
# ``` python
# plt.savefig("File_Name.extension", bbox_inches='tight')
# ```
# ## Keep learning
# I invite you to continue investigating and investigating within the documentation, `Matplotlib` is a very powerful tool and you can take great advantage of it to visualize your data and make sense of your research related to Data Science.
#
# Remember that a visualization says more than a thousand words and is the best means by which you can communicate your research and projects, this to facilitate understanding for technicians and non-technicians.
|
Plot tutorial/Matplotlib-Tutorial-English-Version.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
animals = ["cat", "cow", "dog", "bull"]
my_information = {"name" : "JY", "phone_num" : "010-9354", "email" : "<PASSWORD>"}
for i in animals:
print i
for my_information in my_information.items():
key, value = my_information #대입 연산자
print key
print value
for key, value in my_information.items():
print key
print value
friends = ["jy","jd","ey","hy"]
for i in range(len(friends)):
if i == 2:
friends[i] = "Gd"
print(friends[i])
friends.index("jy")
for i in friends:
index = friends.index(i)
if index == 3:
friends[index] = "GD"
print friends[index]
for i in enumerate(friends):
print i
for index, value in enumerate(friends):
if index == 3:
friends[index] = "GD"
print friends[index]
|
Practice/04-13.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Code to clean and concatenate csv file and initiate text analysis
#
# @Jorge de Leon
# This code cleans csv files and concatenates files to a pandas dataframe
# ## Set-up
import pandas as pd
from glob import glob
# Create list of files that will be concatenated
test_files = sorted(glob('theguardian/articles/microsoft/*.csv'))
test_files
# +
#intialize empty list that we will append dataframes to
all_files = []
#write a for loop that will go through each of the file name through globbing and the end result will be the list of dataframes
for file in test_files:
try:
articles = pd.read_csv(file)
all_files.append(articles)
except pd.errors.EmptyDataError:
print('Note: filename.csv was empty. Skipping')
continue #will skip the rest of the block and move to next file
# -
# The dataframe will be used for data analysis
print(all_articles)
|
python/.ipynb_checkpoints/Clean CSV files -checkpoint.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Writing out a USGSCSM ISD from a PDS3 Cassini ISS image
# +
import os
import json
import ale
from ale.drivers.cassini_drivers import CassiniIssPds3LabelNaifSpiceDriver
from ale.formatters.usgscsm_formatter import to_usgscsm
# -
# ## Instantiating an ALE driver
#
# ALE drivers are objects that define how to acquire common ISD keys from an input image format, in this case we are reading in a PDS3 image using NAIF SPICE kernels for exterior orientation data. If the driver utilizes NAIF SPICE kernels, it is implemented as a [context manager](https://docs.python.org/3/reference/datamodel.html#context-managers) and will furnish metakernels when entering the context (i.e. when entering the `with` block) and free the metakernels on exit. This maintains the integrity of spicelib's internal data structures. These driver objects are short-lived and are input to a formatter function that consumes the API to create a serializable file format. `ale.formatters` contains available formatter functions.
#
# The default config file is located at `ale/config.yml` and is copied into your home directory at `.ale/config.yml` on first use of the library. The config file can be modified using a text editor. `ale.config` is loaded into memory as a dictionary. It is used to find metakernels for different missions. For example, there is an entry for cassini that points to `/usgs/cpkgs/isis3/data/cassini/kernels/mk/` by default. If you want to use your own metakernels, you will need to udpate this path. For example, if the metakernels are located in `/data/cassini/mk/` the cassini entry should be updated with this path. If you are using the default metakernels, then you do not need to update the path.
#
# ALE has a two step process for writing out an ISD: 1. Instantiate your driver (in this case `CassiniIssPds3LabelNaifSpiceDriver`) within a context and 2. pass the driver object into a formatter (in this case, `to_usgscsm`).
#
# Requirements:
# * A PDS3 Cassini ISS image
# * NAIF metakernels installed
# * Config file path for Cassini (ale.config.cassini) pointing to the Cassini NAIF metakernel directory
# * A conda environment with ALE installed into it usisng the `conda install` command or created using the environment.yml file at the base of ALE.
# +
# printing config displays the yaml formatted string
print(ale.config)
# config object is a dictionary so it has the same access patterns
print('Cassini spice directory:', ale.config['cassini'])
# updating config for new LRO path in this notebook
# Note: this will not change the path in `.ale/config.yml`. This change only lives in the notebook.
# ale.config['cassini'] = '/data/cassini/mk/'
# +
# change to desired PDS3 image path
file_name = '/home/kberry/dev/ale/ale/N1702360370_1.LBL'
# metakernels are furnished when entering the context (with block) with a driver instance
# most driver constructors simply accept an image path
with CassiniIssPds3LabelNaifSpiceDriver(file_name) as driver:
# pass driver instance into formatter function
usgscsmString = to_usgscsm(driver)
# -
# ### Write ISD to disk
#
# ALE formatter functions generally return bytes or a string that can be written out to disk. ALE's USGSCSM formatter function returns a JSON encoded string that can be written out using any JSON library.
#
# USGSCSM requires the ISD to be colocated with the image file with a `.json` extension in place of the image extension.
# +
# Load the json string into a dict
usgscsm_dict = json.loads(usgscsmString)
# Write the dict out to the associated file
json_file = os.path.splitext(file_name)[0] + '.json'
# Save off the json and read it back in to check if
# the json exists and was formatted correctly
with open(json_file, 'w') as fp:
json.dump(usgscsm_dict, fp)
with open(json_file, 'r') as fp:
usgscsm_dict = json.load(fp)
usgscsm_dict.keys()
|
notebooks/write_CassiniIssPds3LabelNaifSpiceDriver.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: hydrosar
# language: python
# name: conda-env-.local-hydrosar-py
# ---
# <img src="../Master/NotebookAddons/HydroSARbanner.jpg" width="100%" />
# <font face="Calibri">
# <br>
# <font size="6"> <b>Flood Mapping from Single Sentinel-1 SAR Images</b><img style="padding: 7px" src="../Master/NotebookAddons/UAFLogo_A_647.png" width="170" align="right"/></font>
#
# <br>
# <font size="4"> <b> <NAME>, University of Alaska Fairbanks</b> <br>
# </font>
#
# <font size="3">This notebook presents the SAR-based flood mapping approach developed and used in the HydroSAR project. In its general concepts, the approach follows a methodology developed by the German Aerospace Center and published in <cite><a href="https://www.tandfonline.com/doi/full/10.1080/01431161.2016.1192304"><i>Sentinel-1-based flood mapping: a fully automated processing chain</i></a> by Twele et al.</cite>. The approach is based on radiometrically terrain corrected (RTC processed) Sentinel-1 SAR data and applies a dynamic thresholding method followed by fuzzy-logic-based post processing procedure. This notebook has both steps of this process implemented, but by default, the fuzzy logic step is deactivated to save processing time. The notebook will explain how the fuzzy logic post processing step can be activated should full performance processing be of interest.
#
# The approach is based on image amplitude data and is capable of detecting standing surface water. Note that flooding under vegetation will not be detected by this approach.
# </font>
# <hr>
# + pycharm={"name": "#%%\n"}
# %%javascript
var kernel = Jupyter.notebook.kernel;
var command = ["notebookUrl = ",
"'", window.location, "'" ].join('')
kernel.execute(command)
# +
from IPython.display import Markdown
from IPython.display import display
# user = !echo $JUPYTERHUB_USER
# env = !echo $CONDA_PREFIX
if env[0] == '':
env[0] = 'Python 3 (base)'
if env[0] != '/home/jovyan/.local/envs/hydrosar':
display(Markdown(f'<text style=color:red><strong>WARNING:</strong></text>'))
display(Markdown(f'<text style=color:red>This notebook should be run using the "hydrosar" conda environment.</text>'))
display(Markdown(f'<text style=color:red>It is currently using the "{env[0].split("/")[-1]}" environment.</text>'))
display(Markdown(f'<text style=color:red>Select "hydrosar" from the "Change Kernel" submenu of the "Kernel" menu.</text>'))
display(Markdown(f'<text style=color:red>If the "hydrosar" environment is not present, use <a href="{notebookUrl.split("/user")[0]}/user/{user[0]}/notebooks/conda_environments/Create_OSL_Conda_Environments.ipynb"> Create_OSL_Conda_Environments.ipynb </a> to create it.</text>'))
display(Markdown(f'<text style=color:red>Note that you must restart your server after creating a new environment before it is usable by notebooks.</text>'))
# -
# # General Methodology and Workflow
# <font face="Calibri" size="3">The workflow of the Sentinel-1-based processing chain, as outlined in the figure below, is composed of the following main elements:
# <ol>
# <li><i><b>Find relevant SAR data</b> over your area of interest at the <a href="https://search.asf.alaska.edu/#/">Alaska Satellite Facility's SAR archive</a>,</i></li>
# <li><i><b>Perform geometric and radiometric terrain correction</b> using the RTC processing flow by <a href="https://www.gamma-rs.ch/">GAMMA Remote Sensing</a>,</i></li>
# <li><b>initial flood detection</b> using automatic thresholding,</li>
# <li><b>fuzzy-logic-based classification refinement</b>,</li>
# <li><b>final classification into permanent and flood waters</b> using auxiliary data, and</li>
# <li><b>dissemination of the results</b>.</li>
# </ol>
#
# <b><i>Steps 1 and 2</i></b> of this workflow are operationally implemented in the Alaska Satellite Facility's Hybrid Pluggable Processing Pipeline (HyP3) environment and accessible to the public at the <a href="https://hyp3.asf.alaska.edu/">HyP3 Website</a>.
# <img style= "padding: 7px" src="https://courses.edx.org/asset-v1:AlaskaX+SAR-401+3T2020+type@asset+block@Watermappingworkflow2.jpg" width="70%"/>
# </font>
# # Flood Mapping Procedure
# + [markdown] heading_collapsed=true
# ## Loading Python Libraries
# + hidden=true
# %%capture
import os
import glob
from typing import Tuple
import json
import pandas as pd
from osgeo import gdal
from osgeo import osr
import numpy as np
import rasterio
import pyproj
import skfuzzy
# %matplotlib notebook
import matplotlib.pyplot as plt # for add_subplot, axis, figure, imshow, legend, plot, set_axis_off, set_data,
# set_title, set_xlabel, set_ylabel, set_ylim, subplots, title, twinx
import ipywidgets as ui
import asf_notebook as asfn
asfn.jupytertheme_matplotlib_format()
# + [markdown] heading_collapsed=true
# ## Write Some Helper Scripts
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Write a function to pad an image, so it may be split into tiles with consistent dimensions</b></font>
# + hidden=true
def pad_image(image: np.ndarray, to: int) -> np.ndarray:
height, width = image.shape
n_rows, n_cols = get_tile_row_col_count(height, width, to)
new_height = n_rows * to
new_width = n_cols * to
padded = np.zeros((new_height, new_width))
padded[:image.shape[0], :image.shape[1]] = image
return padded
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Write a function to tile an image</b></font>
# + hidden=true
#def tile_image(image: np.ndarray, width: int = 200, height: int = 200) -> np.ndarray:
def tile_image(image: np.ndarray, width, height) -> np.ndarray:
_nrows, _ncols = image.shape
_strides = image.strides
nrows, _m = divmod(_nrows, height)
ncols, _n = divmod(_ncols, width)
assert _m == 0, "Image must be evenly tileable. Please pad it first"
assert _n == 0, "Image must be evenly tileable. Please pad it first"
return np.lib.stride_tricks.as_strided(
np.ravel(image),
shape=(nrows, ncols, height, width),
strides=(height * _strides[0], width * _strides[1], *_strides),
writeable=False
).reshape(nrows * ncols, height, width)
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Write a function for Kittler-Illingworth Thresholding</b></font>
# + hidden=true
def Kittler(im):
"""
The reimplementation of Kittler-Illingworth Thresholding algorithm by <NAME>
Works on 8-bit images only
Original Matlab code: https://www.mathworks.com/matlabcentral/fileexchange/45685-kittler-illingworth-thresholding
Paper: <NAME>. & <NAME>. Minimum error thresholding. Pattern Recognit. 19, 41–47 (1986).
"""
test = im.ravel()
tindex = np.nonzero(test>0)
h,g = np.histogram(test[tindex],256,[0,256])
h = h.astype(np.float)
g = g.astype(np.float)
g = g[:-1]
c = np.cumsum(h)
m = np.cumsum(h * g)
s = np.cumsum(h * g**2)
sigma_f = np.sqrt(s/c - (m/c)**2)
cb = c[-1] - c
mb = m[-1] - m
sb = s[-1] - s
sigma_b = np.sqrt(sb/cb - (mb/cb)**2)
p = c / c[-1]
v = p * np.log10(sigma_f) + (1-p)*np.log10(sigma_b) - p*np.log10(p) - (1-p)*np.log10(1-p)
v[~np.isfinite(v)] = np.inf
idx = np.argmin(v)
t = g[idx]
return t
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Write a function for multi-class Expectation Maximization Thresholding to replace Kittler-Illingworth</b></font>
# + hidden=true
def EMSeg_opt(image, number_of_classes):
image_copy = image.copy()
image_copy2 = np.ma.filled(image.astype(float), np.nan) # needed for valid posterior_lookup keys
image = image.flatten()
minimum = np.amin(image)
image = image - minimum + 1
maximum = np.amax(image)
size = image.size
histogram = make_histogram(image)
nonzero_indices = np.nonzero(histogram)[0]
histogram = histogram[nonzero_indices]
histogram = histogram.flatten()
class_means = (
(np.arange(number_of_classes) + 1) * maximum /
(number_of_classes + 1)
)
class_variances = np.ones((number_of_classes)) * maximum
class_proportions = np.ones((number_of_classes)) * 1 / number_of_classes
sml = np.mean(np.diff(nonzero_indices)) / 1000
iteration = 0
while(True):
class_likelihood = make_distribution(
class_means, class_variances, class_proportions, nonzero_indices
)
sum_likelihood = np.sum(class_likelihood, 1) + np.finfo(
class_likelihood[0][0]).eps
log_likelihood = np.sum(histogram * np.log(sum_likelihood))
for j in range(0, number_of_classes):
class_posterior_probability = (
histogram * class_likelihood[:,j] / sum_likelihood
)
class_proportions[j] = np.sum(class_posterior_probability)
class_means[j] = (
np.sum(nonzero_indices * class_posterior_probability)
/ class_proportions[j]
)
vr = (nonzero_indices - class_means[j])
class_variances[j] = (
np.sum(vr *vr * class_posterior_probability)
/ class_proportions[j] +sml
)
del class_posterior_probability, vr
class_proportions = class_proportions + 1e-3
class_proportions = class_proportions / np.sum(class_proportions)
class_likelihood = make_distribution(
class_means, class_variances, class_proportions, nonzero_indices
)
sum_likelihood = np.sum(class_likelihood, 1) + np.finfo(
class_likelihood[0,0]).eps
del class_likelihood
new_log_likelihood = np.sum(histogram * np.log(sum_likelihood))
del sum_likelihood
if((new_log_likelihood - log_likelihood) < 0.000001):
break
iteration = iteration + 1
del log_likelihood, new_log_likelihood
class_means = class_means + minimum - 1
s = image_copy.shape
posterior = np.zeros((s[0], s[1], number_of_classes))
posterior_lookup = dict()
for i in range(0, s[0]):
for j in range(0, s[1]):
pixel_val = image_copy2[i,j]
if pixel_val in posterior_lookup:
for n in range(0, number_of_classes):
posterior[i,j,n] = posterior_lookup[pixel_val][n]
else:
posterior_lookup.update({pixel_val: [0]*number_of_classes})
for n in range(0, number_of_classes):
x = make_distribution(
class_means[n], class_variances[n], class_proportions[n],
image_copy[i,j]
)
posterior[i,j,n] = x * class_proportions[n]
posterior_lookup[pixel_val][n] = posterior[i,j,n]
return posterior, class_means, class_variances, class_proportions
def make_histogram(image):
image = image.flatten()
indices = np.nonzero(np.isnan(image))
image[indices] = 0
indices = np.nonzero(np.isinf(image))
image[indices] = 0
del indices
size = image.size
maximum = int(np.ceil(np.amax(image)) + 1)
#maximum = (np.ceil(np.amax(image)) + 1)
histogram = np.zeros((1, maximum))
for i in range(0,size):
#floor_value = int(np.floor(image[i]))
floor_value = np.floor(image[i]).astype(np.uint8)
#floor_value = (np.floor(image[i]))
if floor_value > 0 and floor_value < maximum - 1:
temp1 = image[i] - floor_value
temp2 = 1 - temp1
histogram[0,floor_value] = histogram[0,floor_value] + temp1
histogram[0,floor_value - 1] = histogram[0,floor_value - 1] + temp2
histogram = np.convolve(histogram[0], [1,2,3,2,1])
histogram = histogram[2:(histogram.size - 3)]
histogram = histogram / np.sum(histogram)
return histogram
def make_distribution(m, v, g, x):
x = x.flatten()
m = m.flatten()
v = v.flatten()
g = g.flatten()
y = np.zeros((len(x), m.shape[0]))
for i in range(0,m.shape[0]):
d = x - m[i]
amp = g[i] / np.sqrt(2*np.pi*v[i])
y[:,i] = amp * np.exp(-0.5 * (d * d) / v[i])
return y
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Write a function to calculate the number of rows and columns of tiles needed to tile an image to a given size</b></font>
# + hidden=true
def get_tile_row_col_count(height: int, width: int, tile_size: int) -> Tuple[int, int]:
return int(np.ceil(height / tile_size)), int(np.ceil(width / tile_size))
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Write a function to extract the tiff dates from a wildcard path:</b> </font>
# + hidden=true
def get_dates(paths):
dates = []
pths = glob.glob(paths)
for p in pths:
date = p.split('/')[-1].split("_")[0]
dates.append(date)
dates.sort()
return dates
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Write a function to save a mask</b></font>
# + hidden=true
def write_mask_to_file(mask: np.ndarray, file_name: str, projection: str, geo_transform: str) -> None:
(width, height) = mask.shape
out_image = gdal.GetDriverByName('GTiff').Create(
file_name, height, width, bands=1
)
out_image.SetProjection(projection)
out_image.SetGeoTransform(geo_transform)
out_image.GetRasterBand(1).WriteArray(mask)
out_image.GetRasterBand(1).SetNoDataValue(0)
out_image.FlushCache()
def gdal_write(ary, geoTransform, fileformat="GTiff", filename='jupyter_rocks.tif', format=gdal.GDT_Float64, nodata=None, srs_proj4='+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'):
'''gdal_write(ary, geoTransform, format="GTiff", filename='jupyter_rocks.tif', format=gdal.GDT_Float64 nodata=None, srs_proj4='+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
ary: 2D array.
geoTransform: [top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution]
format: "GTiff"
'''
if ary.ndim ==2:
Ny, Nx = ary.shape
Nb = 1;
elif ary.ndim==3:
Ny,Nx,Nb=ary.shape
else:
print("Input array has to be 2D or 3D.")
return None
driver = gdal.GetDriverByName(fileformat)
ds = driver.Create(filename, Nx, Ny, Nb, gdal.GDT_Float64)
#ds.SetGeoTransform( ... ) # define GeoTransform tuple
# top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
ds.SetGeoTransform( geoTransform )
srs=osr.SpatialReference()
srs.ImportFromProj4(srs_proj4)
ds.SetProjection(srs.ExportToWkt() );
if nodata is not None:
ds.GetRasterBand(1).SetNoDataValue(0);
if Nb==1:
ds.GetRasterBand(1).WriteArray(ary)
else:
for b in range(Nb):
ds.GetRasterBand(b+1).WriteArray(ary[:,:,b])
ds = None
#print("File written to: " + filename);
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Some additional helper functions</b></font>
# + hidden=true
class PathSelector():
def __init__(self,start_dir,select_file=True):
self.file = None
self.select_file = select_file
self.cwd = start_dir
self.select = ui.SelectMultiple(options=['init'],value=(),rows=10,description='')
self.accord = ui.Accordion(children=[self.select])
self.accord.selected_index = None # Start closed (showing path only)
self.refresh(self.cwd)
self.select.observe(self.on_update,'value')
def on_update(self,change):
if len(change['new']) > 0:
self.refresh(change['new'][0])
def refresh(self,item):
path = os.path.abspath(os.path.join(self.cwd,item))
if os.path.isfile(path):
if self.select_file:
self.accord.set_title(0,path)
self.file = path
self.accord.selected_index = None
else:
self.select.value = ()
else: # os.path.isdir(path)
self.file = None
self.cwd = path
# Build list of files and dirs
keys = ['[..]'];
for item in os.listdir(path):
if item[0] == '.':
continue
elif os.path.isdir(os.path.join(path,item)):
keys.append('['+item+']');
else:
keys.append(item);
# Sort and create list of output values
keys.sort(key=str.lower)
vals = []
for k in keys:
if k[0] == '[':
vals.append(k[1:-1]) # strip off brackets
else:
vals.append(k)
# Update widget
self.accord.set_title(0,path)
self.select.options = list(zip(keys,vals))
with self.select.hold_trait_notifications():
self.select.value = ()
def get_proj4(filename):
f=rasterio.open(filename)
return pyproj.Proj(f.crs, preserve_units=True) #used in pysheds
def gdal_read(filename, ndtype=np.float64):
'''
z=readData('/path/to/file')
'''
ds = gdal.Open(filename)
return np.array(ds.GetRasterBand(1).ReadAsArray()).astype(ndtype);
def gdal_get_geotransform(filename):
'''
[top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution]=gdal_get_geotransform('/path/to/file')
'''
#http://stackoverflow.com/questions/2922532/obtain-latitude-and-longitude-from-a-geotiff-file
ds = gdal.Open(filename)
return ds.GetGeoTransform()
def fill_nan(arr):
"""
filled_arr=fill_nan(arr)
Fills Not-a-number values in arr using astropy.
"""
kernel = astropy.convolution.Gaussian2DKernel(x_stddev=3) #kernel x_size=8*stddev
arr_type=arr.dtype
with warnings.catch_warnings():
warnings.simplefilter("ignore")
while np.any(np.isnan(arr)):
arr = astropy.convolution.interpolate_replace_nans(arr.astype(float), kernel, convolve=astropy.convolution.convolve)
return arr.astype(arr_type)
# + [markdown] heading_collapsed=true
# ## Load SAR Data Sets to Process
# + hidden=true
def get_tiff_paths(paths: str) -> list:
# tiff_paths = !ls $paths | sort -t_ -k5,5
return tiff_paths
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Reading a SAR Data Stack:</b>
#
# There are two data sets available for this notebook: Option ```fleven = 1``` is a flood mapping example for Eastern India and shows flood extents during the summer 2020 period. Option ```flevent = 2``` is a data set over El Salvador, acquired as Tropical Storm Amanda passed over the country. While damages occurred in the area. Not much evidence of the storm can be extracted from the data. This may be related to the limited spatial extent of local flooding events or due to the heavy vegation of the country. </font>
# + hidden=true
# Pick Dataset to Analyze
flevent = 1 # Options: 1 - 2020 Bangladesh & Eastern India Event | 2 - Guayaquil flood of 2016-2017
# + hidden=true
if flevent == 1:
name="BangladeshFloodMapping"
tiff_dir = path = f"/home/jovyan/notebooks/SAR_Training/English/HydroSAR/{name}"
asfn.new_directory(tiff_dir)
os.chdir(tiff_dir)
print(f"Current working directory: {os.getcwd()}")
time_series_path = f"s3://asf-jupyter-data/{name}.tar.gz"
time_series = os.path.basename(time_series_path)
# !aws --region=us-east-1 --no-sign-request s3 cp $time_series_path $time_series
# !tar -xvzf {name}.tar.gz
# !rm *.tar.gz
else:
name="TSAmandaElSalvador"
tiff_dir = path = f"/home/jovyan/notebooks/SAR_Training/English/HydroSAR/{name}"
asfn.new_directory(tiff_dir)
os.chdir(tiff_dir)
print(f"Current working directory: {os.getcwd()}")
time_series_path = f"s3://asf-jupyter-data/{name}.tar.gz"
time_series = os.path.basename(time_series_path)
# !aws --region=us-east-1 --no-sign-request s3 cp $time_series_path $time_series
# !tar -xvzf {name}.tar.gz
# !rm *.tar.gz
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Move into the parent directory of the directory containing the data and create a directory in which to store the water masks</b></font>
# + hidden=true
analysis_directory = tiff_dir
os.chdir(tiff_dir)
mask_directory = f'{analysis_directory}/Water_Masks'
asfn.new_directory(mask_directory)
print(f"Current working directory: {os.getcwd()}")
paths = f"{tiff_dir}/*_V*.tif*"
if os.path.exists(tiff_dir):
tiff_paths = get_tiff_paths(paths)
# +
class SARDualPolError(Exception):
"""
Raise when expecting dual-pol SAR data
but single-pol found instead
"""
pass
vv_wild = f"{tiff_dir}/*_VV.tif*"
vh_wild = f"{tiff_dir}/*_VH.tif*"
if os.path.exists(tiff_dir):
vh_paths = get_tiff_paths(vh_wild)
vv_paths = get_tiff_paths(vv_wild)
for i, pth in enumerate(vv_paths):
vh = f"{pth.split('_V')[0]}_VH{os.path.splitext(pth)[1]}"
if vh not in vh_paths:
raise SARDualPolError(f"Found {pth} but not {vh}")
for i, pth in enumerate(vh_paths):
vv = f"{pth.split('_V')[0]}_VV{os.path.splitext(pth)[1]}"
if vv not in vv_paths:
raise SARDualPolError(f"Found {pth} but not {vv}")
print(f"Success: dual-pol data found")
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Write a function to create a dictionary containing lists of each vv/vh pair</b></font>
# + hidden=true
def group_polarizations(tiff_paths: list) -> dict:
pths = {}
for tiff in tiff_paths:
product_name = tiff.split('.')[0][:-2]
if product_name in pths:
pths[product_name].append(tiff)
else:
pths.update({product_name: [tiff]})
pths[product_name].sort()
return pths
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Write a function to confirm the presence of both VV and VH images in all image sets</b></font>
# + hidden=true
def confirm_dual_polarizations(paths: dict) -> bool:
for p in paths:
if len(paths[p]) == 2:
if ('vv' not in paths[p][1] and 'VV' not in paths[p][1]) or \
('vh' not in paths[p][0] and 'VH' not in paths[p][0]):
return False
return True
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Create a dictionary of VV/VH pairs and check it for completeness</b></font>
# + hidden=true
grouped_pths = group_polarizations(tiff_paths)
if not confirm_dual_polarizations(grouped_pths):
print("ERROR: AI_Water requires both VV and VH polarizations.")
else:
print("Confirmed presence of VV and VH polarities for each product.")
#print(grouped_pths) #uncomment to print VV/VH path pairs
# + [markdown] heading_collapsed=true
# ## Load HAND Layer for your AOI and Create HAND-Exclusion Mask (HAND-EM)
# + [markdown] hidden=true
# <font face="Calibri" size="3"><font color='rgba(200,0,0,0.2)'><b>Note:</b></font> This notebook expects the HAND layer to be of the same extent, resolution, and projection as the SAR image stack. This can easily be fixed in future versions of the notebook. The HAND layer you will be using meets all of these requirements.
#
# <b>Please pick the file ```Bangladesh_Training_DEM_hand.tif``` using the path selector in the code cell below!</b></font>
# + hidden=true
print("Choose your HAND layer:")
f = PathSelector('.')
display(f.accord)
# + hidden=true
class NoHANDLayerException(Exception):
"""
Raised when expecting path to HAND layer but none found
"""
pass
#load HAND and derive HAND-EM
Hthresh = 15
HAND_file=f.accord.get_title(0)
print(f"Selected HAND: {HAND_file}")
try:
HAND_gT=gdal_get_geotransform(HAND_file)
except AttributeError:
raise NoHANDLayerException("You must select a HAND layer in the previous code cell")
HAND_proj4=get_proj4(HAND_file)
info = (gdal.Info(HAND_file, options = ['-json']))
info = json.dumps(info)
info = (json.loads(info))['coordinateSystem']['wkt']
Hzone = info.split('ID')[-1].split(',')[1][0:-2]
Hproj_type = info.split('ID')[-1].split('"')[1]
HAND=gdal_read(HAND_file)
hand = np.nan_to_num(HAND)
# Create Binary HAND-EM
Hmask = hand < Hthresh
handem = np.zeros_like(hand)
sel = np.ones_like(hand)
handem[Hmask] = sel[Hmask]
# + hidden=true
fig = plt.figure(figsize=(9, 5))
plt.suptitle('Height Above Nearest Drainage [HAND] (m)')
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
vmin = np.percentile(hand, 5)
vmax = np.percentile(hand, 95)
hh = ax1.imshow(hand, cmap='jet', vmin=vmin, vmax=vmax)
ax1.set_title('HAND [m]')
ax1.grid()
fig.colorbar(hh,ax=ax1)
ax2.imshow(handem, cmap='gray')
ax2.set_title('HAND-EM')
ax2.grid()
# + [markdown] heading_collapsed=true
# ## Do Initial Flood Mapping using Adaptive Dynamic Thresholding
# + [markdown] hidden=true
# <font face="Calibri" size="4"><b>A bit of background on the approach:</b></font>
#
# <font face="Calibri" size="3">An automatic tile-based thresholding procedure (Martinis, Twele, and Voigt 2009) is used to generate an initial land/water classification. The selection of tiles is performed on a bilevel quadtree structure with parent level $L^+$ and child level $L^−$:
#
# 1. Firstly, the entire image is separated into quadratic non-overlapping parent tiles on level $L^+$ with a size of $100 \times 100$ pixels. Each parent object is further represented by four quadratic child objects on a second level $L^−$. The tile selection process is based on statistical hierarchical relations between parent and child objects.
# 2. A number of parent tiles is automatically selected that offer the highest (>95% quantile) coefficient of variation $\frac{\sigma}{\mu}$ on $L^+$ of the mean backscatter values of the respective child objects on $L^−$. This criterion serves as a measure of the degree of variation within a tile and can therefore be used as an indicator of the probability that a tile is characterized by spatial inhomogeneity and contain more than one semantic class. The selected parent objects should also have a mean individual backscatter value lower than the mean of all parent tiles on $L^+$. This ensures that tiles lying on the boundary between water and no water areas are selected. In case that no tiles fulfil these criteria, the tile size on $L^+$ and $L^−$ is halved and the quantile for the tile selection is reduced to 90% to guarantee a successful tile selection also in data with a relatively low extent of water surfaces or with smaller dispersed water bodies.
# 3. To improve the robustness of the automatic threshold derivation we restrict the tile selection in Step (3) to only pixels situated in flood-prone regions as defined by a HAND-based binary Exclustion Mask (HAND-EM). To create the HAND-EM layer, a threshold is applied to a Height Above Nearest Drainage(HAND) data set to identify non-flood prone areas. A threshold value of $\geq 15m$ is used. The HAND-EM further is shrunk by one pixel using an 8-neighbour function to account for potential geometric inaccuracies between the exclude layer and SAR data. Tiles are only considered in case less than 20% of its data pixels are excluded by HAND-EM.
# 4. Out of the number of the initially selected tiles, a limited number of $N$ parent tiles are finally chosen for threshold computation. This selection is accomplished by ranking the parent tiles according to the standard deviation of the mean backscatter values of the respective child objects. Tiles with the highest values are chosen. Extensive testing yielded that $N = 5$ is a sufficient number of parent tiles for threshold computation.
# 5. A multi-mode Expectation Maximization thresholding approach is then employed to derive local threshold values using a cost function which is based on the statistical parameterization of the sub-histograms of all selected tiles. In order to derive a global (i.e. scenebased) threshold, the locally derived thresholds are combined by computing their arithmetic mean.
# 6. Using the dynamically calculated threshold, both the VV and VH scenes are thresholded for creating an initial surface water extent map.
# 7. The surface water extent maps derived from the VV and VH channel are combined to arrive at a combined intial surface water extent mask that is further refined in a post processing (Section 2.6).
# + [markdown] hidden=true
# <font face="Calibri" size="4"><b>Now Let's do the Work:</b></font>
# + hidden=true
# define some variables you might want to change
precentile = 0.95 # Standard deviation percentile threshold for pivotal tile selection
tilesize = 100 # Setting tile size to use in thresholding algorithm
tilesize2 = 50
Hpick = 0.8 # Threshold for required fraction of valid HAND-EM pixels per tile
vv_corr = -17.0 # VV threshold to use if threshold calculation did not succeed
vh_corr = -24.0 # VH threshold to use if threshold calculation did not succeed
# Tile up HAND-EM data
handem_p = pad_image(handem, tilesize)
hand_tiles = tile_image(handem_p,width=tilesize,height=tilesize)
Hsum = np.sum(hand_tiles, axis=(1,2))
Hpercent = Hsum/(tilesize*tilesize)
# Now do adaptive threshold selection
vv_thresholds = np.array([])
vh_thresholds = np.array([])
floodarea = np.array([])
vh_thresholds_corr = np.array([])
vv_thresholds_corr = np.array([])
posterior_lookup = dict()
for i, pair in enumerate(grouped_pths):
print(f"Processing pair {i+1} of {len(grouped_pths)}")
for tiff in grouped_pths[pair]:
f = gdal.Open(tiff)
img_array = f.ReadAsArray()
original_shape = img_array.shape
n_rows, n_cols = get_tile_row_col_count(*original_shape, tile_size=tilesize)
print(f'tiff: {tiff}')
if 'vv' in tiff or 'VV' in tiff:
vv_array = pad_image(f.ReadAsArray(), tilesize)
invalid_pixels = np.nonzero(vv_array == 0.0)
vv_tiles = tile_image(vv_array,width=tilesize,height=tilesize)
a = np.shape(vv_tiles)
vv_std = np.zeros(a[0])
vvt_masked = np.ma.masked_where(vv_tiles==0, vv_tiles)
vv_picktiles = np.zeros_like(vv_tiles)
for k in range(a[0]):
vv_subtiles = tile_image(vvt_masked[k,:,:],width=tilesize2,height=tilesize2)
vvst_mean = np.ma.mean(vv_subtiles, axis=(1,2))
vvst_std = np.ma.std(vvst_mean)
vv_std[k] = np.ma.std(vvst_mean)
# find tiles with largest standard deviations
vv_mean = np.ma.median(vvt_masked, axis=(1,2))
x_vv = np.sort(vv_std/vv_mean)
y_vv = np.arange(1, x_vv.size+1) / x_vv.size
percentile2 = precentile
sort_index = 0
while np.size(sort_index) < 5:
threshold_index_vv = np.ma.min(np.where(y_vv>percentile2))
threshold_vv = x_vv[threshold_index_vv]
#sd_select_vv = np.nonzero(vv_std/vv_mean>threshold_vv)
s_select_vv = np.nonzero(vv_std/vv_mean>threshold_vv)
h_select_vv = np.nonzero(Hpercent > Hpick) # Includes HAND-EM in selection
sd_select_vv = np.intersect1d(s_select_vv, h_select_vv)
# find tiles with mean values lower than the average mean
omean_vv = np.ma.median(vv_mean[h_select_vv])
mean_select_vv = np.nonzero(vv_mean<omean_vv)
# Intersect tiles with large std with tiles that have small means
msdselect_vv = np.intersect1d(sd_select_vv, mean_select_vv)
sort_index = np.flipud(np.argsort(vv_std[msdselect_vv]))
percentile2 = percentile2 - 0.01
finalselect_vv = sort_index[0:5]
# find local thresholds for 5 "best" tiles in the image
l_thresh_vv = np.zeros(5)
EMthresh_vv = np.zeros(5)
temp = np.ma.masked_where(vv_array==0, vv_array)
dbvv = np.ma.log10(temp)+30
scaling = 256/(np.mean(dbvv) + 3*np.std(dbvv))
#scaling = 256/(np.mean(vv_array) + 3*np.std(vv_array))
dbtile = np.ma.log10(vvt_masked)+30
for k in range(5):
test = dbtile[msdselect_vh[finalselect_vh[k]]] * scaling
#test = vvt_masked[msdselect_vv[finalselect_vv[k]]] * scaling
A = np.around(test)
A = A.astype(int)
#t_thresh = Kittler(A)
[posterior, cm, cv, cp] = EMSeg_opt(A, 3)
sorti = np.argsort(cm)
cms = cm[sorti]
cvs = cv[sorti]
cps = cp[sorti]
xvec = np.arange(cms[0],cms[1],step=.05)
x1 = make_distribution(cms[0], cvs[0], cps[0], xvec)
x2 = make_distribution(cms[1], cvs[1], cps[1], xvec)
dx = np.abs(x1 - x2)
diff1 = posterior[:,:,0] - posterior[:,:,1]
t_ind = np.argmin(dx)
EMthresh_vv[k] = xvec[t_ind]/scaling
#l_thresh_vv[k] = t_thresh / scaling
#dbtile = np.ma.log10(vvt_masked)+30
# Mark Tiles used for Threshold Estimation
vv_picktiles[msdselect_vh[finalselect_vh[k]],:,:]= np.ones_like(vv_tiles[msdselect_vh[finalselect_vh[k]],:,:])
# Calculate best threshold for VV and VH as the mean of the 5 thresholds calculated in the previous section
#m_thresh_vv = np.median(l_thresh_vv)
#print(EMthresh_vv-30)
EMts = np.sort(EMthresh_vv)
#m_thresh_vv = np.median(EMthresh_vv)
m_thresh_vv = np.median(EMts[0:4])
print("Best VV Flood Mapping Threshold [dB]: %.2f" % (10*(m_thresh_vv-30)))
print(" ")
# Derive flood mask using the best threshold
if m_thresh_vv < (vv_corr/10.0+30):
change_mag_mask_vv = np.ma.masked_where(dbvv==0, dbvv) < m_thresh_vv
vv_thresholds_corr = np.append(vv_thresholds_corr, 10.0*(m_thresh_vv-30))
#change_mag_mask_vv = np.ma.masked_where(vv_array==0, vv_array) < m_thresh_vv
else:
change_mag_mask_vv = np.ma.masked_where(dbvv==0, dbvv) < (vv_corr/10.0+30)
vv_thresholds_corr = np.append(vv_thresholds_corr, vv_corr)
# Create Binary masks showing flooded pixels as "1"s
flood_vv = np.zeros_like(vv_array)
sel = np.ones_like(vv_array)
flood_vv[change_mag_mask_vv] = sel[change_mag_mask_vv]
np.putmask(flood_vv,vv_array==0 , 0)
# Export flood maps as GeoTIFFs
filename, ext = os.path.basename(tiff).split('.')
outfile = f"{mask_directory}/{filename}_water_mask.{ext}"
write_mask_to_file(flood_vv, outfile, f.GetProjection(), f.GetGeoTransform())
else:
vh_array = pad_image(f.ReadAsArray(), tilesize)
invalid_pixels = np.nonzero(vh_array == 0.0)
vh_tiles = tile_image(vh_array,width=tilesize,height=tilesize)
a = np.shape(vh_tiles)
vh_std = np.zeros(a[0])
vht_masked = np.ma.masked_where(vh_tiles==0, vh_tiles)
vh_picktiles = np.zeros_like(vh_tiles)
for k in range(a[0]):
vh_subtiles = tile_image(vht_masked[k,:,:],width=tilesize2,height=tilesize2)
vhst_mean = np.ma.mean(vh_subtiles, axis=(1,2))
vhst_std = np.ma.std(vhst_mean)
vh_std[k] = np.ma.std(vhst_mean)
# find tiles with largest standard deviations
vh_mean = np.ma.median(vht_masked, axis=(1,2))
x_vh = np.sort(vh_std/vh_mean)
xm_vh = np.sort(vh_mean)
#x_vh = np.sort(vh_std)
y_vh = np.arange(1, x_vh.size+1) / x_vh.size
ym_vh = np.arange(1, xm_vh.size+1) / xm_vh.size
percentile2 = precentile
sort_index = 0
while np.size(sort_index) < 5:
threshold_index_vh = np.ma.min(np.where(y_vh>percentile2))
threshold_vh = x_vh[threshold_index_vh]
#sd_select_vh = np.nonzero(vh_std/vh_mean>threshold_vh)
s_select_vh = np.nonzero(vh_std/vh_mean>threshold_vh)
h_select_vh = np.nonzero(Hpercent > Hpick) # Includes HAND-EM in selection
sd_select_vh = np.intersect1d(s_select_vh, h_select_vh)
# find tiles with mean values lower than the average mean
omean_vh = np.ma.median(vh_mean[h_select_vh])
mean_select_vh = np.nonzero(vh_mean<omean_vh)
# Intersect tiles with large std with tiles that have small means
msdselect_vh = np.intersect1d(sd_select_vh, mean_select_vh)
sort_index = np.flipud(np.argsort(vh_std[msdselect_vh]))
percentile2 = percentile2 - 0.01
finalselect_vh = sort_index[0:5]
# find local thresholds for 5 "best" tiles in the image
l_thresh_vh = np.zeros(5)
EMthresh_vh = np.zeros(5)
temp = np.ma.masked_where(vh_array==0, vh_array)
dbvh = np.ma.log10(temp)+30
scaling = 256/(np.mean(dbvh) + 3*np.std(dbvh))
#scaling = 256/(np.mean(vh_array) + 3*np.std(vh_array))
dbtile = np.ma.log10(vht_masked)+30
for k in range(5):
test = dbtile[msdselect_vh[finalselect_vh[k]]] * scaling
#test = vht_masked[msdselect_vh[finalselect_vh[k]]] * scaling
A = np.around(test)
A = A.astype(int)
#t_thresh = Kittler(A)
[posterior, cm, cv, cp] = EMSeg_opt(A, 3)
sorti = np.argsort(cm)
cms = cm[sorti]
cvs = cv[sorti]
cps = cp[sorti]
xvec = np.arange(cms[0],cms[1],step=.05)
x1 = make_distribution(cms[0], cvs[0], cps[0], xvec)
x2 = make_distribution(cms[1], cvs[1], cps[1], xvec)
dx = np.abs(x1 - x2)
diff1 = posterior[:,:,0] - posterior[:,:,1]
t_ind = np.argmin(dx)
EMthresh_vh[k] = xvec[t_ind]/scaling
#l_thresh_vh[k] = t_thresh / scaling
# Mark Tiles used for Threshold Estimation
vh_picktiles[msdselect_vh[finalselect_vh[k]],:,:]= np.ones_like(vh_tiles[msdselect_vh[finalselect_vh[k]],:,:])
# Calculate best threshold for VV and VH as the mean of the 5 thresholds calculated in the previous section
#m_thresh_vh = np.median(l_thresh_vh)
#print(EMthresh_vh-30)
EMts = np.sort(EMthresh_vh)
#m_thresh_vh = np.median(EMthresh_vh)
m_thresh_vh = np.median(EMts[0:4])
print("Best VH Flood Mapping Threshold [dB]: %.2f" % (10*(m_thresh_vh-30)))
print(" ")
# Derive flood mask using the best threshold
maskedarray = np.ma.masked_where(dbvh==0, dbvh)
#maskedarray = np.ma.masked_where(vh_array==0, vh_array)
if m_thresh_vh < (vh_corr/10.0+30):
change_mag_mask_vh = maskedarray < m_thresh_vh
vh_thresholds_corr = np.append(vh_thresholds_corr, 10.0*(m_thresh_vh-30))
#change_mag_mask_vv = np.ma.masked_where(vv_array==0, vv_array) < m_thresh_vv
else:
change_mag_mask_vh = maskedarray < (vh_corr/10.0+30)
vh_thresholds_corr = np.append(vh_thresholds_corr, vh_corr)
# change_mag_mask_vh = vh_array < m_thresh_vh
# Create Binary masks showing flooded pixels as "1"s
sel = np.ones_like(vh_array)
flood_vh = np.zeros_like(vh_array)
flood_vh[change_mag_mask_vh] = sel[change_mag_mask_vh]
np.putmask(flood_vh,vh_array==0 , 0)
# Export flood maps as GeoTIFFs
filename, ext = os.path.basename(tiff).split('.')
outfile = f"{mask_directory}/{filename}_water_mask.{ext}"
write_mask_to_file(flood_vh, outfile, f.GetProjection(), f.GetGeoTransform())
# Create Maps (Pickfiles) that show which tiles were used for adaptive threshold calculation
vv_picks = vv_picktiles.reshape((n_rows, n_cols, tilesize, tilesize)) \
.swapaxes(1, 2) \
.reshape(n_rows * tilesize, n_cols * tilesize) # yapf: disable
vh_picks = vh_picktiles.reshape((n_rows, n_cols, tilesize, tilesize)) \
.swapaxes(1, 2) \
.reshape(n_rows * tilesize, n_cols * tilesize) # yapf: disable
# Write Pickfiles to GeoTIFFs
#outfile = f"{mask_directory}/{filename[:-3]}_vv_pickfile.{ext}"
#write_mask_to_file(vv_picks, outfile, f.GetProjection(), f.GetGeoTransform())
#outfile = f"{mask_directory}/{filename[:-3]}_vh_pickfile.{ext}"
#write_mask_to_file(vh_picks, outfile, f.GetProjection(), f.GetGeoTransform())
# Combine VV and VH flood maps to produce a combined flood mapping product
comb = flood_vh + flood_vv
comb_mask = comb > 0
flood_comb = np.zeros_like(vv_array)
flood_comb[comb_mask] = sel[comb_mask]
filename, ext = os.path.basename(tiff).split('.')
outfile = f"{mask_directory}/{filename[:-3]}_water_mask_combined.{ext}"
write_mask_to_file(flood_comb, outfile, f.GetProjection(), f.GetGeoTransform())
# Create Information on Thresholds used as well as Flood extent information in km2
vv_thresholds = np.append(vv_thresholds, 10.0*(m_thresh_vv-30))
vh_thresholds = np.append(vh_thresholds, 10.0*(m_thresh_vh-30))
floodarea = np.append(floodarea,(np.sum(flood_comb)*30**2./(1000**2)))
# + [markdown] heading_collapsed=true
# ## Fuzzy Logic Post Processing to Clean up Initial Surface Water Extent Map
# + [markdown] hidden=true
# <font face="Calibri" size=3>This step applies fuzzy logic rules to remove spurious false detection and improve upon the initial flood mapping product created in Section 2.5. Four Fuzzy indicators for the presence of floods are used. These include:
# <ol>
# <li>The radar cross section in a pixel relative to the determined detection threshold.</li>
# <li>The HAND elevation (surface elevation relative to the nearest dranage basin).</li>
# <li>The surface slope.</li>
# <li>The size of a detected flood feature.</li>
# </ol>
# Fuzzy membership functions are calculated for each of these four indicators using a Z-shaped activation function. Membership functions are combined using arithmetric averaging to form a final decision map. This map is then thresholded using a fuzzy threshold of 0.45. <br><br>
#
# <b><u>Upper and lower thresholds for the fuzzy activation functions are calculated as follows:</u></b>
# <ol>
# <li><b>RCS:</b> $\begin{Bmatrix}
# x_{u,RCS} & = & \tau_g \\
# x_{l,RCS} & = & \mu_{\sigma^0(\tau_g)}
# \end{Bmatrix}$
# with $\sigma^0(\tau_g)$ = initial flood classification and flood mapping threshold $\tau_g$.<br><br></li>
# <li><b>HAND:</b> $\begin{Bmatrix}
# x_{u,HAND} & = & \mu_{HAND(water)} + 3 \cdot \sigma_{HAND(water)} \\
# x_{l,HAND} & = & \mu_{HAND(water)}
# \end{Bmatrix}$. This is a departure from <cite><a href="https://www.sciencedirect.com/science/article/pii/S0924271614001981" target="_blank"><i>the paper</i></a> by Martinis et al. (2015)</cite>.<br><br></li>
# <li><b>Surface slope $\alpha$:</b> $\begin{Bmatrix}
# x_{u,\alpha} & = & 0^{\circ} \\
# x_{l,\alpha} & = & 15^{\circ}
# \end{Bmatrix}$.<br><br></li>
# <li><b>Area $A$:</b>$\begin{Bmatrix}
# x_{u,A} & = & 10px \\
# x_{l,A} & = & 3px
# \end{Bmatrix}$. These threshold values are different differently than in <cite><a href="https://www.sciencedirect.com/science/article/pii/S0924271614001981" target="_blank"><i>the paper</i></a> by Martinis et al. (2015)</cite>.</li>
# </ol>
# </font>
# + [markdown] hidden=true
# <hr>
# + [markdown] hidden=true
# <font face="Calibri" size="3"><b>Note</b>: By default, this post-processing step is not used in this notebook. Deactivating the post processing procedure is done to save processing time for this course exercise. Feel free to activate this step by setting the <b>```do_PP```</b> flag to <b>```True```</b> in the following code cell.</font>
# + hidden=true
do_PP = False
# + [markdown] hidden=true
# <hr>
# <font face="Calibri" size="3"><b>This next code cell does the actual fuzzy logic-based post processing work</b>:</font>
# + hidden=true
if do_PP:
import skimage.measure
import skimage.color
from skimage import morphology
from skimage import filters
import time
import astropy.convolution
import warnings #Suppress warnings on occasion
from tqdm.auto import tqdm
vvcount = 0
vhcount = 0
floodareaPP = np.array([])
print('FUZZY LOGIC POST PROCESSING TO REFINE INITIAL SURFACE WATER EXTENT MAPS:')
print(' ')
for pair in grouped_pths:
for tiff in grouped_pths[pair]:
start = time.time()
print('-----------------------------------------------------------------------------------')
print(f'Image: {tiff}')
resampled_dem_path=f'{tiff_dir}/resamp_dem.tif'
f = gdal.Open(tiff)
img_array = f.ReadAsArray()
original_shape = img_array.shape
img_array = 0 # free up RAM
radar_array = pad_image(f.ReadAsArray(), tilesize)
temp = np.ma.masked_where(radar_array==0, radar_array)
np.seterr(divide='ignore')
np.seterr(invalid='ignore')
dbarray = np.log10(temp)+30
del temp
# ------------------------------------------------------------#
# Loading Water Mask File #
#-------------------------------------------------------------#
filename, ext = os.path.basename(tiff).split('.')
waterfile = f"{mask_directory}/{filename}_water_mask.{ext}"
h = gdal.Open(waterfile)
maskimage = h.ReadAsArray()
print(' - Extracting Relevant Subset from HAND Layer ...')
info1 = (gdal.Info(tiff, options = ['-json']))
info1 = json.dumps(info1)
ul = (json.loads(info1))['cornerCoordinates']['upperLeft']
lr = (json.loads(info1))['cornerCoordinates']['lowerRight']
coordsys = (json.loads(info1))['coordinateSystem']['wkt']
Szone = coordsys.split('ID')[-1].split(',')[1][0:-2]
Sproj_type = coordsys.split('ID')[-1].split('"')[1]
west= ul[0]
east= lr[0]
south= lr[1]
north= ul[1]
cmd_resamp=f"gdalwarp -overwrite -s_srs {Hproj_type}:"\
f"{Hzone} -t_srs EPSG:{Szone} -te {west} {south} {east} {north} -ts {original_shape[1]} {original_shape[0]} -r lanczos {HAND_file} {resampled_dem_path}"
#print(cmd_resamp)
os.system(cmd_resamp)
g = gdal.Open(resampled_dem_path)
hand = pad_image(g.ReadAsArray(), tilesize)
print(' - Interpolate NaNs in HAND Layer ...')
hand_interp= fill_nan(hand)
del hand
print(' - Calculate DEM (HAND) Slope magnitude ...')
vgrad = np.gradient(hand_interp)
mag = np.sqrt(vgrad[0]**2 + vgrad[1]**2)
geotransform = g.GetGeoTransform()
res = geotransform[1]
slope = np.arctan(mag/res)/np.pi*180
print(' - Segment initial flood mask to calculate area of connected patches ...')
# Here an attempt to perform a sequence of opening and closing steps to
# reduce the number of segments in the inital flood maps and speed up the next processing steps
med = filters.median(maskimage, morphology.disk(2))
selem = morphology.disk(3)
closed = skimage.morphology.closing(med, selem)
labeled_image = skimage.measure.label(closed, connectivity=2)
label_areas = np.bincount(labeled_image.ravel())[1:]
# Define upper and lower limit of the Z fuzzy activation function
print(' - Now Calculate Fuzzy Weights ...')
## sigma zero upper and lower fuzzy threshold calculation
maskedarray = np.ma.masked_where((maskimage==0) | (radar_array < 0), radar_array)
db_lowerlimit = np.log10(np.ma.median(maskedarray))+30
if 'vv' in tiff or 'VV' in tiff:
db_upperlimit = (vv_thresholds_corr[vvcount]/10.0+30)
vvcount = vvcount + 1
else:
db_upperlimit = (vh_thresholds_corr[vhcount]/10.0+30)
vhcount = vhcount + 1
## HAND upper and lower fuzzy threshold calculation
maskedarray = np.ma.masked_where(maskimage==0, hand_interp)
ma2 = np.ma.masked_where(maskedarray > np.percentile(maskedarray, 90), maskedarray)
hand_lowerlimit = np.ma.median(np.ma.masked_invalid(ma2))
hand_upperlimit = hand_lowerlimit + (np.ma.std(np.ma.masked_invalid(ma2)) + 3.5)*np.ma.std(np.ma.masked_invalid(ma2))
hand_upperlimit = hand_lowerlimit + 3.0*(np.ma.std(np.ma.masked_invalid(ma2)))
# Create vector spanning all possible values for db, HAND, Slope, and Area values for the selected data set
x_db = np.arange(np.min(dbarray), np.max(dbarray), 0.005)
x_hand = np.arange(np.min(np.ma.masked_invalid(hand_interp)), np.max(np.ma.masked_invalid(hand_interp)), 0.1)
x_slope = np.arange(np.min(np.ma.masked_invalid(slope)), np.max(np.ma.masked_invalid(slope)), 0.1)
largestCC = labeled_image == np.argmax(np.bincount(labeled_image.flat, weights=maskimage.flat))
x_area = np.arange(1, np.sum(largestCC)+10, 1)
# Create activation functions for db, HAND, SLope and Area
activation_db = skfuzzy.zmf(x_db,db_lowerlimit,db_upperlimit)
activation_hand = skfuzzy.zmf(x_hand,hand_lowerlimit,hand_upperlimit)
activation_slope = skfuzzy.zmf(x_slope,0,15)
activation_area = 1-skfuzzy.zmf(x_area,3,10)
# Calculate membership functions given your activation function rule
db_membership = skfuzzy.interp_membership(x_db, activation_db, dbarray)
print(' -- Calculating Radar Cross Section Membership ... [min thresholds: %6.2f' % (db_lowerlimit-30),'; max threshold: %6.2f]' % (db_upperlimit-30))
hand_membership = skfuzzy.interp_membership(x_hand, activation_hand, hand_interp)
print(' -- Calculating HAND Membership ... [min thresholds: %6.2f' % (hand_lowerlimit),'; max threshold: %6.2f]' % (hand_upperlimit))
slope_membership = skfuzzy.interp_membership(x_slope, activation_slope, slope)
print(' -- Calculating Slope Membership ... [min thresholds: 0 deg; max threshold: 15 deg]')
area_membership = np.zeros_like(radar_array)
print(' -- Calculating Area Membership ... [This may take a while!]')
test = np.array([])
for x in tqdm(range(1, np.max(labeled_image))):
#clear_output(wait=True)
#np.putmask(area_membership,labeled_image==x,skfuzzy.interp_membership(x_area, activation_area, np.sum(labeled_image==x)))
np.putmask(area_membership,labeled_image==x,skfuzzy.interp_membership(x_area, activation_area, label_areas[x-1]))
water_gT=gdal_get_geotransform(waterfile)
water_proj4=get_proj4(waterfile)
# Uncomment these following lines if you want more intermediary files to be saved off as GeoTIFFs
#filename, ext = os.path.basename(tiff).split('.')
#outfile = f"{mask_directory}/{filename}_dbmembership.{ext}"
#gdal_write(db_membership, water_gT, filename=outfile, srs_proj4=water_proj4.srs, nodata=np.nan, format=gdal.GDT_Float32)
#outfile = f"{mask_directory}/{filename}_handmembership.{ext}"
#gdal_write(hand_membership, water_gT, filename=outfile, srs_proj4=water_proj4.srs, nodata=np.nan, format=gdal.GDT_Float32)
#outfile = f"{mask_directory}/{filename}_slopemembership.{ext}"
#gdal_write(slope_membership, water_gT, filename=outfile, srs_proj4=water_proj4.srs, nodata=np.nan, format=gdal.GDT_Float32)
#outfile = f"{mask_directory}/{filename}_areamembership.{ext}"
#gdal_write(area_membership, water_gT, filename=outfile, srs_proj4=water_proj4.srs, nodata=np.nan, format=gdal.GDT_Float32)
print(' - Combine all fuzzy membership functions to make final flood mapping decision')
dbmask = db_membership != 0.0
handmask = hand_membership != 0.0
slopemask = slope_membership != 0.0
areamask = area_membership != 0.0
combinedm = dbmask * handmask * slopemask * areamask
combinedmask = np.zeros_like(radar_array)
sel = np.ones_like(dbarray)
combinedmask[combinedm] = sel[combinedm]
combinedweights = ((db_membership + hand_membership + slope_membership + area_membership) / 4.0) * combinedmask
acceptance = combinedweights > 0.45
# Uncomment these following lines if you want more intermediary files to be saved off as GeoTIFFs
#outfile = f"{mask_directory}/{filename}_totalmembership.{ext}"
#gdal_write(combinedweights, water_gT, filename=outfile, srs_proj4=water_proj4.srs, nodata=np.nan, format=gdal.GDT_Float32)
sel = np.ones_like(radar_array)
floodmap = np.zeros_like(radar_array)
floodmap[acceptance] = sel[acceptance]
np.putmask(floodmap,radar_array==0 , 0)
if 'vv' in tiff or 'VV' in tiff:
floodmap_vv = floodmap
else:
floodmap_vh = floodmap
# Export flood maps as GeoTIFFs
#filename, ext = os.path.basename(tiff).split('.')
#outfile = f"{mask_directory}/{filename}_final_water_mask.{ext}"
#write_mask_to_file(floodmap, outfile, f.GetProjection(), f.GetGeoTransform())
del floodmap
print(' - Processing time: %6.2f minutes' % ((time.time() - start)/60.0))
print('-----------------------------------------------------------------------------------')
print(' ')
# Combine VV and VH flood maps to produce a combined flood mapping product
comb = floodmap_vh + floodmap_vv
comb_mask = comb > 0
flood_comb = np.zeros_like(radar_array)
flood_comb[comb_mask] = sel[comb_mask]
filename, ext = os.path.basename(tiff).split('.')
outfile = f"{mask_directory}/{filename[:-3]}_fcWM.{ext}"
write_mask_to_file(flood_comb, outfile, f.GetProjection(), f.GetGeoTransform())
floodareaPP = np.append(floodareaPP,(np.sum(flood_comb)*30**2./(1000**2)))
# + [markdown] heading_collapsed=true
# ## Evaluate Flood Mapping Results
# + [markdown] hidden=true
# <font face="Calibri" size="3">This section allows to evaluate the flood mapping information that was created. Different types of plots are offered to visualze the time series of surface water area as well as individual flood extent maps and statistical plots.
#
# This first code cell <b>plots the time series of surface water extent that was found in the analyzed SAR scenes</b></font>
# + hidden=true
validarea = np.array([])
floodpercent = np.array([])
agreggatepx = np.zeros_like(vv_array)
k = 0
for pair in grouped_pths:
for tiff in grouped_pths[pair]:
f = gdal.Open(tiff)
if 'vv' in tiff or 'VV' in tiff:
vv_array = pad_image(f.ReadAsArray(), tilesize)
temp = vv_array > 0
sel = np.ones_like(vv_array)
valid_pixels = np.zeros_like(vv_array)
valid_pixels[temp] = sel[temp]
#np.putmask(valid_pixels,vv_array==0 , 0)
validarea = np.append(validarea,sum(sum(valid_pixels))*30**2./(1000**2))
if do_PP:
floodpercent = np.append(floodpercent,floodareaPP[k]/validarea[k] * 100.0)
else:
floodpercent = np.append(floodpercent,floodarea[k]/validarea[k] * 100.0)
agreggatepx = agreggatepx + valid_pixels
k = k + 1
# + hidden=true
plt.rcParams.update({'font.size': 12})
temp_path = f"{tiff_dir}/*VV.tiff"
dates = get_dates(temp_path)
time_index = pd.DatetimeIndex(dates)
fig = plt.figure(figsize=(9, 4))
ax1 = fig.add_subplot(111) # 121 determines: 2 rows, 2 plots, first plot
ax1.plot(np.unique(time_index), floodpercent, color='b', marker='o', markersize=3, label='Area Covered in Water [%]')
ax1.set_ylim([np.min(floodpercent)-np.min(floodpercent)*0.1,np.max(floodpercent)+np.min(floodpercent)*0.1])
ax1.set_xlabel('Date')
ax1.axhline(y=np.mean(floodpercent), color='k', linestyle='--', label='Average Water Coverage [%]')
ax1.set_ylabel('Image Area Covered in Water [%]')
ax1.grid()
figname = ('ThresholdAndAreaTS.png')
ax1.legend(loc='lower right')
plt.savefig(figname, dpi=300, transparent='true')
# + [markdown] hidden=true
# <hr>
# <font face="Calibri" size="3"><b>The following code cells allow you to visualize individual flood maps superimposed on the respective SAR image they were derived from.</b></font>
# + hidden=true
if do_PP:
wpaths = f"{tiff_dir}/Water_Masks/*fcWM.tif*"
else:
wpaths = f"{tiff_dir}/Water_Masks/*combined.tif*"
spaths = f"{tiff_dir}/*VV.tif*"
vrtcommand = f"gdalbuildvrt -separate Water.vrt {wpaths}"
# !{vrtcommand}
water_file="Water.vrt"
vrtcommand = f"gdalbuildvrt -separate SAR.vrt {spaths}"
# !{vrtcommand}
SAR_file = "SAR.vrt"
img = gdal.Open(SAR_file)
wm = gdal.Open(water_file)
SARstack = img.ReadAsArray(5, 20, 5, 5)
SARsize = np.shape(SARstack)
SARbands = SARsize[0]
# + [markdown] hidden=true
# <hr>
# <font face="Calibri" size="3"><b>Please change the ```band_num``` setting in the next code cell</b> to visualize flood mapping results for different SAR image acquisition dates.
#
# Note the tool bar in the bottom left corner of the image that's created. Feel free to use the toolbar to zoom into the image and navigate around.</font>
# + hidden=true
band_num = 10 # Change the band number to visualize different SAR acquisitions and respective flood mapping results
if band_num > SARbands:
band_num = SARbands
SARraster = img.GetRasterBand(band_num).ReadAsArray()
waterraster = wm.GetRasterBand(band_num).ReadAsArray()
water_masked = np.ma.masked_where(waterraster==0, waterraster)
waterraster = 0
plt.figure(figsize=(9, 6))
vmin = np.percentile(SARraster, 5) #vh_array
vmax = np.percentile(SARraster, 95)
plt.imshow(SARraster, cmap='gray', vmin=vmin, vmax=vmax)
plt.suptitle(f'Water Mask on SAR Image: {time_index.year[band_num-1]} / {time_index.month[band_num-1]} / {time_index.day[band_num-1]}')
plt.grid()
plt.imshow(water_masked, cmap='Blues',vmin=0, vmax=1.2)
# + [markdown] hidden=true
# <br>
# <div class="alert alert-success">
# <font face="Calibri" size="5"> <b> <font color='rgba(200,0,0,0.2)'> <u>EXERCISE</u>: </font> Analyze the Quality of the Water Masks</b>
#
# <font face="Calibri" size="3"> Look at different Flood Maps for your 16 dates and evaluate the performance of the flood map. To do so, use the toolbar in the bottom left corner of the image above to zoom in and navigate around:
# - Zoom into the map and look at the details. Are there some pxiels that you would have added to the mask?
# - If you think flood areas were missed, do you seen anything in the underlying image that may explain why a pixel was not detected? </font>
# </div>
# <br>
# <hr>
# + [markdown] heading_collapsed=true
# ## Create Summary Statistics
# + [markdown] hidden=true
# <font face="Calibri" size="3">Once flood maps for each individual image acquisition date were created, summary statistics can be derived that describe the severity and duration of an event. In the following, <b>we will be deriving a metric describing how many days each image pixel was inundated during an analyzed event</b>. This should provide a template for other metrics to be created.</font>
# + hidden=true
np.seterr(invalid='ignore')
rasterstack = wm.ReadAsArray()
srs = np.shape(rasterstack)
floodcount = np.sum(rasterstack,0)
floodpercent = floodcount / agreggatepx * 100.0
np.putmask(floodpercent, floodpercent>100.0, 100.0)
dt = time_index.dayofyear[SARbands-1] - time_index.dayofyear[0]
flooddays = floodpercent / 100 * float(dt)
rasterstack = 0
fd_masked = np.ma.masked_where(flooddays==0, flooddays)
flood_gT=gdal_get_geotransform(tiff)
flood_proj4=get_proj4(tiff)
outfile = f"{mask_directory}/flooddays.tiff"
gdal_write(flooddays, flood_gT, filename=outfile, srs_proj4=flood_proj4.srs, nodata=np.nan, format=gdal.GDT_Float32)
# + hidden=true
SARraster = img.GetRasterBand(SARbands).ReadAsArray()
plt.figure(figsize=(9, 6))
vmin = np.percentile(SARraster, 5) #vh_array
vmax = np.percentile(SARraster, 95)
plt.suptitle('Number of Inundated Days Per Pixel - Minimum SAR Image as Background')
plt.imshow(SARraster, cmap='gray', vmin=vmin, vmax=vmax)
im = plt.imshow(fd_masked, cmap='jet')
plt.colorbar(im, orientation='vertical')
plt.grid()
outfile = f"{mask_directory}/flooddaysBG.tif"
write_mask_to_file(flooddays, outfile, img.GetProjection(), img.GetGeoTransform())
# + [markdown] hidden=true
# <br>
# <div class="alert alert-success">
# <font face="Calibri" size="5"> <b> <font color='rgba(200,0,0,0.2)'> <u>EXERCISE</u>: </font> Analyze the Summary Statistic Plot</b>
#
# <font face="Calibri" size="3"> Look at different colors in the plot above and try to understand what they mean and whether or not they make sense to you. To do so, use the toolbar in the bottom left corner of the image above to zoom in and navigate around. </font>
# </div>
# <br>
# <hr>
# + [markdown] heading_collapsed=true
# # Version Log
# + [markdown] hidden=true
# <font face="Calibri" size="2"> <i> FloodMappingFromSARImages.ipynb - version 1.4.0 April 2021
# <br>
# <b>Version Changes:</b>
# <ul>
# <li>from osgeo import gdal</li>
# <li>namespace asf_notebook</li>
# </ul>
# </i>
# </font>
|
SAR_Training/English/HydroSAR/Lab2-SurfaceWaterExtentMapping.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import pandas as pd
data = {
'Company' : ['Amazon','Amazon','Facebook','Facebook','Google','Google'],
'Person' : ['Sam','Charlie','Mahesh','Prachi','Carl','Sarah'],
'Sales' : [200,120,180,165,195,210]
}
df = pd.DataFrame(data)
df
bycomp = df.groupby('Company')
bycomp.mean()
bycomp.sum()
bycomp.std()
bycomp.mean().loc['Google']
bycomp.count()
bycomp.min()
df.groupby('Company').describe()
df.groupby('Company').describe().loc['Amazon']
|
2.Python for Data Analysis - Pandas/Groupby.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# + [markdown] deletable=true editable=true
# # Analyis of EEG data
# + [markdown] deletable=true editable=true
# Based on Chip Audette's analysis
#
# + deletable=true editable=true
import mne
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from mne import io, read_proj, read_selection
from mne.datasets import sample
from mne.time_frequency import psd_multitaper
from mne.minimum_norm import read_inverse_operator, compute_source_psd
mne.set_log_level('INFO')
# + deletable=true editable=true
# Authors: <NAME> <<EMAIL>>
from mne import io
from mne.minimum_norm import read_inverse_operator, source_band_induced_power
# + deletable=true editable=true
# from mne_openbci import read_raw_openbci #Convert OpenBCI data
# Alternatively you can use EEG Viewer GUI to convert to edf
fname = "/home/vagrant/notebooks/data/OpenBCI-RAW-2017-01-12_15-57-48.txt"
fnameEDF = "/home/vagrant/notebooks/data/OpenBCI-RAW-2015-12-17_23-17-26_signals_only.edf"
# 250 and 200 for Cylon and Ganglion
fs_Hz = 200.0
# data = np.loadtxt(fname, delimiter = ',', skiprows=5)
data = np.loadtxt(fname,
delimiter=',',
usecols=(0,1,2,3,4),
skiprows=6)
print(data)
# + deletable=true editable=true
# check the packet counter for dropped packets
data_indices = data[:, 0] # the first column is the packet index
d_indices = data_indices[2:]-data_indices[1:-1]
n_jump = np.count_nonzero((d_indices != 1) & (d_indices != -255))
print("Number of discontinuities in the packet counter: " + str(n_jump))
# + deletable=true editable=true
eeg_data_uV = data[:, 1:(8+1)]; #EEG data, 4 for Ganglion
accel_data_counts = data[:, 9:(11+1)]
# convert units
unused_bits = 4 #the 4 LSB are unused?
accel_data_counts = accel_data_counts / (2**unused_bits) # strip off this extra LSB
scale_G_per_count = 0.002 # for full-scale = +/- 4G, scale is 2 mG per count
accel_data_G = scale_G_per_count*accel_data_counts # convert to G
# create a vector with the time of each sample
t_sec = np.arange(len(eeg_data_uV[:, 0])) / fs_Hz
# + deletable=true editable=true
eeg_data_uV
# + deletable=true editable=true
nchan = 4
ncol = 2; nrow = nchan / ncol
plt.figure(figsize=(ncol*5, nrow*3))
for Ichan in range(nchan):
plt.subplot(nrow,ncol,Ichan+1)
plt.plot(t_sec,eeg_data_uV[:, Ichan])
plt.xlabel("Time (sec)")
plt.ylabel("Raw EEG (uV)")
plt.title("Channel " + str(Ichan+1))
#plt.ylim([-1.5, 1.5])
plt.tight_layout()
plt.show()
# + deletable=true editable=true
NFFT = 128 # pitck the length of the fft
FFTstep = NFFT/2 # do a new FFT every FFTstep data points
overlap = NFFT - FFTstep # half-second steps
f_lim_Hz = [0.5, 50] # frequency limits for plotting
ncol = 2
nchan = 4
nrow = nchan / ncol
plt.figure(figsize=(ncol*5, nrow*3))
for Ichan in range(nchan):
ax = plt.subplot(nrow,ncol,Ichan+1)
data = np.array(eeg_data_uV[:,Ichan])
spec_PSDperHz, freqs, t = mlab.specgram(data,
NFFT=NFFT,
window=mlab.window_hanning,
Fs=fs_Hz,
noverlap=overlap
) # returns PSD power per Hz
spec_PSDperBin = spec_PSDperHz * fs_Hz / float(NFFT) #convert to "per bin"
del spec_PSDperHz # remove this variable so that I don't mistakenly use it
plt.pcolor(t, freqs, 10*np.log10(spec_PSDperBin)) # dB re: 1 uV
plt.clim(30+np.array([-50, 0]))
plt.xlim(t_sec[0], t_sec[-1])
plt.ylim([0, fs_Hz/2.0]) # show the full frequency content of the signal
plt.ylim(f_lim_Hz)
plt.xlabel('Time (sec)')
plt.ylabel('Frequency (Hz)')
plt.title("Channel " + str(Ichan+1))
# add annotation for FFT Parameters
ax.text(0.025, 0.95,
"NFFT = " + str(NFFT) + "\nfs = " + str(int(fs_Hz)) + " Hz",
transform=ax.transAxes,
verticalalignment='top',
horizontalalignment='left',
backgroundcolor='w')
plt.tight_layout()
plt.show()
# + deletable=true editable=true
# + [markdown] deletable=true editable=true
# ### alpha and beta bandwave decetion
# + deletable=true editable=true
bands = dict(alpha=[8, 12], beta=[13, 30])
n_cycles = 2
frequencies = np.arange(7, 30, 3) # frequencies of interest
print(frequencies)
# inverse_operator = read_inverse_operator(data)
# + deletable=true editable=true
# stcs = source_band_induced_power(data, inverse_operator,bands, n_cycles=2,use_fft=False, n_jobs=1)
# power, phase_lock = induced_power(data, Fs=Fs, frequencies=frequencies, n_cycles=2, n_jobs=1)
# + deletable=true editable=true
fmin, fmax = 2, 300 # look at frequencies between 2 and 300Hz
n_fft = 2048 # the FFT size (n_fft). Ideally a power of 2
# + deletable=true editable=true
raw = mne.io.read_raw_edf(fnameEDF)
raw.set_eeg_reference()
raw.plot()
# + deletable=true editable=true
raw.plot_psd(tmax=np.inf)
# + deletable=true editable=true
raw.plot()
# + deletable=true editable=true
raw.plot_psd()
# + deletable=true editable=true
# events = mne.find_events(raw)
# inverse_operator = read_inverse_operator(raw)
|
vvThesis_EEGRawSigna.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Training and Testing a Ranking Model
#
# Let's load the data and configs from the previous notebook first.
# +
# %load_ext autoreload
# %autoreload 2
# # %load_ext memory_profiler
import pickle
from pathlib import Path
from pprint import pprint
import numpy as np
import pandas as pd
import requests
from IPython.display import display
import azs_helpers.l2r_helper as azs
from azs_helpers.azure_search_client import azure_search_client as azs_client
interim_data_dir = Path.cwd() / 'data' / 'interim'
df = pd.read_csv(interim_data_dir / 'normalized_features.csv')
display(df.head(5))
# -
# ## Split dataset into features and judgments
#
# The machine learning libraries we're using expect us to separate our training data into features $X$ and judgment values $y$. Let's do that real quick:
#
X, y = df.drop(columns=['grade', 'query_id'], axis=1), df.grade
# ### Hold out a portion of the data for testing.
#
# We need to hold out part of the data to validate that our model works.
#
# For this tutorial, we will hold out **10%** of the data using `scikit-learn.model_selection.GroupShuffleSplit`. This means that the model will use **90%** of the queries for training & validation, while **10%** of the queries (that the model has never seen before) will be used to evaluate the final model's performance.
#
# #### Query labels for documents
#
# Our data preparation and model training process must be aware of query-document relationships in our dataset for accurate training results, so we'll need to pass in the query labels (`query_ids`) as well. The reason this is important is because the loss function used for optimization depends on the NDCG. As discussed above, the NDCG is a metric which indicates how close is an ordered list to its ideal order. To achieve this, the model needs to be aware of how to create those lists out of the training set, which can be achieved by grouping the data using the query_id.
#
# Read the following references for more information:
#
# - [Scikit-Learn: Cross Validation](https://scikit-learn.org/stable/modules/cross_validation.html)
# - [Scikit-Learn: GroupShuffleSplit](https://scikit-learn.org/stable/modules/cross_validation.html#group-shuffle-split)
# +
import numpy as np
from sklearn.model_selection import GroupShuffleSplit
# Hold out 10% of our queries in the test set.
random_seed = 42 # we are using a static random seed so we can easily reproduce results. The actual number has no meaning.
gss = GroupShuffleSplit(n_splits=1, test_size=0.1, random_state=random_seed)
# Query labels for each document in our dataset.
query_ids = df['query_id'].to_numpy()
train_index, test_index = next(gss.split(X, y, groups=query_ids))
print(f"Number of samples in train: {len(train_index)}")
print(f"Number of samples in test: {len(test_index)}")
# Split our features, judgment values, and query labels into train & test sets.
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = y.iloc[train_index], y.iloc[test_index]
query_ids_train, query_ids_test = query_ids[train_index], query_ids[test_index]
# -
# # Model Setup
#
# Now that we're done with feature engineering, we can move on to running the experiment. We'll be using the open-source [XGBoost library](https://xgboost.readthedocs.io/en/latest/index.html), which includes a few implementations of [**Pairwise**](https://en.wikipedia.org/wiki/Learning_to_rank#Pairwise_approach) and [**Listwise**](https://en.wikipedia.org/wiki/Learning_to_rank#Listwise_approach) ranking algorithms.
#
# By setting `'objective': 'rank:ndcg'` in the model constructor, we've chosen to use the [LambdaMART](https://www.microsoft.com/en-us/research/publication/from-ranknet-to-lambdarank-to-lambdamart-an-overview/) algorithm to maximize **listwise** [NDCG](https://en.wikipedia.org/wiki/Discounted_cumulative_gain).
#
# Another objective function that can be used for this problem is `rank:pairwise`, which will perform **pairwise** training instead of listwise training.
#
# ### Further Reading:
# - [Learning to Rank: From Pairwise Approach to Listwise Approach](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-2007-40.pdf)
# - XGBoost Documentation links:
# - [XGBRanker Class](https://xgboost.readthedocs.io/en/latest/python/python_api.html#xgboost.XGBRanker)
# - [XGBoost Parameters](https://xgboost.readthedocs.io/en/latest/parameter.html)
# +
import xgboost as xgb
params = {'objective': 'rank:ndcg', 'learning_rate': 0.1,
'gamma': 1.0, 'min_child_weight': 0.1,
'max_depth': 8, 'n_estimators': 500}
ranker = xgb.XGBRanker(**params)
ranker
# -
# ### Train with K-Fold Cross Validation
#
# K-Fold cross validation is a robust way to avoid overfitting during model training. Let's train with K-fold cross validation with `K=9`. We'll be using `scikit-learn`'s [GroupKFold class](https://scikit-learn.org/stable/modules/cross_validation.html#group-k-fold) to split our training data into 9 approximately even-sized portions. `GroupKFold` ensures that all documents for a particular query remain within the same fold. Before we can get started, we'll need to augment our query labels for training.
# - **If you're running this on Binder, please set `n_splits = 2` in the code.**
#
# #### Computing Document counts per Query
#
# During the training phase, we need to transform our query labels to be compatible with XGBoost. The `GroupKFold` cross-validation tool provided by `scikit-learn` expects a group (or query) label for every document in the dataset. We've already provided this in the form of `query_ids`.
#
# Let's take a look at the example below. Given a simple dataset of 3 queries:
#
# - Query 1: [doc1, doc2, doc3]
# - Query 2: [doc4]
# - Query 3: [doc5, doc6]
#
# **`scikit-learn` expects the following format**: (discrete query label for each document)
#
# ```python
# # query_ids = [query1, query1, query1, query2, query3, query3]
# query_ids = [1, 1, 1, 2, 3, 3]
# ```
#
# **`xgboost` expects the following format**: (document counts for each query)
#
# ```python
# query_doc_counts = [3, 1, 2]
# ```
#
# We can take our scikit-learn compatible query labels and aggregate them using numpy, as follows:
#
# ```python
# labels, query_doc_counts = np.unique(query_ids, return_counts=True)
# ```
#
# or, alternatively:
# ```python
# query_doc_counts = np.unique(query_group_labels, return_counts=True)[1]
# ```
#
# For reference, please refer to the [XGBoost Docs](https://xgboost.readthedocs.io/en/latest/python/python_api.html#xgboost.XGBRanker)
#
# ### Calculating our Results
# Calling `ranker.predict(X_test)` here will allow us to get all of the results. `xgb_scores` is a flat list of scores for queries in the test set. The raw scores are grouped by query and processed within a helper function to compute the precited rankings. Feel free to read the docstring of `azs_helpers.l2r_helper.scores_to_rankings` for more information.
# +
# %%time
from sklearn.model_selection import GroupKFold
from tqdm import tqdm
def calculate_ndcg(ranker, X, y, query_ids):
# **NOTE**
# If you are running this on Binder, please change n_splits to 2 for a faster run! Or skip this part entirely.
n_splits = 9
group_kfold = GroupKFold(n_splits)
ndcg_results = []
cross_validation_folds = group_kfold.split(X, y, groups=query_ids)
progress_bar = tqdm(enumerate(cross_validation_folds)) # Wrap the CV folds in a progress bar object
for fold_idx, (train_idx, validation_idx) in progress_bar:
progress_bar.set_description(f"Training on fold number {fold_idx}")
X_train_fold, X_validation_fold = X.iloc[train_idx], X.iloc[validation_idx]
y_train_fold, y_validation_fold = y.iloc[train_idx], y.iloc[validation_idx]
# XGBoost expects query counts instead of query labels.
# https://stackoverflow.com/questions/10741346/numpy-most-efficient-frequency-counts-for-unique-values-in-an-array
train_groups_xgb = np.unique(query_ids[train_idx], return_counts=True)[1]
validation_groups_xgb = np.unique(query_ids[validation_idx], return_counts=True)[1]
ranker.fit(X_train_fold, y_train_fold, train_groups_xgb,
eval_set=[(X_validation_fold, y_validation_fold)], eval_group=[validation_groups_xgb],
eval_metric='ndcg',
verbose=False)
xgb_scores = ranker.predict(X_validation_fold)
model_judgments, azs_judgments, baseline = azs.scores_to_rankings(xgb_scores, validation_groups_xgb, X_validation_fold, y_validation_fold)
ndcg_results_for_fold = azs.evaluate_ndcg(k_start=1, k_end=10, azs=azs_judgments, predicted=model_judgments)
ndcg_results.append(ndcg_results_for_fold)
return ndcg_results
# # %memit ndcg_results = calculate_ndcg_for_experiment(ranker, X_train, y_train, query_ids_train)
ndcg_results = calculate_ndcg(ranker, X_train, y_train, query_ids_train)
# -
# ### Visualize Cross-Validation Results
#
# Now that we've trained our model multiple times, we can visualize the training results.
#
# Datapoints represent the mean across all training runs, while vertical bars are the standard deviation.
# +
import matplotlib.pyplot as plt
# %matplotlib inline
import seaborn as sns
sns.set()
azs.show_ndcg_results(ndcg_results, 1, 10)
# -
# ### Putting it all together
#
# Now that we're confident that our model performs better than Azure Cognitive Search's built-in retrieval algorithm, let's run it against the test set! This time around, we'll be using all of the training data we've exluded from training.
# +
train_groups_xgb = np.unique(query_ids_train, return_counts=True)[1]
test_groups_xgb = np.unique(query_ids_test, return_counts=True)[1]
ranker.fit(X_train, y_train, train_groups_xgb,
eval_metric='ndcg',
verbose=False)
xgb_scores = ranker.predict(X_test)
model_judgments, azs_judgments, baseline = azs.scores_to_rankings(xgb_scores, test_groups_xgb, X_test, y_test)
test_ndcg_results = azs.evaluate_ndcg(k_start=1, k_end=10, plot=True, show_lift=True, azs=azs_judgments, predicted=model_judgments)
# -
# ### Feature Importances
# We can view which features ended up being the most important in our trained model:
# +
feature_importances = dict(zip(X_train.columns, ranker.feature_importances_))
feature_importances_sorted = {k: v for k, v in sorted(feature_importances.items(), key=lambda item: item[1], reverse=True)}
feature_importances_df = pd.DataFrame({'Features': list(feature_importances_sorted.keys()),
'Feature Importances': list(feature_importances_sorted.values())})
ax, fig = plt.subplots(1, 1, figsize=(12,12))
sns.barplot(y='Features', x='Feature Importances', data=feature_importances_df, orient='h')
# -
# ### How to re-rank a search request's results using our trained model
# When re-ranking an Azure Cognitive Search query, we need to go through the same process to transform the results into features as we did for our training data.
#
# This means
#
# 1. Get features from Azure Cognitive Search
# 2. Compute any additional features that was used int raining
# 3. Apply the same level of normalization
#
# Once we get the features in the expected format, we can feed them into the trained model to infer a new order, which will be used to re-rank our results.
def rerank_search_query(service, query, model, expected_features):
expected_features_format = pd.DataFrame(columns = expected_features, dtype='float64')
json_search_results = azs.get_search_results(service, query, [])
search_results = pd.json_normalize(json_search_results).fillna(0)
search_results["query"] = query
search_features = azs.customize_features(search_results.drop(columns=['url_en_us'], axis=1))
normalized_search_features = azs.normalize_features(expected_features_format.append(search_features))
prediction_score = model.predict(normalized_search_features.drop(columns=['query_id'], axis=1, errors='ignore'))
search_results['prediction'] = prediction_score
new_df = pd.DataFrame()
new_df['Base Azure Cognitive Search order'] = search_results.apply(lambda row: "{0}\n{1}".format(row['title_en_us'], row['url_en_us']), axis=1)
new_df['Trained model order'] = search_results.sort_values('prediction', ascending=False).apply(lambda row: "{0}\n{1}".format(row['title_en_us'], row['url_en_us']), axis=1).tolist() #['title_en_us'].tolist()
return new_df
service_metadata_config_path = Path.cwd() / 'config' / 'config.json'
azs_service = azs_client.from_json(service_metadata_config_path)
azs.pretty_print(rerank_search_query(azs_service, 'Windows Server 2019', ranker, X.columns))
|
l2r_part2_experiment.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import h5py
import os
import subprocess
# ## Precursors
if not os.path.isfile('data/hg19.ml.fa'):
subprocess.call('curl -o data/hg19.ml.fa https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa', shell=True)
subprocess.call('curl -o data/hg19.ml.fa.fai https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa.fai', shell=True)
if not os.path.isdir('models/heart'):
os.mkdir('models/heart')
if not os.path.isfile('models/heart/model_best.tf.meta'):
subprocess.call('curl -o models/heart/model_best.tf.index https://storage.googleapis.com/basenji_tutorial_data/model_best.tf.index', shell=True)
subprocess.call('curl -o models/heart/model_best.tf.meta https://storage.googleapis.com/basenji_tutorial_data/model_best.tf.meta', shell=True)
subprocess.call('curl -o models/heart/model_best.tf.data-00000-of-00001 https://storage.googleapis.com/basenji_tutorial_data/model_best.tf.data-00000-of-00001', shell=True)
# +
lines = [['index','identifier','file','clip','sum_stat','description']]
lines.append(['0', 'CNhs11760', 'data/CNhs11760.bw', '384', 'sum', 'aorta'])
lines.append(['1', 'CNhs12843', 'data/CNhs12843.bw', '384', 'sum', 'artery'])
lines.append(['2', 'CNhs12856', 'data/CNhs12856.bw', '384', 'sum', 'pulmonic_valve'])
samples_out = open('data/heart_wigs.txt', 'w')
for line in lines:
print('\t'.join(line), file=samples_out)
samples_out.close()
# -
# ## SNP activity difference compute
# Analyzing noncoding variation associated with disease is a major application of Basenji. I now offer several tools to enable that analysis. If you have a small set of variants and know what datasets are most relevant, [basenji_sat_vcf.py](https://github.com/calico/basenji/blob/master/bin/basenji_sat_vcf.py) lets you perform a saturation mutagenesis of the variant and surrounding region to see the relevant nearby motifs.
#
# If you want scores measuring the influence of those variants on all datasets,
# * [basenji_sad.py](https://github.com/calico/basenji/blob/master/bin/basenji_sad.py) computes my SNP activity difference (SAD) score--the predicted change in aligned fragments to the region.
# * [basenji_sed.py](https://github.com/calico/basenji/blob/master/bin/basenji_sed.py) computes my SNP expression difference (SED) score--the predicted change in aligned fragments to gene TSS's.
#
# Here, I'll demonstrate those two programs. You'll need
# * Trained model
# * Input file (FASTA or HDF5 with test_in/test_out)
# First, you can either train your own model in the [Train/test tutorial](https://github.com/calico/basenji/blob/master/tutorials/train_test.ipynb) or use one that I pre-trained from the models subdirectory.
# As an example, we'll study a prostate cancer susceptibility allele of rs339331 that increases RFX6 expression by modulating HOXB13 chromatin binding (http://www.nature.com/ng/journal/v46/n2/full/ng.2862.html).
#
# First, we'll use [basenji_sad.py](https://github.com/calico/basenji/blob/master/bin/basenji_sad.py) to predict across the region for each allele and compute stats about the mean and max differences.
#
# The most relevant options are:
#
# | Option/Argument | Value | Note |
# |:---|:---|:---|
# | --cpu | True | Run on CPU (and avoid a GPU prefetch op.) |
# | -f | data/hg19.ml.fa | Genome fasta. |
# | -g | data/human.hg19.genome | Genome assembly chromosome length to bound gene sequences. |
# | --h5 | True | Write output to HDF5. |
# | -o | rfx6_sad | Outplot plot directory. |
# | --rc | True | Ensemble predictions for forward and reverse complement sequences. |
# | --shift | 1,0,-1 | Ensemble predictions for sequences shifted by 1, 0, and -1 bp. |
# | -t | data/heart_wigs.txt | Target labels. |
# | params_file | models/params_small.txt | Table of parameters to setup the model architecture and optimization parameters. |
# | model_file | models/heart/model_best.tf | Trained saved model prefix. |
# | vcf_file | data/rs339331.vcf | VCF file specifying variants to score. |
# ! basenji_sad.py --cpu -f data/hg19.ml.fa -g data/human.hg19.genome --h5 -o output/rfx6_sad --rc --shift "1,0,-1" -t data/heart_wigs.txt models/params_small.txt models/heart/model_best.tf data/rs339331.vcf
# ## SNP activity difference output
# The output HDF5 stores the SNP and target information and predicted scores.
sad_h5 = h5py.File('output/rfx6_sad/sad.h5', 'r')
list(sad_h5.keys())
for snp_key in ['snp', 'chr', 'pos', 'ref']:
print(snp_key, sad_h5[snp_key][:])
for ti in range(3):
cols = (ti, sad_h5['SAD'][0,ti], sad_h5['target_ids'][ti], sad_h5['target_labels'][ti])
print('%2d %7.4f %12s %s' % cols)
# These are inconclusive small effect sizes, not surprising given that we're only studying heart CAGE. The proper cell types and experiments would shed more light.
# ## SNP expression difference compute
# Alternatively, we can directly query the predictions at gene TSS's using [basenji_sed.py](https://github.com/calico/basenji/blob/master/bin/basenji_sed.py). Note that I haven't revised these scripts to make use of tf.data, so they are a bit less wieldy right now.
#
# [basenji_sed.py](https://github.com/calico/basenji/blob/master/bin/basenji_sed.py) takes as input the gene sequence HDF5 format described in [genes.ipynb](https://github.com/calico/basenji/blob/master/tutorials/genes.ipynb). There's no harm to providing an HDF5 that describes all genes, but it's too big to easily move around so I constructed one that focuses on RFX6.
#
# The most relevant options are:
#
# | Option/Argument | Value | Note |
# |:---|:---|:---|
# | -g | data/human.hg19.genome | Genome assembly chromosome length to bound gene sequences. |
# | -o | rfx6_sed | Outplot plot directory. |
# | --rc | | Predict forward and reverse complement versions and average the results. |
# | -w | 128 | Sequence bin width at which predictions are made. |
# | params_file | models/params_med.txt | Table of parameters to setup the model architecture and optimization parameters. |
# | model_file | models/gm12878.tf | Trained saved model prefix. |
# | genes_hdf5_file | data/rfx6.h5 | HDF5 file specifying gene sequences to query. |
# | vcf_file | data/rs339331.vcf | VCF file specifying variants to score. |
# Before running [basenji_sed.py](https://github.com/calico/basenji/blob/master/bin/basenji_sed.py), we need to generate an input data file for RFX6. Using an included GTF file that contains only RFX6, one can use [basenji_hdf5_genes.py](https://github.com/calico/basenji/blob/master/bin/basenji_hdf5_genes.py) to create the required format.
# ! basenji_hdf5_genes.py -g data/human.hg19.genome -l 131072 -c 0.333 -w 128 data/hg19.ml.fa data/rfx6.gtf data/rfx6.h5
# ! basenji_sed.py -a -g data/human.hg19.genome -o output/rfx6_sed --rc models/params_small.txt models/heart/model_best.tf data/rfx6.h5 data/rs339331.vcf
# ## SNP expression difference compute
# ! sort -k9 -g output/rfx6_sed/sed_gene.txt
# ! sort -k9 -gr output/rfx6_sed/sed_gene.txt
|
tutorials/sad.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Solving classification problems with CatBoost
# [](https://colab.research.google.com/github/catboost/tutorials/blob/master/events/intel_hands_on_moscow_oct_11_2019.ipynb)
#
# In this tutorial we will use dataset Amazon Employee Access Challenge from [Kaggle](https://www.kaggle.com) competition for our experiments. Data can be downloaded [here](https://www.kaggle.com/c/amazon-employee-access-challenge/data).
# +
import os
import pandas as pd
import numpy as np
np.set_printoptions(precision=4)
import catboost
print(catboost.__version__)
# -
# ## Reading the data
# +
from catboost.datasets import amazon
(train_df, test_df) = amazon()
train_df.head()
# -
#
#
# ## Preparing the data
# Label values extraction
y = train_df.ACTION
X = train_df.drop('ACTION', axis=1)
# Categorical features declaration
cat_features = list(range(0, X.shape[1]))
print(cat_features)
# Looking on label balance in dataset
print('Labels: {}'.format(set(y)))
print('Zero count = {}, One count = {}'.format(len(y) - sum(y), sum(y)))
# Ways to create Pool class
# +
dataset_dir = './amazon'
if not os.path.exists(dataset_dir):
os.makedirs(dataset_dir)
train_df.to_csv(
os.path.join(dataset_dir, 'train.csv'),
index=False, sep=',', header=True
)
test_df.to_csv(
os.path.join(dataset_dir, 'test.csv'),
index=False, sep=',', header=True
)
# -
# !head -3 amazon/train.csv
# +
from catboost.utils import create_cd
feature_names = dict(list(enumerate(train_df.keys()[1:])))
create_cd(
label=0,
cat_features=list(range(1, train_df.shape[1])),
feature_names=feature_names,
output_path=os.path.join(dataset_dir, 'train.cd')
)
# -
# !cat amazon/train.cd
# +
from catboost import Pool
pool1 = Pool(data=X, label=y, cat_features=cat_features)
pool2 = Pool(
data=os.path.join(dataset_dir, 'train.csv'),
delimiter=',',
column_description=os.path.join(dataset_dir, 'train.cd'),
has_header=True
)
print('Dataset shape: {}\n'.format(pool1.shape))
print('Column names: {}'.format(pool1.get_feature_names()))
# +
from catboost import CatBoostClassifier
CatBoostClassifier(iterations=3).fit(pool1)
CatBoostClassifier(iterations=3).fit(pool2)
CatBoostClassifier(iterations=3).fit(X, y, cat_features=cat_features);
# -
# ## Split your data into train and validation
# +
from sklearn.model_selection import train_test_split
data = train_test_split(X, y, train_size=0.8, random_state=0)
X_train, X_validation, y_train, y_validation = data
train_pool = Pool(
data=X_train,
label=y_train,
cat_features=cat_features
)
validation_pool = Pool(
data=X_validation,
label=y_validation,
cat_features=cat_features
)
# -
# ## Training
# +
model = CatBoostClassifier(
iterations=5,
learning_rate=0.1,
)
model.fit(train_pool, eval_set=validation_pool, verbose=False)
print('Model is fitted: {}'.format(model.is_fitted()))
print('Model params:\n{}'.format(model.get_params()))
# -
# ## Stdout of the training
model = CatBoostClassifier(
iterations=15,
# verbose=5,
)
model.fit(train_pool, eval_set=validation_pool);
# ## Metrics calculation and graph plotting
# +
model = CatBoostClassifier(
iterations=50,
learning_rate=0.5,
custom_loss=['AUC', 'Accuracy']
)
model.fit(
train_pool,
eval_set=validation_pool,
verbose=False,
plot=True
);
# -
# ## Model comparison
# +
model1 = CatBoostClassifier(
learning_rate=0.7,
iterations=100,
train_dir='learing_rate_0.7'
)
model2 = CatBoostClassifier(
learning_rate=0.01,
iterations=100,
train_dir='learing_rate_0.01'
)
model1.fit(train_pool, eval_set=validation_pool, verbose=False)
model2.fit(train_pool, eval_set=validation_pool, verbose=False);
# -
from catboost import MetricVisualizer
MetricVisualizer(['learing_rate_0.7', 'learing_rate_0.01']).start()
# ## Best iteration
model = CatBoostClassifier(
iterations=100,
learning_rate=0.5,
# use_best_model=False
)
model.fit(
train_pool,
eval_set=validation_pool,
verbose=False,
plot=True
);
print('Tree count: ' + str(model.tree_count_))
# ## Overfitting Detector
# +
model_with_early_stop = CatBoostClassifier(
iterations=200,
learning_rate=0.5,
early_stopping_rounds=20
)
model_with_early_stop.fit(
train_pool,
eval_set=validation_pool,
verbose=False,
plot=True
);
# -
print(model_with_early_stop.tree_count_)
# ### Overfitting Detector with eval metric
model_with_early_stop = CatBoostClassifier(
eval_metric='AUC',
iterations=200,
learning_rate=0.5,
early_stopping_rounds=20
)
model_with_early_stop.fit(
train_pool,
eval_set=validation_pool,
verbose=False,
plot=True
);
print(model_with_early_stop.tree_count_)
# ## Cross-validation
# +
from catboost import cv
params = {
'loss_function': 'Logloss',
'iterations': 80,
'custom_loss': 'AUC',
'learning_rate': 0.5,
}
cv_data = cv(
params = params,
pool = train_pool,
fold_count=5,
shuffle=True,
partition_random_seed=0,
plot=True,
stratified=True,
verbose=False
)
# -
cv_data.head(10)
# +
best_value = cv_data['test-Logloss-mean'].min()
best_iter = cv_data['test-Logloss-mean'].values.argmin()
print('Best validation Logloss score: {:.4f}±{:.4f} on step {}'.format(
best_value,
cv_data['test-Logloss-std'][best_iter],
best_iter)
)
# -
# ## Grid Search
model = CatBoostClassifier(iterations=10, eval_metric='AUC')
grid = {'learning_rate': [0.001, 0.01, 0.1, 1.0, 10.0]}
result = model.grid_search(grid, train_pool)
print(result['params'])
print(result['cv_results'].keys())
print(result['cv_results']['test-AUC-mean'])
model.get_params()
model.grid_search(grid, train_pool, plot=True, verbose=False);
# More about parameter tuning you can find in [tutorial](https://github.com/catboost/catboost/blob/master/catboost/tutorials/hyperparameters_tuning/hyperparameters_tuning.ipynb).
# ## Model predictions
# +
model = CatBoostClassifier(iterations=200, learning_rate=0.03)
model.fit(
train_pool,
verbose=False,
plot=True
);
# -
print(model.predict_proba(X_validation))
print(model.predict(X_validation))
# ## Select decision boundary
# 
# +
import matplotlib.pyplot as plt
from catboost.utils import get_roc_curve
from catboost.utils import get_fpr_curve
from catboost.utils import get_fnr_curve
curve = get_roc_curve(model, validation_pool)
(fpr, tpr, thresholds) = curve
(thresholds, fpr) = get_fpr_curve(curve=curve)
(thresholds, fnr) = get_fnr_curve(curve=curve)
# +
plt.figure(figsize=(16, 8))
style = {'alpha':0.5, 'lw':2}
plt.plot(thresholds, fpr, color='blue', label='FPR', **style)
plt.plot(thresholds, fnr, color='green', label='FNR', **style)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.grid(True)
plt.xlabel('Threshold', fontsize=16)
plt.ylabel('Error Rate', fontsize=16)
plt.title('FPR-FNR curves', fontsize=20)
plt.legend(loc="lower left", fontsize=16);
# +
from catboost.utils import select_threshold
print(select_threshold(model, validation_pool, FNR=0.01))
print(select_threshold(model, validation_pool, FPR=0.01))
# -
# ## Metric evaluation on a new dataset
metrics = model.eval_metrics(
data=validation_pool,
metrics=['Logloss','AUC'],
ntree_start=0,
ntree_end=0,
eval_period=1,
plot=True
)
print('AUC values:\n{}'.format(np.array(metrics['AUC'])))
# ## Feature importances
# ### Prediction values change
model.get_feature_importance(prettified=True)
# ### Loss function change
model.get_feature_importance(
validation_pool,
'LossFunctionChange',
prettified=True
)
# ### Shap values
# +
shap_values = model.get_feature_importance(
pool1,
'ShapValues'
)
expected_value = shap_values[0,-1]
shap_values = shap_values[:,:-1]
print(shap_values.shape)
# +
import shap
shap.initjs()
shap.force_plot(expected_value, shap_values[10,:], X.iloc[10,:])
# -
# More information about shap value usage you can find in [tutorial](https://github.com/catboost/catboost/blob/master/catboost/tutorials/model_analysis/shap_values_tutorial.ipynb).
# ## Snapshotting
# +
# # !rm 'catboost_info/snapshot.bkp'
model = CatBoostClassifier(
iterations=100,
save_snapshot=True,
snapshot_file='snapshot.bkp',
snapshot_interval=1
)
model.fit(train_pool, eval_set=validation_pool, verbose=10);
# -
# ## Saving the model
model = CatBoostClassifier(iterations=10)
model.fit(train_pool, eval_set=validation_pool, verbose=False)
model.save_model('catboost_model.bin')
model.save_model('catboost_model.json', format='json')
model.load_model('catboost_model.bin')
print(model.get_params())
print(model.learning_rate_)
# # Bonus
# ## Solving MultiClassification problem
# +
model = CatBoostClassifier(loss_function='MultiClass', iterations=50)
model.fit(
train_pool,
eval_set=validation_pool,
verbose=False,
plot=True
);
# -
# ## Hyperparameter tunning
# +
tunned_model = CatBoostClassifier(
iterations=1000,
learning_rate=0.03,
l2_leaf_reg=3,
boosting_type='Plain',
bootstrap_type='Bernoulli',
subsample=0.5,
rsm=0.5,
random_strength=1,
one_hot_max_size=2,
leaf_estimation_method='Newton',
leaf_estimation_iterations=5,
max_ctr_complexity=1,
)
tunned_model.fit(
X_train, y_train,
cat_features=cat_features,
verbose=False,
eval_set=(X_validation, y_validation),
plot=True
);
|
catboost/tutorials/events/intel_hands_on_moscow_oct_11_2019.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# +
import pymongo as pm
client = pm.MongoClient("mongodb+srv://aditya:<EMAIL>/Database?retryWrites=true&w=majority")
db = client['Database']
col = db['contact']
col.insert_one({"_id":1})
|
.ipynb_checkpoints/Untitled-checkpoint.ipynb
|
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .jl
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Julia 1.1.1
# language: julia
# name: julia-1.1
# ---
# # Demo: a life-cycle model with one random shock on consumption
#
# Using `src.jl` and `Household.jl`. Please read the academic [documentation](https://clpr.github.io/pages/blogs/190622_The_household_life_cycle_problem_with_a_continuous_medical_expenditure_shock.html) for details.
# julia 1.1
push!(LOAD_PATH,pwd()) # add current working directory to search paths
import Household # solvers of the household problem
import src # useful tools, used to prepare data
# ## Part 1: $v_{1}\sim\pi_{\mathbb{v}}$, corresponding to Section 4 in the documentation (analytical solution without borrowing constraint)
#
# First, we construct a common scenario for some variables:
# $$
# \begin{cases}
# A_s \equiv 0.99, s=1,\dots,S-1 \\
# A_S = 1.0, s=S \\
# B_s \equiv (1+r) = 1.05 \\
# F_s = (1-\sigma)w = 0.7, s=1,\dots,20 \\
# F_s = 0, s=21,\dots,S \\
# S = 40
# \end{cases}
# $$
# Then, we define $\dot{E}_s$ as the Section 5.1 in our academic documentation:
# $$
# \dot{E}_s = (1+\mu_s)[ 1 + I(v_s)\cdot \text{cp}_s \cdot v_s + (1-I(v_s))\cdot v_s ], s= 1,\dots,S
# $$
# where $\mu_s\equiv 0.13, \text{cp}_s\equiv 0.3$ are exogenous parameters,
# $v_s$ is a random variable following an AR(1) process $ \ln{v_{s+1}} = (1-\rho)m + \rho\ln{v_{s}} + \epsilon_s, \epsilon\sim \text{i.i.d. }N(0,\sigma_\epsilon) $.
# Please note that we let $A_S=1$ because **all** agents quit the economy at time $S+1$. In some ways, they all live through year $S$.
#
#
# Assuming that we have estimated $\rho=0.95,m=-2.659$ and $\sigma_\epsilon=0.05$ from data.
#
# With $ \dot{f}(v_s) = [ I(v_s)\cdot \text{cp}_s + (1-I(v_s))\cdot ] v_s $, the next thing to do is to computing the expectation of $\dot{E}(v_s)$.
# It consists of:
# 1. Discretizing the AR(1) process of $v_s$ with a discrete Markov Chain
# 2. Computing $\mathbb{E}[\dot{f}(v_s)]$
# 3. Computing $\mathbb{E}[\dot{E}(v_s)]$ with $\mathbb{E}[\dot{f}(v_s)]$
# +
S = 40 # maximum number of periods
# DISCRETIZING AR(1) PROCESS
# 1. get an AR(1) instance
vProcess = src.DiscreteTimeAR1( 0.95, 0.05, Z̄ = -2.659 )
# 2. using (Tauchen, 1986) algorithm to do discretization
vMC = src.approx_ar1(vProcess)
# 3. get the stationary distribution of vMC
π_vMC = src.stationary_distribution(vMC)
# 4. make ln(v_s) to v_s (changing the states of vMC)
vMC.w = exp.(vMC.w)
# display the results
println("The approximating Markov Chain is: ", vMC.w )
# println("With a transition matrix: ", vMC.P )
println("Its stationary distribution is: ", π_vMC )
# -
# Assuming $\text{cp}_s\equiv 0.3$, and the threshold $\underline{v} = 0.08$, we can compute $\mathbb{E}[\dot{f}(v_s)]$:
cp = fill(0.3, S)
tmpidx = (vMC.w .< 0.08, vMC.w .>= 0.08 )::Tuple
𝔼f = sum( vMC.w[tmpidx[1]] .* π_vMC[tmpidx[1]] ) .+ cp .* sum( vMC.w[tmpidx[2]] .* π_vMC[tmpidx[2]] )
println("𝔼f is a ", typeof(𝔼f), " whose length is ", length(𝔼f))
println(𝔼f)
# ------------------
𝔼E = (1 + 0.13) .* ( 1 .+ 𝔼f )
println("𝔼f is: "); println(𝔼E)
# Now, let's prepare a data package and put it into our solver.
dat = Household.LifeCycleDatPkg(
cat(fill(0.99,S-1),[1.0,],dims=1), # As
fill(1.05,S), # Bs
𝔼E,
cat(fill(0.7,20),zeros(S-20),dims=1), # Fs
a1 = 0.0, β = 0.99, γ = 1.5, S = S
)
# let's solve it
@time res = Household.solve(dat)
# Finally, we do some simple visualization
# +
using PyPlot
figure(figsize=(12,4));
subplot(1,2,1)
plot(1:S,res.a); grid(true); title("solved expecation path/distribution of capital"); xlabel("Age"); ylabel("Asset (a)")
subplot(1,2,2)
plot(1:S,res.c); grid(true); title("Consumption"); xlabel("Age"); ylabel("Consumption (c)");
# -
# In the above two figures, we can see that households borrow money to consume in the first 16~17 years, then begin to do savings. Their asset becomes exact zero when age is 41 (not plotted but obvious).
# The underlying assumption is that there is a perfect annuity market in which younger generations are able to borrow money from elder generations without transaction cost (i.e. no friction).
# This case is quite common in theoretical analysis.
# But there is one important disadvantage: <font color=red><b>this method cannot handle the case with borrowing limit(s).</b></font>
# ## Part 2: $v_{1}\sim\pi_{\mathbb{v}}$ corresponding to Section 5.2 in the documentation (deterministic Dynamic Programming with borrowing constraint)
#
# So, if there is a borrowing constraint, e.g. $a_s\geq 0$ for all $s$, how to solve this life-cycle problem?
# Section 5.2 in our [academic documentation](https://clpr.github.io/pages/blogs/190622_The_household_life_cycle_problem_with_a_continuous_medical_expenditure_shock.html) (please carefully read it before trying to understand this demo) discusses this topic. A main conclusion is: <b>if the initial distribution follows the stationary distribution of the discretized Markov Chain, then this stochastic life-cycle model is equivalent to a deterministic dynamic programming problem</b>.
# This part is a demo to show how to use our standard solver provided in `Household.jl` to solve a deterministic Dynamic Programming problem which can be denoted as the following Bellman equation:
# $$
# \begin{aligned}
# V_s(a_s) &= \max_{c_s\geq0} \mathbb{E}\Big{[} u(c_s) + \beta V_{s+1}(k_{s+1}|v_{s}) \Big{]} \\
# \text{s.t.}&\begin{cases}
# a_s\in[\underline{a},\bar{a}],s=1,\dots,S \\
# A_{s} a_{s+1} = B_{s} a_{s} - E_{s} c_s + F_s \\
# a_1 \in R^+ \\
# a_{S+1} = 0 \\
# S\geq 2 \\
# \end{cases}
# \end{aligned}
# $$
# Here because $\mathbb{E}[\dot{E}_s(v_s)]$ is period-independent, we write it as $E_{s}$ for generality.
#
# This solver is developed based on the Gauss programs in [(<NAME>, 2015)](https://www.wiwi.uni-augsburg.de/en/vwl/maussner/chair/maussner/).
#
# <font color=red>We still use the data pacakge `dat` defined above, to display the difference between no-borrowing-constraint and with-borrowing-constraint.</font>
gridnums = [100,200,500,1000]
figure(figsize=(12,4)); # new a blank figure
for tmp_gridnum in gridnums
@time res = Household.solve_dp(dat, gridnum = tmp_gridnum) # solve and print the time cost
subplot(1,2,1); plot(res.a)
subplot(1,2,2); plot(res.c)
end # for
# add title, labels etc.
subplot(1,2,1); title("optimal asset paths at different griding search level"); xlabel("Age"); grid(true); ylabel("Asset (a)")
subplot(1,2,2); title("optimal consumption paths at different griding search level"); xlabel("Age"); grid(true); ylabel("Consumption (c)")
legend( "griding number: " .* string.(gridnums) )
# There are several important conclusions that can be drawed from the above figures. <font color=red><b>They are general and very helpful in your own computing.</b></font>
# 1. Dynamic programming can handle borrowing constraints (we use default setting that $a_s\in[0,\sum^S_{s=1}F_s]$)
# 2. With the number of griding search points grows, the optimal asset distribution curve becomes more smooth which means closer to the latent otpimal solution
# 3. However, DP is time-costing. In this demo, its time cost grows with `gridnum` in an exponential form. This makes your model computing very time-costing even infeasible. Readers need to weigh beween performance and the solution's optimality
# 4. If the life-cycle model can be solved or approximated analytically, then use analytical conclusions but to avoid DP. (In our [another research](https://github.com/Clpr/OLG4UEBMI), we use a kind of analytical approximation which has near-zero time cost but better optimality than DP. The optimality is measured with the present value of life-time utilities)
# ## Part 3: $v_1\sim\tilde{\pi}_{\mathbb{v}},\tilde{\pi}_{\mathbb{v}}\neq\pi_{\mathbb{v}}$ corresponding to Section 5.3 in the documentation (stochastic Dynamic Programming with borrowing constraint)
#
|
190623_LifeCycleWithOneShockOnConsumption/demo.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.7.5 64-bit
# name: python37564bit0101c40685f74ac2afe19d6555c1a2e3
# ---
# +
# imports
import os
import nltk
import nltk.corpus
# +
print(os.listdir(nltk.data.find('corpora')))
# +
# this can be used to download any package of nltk
nltk.download()
# -
from nltk.corpus import brown
brown.words()
# +
nltk.corpus.gutenberg.fileids()
# -
# 500 words from bible-kjv
words = nltk.corpus.gutenberg.words('bible-kjv.txt')
for word in words[:500]:
print(word, sep=' ', end= ' ')
# +
# Tokenization
# sample paragraph
ML = ''' Today, machine learning is used in a wide range of applications. Perhaps one of the most
well-known examples of machine learning in action is therecommendation engine that powers Facebook's News Feed.Facebook uses machine learning to ;
personalize how each member's feed is delivered. If a member frequently stops to read a particular
group’s posts, the recommendation engine will start to show more of that group’s activity earlier
in the feed. '''
from nltk.tokenize import word_tokenize
tokens = word_tokenize(ML) # converting into tokens
print(tokens)
print("\nLength of tokens : ", len(tokens))
# +
# word count of tokens i,e frequency of words in tokens
from nltk.probability import FreqDist
frd = FreqDist()
for token in tokens:
frd[token.lower()] +=1
frd
# +
# get the distinct tokens without repeated words
print('number of distinct words in entire tokens : ',len(frd))
# -
# most common tokens i,e words with high frequency
top_ten = frd.most_common(10)
print(top_ten)
# get the number of paragraphs seperated by new line
from nltk.tokenize import blankline_tokenize
blank_tokens = blankline_tokenize(ML)
print('There are :',len(blank_tokens),' new lines seperating the paragraph ')
# Print a particuar paragraph
index_number = 0 # first paragraph change the index to print others
blank_tokens[index_number]
# +
# make bigrams trigrams and ngram tokens
str = "Nothing Personel,Just Business"
from nltk.util import bigrams, trigrams , ngrams
str_tokens = word_tokenize(str)
print("Bigrams : ",list(bigrams(str_tokens)))
print("Trigrams : ",list(trigrams(str_tokens)))
# for n grams We need to pass the value N , N = 2 for bigram, N = 3 for Trigram and so on...
N = 4
print("Bigrams : ",list(ngrams(str_tokens, N)))
# +
# Stemming : Normalize every word into its base root form
# 1. Using PorterStemmer
from nltk.stem import PorterStemmer
ps = PorterStemmer()
ps.stem('Doing') # get the root form of Doing i,e do
# -
# 2. Using LancasterStemmer
from nltk.stem import LancasterStemmer
ls = LancasterStemmer()
ls.stem('Doing')
# +
# from the results we can conclude that LancasterStemmer is more agressive than PorterStemmer
# -
# 3. Using SnowballStemmer
from nltk.stem import SnowballStemmer
sbs = SnowballStemmer('english') # for SnowballStemmer we need to specify the language
sbs.stem('Doing')
|
Practice.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import pandas as pd
# ## Combine all Vaccine Data Years
# Import compiled vaccine data
data1112 = pd.read_csv("cleanjoin1112.csv", encoding = "ISO-8859-1")
data1213 = pd.read_csv("cleanjoin1213.csv", encoding = "ISO-8859-1")
data1314 = pd.read_csv("cleanjoin1314.csv", encoding = "ISO-8859-1")
data1415 = pd.read_csv("cleanjoin1415.csv", encoding = "ISO-8859-1")
data1516 = pd.read_csv("cleanjoin1516.csv", encoding = "ISO-8859-1")
data1617 = pd.read_csv("cleanjoin1617.csv", encoding = "ISO-8859-1")
data1718 = pd.read_csv("cleanjoin1718.csv", encoding = "ISO-8859-1")
# +
data1112['year']='2012'
data1213['year']='2013'
data1314['year']='2014'
data1415['year']='2015'
data1516['year']='2016'
data1617['year']='2017'
data1718['year']='2018'
data1112['school_year']='2011-2012'
data1213['school_year']='2012-2013'
data1314['school_year']='2013-2014'
data1415['school_year']='2014-2015'
data1516['school_year']='2015-2016'
data1617['school_year']='2016-2017'
data1718['school_year']='2017-2018'
# -
data1112.dtypes
cleanjoin1118=pd.concat([
data1112,
data1213,
data1314,
data1415,
data1516,
data1617,
data1718
],ignore_index=False,sort=False)
cleanjoin1118.head()
#Count how many unique schools there are
len(cleanjoin1118.facility_name.unique())
#Count how many unique cities there are
len(cleanjoin1118.city.unique())
#Count how many unique cities there are
len(cleanjoin1118.county.unique())
cleanjoin1118.dtypes
# # Census
# ### Census Education Data City Level
# +
educ11 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/ACS_11_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
educ12 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/ACS_12_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
educ13 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/ACS_13_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
educ14 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/ACS_14_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
educ15 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/ACS_15_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
educ16 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/ACS_16_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
edu11 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_11_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
edu12 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_12_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
edu13 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_13_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
edu14 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_14_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
edu15 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_15_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
edu16 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_16_5YR_S1501.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
# +
#City
educ11= educ11[['GEO.id', 'HC01_EST_VC16','HC01_EST_VC17']]
educ12= educ12[['GEO.id', 'HC01_EST_VC16','HC01_EST_VC17']]
educ13= educ13[['GEO.id', 'HC01_EST_VC16','HC01_EST_VC17']]
educ14= educ14[['GEO.id', 'HC01_EST_VC16','HC01_EST_VC17']]
educ15= educ15[['GEO.id', 'HC02_EST_VC17','HC02_EST_VC18']]
educ16= educ16[['GEO.id', 'HC02_EST_VC17','HC02_EST_VC18']]
#County
edu11= edu11[['GEO.id', 'HC01_EST_VC16','HC01_EST_VC17']]
edu12= edu12[['GEO.id', 'HC01_EST_VC16','HC01_EST_VC17']]
edu13= edu13[['GEO.id', 'HC01_EST_VC16','HC01_EST_VC17']]
edu14= edu14[['GEO.id', 'HC01_EST_VC16','HC01_EST_VC17']]
edu15= edu15[['GEO.id', 'HC02_EST_VC17','HC02_EST_VC18']]
edu16= edu16[['GEO.id', 'HC02_EST_VC17','HC02_EST_VC18']]
# +
# City
educ11.rename(columns={'GEO.id': 'geoid',
'HC01_EST_VC16': 'hs_degree_pct',
'HC01_EST_VC17': 'bachelor_degree_pct'
},
inplace=True)
educ12.rename(columns={'GEO.id': 'geoid',
'HC01_EST_VC16': 'hs_degree_pct',
'HC01_EST_VC17': 'bachelor_degree_pct'
},
inplace=True)
educ13.rename(columns={'GEO.id': 'geoid',
'HC01_EST_VC16': 'hs_degree_pct',
'HC01_EST_VC17': 'bachelor_degree_pct'
},
inplace=True)
educ14.rename(columns={'GEO.id': 'geoid',
'HC01_EST_VC16': 'hs_degree_pct',
'HC01_EST_VC17': 'bachelor_degree_pct'
},
inplace=True)
educ15.rename(columns={'GEO.id': 'geoid',
'HC02_EST_VC17': 'hs_degree_pct',
'HC02_EST_VC18': 'bachelor_degree_pct'
},
inplace=True)
educ16.rename(columns={'GEO.id': 'geoid',
'HC02_EST_VC17': 'hs_degree_pct',
'HC02_EST_VC18': 'bachelor_degree_pct'
},
inplace=True)
#County
edu11.rename(columns={
'HC01_EST_VC16': 'hs_degree_pct',
'HC01_EST_VC17': 'bachelor_degree_pct'
},
inplace=True)
edu12.rename(columns={
'HC01_EST_VC16': 'hs_degree_pct',
'HC01_EST_VC17': 'bachelor_degree_pct'
},
inplace=True)
edu13.rename(columns={
'HC01_EST_VC16': 'hs_degree_pct',
'HC01_EST_VC17': 'bachelor_degree_pct'
},
inplace=True)
edu14.rename(columns={
'HC01_EST_VC16': 'hs_degree_pct',
'HC01_EST_VC17': 'bachelor_degree_pct'
},
inplace=True)
edu15.rename(columns={
'HC02_EST_VC17': 'hs_degree_pct',
'HC02_EST_VC18': 'bachelor_degree_pct'
},
inplace=True)
edu16.rename(columns={
'HC02_EST_VC17': 'hs_degree_pct',
'HC02_EST_VC18': 'bachelor_degree_pct'
},
inplace=True)
# +
educ11['year']='2011'
educ12['year']='2012'
educ13['year']='2013'
educ14['year']='2014'
educ15['year']='2015'
educ16['year']='2016'
educ17=educ16.copy()
educ17['year']='2017'
educ18=educ16.copy()
educ18['year']='2018'
edu11['year']='2011'
edu12['year']='2012'
edu13['year']='2013'
edu14['year']='2014'
edu15['year']='2015'
edu16['year']='2016'
edu17=edu16.copy()
edu17['year']='2017'
edu18=edu16.copy()
edu18['year']='2018'
# -
educ18.head()
edu18.head()
# +
county_edu=pd.concat([
edu12,
edu13,
edu14,
edu15,
edu16,
edu17,
edu18
],ignore_index=True)
city_edu=pd.concat([
educ12,
educ13,
educ14,
educ15,
educ16,
educ17,
educ18
],ignore_index=True)
# -
county_edu.head()
city_edu.head()
# #### Census population city level
# Import compiled census data
c11 = pd.read_csv("pop_data11.csv", encoding = "ISO-8859-1")
c12 = pd.read_csv("pop_data12.csv", encoding = "ISO-8859-1")
c13 = pd.read_csv("pop_data13.csv", encoding = "ISO-8859-1")
c14 = pd.read_csv("pop_data14.csv", encoding = "ISO-8859-1")
c15 = pd.read_csv("pop_data15.csv", encoding = "ISO-8859-1")
c16 = pd.read_csv("pop_data16.csv", encoding = "ISO-8859-1")
# #Keep relevant variables
# acs11=c11[['geoid','city','male_pct','female_pct','under_5_pct','5_9_pct','10_14_pct',
# '15_19_pct','20_24_pct','25_34_pct','35_44_pct','45_54_pct','55_59_pct','60_64_pct',
# '65_74_pct','75_84_pct','85_over_pct','median_age','hispanic_latino_pct',
# 'white_pct','black_pct','aian_pct','asian_pct','nhopi_pct','other_pct',
# 'median_income', 'insurance_pct', 'private_insure_pct',
# 'public_insure_pct','no_insurance_pct']]
# acs12=c12[['geoid','city','male_pct','female_pct','under_5_pct','5_9_pct','10_14_pct',
# '15_19_pct','20_24_pct','25_34_pct','35_44_pct','45_54_pct','55_59_pct','60_64_pct',
# '65_74_pct','75_84_pct','85_over_pct','median_age','hispanic_latino_pct',
# 'white_pct','black_pct','aian_pct','asian_pct','nhopi_pct','other_pct',
# 'median_income', 'insurance_pct', 'private_insure_pct',
# 'public_insure_pct','no_insurance_pct']]
# acs13=c13[['geoid','city','male_pct','female_pct','under_5_pct','5_9_pct','10_14_pct',
# '15_19_pct','20_24_pct','25_34_pct','35_44_pct','45_54_pct','55_59_pct','60_64_pct',
# '65_74_pct','75_84_pct','85_over_pct','median_age','hispanic_latino_pct',
# 'white_pct','black_pct','aian_pct','asian_pct','nhopi_pct','other_pct',
# 'median_income', 'insurance_pct', 'private_insure_pct',
# 'public_insure_pct','no_insurance_pct']]
# acs14=c14[['geoid','city','male_pct','female_pct','under_5_pct','5_9_pct','10_14_pct',
# '15_19_pct','20_24_pct','25_34_pct','35_44_pct','45_54_pct','55_59_pct','60_64_pct',
# '65_74_pct','75_84_pct','85_over_pct','median_age','hispanic_latino_pct',
# 'white_pct','black_pct','aian_pct','asian_pct','nhopi_pct','other_pct',
# 'median_income', 'insurance_pct', 'private_insure_pct',
# 'public_insure_pct','no_insurance_pct']]
# acs15=c15[['geoid','city','male_pct','female_pct','under_5_pct','5_9_pct','10_14_pct',
# '15_19_pct','20_24_pct','25_34_pct','35_44_pct','45_54_pct','55_59_pct','60_64_pct',
# '65_74_pct','75_84_pct','85_over_pct','median_age','hispanic_latino_pct',
# 'white_pct','black_pct','aian_pct','asian_pct','nhopi_pct','other_pct',
# 'median_income', 'insurance_pct', 'private_insure_pct',
# 'public_insure_pct','no_insurance_pct']]
# acs16=c16[['geoid','city','male_pct','female_pct','under_5_pct','5_9_pct','10_14_pct',
# '15_19_pct','20_24_pct','25_34_pct','35_44_pct','45_54_pct','55_59_pct','60_64_pct',
# '65_74_pct','75_84_pct','85_over_pct','median_age','hispanic_latino_pct',
# 'white_pct','black_pct','aian_pct','asian_pct','nhopi_pct','other_pct',
# 'median_income', 'insurance_pct', 'private_insure_pct',
# 'public_insure_pct','no_insurance_pct']]
# +
c11['year']='2011'
c12['year']='2012'
c13['year']='2013'
c14['year']='2014'
c15['year']='2015'
c16['year']='2016'
c17=c16.copy()
c17['year']='2017'
c18=c16.copy()
c18['year']='2018'
# acs11['year']='2011'
# acs12['year']='2012'
# acs13['year']='2013'
# acs14['year']='2014'
# acs15['year']='2015'
# acs16['year']='2016'
# acs17=acs16.copy()
# acs17['year']='2017'
# acs18=acs16.copy()
# acs18['year']='2017'
# -
city_pct_12_16=pd.concat([
c12,
c13,
c14,
c15,
c16,
c17,
c18
],ignore_index=True, sort=False)
city_pct_12_16.head()
# Combine with education data
cityjoin=city_pct_12_16.merge(city_edu, left_on=['geoid','year'], right_on=['geoid','year'], how='left')
cityjoin.head()
# ### Make Correlation Datasets
# ### City
#Keep county, city, school grade, population #, enrollment, vaccinated (n),
vac1112=data1112[['county','city','enrollment','n','vac_info_type']]
vac1213=data1213[['county','city','enrollment','n','vac_info_type']]
vac1314=data1314[['county','city','enrollment','n','vac_info_type']]
vac1415=data1415[['county','city','enrollment','n','vac_info_type']]
vac1516=data1516[['county','city','enrollment','n','vac_info_type']]
vac1617=data1617[['county','city','enrollment','n','vac_info_type']]
vac1718=data1718[['county','city','enrollment','n','vac_info_type']]
vac1112.head()
data1112.head()
vac1112=vac1112.groupby(by=['city'], as_index=False)['enrollment','n'].sum()
vac1213=vac1213.groupby(by=['city'], as_index=False)['enrollment','n'].sum()
vac1314=vac1314.groupby(by=['city'], as_index=False)['enrollment','n'].sum()
vac1415=vac1415.groupby(by=['city'], as_index=False)['enrollment','n'].sum()
vac1516=vac1516.groupby(by=['city'], as_index=False)['enrollment','n'].sum()
vac1617=vac1617.groupby(by=['city'], as_index=False)['enrollment','n'].sum()
vac1718=vac1718.groupby(by=['city'], as_index=False)['enrollment','n'].sum()
# +
vac1112['school_year']='2011-2012'
vac1112['year']='2012'
vac1213['school_year']='2012-2013'
vac1213['year']='2013'
vac1314['school_year']='2013-2014'
vac1314['year']='2014'
vac1415['school_year']='2014-2015'
vac1415['year']='2015'
vac1516['school_year']='2015-2016'
vac1516['year']='2016'
vac1617['school_year']='2016-2017'
vac1617['year']='2017'
vac1718['school_year']='2017-2018'
vac1718['year']='2018'
# -
vac_11_18=pd.concat([vac1112,
vac1213,
vac1314,
vac1415,
vac1516,
vac1617,
vac1718
],ignore_index=True, sort=False)
# +
# # Fix typos
# vac_11_18.loc[vac_11_18.city=='Ananheim', 'city']='Anaheim'
# vac_11_18.loc[vac_11_18.city=='Costa Mesa,', 'city']='Costa Mesa'
# vac_11_18.loc[vac_11_18.city=='Paso Robles', 'city']='El Paso De Robles (Paso Robles)'
# vac_11_18.loc[vac_11_18.city=='El Paso de Robles', 'city']='El Paso De Robles (Paso Robles)'
# vac_11_18.loc[vac_11_18.city=='Chasworth', 'city']='Los Angeles'
# vac_11_18.loc[vac_11_18.city=='Huntington Beach', 'city']='Huntington Beach'
# vac_11_18.loc[vac_11_18.city=='Long Beach', 'city']='Long Beach'
# vac_11_18.loc[vac_11_18.city=='Mt Baldy', 'city']='Mount Baldy'
# vac_11_18.loc[vac_11_18.city=='Mt. Baldy', 'city']='Mount Baldy'
# vac_11_18.loc[vac_11_18.city=='North Hollywood', 'city']='Los Angeles'
# vac_11_18.loc[vac_11_18.city=='Oneals', 'city']="O'Neals"
# vac_11_18.loc[vac_11_18.city=='Canyon County', 'city']='Santa Clarita'
# vac_11_18.loc[vac_11_18.city=='Coaresgold', 'city']='Coarsegold'
# vac_11_18.loc[vac_11_18.city=='El Toro', 'city']='Lake Forest'
# vac_11_18.loc[vac_11_18.city=='Herber', 'city']='Heber'
# vac_11_18.loc[vac_11_18.city=='Hespera', 'city']='Hesperia'
# vac_11_18.loc[vac_11_18.city=='Los Oso', 'city']='Los Osos'
# vac_11_18.loc[vac_11_18.city=='Newport Coast', 'city']='Newport Beach'
# vac_11_18.loc[vac_11_18.city=='Pinedale', 'city']='Fresno'
# vac_11_18.loc[vac_11_18.city=='Rancho Tehema', 'city']='Rancho Tehama Reserve'
# vac_11_18.loc[vac_11_18.city=='Redding ', 'city']='Redding'
# vac_11_18.loc[vac_11_18.city=='Riversidty', 'city']='Riverside'
# vac_11_18.loc[vac_11_18.city=='San Bernadino', 'city']='San Bernardino'
# vac_11_18.loc[vac_11_18.city=='Simi Valley', 'city']='Simi Valley'
# vac_11_18.loc[vac_11_18.city=='Hilmar', 'city']='Hilmar-Irwin'
# -
vac_11_18.rename(columns={'n': 'vaccinated'}, inplace=True)
vac_11_18['vac_pct']=vac_11_18.vaccinated/vac_11_18.enrollment*100
vac_11_18.city.unique()
vac_11_18.tail()
#Export full cleaned data
vac_11_18.to_csv("vac_11_18_combined.csv", index=False)
combined_1118=vac_11_18.merge(cityjoin, left_on=['city', 'year'], right_on=['city','year'], how='inner')
combined_1118
# more data cleaning on cities that didn't merge with census
combined_1118.loc[combined_1118.city=='La Canada Flintridge', 'geoid']='1600000US0639003'
combined_1118.loc[combined_1118.city=='Pinon Hills', 'geoid']='1600000US0657302'
combined_1118.loc[combined_1118.city=='El Paso De Robles (Paso Robles)', 'geoid']='1600000US0622300'
combined_1118.loc[combined_1118.city=='San Miguel (San Luis Obispo County)', 'geoid']='1600000US0668266'
combined_1118.loc[combined_1118.city=='Spring Valley (San Diego County)', 'geoid']='1600000US0673696'
combined_1118.to_csv('city_correlation.csv', index=False)
city_map=combined_1118.copy()
city_map=city_map[['city','enrollment','vaccinated', 'year','vac_pct','geoid']]
# rename to avoid key variable name conflicts
city_map.rename(columns={'year': 's_year'
},
inplace=True)
city_map.head()
# +
# city_map.to_csv('city_vaxmap.csv', index=False)
# -
city_map18=city_map[city_map.s_year=='2018']
city_map18.head()
# +
# city_map18.to_csv('city_vaxmap18.csv', index=False)
# -
# Combine with education data
fulljoin=cleanjoin1118.merge(city_edu, left_on=['geoid','year'], right_on=['geoid','year'], how='left')
fulljoin.head()
fulljoin.to_csv("cleanjoin1118.csv", index=False)
# ## County
# #### Vaccine County level
#Keep county, city, school grade, population #, enrollment, vaccinated (n),
cvac1112=data1112[['county','city','enrollment','n','vac_info_type']]
cvac1213=data1213[['county','city','enrollment','n','vac_info_type']]
cvac1314=data1314[['county','city','enrollment','n','vac_info_type']]
cvac1415=data1415[['county','city','enrollment','n','vac_info_type']]
cvac1516=data1516[['county','city','enrollment','n','vac_info_type']]
cvac1617=data1617[['county','city','enrollment','n','vac_info_type']]
cvac1718=data1718[['county','city','enrollment','n','vac_info_type']]
cvac1112=cvac1112.groupby(by=['county'], as_index=False)['enrollment','n'].sum()
cvac1213=cvac1213.groupby(by=['county'], as_index=False)['enrollment','n'].sum()
cvac1314=cvac1314.groupby(by=['county'], as_index=False)['enrollment','n'].sum()
cvac1415=cvac1415.groupby(by=['county'], as_index=False)['enrollment','n'].sum()
cvac1516=cvac1516.groupby(by=['county'], as_index=False)['enrollment','n'].sum()
cvac1617=cvac1617.groupby(by=['county'], as_index=False)['enrollment','n'].sum()
cvac1718=cvac1718.groupby(by=['county'], as_index=False)['enrollment','n'].sum()
# +
cvac1112['school_year']='2011-2012'
cvac1112['year']='2012'
cvac1213['school_year']='2012-2013'
cvac1213['year']='2013'
cvac1314['school_year']='2013-2014'
cvac1314['year']='2014'
cvac1415['school_year']='2014-2015'
cvac1415['year']='2015'
cvac1516['school_year']='2015-2016'
cvac1516['year']='2016'
cvac1617['school_year']='2016-2017'
cvac1617['year']='2017'
cvac1718['school_year']='2017-2018'
cvac1718['year']='2018'
# -
cvac1112.head()
county_vac1118=pd.concat([cvac1112,
cvac1213,
cvac1314,
cvac1415,
cvac1516,
cvac1617,
cvac1718
],ignore_index=True)
county_vac1118.tail()
# #### Census County level data
# Import and clean census data for basic demographics age gender race is DP05 file
demo11 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_11_5YR_DP05.csv",
encoding = "ISO-8859-1",
header=[0],na_values=['-'])
demo12 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_12_5YR_DP05.csv",
encoding = "ISO-8859-1",
header=[0],na_values=['-'])
demo13 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_13_5YR_DP05.csv",
encoding = "ISO-8859-1",
header=[0],na_values=['-'])
demo14 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_14_5YR_DP05.csv",
encoding = "ISO-8859-1",
header=[0],na_values=['-'])
demo15 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_15_5YR_DP05.csv",
encoding = "ISO-8859-1",
header=[0],na_values=['-'])
demo16 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_16_5YR_DP05.csv",
encoding = "ISO-8859-1",
header=[0],na_values=['-'])
demo11 = demo11[['GEO.id','GEO.id2','GEO.display-label',
'HC01_VC03',
'HC01_VC04', 'HC03_VC04',
'HC01_VC05', 'HC03_VC05',
'HC01_VC07', 'HC03_VC07',
'HC01_VC08', 'HC03_VC08',
'HC01_VC09', 'HC03_VC09',
'HC01_VC10', 'HC03_VC10',
'HC01_VC11', 'HC03_VC11',
'HC01_VC12', 'HC03_VC12',
'HC01_VC13', 'HC03_VC13',
'HC01_VC14', 'HC03_VC14',
'HC01_VC15', 'HC03_VC15',
'HC01_VC16', 'HC03_VC16',
'HC01_VC17', 'HC03_VC17',
'HC01_VC18', 'HC03_VC18',
'HC01_VC19', 'HC03_VC19',
'HC01_VC21', 'HC03_VC21',
'HC01_VC82', 'HC03_VC82',
'HC01_VC83', 'HC03_VC83',
'HC01_VC88', 'HC03_VC88',
'HC01_VC89', 'HC03_VC89',
'HC01_VC90', 'HC03_VC90',
'HC01_VC91', 'HC03_VC91',
'HC01_VC92', 'HC03_VC92',
'HC01_VC93', 'HC03_VC93',
'HC01_VC94', 'HC03_VC94',
'HC01_VC95', 'HC03_VC95',
'HC01_VC96', 'HC03_VC96']]
demo12 = demo12[['GEO.id','GEO.id2','GEO.display-label',
'HC01_VC03',
'HC01_VC04', 'HC03_VC04',
'HC01_VC05', 'HC03_VC05',
'HC01_VC07', 'HC03_VC07',
'HC01_VC08', 'HC03_VC08',
'HC01_VC09', 'HC03_VC09',
'HC01_VC10', 'HC03_VC10',
'HC01_VC11', 'HC03_VC11',
'HC01_VC12', 'HC03_VC12',
'HC01_VC13', 'HC03_VC13',
'HC01_VC14', 'HC03_VC14',
'HC01_VC15', 'HC03_VC15',
'HC01_VC16', 'HC03_VC16',
'HC01_VC17', 'HC03_VC17',
'HC01_VC18', 'HC03_VC18',
'HC01_VC19', 'HC03_VC19',
'HC01_VC21', 'HC03_VC21',
'HC01_VC82', 'HC03_VC82',
'HC01_VC83', 'HC03_VC83',
'HC01_VC88', 'HC03_VC88',
'HC01_VC89', 'HC03_VC89',
'HC01_VC90', 'HC03_VC90',
'HC01_VC91', 'HC03_VC91',
'HC01_VC92', 'HC03_VC92',
'HC01_VC93', 'HC03_VC93',
'HC01_VC94', 'HC03_VC94',
'HC01_VC95', 'HC03_VC95',
'HC01_VC96', 'HC03_VC96']]
#combine other race, two or more races (HC01_VC99, HC01_VC100, HC01_VC101, HC01_VC102)
demo11['other']=pd.Series(demo11['HC01_VC93']+demo11['HC01_VC94']+demo11['HC01_VC95']+demo11['HC01_VC96'])
demo12['other']=pd.Series(demo12['HC01_VC93']+demo12['HC01_VC94']+demo12['HC01_VC95']+demo12['HC01_VC96'])
demo11['other_pct']=pd.Series(demo11['HC03_VC93']+demo11['HC03_VC94']+demo11['HC03_VC95']+demo11['HC03_VC96'])
demo12['other_pct']=pd.Series(demo12['HC03_VC93']+demo12['HC03_VC94']+demo12['HC03_VC95']+demo12['HC03_VC96'])
demo11=demo11.drop(columns=['HC01_VC93','HC03_VC93','HC01_VC94','HC03_VC94','HC01_VC95','HC03_VC95','HC01_VC96','HC03_VC96'])
demo12=demo12.drop(columns=['HC01_VC93','HC03_VC93','HC01_VC94','HC03_VC94','HC01_VC95','HC03_VC95','HC01_VC96','HC03_VC96'])
# +
demo11.rename(columns={'GEO.display-label': 'county',
'HC01_VC03': 'tot_pop',
'HC01_VC04': 'male',
'HC01_VC05': 'female',
'HC01_VC07':'under_5',
'HC01_VC08':'5_9',
'HC01_VC09':'10_14',
'HC01_VC10':'15_19',
'HC01_VC11':'20_24',
'HC01_VC12':'25_34',
'HC01_VC13':'35_44',
'HC01_VC14':'45_54',
'HC01_VC15':'55_59',
'HC01_VC16':'60_64',
'HC01_VC17':'65_74',
'HC01_VC18':'75_84',
'HC01_VC19':'85_over',
'HC01_VC21':'median_age',
'HC01_VC82':'hispanic_latino',
'HC01_VC83':'mexican',
'HC01_VC88':'white',
'HC01_VC89':'black',
'HC01_VC90':'aian',
'HC01_VC91':'asian',
'HC01_VC92':'nhopi',
'HC03_VC04': 'male_pct',
'HC03_VC05': 'female_pct',
'HC03_VC07':'under_5_pct',
'HC03_VC08':'5_9_pct',
'HC03_VC09':'10_14_pct',
'HC03_VC10':'15_19_pct',
'HC03_VC11':'20_24_pct',
'HC03_VC12':'25_34_pct',
'HC03_VC13':'35_44_pct',
'HC03_VC14':'45_54_pct',
'HC03_VC15':'55_59_pct',
'HC03_VC16':'60_64_pct',
'HC03_VC17':'65_74_pct',
'HC03_VC18':'75_84_pct',
'HC03_VC19':'85_over_pct',
'HC03_VC21':'median_age_pct',
'HC03_VC82':'hispanic_latino_pct',
'HC03_VC83':'mexican_pct',
'HC03_VC88':'white_pct',
'HC03_VC89':'black_pct',
'HC03_VC90':'aian_pct',
'HC03_VC91':'asian_pct',
'HC03_VC92':'nhopi_pct'
},
inplace=True)
demo12.rename(columns={'GEO.display-label': 'county',
'HC01_VC03': 'tot_pop',
'HC01_VC04': 'male',
'HC01_VC05': 'female',
'HC01_VC07':'under_5',
'HC01_VC08':'5_9',
'HC01_VC09':'10_14',
'HC01_VC10':'15_19',
'HC01_VC11':'20_24',
'HC01_VC12':'25_34',
'HC01_VC13':'35_44',
'HC01_VC14':'45_54',
'HC01_VC15':'55_59',
'HC01_VC16':'60_64',
'HC01_VC17':'65_74',
'HC01_VC18':'75_84',
'HC01_VC19':'85_over',
'HC01_VC21':'median_age',
'HC01_VC82':'hispanic_latino',
'HC01_VC83':'mexican',
'HC01_VC88':'white',
'HC01_VC89':'black',
'HC01_VC90':'aian',
'HC01_VC91':'asian',
'HC01_VC92':'nhopi',
'HC03_VC04': 'male_pct',
'HC03_VC05': 'female_pct',
'HC03_VC07':'under_5_pct',
'HC03_VC08':'5_9_pct',
'HC03_VC09':'10_14_pct',
'HC03_VC10':'15_19_pct',
'HC03_VC11':'20_24_pct',
'HC03_VC12':'25_34_pct',
'HC03_VC13':'35_44_pct',
'HC03_VC14':'45_54_pct',
'HC03_VC15':'55_59_pct',
'HC03_VC16':'60_64_pct',
'HC03_VC17':'65_74_pct',
'HC03_VC18':'75_84_pct',
'HC03_VC19':'85_over_pct',
'HC03_VC21':'median_age_pct',
'HC03_VC82':'hispanic_latino_pct',
'HC03_VC83':'mexican_pct',
'HC03_VC88':'white_pct',
'HC03_VC89':'black_pct',
'HC03_VC90':'aian_pct',
'HC03_VC91':'asian_pct',
'HC03_VC92':'nhopi_pct'
},
inplace=True)
# AIAN is american Indian Alaskan Native
# NHOPI is Native Hawaiian and Other Pacific Islander
# Other race categories
# 'HC01_VC93':'other_only',
# 'HC01_VC94':'more_two_races',
# 'HC01_VC95':'more_two_races_other',
# 'HC01_VC96':'more_two_races_other_exclude',
# -
demo11.head()
demo13 = demo13[['GEO.id','GEO.id2','GEO.display-label',
'HC01_VC03',
'HC01_VC04','HC03_VC04',
'HC01_VC05','HC03_VC05',
'HC01_VC08','HC03_VC08',
'HC01_VC09','HC03_VC09',
'HC01_VC10','HC03_VC10',
'HC01_VC11','HC03_VC11',
'HC01_VC12','HC03_VC12',
'HC01_VC13','HC03_VC13',
'HC01_VC14','HC03_VC14',
'HC01_VC15','HC03_VC15',
'HC01_VC16','HC03_VC16',
'HC01_VC17','HC03_VC17',
'HC01_VC18','HC03_VC18',
'HC01_VC19','HC03_VC19',
'HC01_VC20','HC03_VC20',
'HC01_VC23','HC03_VC23',
'HC01_VC88','HC03_VC88',
'HC01_VC94','HC03_VC94',
'HC01_VC95','HC03_VC95',
'HC01_VC96','HC03_VC96',
'HC01_VC97','HC03_VC97',
'HC01_VC98','HC03_VC98',
'HC01_VC99','HC03_VC99',
'HC01_VC100','HC03_VC100',
'HC01_VC101','HC03_VC101',
'HC01_VC102','HC03_VC102'
]]
demo14 = demo14[['GEO.id','GEO.id2','GEO.display-label',
'HC01_VC03',
'HC01_VC04','HC03_VC04',
'HC01_VC05','HC03_VC05',
'HC01_VC08','HC03_VC08',
'HC01_VC09','HC03_VC09',
'HC01_VC10','HC03_VC10',
'HC01_VC11','HC03_VC11',
'HC01_VC12','HC03_VC12',
'HC01_VC13','HC03_VC13',
'HC01_VC14','HC03_VC14',
'HC01_VC15','HC03_VC15',
'HC01_VC16','HC03_VC16',
'HC01_VC17','HC03_VC17',
'HC01_VC18','HC03_VC18',
'HC01_VC19','HC03_VC19',
'HC01_VC20','HC03_VC20',
'HC01_VC23','HC03_VC23',
'HC01_VC88','HC03_VC88',
'HC01_VC94','HC03_VC94',
'HC01_VC95','HC03_VC95',
'HC01_VC96','HC03_VC96',
'HC01_VC97','HC03_VC97',
'HC01_VC98','HC03_VC98',
'HC01_VC99','HC03_VC99',
'HC01_VC100','HC03_VC100',
'HC01_VC101','HC03_VC101',
'HC01_VC102','HC03_VC102'
]]
demo15 = demo15[['GEO.id','GEO.id2','GEO.display-label',
'HC01_VC03',
'HC01_VC04','HC03_VC04',
'HC01_VC05','HC03_VC05',
'HC01_VC08','HC03_VC08',
'HC01_VC09','HC03_VC09',
'HC01_VC10','HC03_VC10',
'HC01_VC11','HC03_VC11',
'HC01_VC12','HC03_VC12',
'HC01_VC13','HC03_VC13',
'HC01_VC14','HC03_VC14',
'HC01_VC15','HC03_VC15',
'HC01_VC16','HC03_VC16',
'HC01_VC17','HC03_VC17',
'HC01_VC18','HC03_VC18',
'HC01_VC19','HC03_VC19',
'HC01_VC20','HC03_VC20',
'HC01_VC23','HC03_VC23',
'HC01_VC88','HC03_VC88',
'HC01_VC94','HC03_VC94',
'HC01_VC95','HC03_VC95',
'HC01_VC96','HC03_VC96',
'HC01_VC97','HC03_VC97',
'HC01_VC98','HC03_VC98',
'HC01_VC99','HC03_VC99',
'HC01_VC100','HC03_VC100',
'HC01_VC101','HC03_VC101',
'HC01_VC102','HC03_VC102'
]]
demo16 = demo16[['GEO.id','GEO.id2','GEO.display-label',
'HC01_VC03',
'HC01_VC04','HC03_VC04',
'HC01_VC05','HC03_VC05',
'HC01_VC08','HC03_VC08',
'HC01_VC09','HC03_VC09',
'HC01_VC10','HC03_VC10',
'HC01_VC11','HC03_VC11',
'HC01_VC12','HC03_VC12',
'HC01_VC13','HC03_VC13',
'HC01_VC14','HC03_VC14',
'HC01_VC15','HC03_VC15',
'HC01_VC16','HC03_VC16',
'HC01_VC17','HC03_VC17',
'HC01_VC18','HC03_VC18',
'HC01_VC19','HC03_VC19',
'HC01_VC20','HC03_VC20',
'HC01_VC23','HC03_VC23',
'HC01_VC88','HC03_VC88',
'HC01_VC94','HC03_VC94',
'HC01_VC95','HC03_VC95',
'HC01_VC96','HC03_VC96',
'HC01_VC97','HC03_VC97',
'HC01_VC98','HC03_VC98',
'HC01_VC99','HC03_VC99',
'HC01_VC100','HC03_VC100',
'HC01_VC101','HC03_VC101',
'HC01_VC102','HC03_VC102'
]]
demo13.rename(columns={'GEO.display-label': 'county',
'HC01_VC03': 'tot_pop',
'HC01_VC04': 'male',
'HC01_VC05': 'female',
'HC01_VC08':'under_5',
'HC01_VC09':'5_9',
'HC01_VC10':'10_14',
'HC01_VC11':'15_19',
'HC01_VC12':'20_24',
'HC01_VC13':'25_34',
'HC01_VC14':'35_44',
'HC01_VC15':'45_54',
'HC01_VC16':'55_59',
'HC01_VC17':'60_64',
'HC01_VC18':'65_74',
'HC01_VC19':'75_84',
'HC01_VC20':'85_over',
'HC01_VC23':'median_age',
'HC01_VC88':'hispanic_latino',
'HC01_VC89':'mexican',
'HC01_VC94':'white',
'HC01_VC95':'black',
'HC01_VC96':'aian',
'HC01_VC97':'asian',
'HC01_VC98':'nhopi',
'HC03_VC04': 'male_pct',
'HC03_VC05': 'female_pct',
'HC03_VC08':'under_5_pct',
'HC03_VC09':'5_9_pct',
'HC03_VC10':'10_14_pct',
'HC03_VC11':'15_19_pct',
'HC03_VC12':'20_24_pct',
'HC03_VC13':'25_34_pct',
'HC03_VC14':'35_44_pct',
'HC03_VC15':'45_54_pct',
'HC03_VC16':'55_59_pct',
'HC03_VC17':'60_64_pct',
'HC03_VC18':'65_74_pct',
'HC03_VC19':'75_84_pct',
'HC03_VC20':'85_over_pct',
'HC03_VC23':'median_age_pct',
'HC03_VC88':'hispanic_latino_pct',
'HC03_VC89':'mexican_pct',
'HC03_VC94':'white_pct',
'HC03_VC95':'black_pct',
'HC03_VC96':'aian_pct',
'HC03_VC97':'asian_pct',
'HC03_VC98':'nhopi_pct'
},
inplace=True)
demo14.rename(columns={'GEO.display-label': 'county',
'HC01_VC03': 'tot_pop',
'HC01_VC04': 'male',
'HC01_VC05': 'female',
'HC01_VC08':'under_5',
'HC01_VC09':'5_9',
'HC01_VC10':'10_14',
'HC01_VC11':'15_19',
'HC01_VC12':'20_24',
'HC01_VC13':'25_34',
'HC01_VC14':'35_44',
'HC01_VC15':'45_54',
'HC01_VC16':'55_59',
'HC01_VC17':'60_64',
'HC01_VC18':'65_74',
'HC01_VC19':'75_84',
'HC01_VC20':'85_over',
'HC01_VC23':'median_age',
'HC01_VC88':'hispanic_latino',
'HC01_VC89':'mexican',
'HC01_VC94':'white',
'HC01_VC95':'black',
'HC01_VC96':'aian',
'HC01_VC97':'asian',
'HC01_VC98':'nhopi',
'HC03_VC04': 'male_pct',
'HC03_VC05': 'female_pct',
'HC03_VC08':'under_5_pct',
'HC03_VC09':'5_9_pct',
'HC03_VC10':'10_14_pct',
'HC03_VC11':'15_19_pct',
'HC03_VC12':'20_24_pct',
'HC03_VC13':'25_34_pct',
'HC03_VC14':'35_44_pct',
'HC03_VC15':'45_54_pct',
'HC03_VC16':'55_59_pct',
'HC03_VC17':'60_64_pct',
'HC03_VC18':'65_74_pct',
'HC03_VC19':'75_84_pct',
'HC03_VC20':'85_over_pct',
'HC03_VC23':'median_age_pct',
'HC03_VC88':'hispanic_latino_pct',
'HC03_VC89':'mexican_pct',
'HC03_VC94':'white_pct',
'HC03_VC95':'black_pct',
'HC03_VC96':'aian_pct',
'HC03_VC97':'asian_pct',
'HC03_VC98':'nhopi_pct'
},
inplace=True)
demo15.rename(columns={'GEO.display-label': 'county',
'HC01_VC03': 'tot_pop',
'HC01_VC04': 'male',
'HC01_VC05': 'female',
'HC01_VC08':'under_5',
'HC01_VC09':'5_9',
'HC01_VC10':'10_14',
'HC01_VC11':'15_19',
'HC01_VC12':'20_24',
'HC01_VC13':'25_34',
'HC01_VC14':'35_44',
'HC01_VC15':'45_54',
'HC01_VC16':'55_59',
'HC01_VC17':'60_64',
'HC01_VC18':'65_74',
'HC01_VC19':'75_84',
'HC01_VC20':'85_over',
'HC01_VC23':'median_age',
'HC01_VC88':'hispanic_latino',
'HC01_VC89':'mexican',
'HC01_VC94':'white',
'HC01_VC95':'black',
'HC01_VC96':'aian',
'HC01_VC97':'asian',
'HC01_VC98':'nhopi',
'HC03_VC04': 'male_pct',
'HC03_VC05': 'female_pct',
'HC03_VC08':'under_5_pct',
'HC03_VC09':'5_9_pct',
'HC03_VC10':'10_14_pct',
'HC03_VC11':'15_19_pct',
'HC03_VC12':'20_24_pct',
'HC03_VC13':'25_34_pct',
'HC03_VC14':'35_44_pct',
'HC03_VC15':'45_54_pct',
'HC03_VC16':'55_59_pct',
'HC03_VC17':'60_64_pct',
'HC03_VC18':'65_74_pct',
'HC03_VC19':'75_84_pct',
'HC03_VC20':'85_over_pct',
'HC03_VC23':'median_age_pct',
'HC03_VC88':'hispanic_latino_pct',
'HC03_VC89':'mexican_pct',
'HC03_VC94':'white_pct',
'HC03_VC95':'black_pct',
'HC03_VC96':'aian_pct',
'HC03_VC97':'asian_pct',
'HC03_VC98':'nhopi_pct'
},
inplace=True)
demo16.rename(columns={'GEO.display-label': 'county',
'HC01_VC03': 'tot_pop',
'HC01_VC04': 'male',
'HC01_VC05': 'female',
'HC01_VC08':'under_5',
'HC01_VC09':'5_9',
'HC01_VC10':'10_14',
'HC01_VC11':'15_19',
'HC01_VC12':'20_24',
'HC01_VC13':'25_34',
'HC01_VC14':'35_44',
'HC01_VC15':'45_54',
'HC01_VC16':'55_59',
'HC01_VC17':'60_64',
'HC01_VC18':'65_74',
'HC01_VC19':'75_84',
'HC01_VC20':'85_over',
'HC01_VC23':'median_age',
'HC01_VC88':'hispanic_latino',
'HC01_VC89':'mexican',
'HC01_VC94':'white',
'HC01_VC95':'black',
'HC01_VC96':'aian',
'HC01_VC97':'asian',
'HC01_VC98':'nhopi',
'HC03_VC04': 'male_pct',
'HC03_VC05': 'female_pct',
'HC03_VC08':'under_5_pct',
'HC03_VC09':'5_9_pct',
'HC03_VC10':'10_14_pct',
'HC03_VC11':'15_19_pct',
'HC03_VC12':'20_24_pct',
'HC03_VC13':'25_34_pct',
'HC03_VC14':'35_44_pct',
'HC03_VC15':'45_54_pct',
'HC03_VC16':'55_59_pct',
'HC03_VC17':'60_64_pct',
'HC03_VC18':'65_74_pct',
'HC03_VC19':'75_84_pct',
'HC03_VC20':'85_over_pct',
'HC03_VC23':'median_age_pct',
'HC03_VC88':'hispanic_latino_pct',
'HC03_VC89':'mexican_pct',
'HC03_VC94':'white_pct',
'HC03_VC95':'black_pct',
'HC03_VC96':'aian_pct',
'HC03_VC97':'asian_pct',
'HC03_VC98':'nhopi_pct'
},
inplace=True)
# Other race categories
# 'HC01_VC99':'other_only',
# 'HC01_VC100':'more_two_races',
# 'HC01_VC101':'more_two_races_other',
# 'HC01_VC102':'more_two_races_other_exclude',
#combine other race, two or more races (HC01_VC99, HC01_VC100, HC01_VC101, HC01_VC102)
demo13['other']=pd.Series(demo13['HC01_VC99']+demo13['HC01_VC100']+demo13['HC01_VC101']+demo13['HC01_VC102'])
demo14['other']=pd.Series(demo14['HC01_VC99']+demo14['HC01_VC100']+demo14['HC01_VC101']+demo14['HC01_VC102'])
demo15['other']=pd.Series(demo15['HC01_VC99']+demo15['HC01_VC100']+demo15['HC01_VC101']+demo15['HC01_VC102'])
demo16['other']=pd.Series(demo16['HC01_VC99']+demo16['HC01_VC100']+demo16['HC01_VC101']+demo16['HC01_VC102'])
demo13['other_pct']=pd.Series(demo13['HC03_VC99']+demo13['HC03_VC100']+demo13['HC03_VC101']+demo13['HC03_VC102'])
demo14['other_pct']=pd.Series(demo14['HC03_VC99']+demo14['HC03_VC100']+demo14['HC03_VC101']+demo14['HC03_VC102'])
demo15['other_pct']=pd.Series(demo15['HC03_VC99']+demo15['HC03_VC100']+demo15['HC03_VC101']+demo15['HC03_VC102'])
demo16['other_pct']=pd.Series(demo16['HC03_VC99']+demo16['HC03_VC100']+demo16['HC03_VC101']+demo16['HC03_VC102'])
demo13=demo13.drop(columns=['HC01_VC99','HC03_VC99','HC01_VC100','HC03_VC100','HC01_VC101','HC03_VC101','HC01_VC102','HC03_VC102'])
demo14=demo14.drop(columns=['HC01_VC99','HC03_VC99','HC01_VC100','HC03_VC100','HC01_VC101','HC03_VC101','HC01_VC102','HC03_VC102'])
demo15=demo15.drop(columns=['HC01_VC99','HC03_VC99','HC01_VC100','HC03_VC100','HC01_VC101','HC03_VC101','HC01_VC102','HC03_VC102'])
demo16=demo16.drop(columns=['HC01_VC99','HC03_VC99','HC01_VC100','HC03_VC100','HC01_VC101','HC03_VC101','HC01_VC102','HC03_VC102'])
demo13.head()
# #### Census income
# Import and clean acs data for income and insurance status
inc11 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_11_5YR_DP03.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
inc12 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_12_5YR_DP03.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
inc13 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_13_5YR_DP03.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
inc14 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_14_5YR_DP03.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
inc15 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_15_5YR_DP03.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
inc16 = pd.read_csv("/Users/42/desktop/capstone/mids_capstone/vaxxfacts/raw_data/Census/County/ACS_16_5YR_DP03.csv",
encoding = "ISO-8859-1", header=[0], na_values=['-'])
# +
inc11=inc11[['GEO.id','GEO.id2','GEO.display-label','HC01_VC85','HC01_VC128','HC03_VC128',
'HC01_VC129','HC03_VC129','HC01_VC130','HC03_VC130','HC01_VC131','HC03_VC131']]
inc12=inc12[['GEO.id','GEO.id2','GEO.display-label','HC01_VC85','HC01_VC128','HC03_VC128',
'HC01_VC129','HC03_VC129','HC01_VC130','HC03_VC130','HC01_VC131','HC03_VC131']]
inc13=inc13[['GEO.id','GEO.id2','GEO.display-label','HC01_VC85','HC01_VC131','HC03_VC131',
'HC01_VC132','HC03_VC132','HC01_VC133','HC03_VC133','HC01_VC134','HC03_VC134']]
inc14=inc14[['GEO.id','GEO.id2','GEO.display-label','HC01_VC85','HC01_VC131','HC03_VC131',
'HC01_VC132','HC03_VC132','HC01_VC133','HC03_VC133','HC01_VC134','HC03_VC134']]
inc15=inc15[['GEO.id','GEO.id2','GEO.display-label','HC01_VC85','HC01_VC131','HC03_VC131',
'HC01_VC132','HC03_VC132','HC01_VC133','HC03_VC133','HC01_VC134','HC03_VC134']]
inc16=inc16[['GEO.id','GEO.id2','GEO.display-label','HC01_VC85','HC01_VC131','HC03_VC131',
'HC01_VC132','HC03_VC132','HC01_VC133','HC03_VC133','HC01_VC134','HC03_VC134']]
# +
inc11.rename(columns={'GEO.display-label': 'county',
'HC01_VC85': 'median_income',
'HC01_VC128': 'insurance',
'HC01_VC129': 'private_insure',
'HC01_VC130': 'public_insure',
'HC01_VC131': 'no_insurance',
'HC03_VC128': 'insurance_pct',
'HC03_VC129': 'private_insure_pct',
'HC03_VC130': 'public_insure_pct',
'HC03_VC131': 'no_insurance_pct'
},
inplace=True)
inc12.rename(columns={'GEO.display-label': 'county',
'HC01_VC85': 'median_income',
'HC01_VC128': 'insurance',
'HC01_VC129': 'private_insure',
'HC01_VC130': 'public_insure',
'HC01_VC131': 'no_insurance',
'HC03_VC128': 'insurance_pct',
'HC03_VC129': 'private_insure_pct',
'HC03_VC130': 'public_insure_pct',
'HC03_VC131': 'no_insurance_pct'
},
inplace=True)
inc13.rename(columns={'GEO.display-label': 'county',
'HC01_VC85': 'median_income',
'HC01_VC131': 'insurance',
'HC01_VC132': 'private_insure',
'HC01_VC133': 'public_insure',
'HC01_VC134': 'no_insurance',
'HC03_VC131': 'insurance_pct',
'HC03_VC132': 'private_insure_pct',
'HC03_VC133': 'public_insure_pct',
'HC03_VC134': 'no_insurance_pct'
},
inplace=True)
inc14.rename(columns={'GEO.display-label': 'county',
'HC01_VC85': 'median_income',
'HC01_VC131': 'insurance',
'HC01_VC132': 'private_insure',
'HC01_VC133': 'public_insure',
'HC01_VC134': 'no_insurance',
'HC03_VC131': 'insurance_pct',
'HC03_VC132': 'private_insure_pct',
'HC03_VC133': 'public_insure_pct',
'HC03_VC134': 'no_insurance_pct'
},
inplace=True)
inc15.rename(columns={'GEO.display-label': 'county',
'HC01_VC85': 'median_income',
'HC01_VC131': 'insurance',
'HC01_VC132': 'private_insure',
'HC01_VC133': 'public_insure',
'HC01_VC134': 'no_insurance',
'HC03_VC131': 'insurance_pct',
'HC03_VC132': 'private_insure_pct',
'HC03_VC133': 'public_insure_pct',
'HC03_VC134': 'no_insurance_pct'
},
inplace=True)
inc16.rename(columns={'GEO.display-label': 'county',
'HC01_VC85': 'median_income',
'HC01_VC131': 'insurance',
'HC01_VC132': 'private_insure',
'HC01_VC133': 'public_insure',
'HC01_VC134': 'no_insurance',
'HC03_VC131': 'insurance_pct',
'HC03_VC132': 'private_insure_pct',
'HC03_VC133': 'public_insure_pct',
'HC03_VC134': 'no_insurance_pct'
},
inplace=True)
# -
inc11['year']='2011'
inc12['year']='2012'
inc13['year']='2013'
inc14['year']='2014'
inc15['year']='2015'
inc16['year']='2016'
inc11.head()
county11=demo11.merge(inc11, left_on='GEO.id', right_on='GEO.id', how='outer')
county12=demo12.merge(inc12, left_on='GEO.id', right_on='GEO.id', how='outer')
county13=demo13.merge(inc13, left_on='GEO.id', right_on='GEO.id', how='outer')
county14=demo14.merge(inc14, left_on='GEO.id', right_on='GEO.id', how='outer')
county15=demo15.merge(inc15, left_on='GEO.id', right_on='GEO.id', how='outer')
county16=demo16.merge(inc16, left_on='GEO.id', right_on='GEO.id', how='outer')
county11.head()
# +
county11=county11.drop(columns=['GEO.id2_x','county_y'])
county12=county12.drop(columns=['GEO.id2_x','county_y'])
county13=county13.drop(columns=['GEO.id2_x','county_y'])
county14=county14.drop(columns=['GEO.id2_x','county_y'])
county15=county15.drop(columns=['GEO.id2_x','county_y'])
county16=county16.drop(columns=['GEO.id2_x','county_y'])
county11=county11.rename(columns={'county_x': 'county'})
county12=county12.rename(columns={'county_x': 'county'})
county13=county13.rename(columns={'county_x': 'county'})
county14=county14.rename(columns={'county_x': 'county'})
county15=county15.rename(columns={'county_x': 'county'})
county16=county16.rename(columns={'county_x': 'county'})
# -
county16.head()
# +
# Use 2016 data as a proxy for 2017 and 2018 data
county17=county16.copy()
county17['year']='2017'
county18=county16.copy()
county18['year']='2018'
# -
county16.head()
#Make county census file for 12-18 using 16 as proxy for 17 and 18
county_12_18=pd.concat([
county12,
county13,
county14,
county15,
county16,
county17,
county18
],ignore_index=True,sort=False)
county_12_18.head()
county_edu.head()
# merge county education data
county_acs_1218=county_12_18.merge(county_edu, left_on=['GEO.id', 'year'], right_on=['GEO.id','year'], how='left')
county_acs_1218
# county_11_16['county']=county_11_16.county.replace('County, California', '', regex=True)
county_acs_1218['county']=county_acs_1218.county.replace(' County, California', '', regex=True)
county_acs_1218.head()
# +
#Export full combined County city data
# county_acs_12_18.to_csv("county_acs_12_18.csv", index=False)
# -
# #### Merge city vaccine and city census geoids
county_vac1118.rename(columns={'n': 'vaccinated'}, inplace=True)
county_vac1118['vac_pct']=county_vac1118.vaccinated/county_vac1118.enrollment*100
county_vac1118.head()
list(county_vac1118.county.unique())
combined_county_1118=county_vac1118.merge(county_acs_1218, left_on=['county','year'], right_on=['county','year'], how='left')
combined_county_1118.head()
combined_county_1118.to_csv('county_correlation.csv', index=False)
county_map=combined_county_1118.copy()
county_map=county_map[['county','enrollment','vaccinated', 'year','vac_pct','GEO.id']]
# Rename variables to be compatible for mapping
county_map.rename(columns={'GEO.id': 'geoid',
'year': 's_year'
},
inplace=True)
county_map.head()
county_map18=county_map[county_map.s_year=='2018']
county_map18.head()
# +
# county_map18.to_csv('county_vaxmap18.csv', index=False)
# +
# county_map.to_csv('county_vaxmap.csv', index=False)
|
vaxxfacts/cleaning_etl/Cleaning_File_Drafts/Reshaping_Data_For_Viz.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Polarization on Twitter
# ### By <NAME>
# ### I. Dependencies
# +
import os
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits import mplot3d
import seaborn as sns
import math
import numpy as np
np.random.seed(42)
from scipy.stats import mstats
import sklearn.metrics as skm
import pandas as pd
import dask.dataframe as dd
from igraph import Graph
import igraph as ig
import warnings
warnings.filterwarnings('ignore')
print("All packages imported!")
# -
# ### II. Matplotlib Parameters
mpl.rcParams['figure.dpi'] = 100
mpl.rcParams['font.size'] = 9
# +
# Latex document Text width
latex_width = 390.0
def set_size(width=latex_width, height=latex_width, fraction=1, subplots=(1, 1)):
"""Set figure dimensions to avoid scaling in LaTeX.
Credit to <NAME> for the function.
Source: https://jwalton.info/Embed-Publication-Matplotlib-Latex/
"""
fig_width_pt = width * fraction
fig_height_pt = height * fraction
inches_per_pt = 1 / 72.27
fig_width_in = fig_width_pt * inches_per_pt
fig_height_in = fig_height_pt * inches_per_pt * (subplots[0] / subplots[1])
return (fig_width_in, fig_height_in)
# -
# ## III. Color Palette
#
# The palette is from the [iWantHue](http://medialab.github.io/iwanthue/) website by <NAME> at the Sciences-Po Medialab.
colors = [
"#ba4c40",
"#45c097",
"#573485",
"#a8ae3e",
"#8874d9",
"#69a050",
"#be64b2",
"#bc7d36",
"#5d8ad4",
"#b94973"
]
# ## IV. Twitter Dataset
#
# **Provenance:** <NAME>, "USA Nov.2020 Election 20 Mil. Tweets (with Sentiment and Party Name Labels) Dataset." *IEEE Dataport*, 14 Aug. 2020, doi: https://dx.doi.org/10.21227/25te-j338.
#
# **License:** [Developer Agreement](https://developer.twitter.com/en/developer-terms/agreement)
#
# **Usage Information:**
# - "you may only use the following information for non-commercial, internal purposes (e.g., to improve the functionality of the Services): (a) aggregate Twitter Applications user metrics, such as number of active users or accounts on Twitter Applications; (b) the responsiveness of Twitter Applications; and (c) results, usage statistics, data or other information (in the aggregate or otherwise) derived from analyzing, using, or regarding the performance of the Twitter API."
#
# - "you may not use, or knowingly display, distribute, or otherwise make Twitter Content, or information derived from Twitter Content, available to any entity for the purpose of: (a) conducting or providing surveillance or gathering intelligence, including but not limited to investigating or tracking Twitter users or Twitter Content; (b) conducting or providing analysis or research for any unlawful or discriminatory purpose, or in a manner that would be inconsistent with Twitter users' reasonable expectations of privacy; (c) monitoring sensitive events (including but not limited to protests, rallies, or community organizing meetings); or (d) targeting, segmenting, or profiling individuals based on sensitive personal information, including their health (e.g., pregnancy), negative financial status or condition, political affiliation or beliefs, racial or ethnic origin, religious or philosophical affiliation or beliefs, sex life or sexual orientation, trade union membership, Twitter Content relating to any alleged or actual commission of a crime, or any other sensitive categories of personal information prohibited by law."
#
# **Number of tweets:** 24,201,654
#
# **Demographic:** Anybody who tweeted #USAelection, #NovemberElection, @DNC, @TheDemocrats, Biden, @JoeBiden, "Our best days still lie ahead", "No Malarkey!", #MAGA2020, @GOP, Trump, @POTUS, @realDonaldTrump, Pence, @Mike_Pence, @VP OR "Keep America Great", @GreenPartyUS, @TheGreenParty, “<NAME>”, @HowieHawkins, “<NAME>”, @AngelaNWalker, @LPNational, “<NAME>”, @Jorgensen4POTUS, “<NAME>”, @RealSpikeCohen between July 1st and November 12th, 2020.
#
#
# **Sentiment analysis tool:** 5. <NAME>, and <NAME>. “VADER: A Parsimonious Rule-based Model for Sentiment Analysis of Social Media Text.” *Eighth International Conference on Weblogs and Social Media*. 2014. [GitHub](https://github.com/cjhutto/vaderSentiment)
#
# <center> <h3>Dataset Contents*</h3> </center>
#
# <center> <h4><code>uselection_tweets_1jul_11nov.csv</code></h4> </center>
#
# | Variable | Format | Description | Example |
# | :- | :- | :- | :- |
# | `Created-At`$\,$ | Timestamp$\,$ | Time at which tweet was created $\,$ | 7/1/20 7:44 PM |
# | `From-User-Id`$\,$ | String$\,$ | Unique identifier of the user that sent the tweet $\,$ | 1223446325758394369 |
# | `To-User-Id`$\,$ | String$\,$ | Unique identifier of the user that tweet sent to, -1 if nobody $\,$ | 387882597 |
# | `Language`$\,$ | String$\,$ | ISO 639-1 language of the tweet $\,$ | en |
# | `PartyName`$\,$ | String$\,$ | Which party is mentioned in the tweet $\,$ | BothParty |
# | `Id`$\,$ | String$\,$ | Unique identifier of the tweet $\,$ | 1278368973948694528 |
# | `Score`$\,$ | Float$\,$ | The sentiment score of the tweet $\,$ | 0.102564 |
# | `Scoring String`$\,$ | String$\,$ | The sentiment score of the tweet $\,$ | 0.102564 |
#
# \**only imported fields are shown.*
# ### Importing
# +
twitter_cols = ['Created-At', 'From-User-Id', 'To-User-Id', 'Language', 'PartyName', 'Id', 'Score', 'Scoring String']
twitter_filepath = os.path.join(os.getcwd(), 'data', 'twitter', 'uselection_tweets_1jul_11nov.csv')
# twitter dask dataframe
tdd = dd.read_csv(twitter_filepath, sep=';', usecols=twitter_cols)
# -
# ### Cleaning
#
# - No duplicates found.
#
# - Extreme values were found, but were kept.
# #### Correcting Inferred Variable Types
tdd.dtypes
# - `Created-At` should be a timestamp
# - `From-User_Id` should be a string
# - `To-User_Id` should be a string
# - `Id` should be a string
tdd['Created-At'] = dd.to_datetime(tdd['Created-At'])
tdd['From-User-Id'] = tdd['From-User-Id'].astype('str')
tdd['To-User-Id'] = tdd['To-User-Id'].astype('str')
tdd['Id'] = tdd['Id'].astype('str')
tdf = tdd.compute()
print(len(tdf))
tdf.head(5)
# #### Remove `NaN` Values
#
# Some tweets were unscored and hence the `Scoring String` is `NaN`. These tweets were all removed.
tdd = tdd.dropna()
# #### Initial Filters
#
# - We filter for English to get more relevant tweets; the US speaks English. Further, the experiment done later involved English Speakers.
#
# - We are primarily interested in tweets that can be fitted along the conservative-democrat political axis.
tdd = tdd[tdd['Language'] == 'en']
tdd = tdd[(tdd['PartyName'] == 'Republicans') | (tdd['PartyName'] == 'Democrats')]
# #### Political Polarity
#
# - We convert the categories into numerical values by sign.
# +
polarity = {'Republicans': -1, 'Democrats' : 1}
tdd['PartyName'] = tdd['PartyName'].replace(polarity)
# -
# #### Drop Unused Columns
tdd = tdd.drop(columns=['Language', 'Scoring String'])
# #### Rename and Reorder Columns
#
# No particular reason, just prefer not using dictionary to access dataframe columns and a certain order of columns.
# +
old_to_new = {
'Created-At' : 'time',
'Id' : 'id',
'From-User-Id' : 'by',
'To-User-Id' : 'to',
'PartyName' : 'party',
'Score' : 'emotion'
}
order = ['time', 'id', 'by', 'to', 'party', 'emotion']
tdd = tdd.rename(columns=old_to_new)[order]
# -
# #### Compute Changes
# Compute all cleaning at once and get a **Pandas** Dataframe.
tdf = tdd.compute()
# ## 1 Political Opinion
#
# ### 1.1 How well does `party` and `emotion` capture Political Opinion?
#
# To test the accuracy of the metrics, we will take a random sample of 1000 tweets and have I and a non-author assign the tweets to the four quadrants made up of party and emotion axis.
def quadrant(row):
p = row.party
e = row.emotion
if (e > 0) and (p == 1):
result = 1
elif (e < 0) and (p == 1):
result = 2
elif (e < 0) and (p == -1):
result = 3
elif (e > 0) and (p == -1):
result = 4
else:
result = 0
return result
# To convert quadrants to political opinion metric discussed in 1.2
def quadToOp(x):
if x == 1:
result = 1
elif x == 2:
result = -1
elif x == 3:
result = 1
elif x == 4:
result = -1
else:
result = 0
return result
# #### Creating sample
#
# Retrieving 2000 ids as some tweets may be privated, deleted etc...
# +
#file = 'sample.csv'
#tdf.id.sample(2000).to_csv(file, header = False, index = False)
# -
# #### Exporting Hydrated Sample
# +
#sample_cols = ['id', 'text']
#sample_filepath = os.path.join(os.getcwd(), 'data', file)
#sdf = pd.read_csv(sample_filepath, usecols=sample_cols, dtype=str)
# prepare experiment
#sdf = sdf.dropna().head(1000)
#sdf = sdf.merge(right=tdf, how='left', on='id')
#sdf['label'] = sdf.apply(quadrant, axis=1)
#sdf = sdf[['id', 'text', 'label']]
#experiment_filepath = os.path.join(os.getcwd(), 'data', 'experiment.csv')
#sdf.to_csv(experiment_filepath, index=False)
# -
# A script was used for participants to input quadrants for tweets. I, the author, annotated 500 tweets (column `test2`) and a non-author annotated 140 tweets (column `test1`).
# #### Import Experiment Data
experiment_filepath = os.path.join(os.getcwd(), 'data', 'experiment.csv')
edf = pd.read_csv(experiment_filepath).head(500)
# #### Measuring Agreement
#
# Firstly, we measure the agreement between the participants on labelling. We evaluate this with the 140 tweets that both participants labelled. The metric commonly applied in this situation is Cohen's Kappa,
#
# $\kappa = \dfrac{p_o - p_e}{1 - p_e}$
#
# where $p_o$ is the observed agreement ratio between the annotators and $p_e$ is the expected agreement when both annotators are randomly assigning labels given each annotators relative frequency of class labels.
#
# **Metric:** <NAME> (1960). “A coefficient of agreement for nominal scales”. *Educational and Psychological Measurement 20(1):37-46*. doi:10.1177/001316446002000104.
# +
bdf = edf.iloc[0:140]
kl = skm.cohen_kappa_score(bdf.test1, bdf.test2)
ko = skm.cohen_kappa_score(bdf.test1Op, bdf.test2Op)
print(f'Label k: {kl}')
print(f'Opinion k: {ko}')
# -
# $\kappa$ between 0.6-0.8 is considered substantial agreement. This would support that the labels assigned by participants capture a similar notion of the political content in the tweets. This suggests that the participants labelling can be used to measure the accuracy of the sentiment analysis and party tagging in capturing the political content of the tweets.
#
# **Source:** <NAME>, <NAME>. Understanding interobserver agreement: the kappa statistic. *Fam Med*. 2005 May;37(5):360-3. PMID: 15883903.
# +
t1_acc = len(bdf[bdf.test1 == bdf.label]) / 140
t1Op_acc = len(bdf[bdf.test1Op == bdf.labelOp]) / 140
t2_acc = len(edf[edf.label == edf.test2]) / 500
t2Op_acc = len(edf[edf.labelOp == edf.test2Op]) / 500
print(f'Participant 1 label accuracy: {t1_acc}')
print(f'Participant 2 label accuracy: {t2_acc}\n')
print(f'Participant 1 opinion accuracy: {t1Op_acc}')
print(f'Participant 2 opinion accuracy: {t2Op_acc}\n')
# -
bldf = bdf[bdf.test1 == bdf.test2]
print(skm.classification_report(bldf.test1, bldf.label))
bodf = bdf[bdf.test1Op == bdf.test2Op]
print(skm.classification_report(bodf.test1Op, bodf.labelOp))
# ### 1.2 Political Opinion Metric
#
# The political opinion of a tweet is the *point along the conservative-democrat political axis $[-1,1]$ that the content in the tweet expresses*. We want to convert tweets to these values as it lets us quantitively study political polarization over the time period the tweets were collected.
#
# #### `party` x Linearly Scaled `emotion`
#
# We will be scaling the `emotion` to $[-1,1]$ using minimum and maximum `emotion` values, however we do not want the outliers to have a disproportionate effect. To fix this, we will winzorise the emotion scores. Intuitively, it is unlikely that outliers are expressing particularly more emotions than the 0.01 percentile or more than the 99.99 percentile (~2500 tweets). These tweets are largely result from people repeating a certain connotated word (e.g., love or loser) that is picked up by the sentiment analysis tool leading to extreme values.
# +
xs = mstats.winsorize(tdf.emotion, limits=[0.0001, 0.0001])
# maximum magnitude of emotion
scale = max(-xs.min(), xs.max())
# political opinion metric
tdf['opinion'] = (tdf.party * xs / scale).values
# -
sns.histplot(tdf.opinion.sample(5000))
plt.show()
# The distribution of political opinions shows a clear sign of polarization in the tweets. From 1.1, we see that this metric can moderately capture the political content of a tweet, and therefore, we will continue to use this dataset for our study of polarization. The next step is to create the network from the users.
# ## 2 Political Influence
# ### 2.1 Largest Strongly Connected Component
#
# We will study opinions expressed in the largest strongly connected component as this forms a user network that characterises the majority of the behaviour happening in the twitter feed. The network includes 108737 users, the second largest cluster includes 14 users.
# +
cdf = tdf[tdf.to != '-1'][['by','to']]
cg = Graph.DataFrame(cdf, directed=True)
cs = cg.components()
lcg = cs.giant()
lc_ids = lcg.vs['name']
lcdf = tdf[tdf.by.isin(lc_ids) & (tdf.to.isin(lc_ids) | (tdf.to == '-1'))][['time','by', 'to', 'opinion']]
# -
# ### 2.2 Influence of Received Opinions on Sent Opinions
# +
INTR_COLS = ['time', 'opinion']
def interaction(user, df):
by = df[df.by == user][INTR_COLS]
to = df[df.to == user][INTR_COLS]
result = []
for _, msg in by.iterrows():
result.append((msg, to[to.time < msg.time]))
return result
# -
def interaction_analysis(df, sample_total):
users = np.random.choice(df.by.unique(), size=sample_total)
intrs = [interaction(user, df) for user in users]
result = []
for i in range(len(users)):
by_ops = []
to_ops = []
for by, to in intrs[i]:
by_ops.append(by.opinion)
to_ops.append(to.opinion.mean())
result.append((users[i], by_ops, to_ops))
return result
intra = interaction_analysis(lcdf, 1000)
coefs = []
for user, by_ops, to_ops in intra:
by_ops_valid = []
to_ops_valid = []
for i in range(len(by_ops)):
if not math.isnan(to_ops[i]):
by_ops_valid.append(by_ops[i])
to_ops_valid.append(to_ops[i])
if len(by_ops_valid) > 2:
corr = np.corrcoef(by_ops_valid, to_ops_valid)[0,1]
if not math.isnan(corr):
coefs.append((user, corr))
sns.histplot(list(map(lambda x: x[1], coefs)))
plt.show()
init_corr_ops = list(map(lambda x: (lcdf[lcdf.by == x[0]].opinion.values[0], x[1]), coefs))
x = list(map(lambda x: abs(x[0]), init_corr_ops))
y = list(map(lambda x: x[1],init_corr_ops))
sns.scatterplot(x=x, y=y)
# #### 2.3 Largest Cluster in Outspoken Users
weeks_total = (tdf.time.max() - tdf.time.min()).days / 7
odf = tdf.groupby('by').filter(lambda x: len(x) > weeks_total)
# +
ocdf = odf[odf.to != '-1'][['by', 'to']]
ocg = Graph.DataFrame(ocdf, directed=True)
ocs = ocg.components()
olcg = ocs.giant()
olc_ids = olcg.vs['name']
olcdf = tdf[tdf.by.isin(lc_ids) & (tdf.to.isin(lc_ids) | (tdf.to == '-1'))][['time','by', 'to', 'opinion']]
# -
# #### 2.4 Influence of Recieved Opinion on Sent Opinion with Outspoken Users
intra = interaction_analysis(olcdf, 1000)
coefs = []
for user, by_ops, to_ops in intra:
by_ops_valid = []
to_ops_valid = []
for i in range(len(by_ops)):
if not math.isnan(to_ops[i]):
by_ops_valid.append(by_ops[i])
to_ops_valid.append(to_ops[i])
if len(by_ops_valid) > 2:
corr = np.corrcoef(by_ops_valid, to_ops_valid)[0,1]
if not math.isnan(corr):
coefs.append((user, corr))
sns.histplot(list(map(lambda x: x[1], coefs)))
plt.show()
init_corr_ops = list(map(lambda x: (olcdf[olcdf.by == x[0]].opinion.values[0], x[1]), coefs))
x = list(map(lambda x: abs(x[0]), init_corr_ops))
y = list(map(lambda x: x[1],init_corr_ops))
sns.scatterplot(x=x, y=y)
plt.show()
# ### 2.5 Moving Towards or Away from Sent Opinions in Outspoken Cluster
def interaction_mean(user, df):
by = df[df.by == user][INTR_COLS]
to = df[df.to == user][INTR_COLS]
result = []
for _, msg in by.iterrows():
byop = msg.opinion
toop = to[(msg.time - pd.Timedelta(days=7) <= to.time) & (to.time < msg.time)].opinion.mean()
if not math.isnan(toop):
result.append((byop, toop))
return result
def direction_analysis(df, sample_total):
users = np.random.choice(df.by.unique(), size=sample_total)
valid_users = []
intrs = []
for user in users:
intr = interaction_mean(user, df)
# We need at least two opinion changes to see difference
if len(intr) > 1:
valid_users.append(user)
intrs.append(intr)
result = []
for i in range(len(valid_users)):
dirs = []
for j in range(1,len(intrs[i])):
if abs(intrs[i][j][1] - intrs[i][j][0]) < abs(intrs[i][j][1] - intrs[i][j-1][0]):
dirs.append(1)
elif abs(intrs[i][j][1] - intrs[i][j][0]) > abs(intrs[i][j][1] - intrs[i][j-1][0]):
dirs.append(-1)
else:
dirs.append(0)
result.append((valid_users[i], dirs))
return result
dirsa = direction_analysis(olcdf, 1000)
initial = list(map(lambda x: olcdf[olcdf.by == x[0]].opinion.values[0], dirsa))
overall = list(map(lambda x: np.sum(x[1]), dirsa))
sns.histplot(overall, discrete=True)
sns.scatterplot(map(abs, initial), overall)
towards = []
away = []
for user, dirs in dirsa:
towards.append(dirs.count(1))
away.append(dirs.count(-1))
sns.scatterplot(towards,away)
plt.show()
# ### 2.6 Polarity of User and Polarity of Tweets received
def interaction_polarity(user, df):
by = df[df.by == user].opinion.mean()
to = df[df.to == user].opinion
return list(map(lambda x: np.sign(by * x), to))
def polarity_analysis(df, sample_total):
users = np.random.choice(df.by.unique(), size=sample_total)
result = [(df[df.by == user].opinion.values[0], interaction_polarity(user, df)) for user in users]
return result
sns.scatterplot(map(lambda x: x[0], polsa),map(lambda x: x[1].count(-1), polsa))
plt.show()
sns.scatterplot(map(lambda x: x[0], polsa),map(lambda x: x[1].count(1), polsa))
plt.show()
|
us.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import json
import gmaps
import os
import time
import csv
import gmaps.datasets
#from ipywidgets.embed import embed_minimal_html
# Import API key
from api_keys import g_key
# +
# Loading csv file exported from WeatherPy to new DataFrame:
path = os.path.join("..","python-api-challenge","output_data", "cities.csv")
# Reading in the csv file and creating the new dataframe:
new_city_df = pd.read_csv(path)
# Cleaning new cihty dataframe:
city_df_cleaned = new_city_df.dropna()
city_df_cleaned
# -
# Configure gmaps:
gmaps.configure(api_key=g_key)
# +
# Using Lat and Lng as locations:
locations = city_df_cleaned[["Lat", "Lng"]]
# Using Humidity as the weight:
humidity = city_df_cleaned["Humidity"].astype(float)
# +
# Add Heatmap layer to map:
fig = gmaps.figure()
heatmap_layer = gmaps.heatmap_layer(locations, weights=humidity,
dissipating=False, max_intensity=100,
point_radius=2)
# Add layer
fig.add_layer(heatmap_layer)
# Display figure
fig
# +
# Narrow down the cities to fit weather conditions"
# Zero cloudiness:
cloud_df = city_df_cleaned[city_df_cleaned["Cloudiness"] == 0]
# A max temperature lower than 80 degrees but higher than 70:
temp_df = cloud_df[(cloud_df["Max Temp"] > 70) & (cloud_df["Max Temp"] < 80)]
# Wind speed less than 10 mph:
wind_df = temp_df[temp_df["Wind Speed"] < 10]
# Drop any rows will null values:
wind_df = wind_df.dropna()
wind_df
# +
# Store into variable named hotel_df:
hotel_df = wind_df
# Add a "Hotel Name" column to the DataFrame: (setting new columns to hold values)
hotel_df["Hotel Name"] = ""
# Set parameters to search for hotels with 5000 meters:
# Set params:
params = {
"radius": 5000,
"types": "hotel",
"keyword": "hotels",
"key": g_key
}
# Loop through to identify hotels:
for index, row in hotel_df.iterrows():
base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
lat = row["Lat"]
lng = row["Lng"]
params['location'] = f'{lat},{lng}'
hotel_data = requests.get(base_url, params=params).json()
try:
hotel_df.loc[index, "Hotel Name"] = hotel_data['results'][0]['name']
except:
print('Issues with finding a hotel at', row['City'])
hotel_df.loc[index, "Hotel Name"] = "NA"
hotel_df
# -
#deletes any rows without hotels in 5000 meters
hotel_df = hotel_df[hotel_df["Hotel Name"] != "NA"]
hotel_df
# Checking hotels:
len(hotel_df[["Lat", "Lng"]])
# Using the template add the hotel marks to the heatmap
info_box_template = """
<dl>
<dt>Name</dt><dd>{Hotel Name}</dd>
<dt>City</dt><dd>{City}</dd>
<dt>Country</dt><dd>{Country}</dd>
</dl>
"""
# Store the DataFrame Row
# NOTE: be sure to update with your DataFrame name
hotel_info = [info_box_template.format(**row) for index, row in hotel_df.iterrows()]
locations = hotel_df[["Lat", "Lng"]]
# Checking hotel info:
len(hotel_info)
# +
# Add marker layer ontop of heat map
marker_layer = gmaps.marker_layer(locations, info_box_content=hotel_info)
fig.add_layer(marker_layer)
# Display figure
fig
# -
|
.ipynb_checkpoints/Vacation-checkpoint.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import ipycytoscape
import json
with open("DAGData.json") as fi:
json_file = json.load(fi)
cytoscapeobj = ipycytoscape.CytoscapeWidget()
cytoscapeobj.graph.add_graph_from_json(json_file)
cytoscapeobj.set_layout(name='dagre', nodeSpacing=10, edgeLengthVal=10)
cytoscapeobj.set_style([{
'selector': 'node',
'css': {
'background-color': '#11479e'
}
},
{
'selector': 'node:parent',
'css': {
'background-opacity': 0.333
}
},
{
'selector': 'edge',
'style': {
'width': 4,
'line-color': '#9dbaea',
'target-arrow-shape': 'triangle',
'target-arrow-color': '#9dbaea',
'curve-style': 'bezier'
}
}])
cytoscapeobj
|
examples/DAG example.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:ml4t-dl]
# language: python
# name: conda-env-ml4t-dl-py
# ---
# # Stacked LSTMs for Time Series Classification with TensorFlow
# We'll now build a slightly deeper model by stacking two LSTM layers using the Quandl stock price data. Furthermore, we will include features that are not sequential in nature, namely indicator variables for identifying the equity and the month.
# ## Imports
import warnings
warnings.filterwarnings('ignore')
# +
# %matplotlib inline
from pathlib import Path
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.metrics import roc_auc_score
import tensorflow as tf
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, LSTM, Input, concatenate, Embedding, Reshape, BatchNormalization
import tensorflow.keras.backend as K
import matplotlib.pyplot as plt
import seaborn as sns
# -
gpu_devices = tf.config.experimental.list_physical_devices('GPU')
if gpu_devices:
print('Using GPU')
tf.config.experimental.set_memory_growth(gpu_devices[0], True)
else:
print('Using CPU')
idx = pd.IndexSlice
sns.set_style('whitegrid')
np.random.seed(42)
results_path = Path('results', 'lstm_embeddings')
if not results_path.exists():
results_path.mkdir(parents=True)
# ## Data
# Data produced by the notebook [build_dataset](00_build_dataset.ipynb).
data = pd.read_hdf('data.h5', 'returns_weekly')
data['ticker'] = pd.factorize(data.index.get_level_values('ticker'))[0]
data['month'] = data.index.get_level_values('date').month
data = pd.get_dummies(data, columns=['month'], prefix='month')
data.info()
# ## Train-test split
#
# To respect the time series nature of the data, we set aside the data at the end of the sample as hold-out or test set. More specifically, we'll use the data for 2017.
window_size=52
sequence = list(range(1, window_size+1))
ticker = 1
months = 12
n_tickers = data.ticker.nunique()
train_data = data.drop('fwd_returns', axis=1).loc[idx[:, :'2016'], :]
test_data = data.drop('fwd_returns', axis=1).loc[idx[:, '2017'],:]
# For each train and test dataset, we generate a list with three input arrays containing the return series, the stock ticker (converted to integer values), and the month (as an integer), as shown here:
X_train = [
train_data.loc[:, sequence].values.reshape(-1, window_size , 1),
train_data.ticker,
train_data.filter(like='month')
]
y_train = train_data.label
[x.shape for x in X_train], y_train.shape
# keep the last year for testing
X_test = [
test_data.loc[:, list(range(1, window_size+1))].values.reshape(-1, window_size , 1),
test_data.ticker,
test_data.filter(like='month')
]
y_test = test_data.label
[x.shape for x in X_test], y_test.shape
# ## Define the Model Architecture
# The functional API of Keras makes it easy to design architectures with multiple inputs and outputs. This example illustrates a network with three inputs, as follows:
#
# - A two stacked LSTM layers with 25 and 10 units respectively
# - An embedding layer that learns a 10-dimensional real-valued representation of the equities
# - A one-hot encoded representation of the month
#
# This can be constructed using just a few lines - see e.g.,
# - the [general Keras documentation](https://keras.io/getting-started/sequential-model-guide/),
# - the [LSTM documentation](https://keras.io/layers/recurrent/).
#
# Make sure you are initializing your optimizer given the [keras-recommended approach for RNNs](https://keras.io/optimizers/)
#
# We begin by defining the three inputs with their respective shapes, as described here:
K.clear_session()
n_features = 1
# +
returns = Input(shape=(window_size, n_features),
name='Returns')
tickers = Input(shape=(1,),
name='Tickers')
months = Input(shape=(12,),
name='Months')
# -
# ### LSTM Layers
# To define stacked LSTM layers, we set the `return_sequences` keyword to `True`. This ensures that the first layer produces an output that conforms to the expected three-dimensional input format. Note that we also use dropout regularization and how the functional API passes the tensor outputs from one layer to the subsequent layer:
lstm1_units = 25
lstm2_units = 10
# +
lstm1 = LSTM(units=lstm1_units,
input_shape=(window_size,
n_features),
name='LSTM1',
dropout=.2,
return_sequences=True)(returns)
lstm_model = LSTM(units=lstm2_units,
dropout=.2,
name='LSTM2')(lstm1)
# -
# ### Embedding Layer
# The embedding layer requires the `input_dim` keyword, which defines how many embeddings the layer will learn, the `output_dim` keyword, which defines the size of the embedding, and the `input_length` keyword to set the number of elements passed to the layer (here only one ticker per sample).
#
# To combine the embedding layer with the LSTM layer and the months input, we need to reshape (or flatten) it, as follows:
ticker_embedding = Embedding(input_dim=n_tickers,
output_dim=5,
input_length=1)(tickers)
ticker_embedding = Reshape(target_shape=(5,))(ticker_embedding)
# ### Concatenate Model components
# Now we can concatenate the three tensors and add fully-connected layers to learn a mapping from these learned time series, ticker, and month indicators to the outcome, a positive or negative return in the following week, as shown here:
# +
merged = concatenate([lstm_model,
ticker_embedding,
months], name='Merged')
bn = BatchNormalization()(merged)
hidden_dense = Dense(10, name='FC1')(bn)
output = Dense(1, name='Output', activation='sigmoid')(hidden_dense)
rnn = Model(inputs=[returns, tickers, months], outputs=output)
# -
# The summary lays out this slightly more sophisticated architecture with 29,371 parameters, as follows:
rnn.summary()
# ## Train the Model
# We compile the model to compute a custom auc metric as follows:
optimizer = tf.keras.optimizers.RMSprop(lr=0.001,
rho=0.9,
epsilon=1e-08,
decay=0.0)
rnn.compile(loss='binary_crossentropy',
optimizer=optimizer,
metrics=['accuracy',
tf.keras.metrics.AUC(name='AUC')])
# +
lstm_path = (results_path / 'lstm.classification.h5').as_posix()
checkpointer = ModelCheckpoint(filepath=lstm_path,
verbose=1,
monitor='val_AUC',
mode='max',
save_best_only=True)
# -
early_stopping = EarlyStopping(monitor='val_AUC',
patience=5,
restore_best_weights=True,
mode='max')
training = rnn.fit(X_train,
y_train,
epochs=50,
batch_size=32,
validation_data=(X_test, y_test),
callbacks=[early_stopping, checkpointer],
verbose=1)
# Training stops after 18 epochs, producing a test area under the curve (AUC) of 0.63 for the best model with 13 rounds of training (each of which takes around three minutes on a single GPU).
loss_history = pd.DataFrame(training.history)
def which_metric(m):
return m.split('_')[-1]
# +
fig, axes = plt.subplots(ncols=3, figsize=(18,4))
for i, (metric, hist) in enumerate(loss_history.groupby(which_metric, axis=1)):
hist.plot(ax=axes[i], title=metric)
axes[i].legend(['Training', 'Validation'])
sns.despine()
fig.tight_layout()
fig.savefig(results_path / 'lstm_stacked_classification', dpi=300);
# -
# ## Evaluate model performance
test_predict = pd.Series(rnn.predict(X_test).squeeze(), index=y_test.index)
roc_auc_score(y_score=test_predict, y_true=y_test)
((test_predict>.5) == y_test).astype(int).mean()
spearmanr(test_predict, y_test)[0]
|
19_recurrent_neural_nets/02_stacked_lstm_with_feature_embeddings.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# %matplotlib inline
df = pd.read_csv('Train_SU63ISt.csv')
df
train = df[0:10392]
test = df[10392:11855]
df.Timestamp = pd.to_datetime(df.Datetime, format='%d-%m-%Y %H:%M')
df.index = df.Timestamp
df = df.resample('D').sum()
train.Timestamp = pd.to_datetime(train.Datetime, format='%d-%m-%Y %H:%M')
train.index = train.Timestamp
train = train.resample('D').sum()
test.Timestamp = pd.to_datetime(test.Datetime, format='%d-%m-%Y %H:%M')
test.index = test.Timestamp
test = test.resample('D').sum()
df
train
test
train.Count.plot(figsize=(15,8), title= 'Daily Ridership', fontsize=14)
test.Count.plot(figsize=(15,8), title= 'Daily Ridership', fontsize=14)
plt.show()
|
workspace/time-series/Untitled.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# %matplotlib inline
# Set up figure size and DPI for screen demo
plt.rcParams['figure.figsize'] = (6,4)
plt.rcParams['figure.dpi'] = 150
nums = np.arange(0,10,0.1)
plt.plot(nums, np.sin(nums))
# Circle
circ = mpl.patches.Circle((5,0), radius=1)
plt.plot(nums, np.sin(nums))
plt.gca().add_patch(circ)
plt.gca().set_aspect('equal')
# zorder
c1 = mpl.patches.Circle((5,0), radius=1, zorder=1)
c2 = mpl.patches.Circle((4,0), radius=1, zorder=0, color='r')
plt.plot(nums, 10/3.*np.sin(nums))
plt.gca().add_patch(c2)
plt.gca().add_patch(c1)
# +
# Different kinds of simple patches
circle = mpl.patches.Circle(xy=(2,-2), radius=1)
arc = mpl.patches.Arc(xy=(1,2), width=1, height=3, angle=0, theta1=90, theta2=270)
wedge = mpl.patches.Wedge(center=(2,2), r=1, theta1=-180, theta2=100, width=0.5)
arrow = mpl.patches.Arrow(x=4,y=-3, dx=2, dy=2)
ellipse = mpl.patches.Ellipse(xy=(5,2), width=1, height=3, angle=60)
rect = mpl.patches.Rectangle(xy=(7,-2), width=2, height=2, angle=-30)
poly = mpl.patches.RegularPolygon(xy=(8,2), numVertices=3, orientation=45, radius=1)
plt.plot(nums, 10/3.*np.sin(nums))
plt.gca().add_patch(circle)
plt.gca().add_patch(arc)
plt.gca().add_patch(wedge)
plt.gca().add_patch(arrow)
plt.gca().add_patch(ellipse)
plt.gca().add_patch(rect)
plt.gca().add_patch(poly)
# -
# Making your own polygons
pos = [(3,0),(7,0), (6,1), (4,1)]
poly = mpl.patches.Polygon(pos)
plt.plot(nums, 10/3.*np.sin(nums))
plt.gca().add_patch(poly)
|
Chapter02/Playing with polygons And shapes.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import tensorflow as tf
import numpy as np
node1 = tf.constant(3.0, tf.float32)
node2 = tf.constant(4.0)
print(node2, node2)
sess = tf.Session()
print(sess.run([node1, node2]))
node3 = tf.add(node1, node2)
print('node 3: ', node3, '\n', sess.run([node3]))
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = tf.add(a,b)
sess.run(adder_node, {a:[3,2] ,b:[3,2]})
weight = tf.Variable(.3, tf.float32)
bias = tf.Variable(-.5, tf.float32)
input = tf.placeholder(tf.float32)
linear_model = input * weight + bias
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(linear_model, {input:[1,2,3,4]}))
error = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - error)
loss = tf.reduce_sum(squared_deltas)
print(sess.run(loss, {input:[1,2,3,4], error:[-.1, .2, .3, .3]}))
fixWeight = tf.assign(weight, -1)
fixBias = tf.assign(bias, 1)
sess.run([fixWeight, fixBias])
print(sess.run(loss, {input:[1,2,3,4], error:[-0,-1,-2,-3]}))
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
for i in range(1000):
sess.run(train, {input:[1,2,3,4], error:[-0,-1,-2,-3]})
print(sess.run([weight, bias]))
|
intro-to-rnns/NN from Scratch.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Day 0: Mean, Median, and Mode
#
#
# `Task `
# Given an array, `X`, `N` of integers, calculate and print the respective mean, median, and mode on separate lines. If your array contains more than one modal value, choose the numerically smallest one.
#
# `Note`: Other than the modal value (which will always be an integer), your answers should be in decimal form, rounded to a scale of `1` decimal place (i.e., 12.3, 7.0 format).
#
# `Input Format`
#
# The first line contains an integer, `N`, denoting the number of elements in the array.
# The second line contains `N` space-separated integers describing the array's elements.
#
# `Output Format`
#
# Print `3` lines of output in the following order:
#
# 1. Print the mean on a new line, to a scale of `1` decimal place (i.e., 12.3, 7.0).
# 2. Print the median on a new line, to a scale of `1` decimal place (i.e., 12.3, 7.1).
# 3. Print the mode on a new line; if more than one such value exists, print the numerically smallest one.
#
# `Sample Input`
# ```
# 10
# 64630 11735 14216 99233 14470 4978 73429 38120 51135 67060
# ```
# `Sample Output`
# ```
# 43900.6
# 44627.5
# 4978
# ```
# +
num_length = int(input())
numbers = list(map(int, input().split()))
#mean
num_sum = 0
for number in numbers:
num_sum += number
x_mean = num_sum / num_length
#median
index = num_length//2
x_median = (sorted(numbers)[index] + sorted(numbers)[index-1])/2
#mode
input_dict = {x: numbers.count(x) for x in numbers}
x_mode = 0
x_val = 0
for key, val in input_dict.items():
if val > x_val or (val == x_val and key < x_mode):
x_mode = key
x_val = val
print(f'{x_mean:.1f}')
print(f'{x_median:.1f}')
print(f'{x_mode:.1f}')
|
10 Days of Statistics/Day_0. Mean, Median, and Mode.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import psycopg2
class MyDB:
def __init__(self):
self.conn = None
def __enter__(self):
self.conn = psycopg2.connect("host=localhost dbname=test user=postgres password=<PASSWORD>")
self.conn.autocommit = True
def __exit__(self, *args):
if self.conn:
self.conn.close()
self.conn = None
MyPG = MyDBe()
with MyPG:
cursor = MyPG.conn.cursor()
cursor.execute("SELECT * FROM test_table")
# MyPG.conn.rollback()
results_1 = cursor.fetchone()
print(results_1)
|
days/10-12-pytest/Day3.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
import tensorflow as tf
import numpy as np
from tensor2tensor.data_generators import problem_hparams
from tensor2tensor.models import evolved_transformer
from tensor2tensor.models import transformer
from tensor2tensor.utils import optimize
# +
import json
with open('train-test-bpe.json') as fopen:
dataset = json.load(fopen)
# -
train_X = dataset['train_X']
train_Y = dataset['train_Y']
test_X = dataset['test_X']
test_Y = dataset['test_Y']
PAD = 0
EOS = 1
UNK = 2
GO = 3
class Translator:
def __init__(self, size_layer, num_layers, embedded_size,
from_dict_size, to_dict_size, learning_rate, beam_width = 10):
def cells(reuse=False):
return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)
def attention(encoder_out, seq_len, reuse=False):
attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer,
memory = encoder_out,
memory_sequence_length = seq_len)
return tf.contrib.seq2seq.AttentionWrapper(
cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse) for _ in range(num_layers)]),
attention_mechanism = attention_mechanism,
attention_layer_size = size_layer)
self.X = tf.placeholder(tf.int32, [None, None])
self.Y = tf.placeholder(tf.int32, [None, None])
self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)
self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)
batch_size = tf.shape(self.X)[0]
encoder_embedding = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))
decoder_embedding = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))
encoder_out, encoder_state = tf.nn.dynamic_rnn(
cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]),
inputs = tf.nn.embedding_lookup(encoder_embedding, self.X),
sequence_length = self.X_seq_len,
dtype = tf.float32)
main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])
decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)
dense = tf.layers.Dense(to_dict_size)
with tf.variable_scope('decode'):
decoder_cells = attention(encoder_out, self.X_seq_len)
training_helper = tf.contrib.seq2seq.TrainingHelper(
inputs = tf.nn.embedding_lookup(decoder_embedding, decoder_input),
sequence_length = self.Y_seq_len,
time_major = False)
training_decoder = tf.contrib.seq2seq.BasicDecoder(
cell = decoder_cells,
helper = training_helper,
initial_state = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state),
output_layer = dense)
training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
decoder = training_decoder,
impute_finished = True,
maximum_iterations = tf.reduce_max(self.Y_seq_len))
self.training_logits = training_decoder_output.rnn_output
with tf.variable_scope('decode', reuse=True):
predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(
embedding = decoder_embedding,
start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),
end_token = EOS)
predicting_decoder = tf.contrib.seq2seq.BasicDecoder(
cell = decoder_cells,
helper = predicting_helper,
initial_state = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state),
output_layer = dense)
predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
decoder = predicting_decoder,
impute_finished = True,
maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))
self.greedy = predicting_decoder_output.sample_id
self.greedy = tf.identity(self.greedy,name='greedy')
with tf.variable_scope('decode', reuse=True):
encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)
encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)
X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)
decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)
predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(
cell = decoder_cell,
embedding = decoder_embedding,
start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),
end_token = EOS,
initial_state = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(
cell_state = encoder_state_tiled),
beam_width = beam_width,
output_layer = dense,
length_penalty_weight = 0.0)
predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
decoder = predicting_decoder,
impute_finished = False,
maximum_iterations = tf.reduce_max(self.X_seq_len))
self.beam = predicting_decoder_output.predicted_ids[:, :, 0]
self.beam = tf.identity(self.beam,name='beam')
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.training_logits,
targets = self.Y,
weights = masks)
self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)
y_t = tf.argmax(self.training_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 = 256
learning_rate = 1e-3
batch_size = 64
epoch = 20
tf.reset_default_graph()
sess = tf.InteractiveSession()
model = Translator(size_layer, num_layers, embedded_size, 10000, 10000, learning_rate)
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver(tf.trainable_variables())
saver.save(sess, 'lstm/model.ckpt')
def pad_sentence_batch(sentence_batch, pad_int):
padded_seqs = []
seq_lens = []
max_sentence_len = max([len(sentence) for sentence in sentence_batch])
for sentence in sentence_batch:
padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))
seq_lens.append(len(sentence))
return padded_seqs, seq_lens
batch_x, _ = pad_sentence_batch(train_X[: 5], 0)
batch_y, _ = pad_sentence_batch(train_Y[: 5], 0)
sess.run([model.cost, model.optimizer], feed_dict = {model.X: batch_x, model.Y: batch_y})
greedy, beam = sess.run([model.greedy, model.beam], feed_dict = {model.X: test_X[:1]})
# +
import tqdm
for e in range(epoch):
pbar = tqdm.tqdm(
range(0, len(train_X), batch_size), desc = 'minibatch loop')
train_loss, train_acc, test_loss, test_acc = [], [], [], []
for i in pbar:
index = min(i + batch_size, len(train_X))
batch_x, seq_x = pad_sentence_batch(train_X[i : index], PAD)
batch_y, seq_y = pad_sentence_batch(train_Y[i : index], PAD)
feed = {model.X: batch_x,
model.Y: batch_y}
accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],
feed_dict = feed)
train_loss.append(loss)
train_acc.append(accuracy)
pbar.set_postfix(cost = loss, accuracy = accuracy)
pbar = tqdm.tqdm(
range(0, len(test_X), batch_size), desc = 'minibatch loop')
for i in pbar:
index = min(i + batch_size, len(test_X))
batch_x, seq_x = pad_sentence_batch(test_X[i : index], PAD)
batch_y, seq_y = pad_sentence_batch(test_Y[i : index], PAD)
feed = {model.X: batch_x,
model.Y: batch_y,}
accuracy, loss = sess.run([model.accuracy,model.cost],
feed_dict = feed)
test_loss.append(loss)
test_acc.append(accuracy)
pbar.set_postfix(cost = loss, accuracy = accuracy)
print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,
np.mean(train_loss),np.mean(train_acc)))
print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,
np.mean(test_loss),np.mean(test_acc)))
# -
saver = tf.train.Saver(tf.trainable_variables())
saver.save(sess, 'lstm-bahdanau/model.ckpt')
tf.reset_default_graph()
sess = tf.InteractiveSession()
model = Translator(training = False)
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver(tf.trainable_variables())
saver.restore(sess, 'transformer-tiny/model.ckpt')
import youtokentome as yttm
bpe = yttm.BPE(model='stemmer.model')
berjalankan = bpe.encode('berjalankansangat', output_type=yttm.OutputType.ID)
greedy, beam = sess.run([model.greedy, model.beam], feed_dict = {model.X: [berjalankan]})
bpe.decode(predicted)
bpe.decode(predicted_b)
strings = ','.join(
[
n.name
for n in tf.get_default_graph().as_graph_def().node
if ('Variable' in n.op
or 'Placeholder' in n.name
or 'greedy' in n.name
or 'beam' in n.name
or 'alphas' in n.name)
and 'Adam' not in n.name
and 'beta' not in n.name
and 'OptimizeLoss' not in n.name
and 'Global_Step' not in n.name
]
)
strings.split(',')
def freeze_graph(model_dir, output_node_names):
if not tf.gfile.Exists(model_dir):
raise AssertionError(
"Export directory doesn't exists. Please specify an export "
"directory: %s" % model_dir)
checkpoint = tf.train.get_checkpoint_state(model_dir)
input_checkpoint = checkpoint.model_checkpoint_path
absolute_model_dir = "/".join(input_checkpoint.split('/')[:-1])
output_graph = absolute_model_dir + "/frozen_model.pb"
clear_devices = True
with tf.Session(graph=tf.Graph()) as sess:
saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)
saver.restore(sess, input_checkpoint)
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess,
tf.get_default_graph().as_graph_def(),
output_node_names.split(",")
)
with tf.gfile.GFile(output_graph, "wb") as f:
f.write(output_graph_def.SerializeToString())
print("%d ops in the final graph." % len(output_graph_def.node))
freeze_graph("lstm-bahdanau", strings)
def load_graph(frozen_graph_filename):
with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def)
return graph
g=load_graph('lstm-bahdanau/frozen_model.pb')
x = g.get_tensor_by_name('import/Placeholder:0')
i_greedy = g.get_tensor_by_name('import/decode_1/greedy:0')
i_beam = g.get_tensor_by_name('import/decode_2/beam:0')
test_sess = tf.InteractiveSession(graph=g)
greedy, beam = test_sess.run([i_greedy, i_beam], feed_dict = {x: [berjalankan]})
bpe.decode(berjalankan)
bpe.decode(greedy.tolist()[0])
bpe.decode(beam.tolist()[0])
# +
import boto3
s3 = boto3.client('s3')
bucketName = 'huseinhouse-storage'
Key = 'lstm-bahdanau/frozen_model.pb'
outPutname = "v34/stem/model.pb"
s3.upload_file(Key,bucketName,outPutname)
# -
Key = 'stemmer.model'
outPutname = "v34/stem/bpe.model"
s3.upload_file(Key,bucketName,outPutname)
|
session/stemmer/lstm-bahdanau.ipynb
|