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 (ipykernel)
# language: python
# name: python3
# ---
# # Homework: Data visualization and exploration with Pandas
#
# Author: <NAME>
# ### Data:
#
# MovieLens 1M Data Set contain les grades given to movies by users on the Movielens website.
#
# The data are available at:
#
# https://www.dropbox.com/s/qrkmr9avt7rx821/ml-1m.zip?dl=0
#
# and come from:
#
# http://grouplens.org/datasets/movielens/
# ### Import necessary packages
import pandas as pd
import numpy as np
# ### Load the "users" data as Pandas DataFrame
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_csv('ml-1m/users.dat', sep='::', header=None, names=unames, engine='python')
users.head()
# ### Read the "rating"
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_csv('ml-1m/ratings.dat', sep='::', header=None, names=rnames, engine='python')
ratings.head(10)
# ### Read the movies
mnames = ['movie_id', 'title', 'genres']
movies = pd.read_csv('ml-1m/movies.dat', sep='::', header=None,
encoding='latin_1', names=mnames, engine='python')
# +
# pd.read_csv?
# -
movies.head(10)
# ### Let's merge everything as a single DataFrame
data = pd.merge(pd.merge(ratings, users), movies)
data.head()
# # Let's explore the data
# ### Question 1
#
# How many movies have a grade higher than 4.5 ?
# Is there a difference between Male or Females?
# ### Question 2
#
# How many movies have a median grade higher than 4,5 among the men older than 30 years? And among the women older than 30?
# ### Question 3a
#
# What are the most popular movies?
#
# Hint: use the `DataFrame.nlargest` method.
# ### Question 3b
#
# What are the most popular movies among the movies that have at least 30 grades?
# ### Question 3c
#
# What is the movie with the highest number of ratings?
# # Data Visualization
# %matplotlib inline
# ### Question 4
#
# Show the histogram of the ratings.
# ### Question 5
#
# Show the histogram of the number of grades obtained for each movie.
# ### Question 6
#
# Show the histogram of the mean grade for each movie.
#
# Does the distribution of the grade depend on the gender of the user?
# ### Question 7
#
# Show the histogram of grades among the movies that have been graded at least 30 times.
# ### Question 8
#
# Show as "scatter plot" the mean grades for the men vs the grades of the women.
#
# Now restrict the plot to the movies with at least 100 grades.
# ### Question Bonus
#
# Make nice data visualization to highligh a specific effect in the data.
| 01_pandas/02-data_exploration_visualization.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
# ---
# + colab={"base_uri": "https://localhost:8080/"} id="EffQTx-23t36" executionInfo={"status": "ok", "timestamp": 1647889807245, "user_tz": 300, "elapsed": 749, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjbz-g1gDVozJOQvoEjIlrsInvjQAooYZpbLX29HQ=s64", "userId": "09694454376427194239"}} outputId="48c4373c-31c4-4a1e-b45d-5a5a65329cea"
from google.colab import drive
drive.mount('/content/gdrive')
# + id="LFoukUhZ4Lav" executionInfo={"status": "ok", "timestamp": 1647889932511, "user_tz": 300, "elapsed": 126, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjbz-g1gDVozJOQvoEjIlrsInvjQAooYZpbLX29HQ=s64", "userId": "09694454376427194239"}} colab={"base_uri": "https://localhost:8080/"} outputId="5e2b07cb-3b33-4ee2-c3d1-dd46d4c5b79d"
# %cd /content/gdrive/MyDrive/Workshop/Github/otdd
# + colab={"base_uri": "https://localhost:8080/", "height": 130} id="SRkO1sUV_ivh" executionInfo={"status": "error", "timestamp": 1647891627291, "user_tz": 300, "elapsed": 167, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjbz-g1gDVozJOQvoEjIlrsInvjQAooYZpbLX29HQ=s64", "userId": "09694454376427194239"}} outputId="0876d4d3-fcf0-4d04-e555-be6bf77c7d7a"
conda env create -f environment.yaml python=3.8
| Untitled0.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
# ---
# # Evaluate all embeddings generated with parameter_search
import os
import pandas as pd
import numpy as np
from pathlib import Path
import datetime
import pickle
import seaborn as sns
import matplotlib.pyplot as plt
from evaluation_functions import nn, sil
# +
wd = os.getcwd()
DF = os.path.join(os.path.sep, str(Path(wd).parents[0]), "data", "processed", "df_focal_reduced.pkl")
OUT_COORDS = os.path.join(os.path.sep, str(Path(wd).parents[0]), "data", "interim", "parameter_search", "umap_coords")
OUT_EVALS = os.path.join(os.path.sep, str(Path(wd).parents[0]), "data", "interim", "parameter_search", "umap_evals")
# +
spec_df = pd.read_pickle(DF)
print(spec_df.shape)
labels = spec_df.call_lable.values
labeltypes = sorted(list(set(labels)))
# +
#outname = os.path.join(os.path.sep, OUT_EVALS, 'eval_table_5.csv')
#eval_table = pd.read_csv(outname, sep=";")
#already_evaluated = [x+'.csv' for x in eval_table[params].astype(str).agg('_'.join, axis=1)]
#not_evaluated = list(set(all_embedding_files) - set(already_evaluated))
# -
params = ['preprocess_type', 'metric_type', 'duration_method','min_dist', 'spread', 'n_neighbors', 'n_comps', 'input_type', 'denoised', 'n_mels', 'f_unit', 'n_repeat']
all_embedding_files = list(sorted(os.listdir(OUT_COORDS)))
print(len(all_embedding_files))
# +
eval_colnames = params+ ['S_total'] + ['S_'+x for x in labeltypes] + ['Snorm_total'] + ['Snorm_'+x for x in labeltypes] + ['SIL_total'] + ['SIL_'+x for x in labeltypes]+['knncc_'+x for x in labeltypes]
print(eval_colnames)
eval_table = np.zeros((len(all_embedding_files), len(eval_colnames)))
eval_table = pd.DataFrame(eval_table, columns=eval_colnames)
# +
k=5
for i,embedding_file in enumerate(all_embedding_files):
embedding = np.loadtxt(os.path.join(os.path.sep, OUT_COORDS, embedding_file),delimiter=";")
embedding_params_string = embedding_file.replace('.csv', '')
embedding_params_list = embedding_params_string.split('_')
nn_stats = nn(embedding, labels, k=k)
sil_stats = sil(embedding, labels)
eval_vector = embedding_params_list + [nn_stats.get_S()] + list(nn_stats.get_ownclass_S()) + [nn_stats.get_Snorm()] + list(nn_stats.get_ownclass_Snorm()) + [sil_stats.get_avrg_score()] + list(sil_stats.get_score_per_class()) + list(nn_stats.knn_cc())
eval_table.loc[i,:] = eval_vector
# -
eval_table
eval_table['knncc_total'] = eval_table[['knncc_'+x for x in labeltypes]].mean(axis=1)
outname = os.path.join(os.path.sep, OUT_EVALS, 'eval_table_'+str(k)+'.csv')
eval_table.to_csv(outname, sep=";", index=False)
# ## Plot results
FIGURES = os.path.join(os.path.sep, str(Path(wd).parents[0]), "reports", "figures", "parameter_search")
outname = os.path.join(os.path.sep, OUT_EVALS, 'eval_table_5.csv')
eval_table = pd.read_csv(outname, sep=";")
eval_table["min_dist"] = pd.to_numeric(eval_table["min_dist"])
eval_table["n_neighbors"] = pd.to_numeric(eval_table["n_neighbors"])
eval_table["spread"] = pd.to_numeric(eval_table["spread"])
eval_table["n_comps"] = pd.to_numeric(eval_table["n_comps"])
eval_table["n_mels"] = pd.to_numeric(eval_table["n_mels"])
eval_table["n_repeat"] = pd.to_numeric(eval_table["n_repeat"])
eval_table
calltypes = sorted(list(set(spec_df.call_lable)))
pal = sns.color_palette("Set2", n_colors=len(calltypes))
params = ['preprocess_type', 'metric_type', 'duration_method','min_dist', 'spread', 'n_neighbors', 'n_comps', 'input_type','denoised', 'n_mels', 'f_unit', 'n_repeat']
p_default = dict(zip(params[:-1], ['zs', 'euclidean', 'pad', 0.0, 1.0, 15, 5, 'melspecs', 'no', 40, 'dB']))
# +
param = 'denoised'
print(param)
outvar="S_total"
other_params = set(params).difference([param, 'n_repeat'])
df = eval_table
for p in other_params:
df = df.loc[df[p]==p_default[p],:]
boxplot = df[[param]+[outvar]].boxplot(by=param)
plt.ylim(50,67)
# -
y_lower_dict = {"SIL":-0.65,
"SIL_total": -0.05,
"S":0,
"S_total": 50,
"knncc":0}
y_upper_dict = {"SIL":0.65,
"SIL_total": 0.23,
"S":100,
"S_total": 67,
"knncc":100}
# +
# BOXPLOTS
for outvar in ['S_total', 'SIL_total']:
for param in params[:-1]:
other_params = set(params).difference([param, 'n_repeat'])
df = eval_table
for p in other_params:
df = df.loc[df[p]==p_default[p],:]
boxplot = df[[param]+[outvar]].boxplot(by=param)
plt.ylim(y_lower_dict[outvar], y_upper_dict[outvar])
plt.suptitle('')
plt.title('')
plt.xlabel(param)
plt.savefig(os.path.join(os.path.sep, FIGURES,'box_'+outvar+'_'+param+'.jpg'))
plt.close()
# +
# LINE PLOTS
for out_v in ["SIL", "S", "knncc"]:
outvars = [out_v+'_'+x for x in calltypes]
#outvars = [out_v+'_total']+outvars
for param in params[:-1]:
other_params = set(params).difference([param, 'n_repeat'])
df = eval_table
for p in other_params:
df = df.loc[df[p]==p_default[p],:]
#print(df.shape)
means = df[[param, out_v+'_total']]
df = df[[param]+outvars]
melted = pd.melt(df, id_vars=param, value_vars=outvars)
melted = melted.sort_values(by=param)
sns.lineplot(x=param, y="value", hue="variable", data=melted, palette="Set2", hue_order=outvars, err_style='band')
sns.lineplot(x=param, y=out_v+'_total', data=means, color='black')
plt.ylabel(out_v)
plt.ylim(y_lower_dict[out_v], y_upper_dict[out_v])
lg = plt.legend(bbox_to_anchor=(1.05,1),loc=2, borderaxespad=0.)
plt.savefig(os.path.join(os.path.sep, FIGURES,'line_'+out_v+'_'+param+'.jpg'), bbox_extra_artists=(lg,), bbox_inches='tight')
plt.close()
# +
# Lineplots with error bars
for out_v in ["SIL", "S", "knncc"]:
outvars = [out_v+'_'+x for x in calltypes]
color_dict = dict(zip(outvars, pal))
for param in params[:-1]:
other_params = set(params).difference([param, 'n_repeat'])
df = eval_table
for p in other_params:
df = df.loc[df[p]==p_default[p],:]
#print(df.shape)
means = df[[param, out_v+'_total']]
df = df[[param]+outvars]
levels = sorted(list(set(df[param])))
mean_df = df.groupby([param]).mean()
std_df = df.groupby([param]).std()
fig, ax = plt.subplots(figsize=(7, 4))
for outvar in outvars:
y = mean_df[outvar].values
yerr = std_df[outvar].values
ax.errorbar(levels, y, yerr=yerr,color=color_dict[outvar]) # linestype=ls
ax.set_ylim(y_lower_dict[out_v], y_upper_dict[out_v])
ax.set_title(param)
plt.savefig(os.path.join(os.path.sep, FIGURES,'err_'+out_v+'_'+param+'.jpg'))
plt.close()
# +
# Lineplots with error bars with Mean (?)
for out_v in ["SIL", "S", "knncc"]:
#for out_v in ["S"]:
outvars = [out_v+'_'+x for x in calltypes]
color_dict = dict(zip(outvars, pal))
outvars = [out_v+'_total']+outvars
color_dict[out_v+'_total'] = "black"
#for param in params[0:2]:
for param in params[:-1]:
other_params = set(params).difference([param, 'n_repeat'])
df = eval_table
for p in other_params:
df = df.loc[df[p]==p_default[p],:]
#print(df.shape)
means = df[[param, out_v+'_total']]
df = df[[param]+outvars]
levels = sorted(list(set(df[param])))
mean_df = df.groupby([param]).mean()
std_df = df.groupby([param]).std()
fig, ax = plt.subplots(figsize=(7, 4))
for outvar in outvars:
y = mean_df[outvar].values
yerr = std_df[outvar].values
ax.errorbar(levels, y, yerr=yerr,color=color_dict[outvar]) # linestype=ls
ax.set_ylim(y_lower_dict[out_v], y_upper_dict[out_v])
ax.set_title(param)
plt.savefig(os.path.join(os.path.sep, FIGURES,'errmean_'+out_v+'_'+param+'.jpg'))
plt.close()
# +
#df = df.groupby([param]).mean()
# +
n_rows = 4
n_cols = 3
cs = list(range(0,n_cols)) * n_rows
rs_list = [[x]*n_cols for x in list(range(0,n_rows))]
rs = list()
for x in rs_list:
for y in x:
rs.append(y)
print(rs)
print(cs)
# -
# # Plot all
plot_params = ['preprocess_type',
'metric_type',
'duration_method',
'min_dist',
'spread',
'n_neighbors',
'input_type',
'denoised',
'n_mels',
'f_unit']
# +
# BOXPLOTS
n_rows = 4
n_cols = 3
cs = list(range(0,n_cols)) * n_rows
rs_list = [[x]*n_cols for x in list(range(0,n_rows))]
rs = list()
for x in rs_list:
for y in x:
rs.append(y)
fig, axes = plt.subplots(n_rows, n_cols, figsize=(18, 10))
fig.suptitle('Title')
#for outvar in ['S_total', 'SIL_total']:
for outvar in ['S_total']:
for i,param in enumerate(plot_params):
other_params = set(params).difference([param, 'n_repeat'])
df = eval_table
for p in other_params:
df = df.loc[df[p]==p_default[p],:]
color_dict = {level: "red" if level == p_default[param] else "black" for level in list(set(df[param]))}
sns.boxplot(ax=axes[rs[i], cs[i]], data=df, x=param, y=outvar, palette = color_dict)
ax.set_ylim(y_lower_dict[outvar], y_upper_dict[outvar])
#plt.tight_layout()
#plt.savefig(os.path.join(os.path.sep, FIGURES,'box_'+outvar+'_all.jpg'))
#plt.close()
# -
color_dict
from plot_functions import mara_3Dplot, plotly_viz
eval_table
eval_table.loc[eval_table.input_type=='mfccs',:]
embedding_file = 'zs_manhattan_pad_0_1_15_5_mfccs_2.csv'
embedding = np.loadtxt(os.path.join(os.path.sep, OUT_COORDS, embedding_file),delimiter=";")
labels = spec_df.call_lable.values
pal="Set2"
mara_3Dplot(embedding[:,0],
embedding[:,1],
embedding[:,2],
labels,
pal,
None)
| notebooks/.ipynb_checkpoints/old_Evaluate_UMAP_parameter_search-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 matplotlib.image as mpimg
import matplotlib.pyplot as plt
import pandas as pd
import math
# %matplotlib inline
# This serves as a check on our choice of process noise values.
Radar95_confi = 7.82
# Laser measurements have 2 degrees of freedom,
# so the threshold is different.
Lidar95_confi = 5.99
#input file fields as they are saved into the UKF output file
my_cols = ['px_meas','py_meas','NIS_radar', 'NIS_laser', 'px', 'py']
with open('./build/data_out.txt') as f:
table_ekf_output = pd.read_table(f, sep=';', header=None, names=my_cols, lineterminator='\n')
table_ekf_output[0:5]
# +
plt.figure(figsize=(20,10))
ax1 = plt.subplot(111)
plt.scatter(table_ekf_output['px_meas'],table_ekf_output['py_meas'], s=12)
plt.scatter(table_ekf_output['px'],table_ekf_output['py'], s=12)
ax1.legend(['measured', 'Kalman filtered'])
plt.savefig('./images/Meas_vs_Kalmanfilt.png')
# +
plt.figure(figsize=(20,10))
ax1 = plt.subplot(121)
plt.title('std_a_ = 1| std_yawdd_ = 0.3')
plt.plot(table_ekf_output['NIS_radar'])
plt.axhline(Radar95_confi, color = 'g')
ax1.legend(['NIS Radar', '95% Radar'])
ax1.set_ylim([0, 30])
#######
ax2 = plt.subplot(122)
plt.title('std_a_ = 1| std_yawdd_ = 0.3')
plt.plot(table_ekf_output['NIS_laser'])
plt.axhline(Lidar95_confi, color = 'r')
ax2.legend(['NIS Lidar', '95% Lidar'])
ax2.set_ylim([0, 30])
plt.savefig('./images/NIS_process_noise.png')
# -
| UKF_Visualizer.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
# ---
# + raw_mimetype="text/restructuredtext" active=""
# .. _nb_scatter:
# -
# ## Scatter Plot
#
# The traditional scatter plot is mostly used for lower dimensional objective spaces.
# ### Scatter 2D
# + code="visualization/usage_scatter.py" section="scatter2d"
from pymoo.visualization.scatter import Scatter
from pymoo.factory import get_problem, get_reference_directions
F = get_problem("zdt3").pareto_front()
Scatter().add(F).show()
# + active=""
# The plot can be further customized by supplying a title, labels, and by using the plotting directives from matplotlib.
# + code="visualization/usage_scatter.py" section="scatter2d_custom"
F = get_problem("zdt3").pareto_front(use_cache=False, flatten=False)
plot = Scatter()
plot.add(F, s=30, facecolors='none', edgecolors='r')
plot.add(F, plot_type="line", color="black", linewidth=2)
plot.show()
# -
# ### Scatter 3D
# + code="visualization/usage_scatter.py" section="scatter3d"
ref_dirs = get_reference_directions("uniform", 3, n_partitions=12)
F = get_problem("dtlz1").pareto_front(ref_dirs)
plot = Scatter()
plot.add(F)
plot.show()
# -
# ### Scatter ND / Pairwise Scatter Plots
# + code="visualization/usage_scatter.py" section="scatter4d"
import numpy as np
F = np.random.random((30, 4))
plot = Scatter(tight_layout=True)
plot.add(F, s=10)
plot.add(F[10], s=30, color="red")
plot.show()
# -
# ### API
# + raw_mimetype="text/restructuredtext" active=""
# .. autoclass:: pymoo.visualization.scatter.Scatter
# :noindex:
| doc/source/visualization/scatter.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
# ---
# # Now You Code 2: Multiply By
#
# Write a program to ask for a number to multiply by and then lists the multiplication table for that number from 1 to 10. This process will repeat until you enter quit as which point the program will exit.
#
# Wow. Seems complicated! We'll use technique called problem simplification to make this problem a little easier to solve.
#
# First we'll write a complete program to solve *part* of the problem, then we will take our new level of understanding to solve the *entire* problem.
#
# ## Start with Sub-Problem 1
#
# Let's write a program to simply input a number and then uses a loop to print out the multiplication table up to 10 for that number.
#
# For example, when you input `5`:
#
# ```
# Enter number to multiply by: 5
# 1 x 5 = 5
# 2 x 5 = 10
# 3 x 5 = 15
# 4 x 5 = 20
# 5 x 5 = 25
# 6 x 5 = 30
# 7 x 5 = 35
# 8 x 5 = 40
# 9 x 5 = 45
# 10 x 5 = 50
# ```
#
# ## Step 1: Problem Analysis for Sub-Problem 1
#
# Inputs: a number
#
# Outputs: the time table for that number up to 10
#
# Algorithm (Steps in Program):
#
#
# -input the number as an integer
#
# -for numbers one to 10
#
# -print the number, the increment, and the product of the two
#
# Step 2: write code for sub-problem 1
number = int(input("Enter a number: "))
for i in range(1, 11):
print ("%d X %d = %d" % (number, i, number * i))
# # Full Problem
#
# Now that we've got part of the problem figured out, let's solve the entire problem. The program should keep asking for numbers and then print out multiplcation tables until you enter `quit`. Here's an example:
#
# Example Run:
#
# ```
# Enter number to multiply by or type 'quit': 10
# 1 x 10 = 10
# 2 x 10 = 20
# 3 x 10 = 30
# 4 x 10 = 40
# 5 x 10 = 50
# 6 x 10 = 60
# 7 x 10 = 70
# 8 x 10 = 80
# 9 x 10 = 90
# 10 x 10 = 100
# Enter number to multiply by or type 'quit': 5
# 1 x 5 = 5
# 2 x 5 = 10
# 3 x 5 = 15
# 4 x 5 = 20
# 5 x 5 = 25
# 6 x 5 = 30
# 7 x 5 = 35
# 8 x 5 = 40
# 9 x 5 = 45
# 10 x 5 = 50
# Enter number to multiply by or type 'quit': quit
# ```
#
# **NOTE:** you need another loop complete this program. Take the code you wrote in the first part and repeat it in another loop until you type quit.
# ## Step 3: Problem Analysis for Full Problem
#
# Inputs: a number or "quit"
#
# Outputs: The time table of the number
#
# Algorithm (Steps in Program):
# - input the number (or quit)
# - loop indefinitely:
# - if the input is "quit": break
# - else:
# - convert the number to integer
# - for numbers 1-10, print the number, the increment, and the product of the two
# Step 4: Write code for full problem
while True:
number = input('Enter a number to multiply or type "quit": ')
if number == "quit":
break
else:
number = int(number)
for i in range(1, 11):
print ("%d X %d = %d" % (number, i, number * i))
# ## Step 3: Questions
#
# 1. What is the loop control variable for the first (outer) loop?
#
# The input being "quit" determines whether the outer loop continues or closes.
#
# 2. What is the loop control variable for the second (inner) loop?
#
# The inner loop is controlled by the increment being in the range (1,11).
#
# 3. Provide at least one way this program can be improved, or make more flexible by introducing more inputs?
#
# The program can be improved by saying the input is invalid when a string other than "quit" is entered.
# ## Reminder of Evaluation Criteria
#
# 1. What the problem attempted (analysis, code, and answered questions) ?
# 2. What the problem analysis thought out? (does the program match the plan?)
# 3. Does the code execute without syntax error?
# 4. Does the code solve the intended problem?
# 5. Is the code well written? (easy to understand, modular, and self-documenting, handles errors)
#
| content/lessons/05/Now-You-Code/NYC2-Multiply-By.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [default]
# language: python
# name: python3
# ---
from astropy.io import ascii
d = ascii.read('data/rmp.csv')
d.keys()
data = []
for row in d:
if row['quality'] == 'awful':
rating = 0
else:
rating = 1
data.append((row['comment'], rating))
size = len(data)
r = int((size+1)*.7)
train = data[:r]
test = data[r:]
# +
#Importing a model
from textblob.classifiers import NaiveBayesClassifier
cl = NaiveBayesClassifier(train)
# -
cl.accuracy(test)
cl.show_informative_features(20)
db = ascii.read('data/Evaluations-Binary.csv')
hit, miss = 0, 0
for row in db:
#print(cl.classify(row['col1']), row['col2'])
if cl.classify(row['Review']) == row['Useful']:
hit += 1
else:
miss += 1
# for sentence in row['col1'].split('.'):
# if cl.classify(sentence) == 0:
# print(sentence)
# print(cl.classify(sentence), row['col2'])
print(hit, miss, hit/(hit+miss), miss/(hit+miss))
cl.classify("")
| notebooks/ProfEvalsIR.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/Norod/my-colab-experiments/blob/master/3D_Photo_Inpainting_args.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="IY-s3ZpHBeAU" colab_type="text"
# **[CVPR 2020] 3D Photography using Context-aware Layered Depth Inpainting**
#
# [project website](https://shihmengli.github.io/3D-Photo-Inpainting/)
#
# * Based on the improvements by @Buntworthy
# * Colab updates by @Norod78
#
# + [markdown] id="LPQ0EWxgvMIc" colab_type="text"
# - **Prepare environment**
#
# + id="5o-EIMeaghU0" colab_type="code" outputId="629a2bb9-e57a-4f8d-97e1-bd9ba8d52459" colab={"base_uri": "https://localhost:8080/", "height": 1000}
# !pip3 install torch==1.4.0+cu100 torchvision==0.5.0+cu100 -f https://download.pytorch.org/whl/torch_stable.html
# !pip3 install opencv-python==4.2.0.32
# !pip3 install vispy==0.6.4
# !pip3 install moviepy==1.0.2
# !pip3 install transforms3d==0.3.1
# !pip3 install networkx==2.3
# + [markdown] id="c-g7AeLMvY0R" colab_type="text"
# - **Download script and pretrained model**
#
# + id="cOFIBkWrBlNM" colab_type="code" outputId="333c7d3d-5a88-48b7-c82e-1c7a55495904" colab={"base_uri": "https://localhost:8080/", "height": 35}
# cd /content/
# + id="n-Kl6fo1oows" colab_type="code" outputId="881d6b9b-f351-41db-d529-27b70c65868f" colab={"base_uri": "https://localhost:8080/", "height": 231}
# #!gdown https://drive.google.com/uc?id=1Jmiq1-hSIsHiq_GCcmiNXtrs_T62AY_z
# !wget 'https://norod78.s3-eu-west-1.amazonaws.com/models/3d-photo-inpainting-master+(2).zip'
# #!mv "/content/3d-photo-inpainting-master (2).zip" "/content/3d-photo-inpainting-master.zip"
# !mv '/content/3d-photo-inpainting-master+(2).zip' '/content/3d-photo-inpainting-master.zip'
# + id="seX7gKalBPiH" colab_type="code" outputId="ced853f7-6ae0-47a0-e28e-9293a994e504" colab={"base_uri": "https://localhost:8080/", "height": 476}
# !unzip 3d-photo-inpainting-master.zip
# + id="i5-MWEjfBjYx" colab_type="code" colab={}
# rm 3d-photo-inpainting-master.zip
# + id="ur_o4jPCyp5L" colab_type="code" outputId="6e4948eb-d05b-4546-9585-b35de14c217c" colab={"base_uri": "https://localhost:8080/", "height": 35}
# cd 3d-photo-inpainting-master
# + id="vmX2ZWus9UrU" colab_type="code" outputId="f4c7b102-ad31-40d9-b5f8-f17cf1f37063" colab={"base_uri": "https://localhost:8080/", "height": 141}
# !pwd
# !ls -latr ./checkpoints/
# + [markdown] id="dz0ESEU0nmA0" colab_type="text"
# - **Please upload `.jpg` files to `/content/3d-photo-inpainting-master/image/`**
#
# - 
#
#
# + [markdown] id="IYC4c6r6vjVh" colab_type="text"
# - **Execute the 3D Photo Inpainting**
# - Note: The 3D photo generation process usually takes about 2-3 minutes or more depending on the available computing resources.
# + id="XLfE-6atlkeA" colab_type="code" colab={} language="sh"
# cat <<EOT >> argument.yml
# depth_edge_model_ckpt: checkpoints/edge-model.pth
# depth_feat_model_ckpt: checkpoints/depth-model.pth
# rgb_feat_model_ckpt: checkpoints/color-model.pth
# MiDaS_model_ckpt: MiDaS/model.pt
# fps: 60
# num_frames: 540 #240
# x_shift_range: -0.03
# y_shift_range: -0.00
# z_shift_range: -0.07
# specific: ''
# longer_side_len: 960
# src_folder: image
# depth_folder: depth
# mesh_folder: mesh
# video_folder: video
# load_ply: False
# save_ply: False
# inference_video: True
# gpu_ids: 0
# img_format: '.jpg'
# depth_threshold: 2.4 #1.2 #0.04
# ext_edge_threshold: 0.002
# sparse_iter: 5
# filter_size: [7, 7, 5, 5, 5]
# sigma_s: 4.0
# sigma_r: 0.5
# redundant_number: 12
# background_thickness: 180 #140 #70
# context_thickness: 220 #180 # 140
# background_thickness_2: 70
# context_thickness_2: 70
# discount_factor: 1.00
# log_depth: True
# largest_size: 1024 #512
# depth_edge_dilate: 10
# depth_edge_dilate_2: 5
# extrapolate_border: True
# extrapolation_thickness: 100 #80 #60
# repeat_inpaint_edge: True
# crop_border: False
# EOT
# + id="zo5uPQuBgw2j" colab_type="code" outputId="b3da9e3e-0097-4eba-fa33-b7f2db4db694" colab={"base_uri": "https://localhost:8080/", "height": 1000}
# !python main.py --config argument.yml
# + [markdown] id="wPvkMT0msIJB" colab_type="text"
# - **The results are stored in the following directories**
# - Corresponding depth map estimated by [MiDaS](https://github.com/intel-isl/MiDaS.git)
# - E.g. ```depth/moon.npy```
# - Inpainted 3D mesh
# - E.g. ```mesh/moon.ply```
# - Rendered videos with circular motion
# - E.g. ```mesh/moon.mp4```
#
# 
# + id="xlRceMM-kV1I" colab_type="code" outputId="dd3e0102-f322-4d19-8058-4e70b699cf08" colab={"base_uri": "https://localhost:8080/", "height": 944}
# %matplotlib inline
from matplotlib import pyplot as plt
from matplotlib.pyplot import imshow
from PIL import Image
import numpy as np
import os
# %cd /content/3d-photo-inpainting-master/depth
files = [i for i in os.listdir("./") if i.endswith("npy")]
for file in files:
data = np.load(file)
plt.imshow(data, interpolation='nearest')
plt.savefig(file+str('-fig-depth.jpg'),bbox_inches='tight')
plt.show()
img = Image.fromarray(255.0*data).convert('RGB')
display(img)
img.save(file+str('-depth.jpg'))
img = Image.fromarray(255.0*(1.0-data)).convert('RGB')
img.save(file+str('-inverse-depth.jpg'))
# %cd /content/3d-photo-inpainting-master
# + id="xxNwI30jwTZ4" colab_type="code" outputId="f3fd1627-1407-4c4e-caa5-89d47754d685" colab={"base_uri": "https://localhost:8080/", "height": 70}
# !zip ./depth-maps.zip ./depth/*.jpg
| 3D_Photo_Inpainting_args.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
# ---
# [UMAP](https://umap-learn.readthedocs.io/en/latest/) is a powerful dimensionality reduction tool which NVIDIA recently ported to GPUs with a python interface. In this notebook we will demostrate basic usage, plotting, and timing comparisons between the CUDA (GPU) version of UMAP and the original CPU version of UMAP
# !pip install umap-learn
# !pip install seaborn
# !pip install matplotlib
# !nvidia-smi
# +
import os
import pandas as pd
import numpy as np
# CPU UMAP
import umap
# libraries for scoring/clustering
from sklearn.manifold.t_sne import trustworthiness
# GPU UMAP
import cudf
from cuml.manifold.umap import UMAP as cumlUMAP
# plotting
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
# %matplotlib inline
sns.set(style='white', rc={'figure.figsize':(25, 12.5)})
# -
# We are going to work with the [fashion mnist](https://github.com/zalandoresearch/fashion-mnist) data set. This is a dataset consisting of 70,000 28x28 grayscale images of clothing.
if not os.path.exists('fashion_mnist'):
# !git clone https://github.com/zalandoresearch/fashion-mnist.git fashion_mnist
# https://github.com/zalandoresearch/fashion-mnist/blob/master/utils/mnist_reader.py
def load_mnist(path, kind='train'):
import os
import gzip
import numpy as np
"""Load MNIST data from `path`"""
labels_path = os.path.join(path,
'%s-labels-idx1-ubyte.gz'
% kind)
images_path = os.path.join(path,
'%s-images-idx3-ubyte.gz'
% kind)
with gzip.open(labels_path, 'rb') as lbpath:
labels = np.frombuffer(lbpath.read(), dtype=np.uint8,
offset=8)
with gzip.open(images_path, 'rb') as imgpath:
images = np.frombuffer(imgpath.read(), dtype=np.uint8,
offset=16).reshape(len(labels), 784)
return images, labels
train, train_labels = load_mnist('fashion_mnist/data/fashion', kind='train')
test, test_labels = load_mnist('fashion_mnist/data/fashion', kind='t10k')
data = np.array(np.vstack([train, test]), dtype=np.float64) / 255.0
target = np.array(np.hstack([train_labels, test_labels]))
# There are 60000 training images and 10000 test images
f"Train shape: {train.shape} and Test Shape: {test.shape}"
train[0].shape
# As mentioned previously, each row in the train matrix is an image
# display a Nike? sneaker
pixels = train[0].reshape((28, 28))
plt.imshow(pixels, cmap='gray')
# There is cost with moving data between host memory and device memory (GPU memory) and we will include that core when comparing speeds
# %%time
gdf = cudf.DataFrame()
for i in range(data.shape[1]):
gdf['fea%d'%i] = data[:,i]
# %%timeit
g_embedding = cumlUMAP(n_neighbors=5, init="spectral").fit_transform(gdf)
# `gdf` is a GPU backed dataframe -- all the data is stored in the device memory of the GPU. With the data converted, we can apply the `cumlUMAP` the same inputs as we do for the standard UMAP. Additionally, it should be noted that within cuml, [FAISS] https://github.com/facebookresearch/faiss) is used for extremely fast kNN and it's limited to single precision. `cumlUMAP` will automatically downcast to `float32` when needed.
# %%timeit
embedding = umap.UMAP(n_neighbors=5, init="spectral").fit_transform(data)
# Compute Runtimes of UMAP training (lower is better):
# - cumlUMAP (GPU): 10.5
# - UMAP (CPU): 100 seconds
#
# cumlMAP is ~9.5x speed up over UMAP CPU. We should also qualitatively compare output accuracy. We can do this easily by plotting the embeddings and noting simlarites in the plot
classes = [
'T-shirt/top',
'Trouser',
'Pullover',
'Dress',
'Coat',
'Sandal',
'Shirt',
'Sneaker',
'Bag',
'Ankle boot']
#Needs to be redone because of timeit loses our variables sometimes
embedding = umap.UMAP(n_neighbors=5, init="spectral").fit_transform(data)
g_embedding = cumlUMAP(n_neighbors=5, init="spectral").fit_transform(gdf)
# Just as the original author of UMAP, <NAME>, states in the [UMAP docs](https://umap-learn.readthedocs.io/en/latest/supervised.html), we can plot the results and show the separation between the various classes defined above.
# +
g_embedding_numpy = g_embedding.to_pandas().values #it is necessary to convert to numpy array to do the visual mapping
fig, ax = plt.subplots(1, figsize=(14, 10))
plt.scatter(g_embedding_numpy[:,1], g_embedding_numpy[:,0], s=0.3, c=target, cmap='Spectral', alpha=1.0)
plt.setp(ax, xticks=[], yticks=[])
cbar = plt.colorbar(boundaries=np.arange(11)-0.5)
cbar.set_ticks(np.arange(10))
cbar.set_ticklabels(classes)
plt.title('Fashion MNIST Embedded via cumlUMAP');
# -
# And side-by-side we can see that the separation is very similar between both GPU and CPU versions of UMAP. Both cluster Ankle Boot, Sneaker, and Sandal together (Green/Yellow/Purple), both separate Trousers and Bags entirely, and both have T-shirts, Shirts, Coats, etc. all mixed toether.
# +
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(20, 10))
ax[0].scatter(g_embedding_numpy[:,1], g_embedding_numpy[:,0], s=0.3, c=target, cmap='Spectral', alpha=1.0)
im = ax[1].scatter(embedding[:,1], embedding[:,0], s=0.3, c=target, cmap='Spectral', alpha=1.0)
ax[0].set_title('Fashion MNIST Embedded via cumlUMAP');
ax[1].set_title('Fashion MNIST Embedded via UMAP');
fig.subplots_adjust(right=0.8)
cax,kw = mpl.colorbar.make_axes([a for a in ax.flat])
cbar = plt.colorbar(im, cax=cax, **kw)
cbar.set_ticks(np.arange(10))
cbar.set_ticklabels(classes)
# -
# Additionally, we can also quanititaviely compare the perfomance of `cumlUMAP` (GPU UMAP) to the reference/original implementation (CPU UMAP) using the [trustworthiness score](https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/manifold/t_sne.py#L395). From the docstring:
#
# > Trustworthiness expresses to what extent the local structure is retained. The trustworthiness is within [0, 1].
#
#
# Like `t-SNE`, UMAP tries to capture both global and local structure and thus, we can apply the `trustworthiness` of the `embedding/g_embedding` data against the original input. With a higher score we are demonstrating that the algorithm does a better and better job of local structure retention. As [<NAME>](https://github.com/cjnolet) notes:
# > Algorithms like UMAP aim to preserve local neighborhood structure and so measuring this property (trustworthiness) measures the algorithm's performance.
# Scoring ~97% shows the GPU implementation is comparable to the original CPU implementation and the training time was ~9.5X faster
| community_tutorials_and_guides/umap_demo_full.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <h2 align="center"> Multivariable Regression </h2>
# ## Machine Learning - <NAME> ( Python Implementation)
#
# ## Multivariable Linear Regression
# ### Loading Data & Libraries
import pandas as pd
import numpy as np
import seaborn as sns
# +
import matplotlib.pyplot as plt
# %matplotlib inline
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (12,8)
# -
data = pd.read_csv('Multi_linear.txt', header = None)
data.head()
data.info
data.describe()
# ### Plotting Data
# +
# Create 2 Subplot, 1 for Each Variable
fig, axes = plt.subplots(figsize=(12,4),nrows=1,ncols=2)
axes[0].scatter(data[0],data[2],color="b")
axes[0].set_xlabel("Size (Square Feet)")
axes[0].set_ylabel("Prices")
axes[0].set_title("House prices against size of house")
axes[1].scatter(data[1],data[2],color="r")
axes[1].set_xlabel("Number of bedroom")
axes[1].set_ylabel("Prices")
axes[1].set_xticks(np.arange(1,6,step=1))
axes[1].set_title("House prices against number of bedroom")
# Enhance Layout
plt.tight_layout()
# -
# ### Make predictions using the optimized $\Theta$ values
#
# $h_\Theta(x) = \Theta^Tx$
def predict(x,theta):
"""
Takes in numpy array of x and theta and return the predicted value of y based on theta
"""
predictions= np.dot(theta.transpose(),x)
return predictions[0]
# ### Feature Normalization
#
# To make sure features are on a similar scale:
#
# $x_i = \frac{x_i - \mu_i}{\sigma_i}$
# ---
def featureNormalization(X):
"""
Take in numpy array of X values and return normalize X values,
the mean and standard deviation of each feature
"""
mean=np.mean(X,axis=0)
std=np.std(X,axis=0)
X_norm = (X - mean)/std
return X_norm , mean , std
# ### Compute the Cost Function $J(\Theta)$
#
# $J(\Theta) = \frac{1}{2m} \sum_{i=1}^m (h_\Theta(x^{(i)}) - y^{(i)} )^2$
def computeCost(X,y,theta):
"""
Take in a numpy array X,y, theta and generate the cost function of using theta as parameter
in a linear regression model
"""
m=len(y)
predictions=X.dot(theta)
square_err=(predictions - y)**2
return 1/(2*m) * np.sum(square_err)
data_n=data.values
m=len(data_n[:,-1])
X=data_n[:,0:2].reshape(m2,2)
X, mean_X, std_X = featureNormalization(X)
X = np.append(np.ones((m,1)),X,axis=1)
y=data_n[:,-1].reshape(m,1)
theta=np.zeros((3,1))
# ### Compute Cost $J(\Theta)$
#
# In the multivariate case, the cost function can also be written in the following vectorized form:
#
# $J(\Theta) = \frac{1}{2m} (X\Theta - \overrightarrow{y})^T (X\Theta - \overrightarrow{y})$
#
computeCost(X,y,theta)
# ### Gradient Descent
theta, J_history = gradientDescent(X,y,theta,0.1,2000)
print("h(x) ="+str(round(theta[0,0],2))+" + "+str(round(theta[1,0],2))+"x1 + "+str(round(theta[2,0],2))+"x2")
# ### Visualising the Cost Function $J(\Theta)$
#
plt.plot(J_history)
plt.xlabel("Iteration")
plt.ylabel("$J(\Theta)$")
plt.title("Cost function using Gradient Descent");
# ### Make predictions using the optimized $\Theta$ values
#feature normalisation of x values
x_sample = featureNormalization(np.array([1650,3]))[0]
x_sample=np.append(np.ones(1),x_sample)
predict3=predict(x_sample,theta2)
print("For size of house = 1650, Number of bedroom = 3, we predict a house value of $"+str(round(predict3,0)))
| Multivariable Regression/Multivariable 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.9.0 64-bit
# name: python39064bit25f93b01dc6c466c8dbbb9de8d4a97a4
# ---
# +
l=1.0
n=100
h=l/(n-1)
τ = 1e-4
δ = 0.01
Gr = 100
C = 1
from sympy import simplify, collect
from sympy.abc import y, x, z, m, C, h, G, d, t
m = x - t*((d**2)*(y - 2*x + z)/(h**2) - G*(d**2)*m*(y-z)/(2*h) - C)
# -
collect(m, m)
#
| simplify.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + id="F1DhLvlWdmC9" colab_type="code" outputId="ed62c0f6-537c-48c5-b031-ff9c5b1186d5" executionInfo={"status": "ok", "timestamp": 1581679828625, "user_tz": -60, "elapsed": 5952, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 292}
# !pip install eli5
# + id="eVzARTFBdqdi" colab_type="code" colab={}
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import cross_val_score
import eli5
from eli5.sklearn import PermutationImportance
from ast import literal_eval
from tqdm import tqdm_notebook
# + id="l6mGZC9Nk7M0" colab_type="code" outputId="a85dc0aa-1f76-482b-e31e-3bb46c4d30d9" executionInfo={"status": "ok", "timestamp": 1581681747216, "user_tz": -60, "elapsed": 644, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
# cd "/content/drive/My Drive/Colab Notebooks/dw_matrix"
# + id="PnB2Tq5elIiu" colab_type="code" colab={}
# + id="mNRJb1mClAMG" colab_type="code" colab={}
# # ls data
df = pd.read_csv('data/men_shoes.csv', low_memory=False)
# + id="7e0PwlICyQiV" colab_type="code" outputId="ad17c87f-1f5d-41c4-ffb1-76aea252fcca" executionInfo={"status": "ok", "timestamp": 1581687015905, "user_tz": -60, "elapsed": 851, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 221}
df.columns
# + id="FDd6HD7e5IXf" colab_type="code" colab={}
def run_model(feats, model = DecisionTreeRegressor(max_depth=5)):
X = df[ feats ].values
y = df['prices_amountmin'].values
scores = cross_val_score(model, X, y, scoring='neg_mean_absolute_error')
return np.mean(scores), np.std(scores)
# + id="VcsMCukT6HoN" colab_type="code" outputId="0a0cef86-99b4-441f-b649-69dbc64adb67" executionInfo={"status": "ok", "timestamp": 1581688470064, "user_tz": -60, "elapsed": 337, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
df['brand_cat'] = df['brand'].map(lambda x: str(x).lower()).factorize()[0]
run_model(['brand_cat'])
# + id="P2cx1tl29Dl7" colab_type="code" outputId="c1276947-1364-454d-aa8b-b911c2cf2160" executionInfo={"status": "ok", "timestamp": 1581688497909, "user_tz": -60, "elapsed": 3976, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
model = RandomForestRegressor(max_depth=5, n_estimators=100, random_state=0)
run_model(['brand_cat'], model)
# + id="1yIYtvR09tpA" colab_type="code" outputId="01ba2913-3a10-4e17-e39b-841063206316" executionInfo={"status": "ok", "timestamp": 1581688863778, "user_tz": -60, "elapsed": 1126, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 139}
df.features.head().values
# + id="SVLptGwg-Zvb" colab_type="code" outputId="0d2dff68-6f4f-4f92-90ec-0f04cb2864ca" executionInfo={"status": "ok", "timestamp": 1581689042137, "user_tz": -60, "elapsed": 615, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
test = {'key': 'value'}
test['key']
str(test)
# + id="WgPWsbRvBNOX" colab_type="code" outputId="7be491b9-2dbe-43c9-d80d-1febd48c46c5" executionInfo={"status": "ok", "timestamp": 1581689358608, "user_tz": -60, "elapsed": 569, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
str_dict = '[{"key":"Gender","value":["Men"]},{"key":"Shoe Size","value":["M"]},{"key":"Shoe Category","value":["Men\'s Shoes"]},{"key":"Color","value":["Multicolor"]},{"key":"Manufacturer Part Number","value":["8190-W-NAVY-7.5"]},{"key":"Brand","value":["Josmo"]}]'
literal_eval(str_dict)
literal_eval(str_dict)[0]
literal_eval(str_dict)[0]['key']
literal_eval(str_dict)[0]['value']
literal_eval(str_dict)[0]['value'][0]
# + id="okg_wkzdCh_G" colab_type="code" colab={}
def parse_features(x):
output_dict = {}
if str(x) == 'nan' : return output_dict
features = literal_eval(x.replace('\\"', '"'))
for item in features:
key = item['key'].lower().strip()
value = item['value'][0].lower().strip()
output_dict[key] = value
return output_dict
df['features_parsed'] = df['features'].map(parse_features)
# + id="0KstIL5BEMmZ" colab_type="code" outputId="841f6a5d-fb8a-45ab-eccd-649b9ee46642" executionInfo={"status": "ok", "timestamp": 1581693147836, "user_tz": -60, "elapsed": 663, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 139}
df['features_parsed'].head()
df['features_parsed'].head().values
# + id="EXc1F7C8Qzgv" colab_type="code" outputId="ad0faa8e-a1bf-4886-bdd5-b067ac460b6f" executionInfo={"status": "ok", "timestamp": 1581693252869, "user_tz": -60, "elapsed": 983, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
keys = set()
df['features_parsed'].map(lambda x: keys.update(x.keys()))
len(keys)
# + id="pBidySMRRSZY" colab_type="code" outputId="960c1fed-5e71-4deb-d592-1696618ec9aa" executionInfo={"status": "ok", "timestamp": 1581693363000, "user_tz": -60, "elapsed": 809, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 139}
df.features_parsed.head().values
# + id="pyjDhmk4RBn3" colab_type="code" outputId="523ba2e6-fdfd-4580-83b5-81416a3cb12c" executionInfo={"status": "ok", "timestamp": 1581693534379, "user_tz": -60, "elapsed": 4764, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 66, "referenced_widgets": ["de42fcf8127f48abbb9a40014f001d95", "6ad227cd913c4e468730ec208080b743", "f55c8c9e25664adfa709829286b545f9", "e82167cffd7d4d43af45b4c022ac7629", "65b269fc187943128dc408144704ac2a", "81a4953588eb497fb432b8f7920af654", "54413ed3f4664b9291b3d8266ae66042", "68b2847de568443da2ef264b945c5c97"]}
def get_name_feat(key):
return 'feat_' + key
for key in tqdm_notebook(keys):
df[get_name_feat(key)] = df.features_parsed.map(lambda feats: feats[key] if key in feats else np.nan)
# + id="HB63bM30SF6_" colab_type="code" outputId="f2942d63-81af-44a8-803e-aa32cf6f759f" executionInfo={"status": "ok", "timestamp": 1581693563984, "user_tz": -60, "elapsed": 689, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 170}
df.columns
# + id="aVC4SwLWSMe1" colab_type="code" colab={}
keys_stat = {}
for key in keys:
keys_stat[key] = df[ False == df[get_name_feat(key)].isnull()].shape[0] / df.shape[0] * 100
# + id="6BFU0nVLVgAC" colab_type="code" outputId="431e3e20-2fb3-4fb5-bb0b-ced84be10622" executionInfo={"status": "ok", "timestamp": 1581694579624, "user_tz": -60, "elapsed": 763, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 102}
{k:v for k,v in keys_stat.items() if v > 30}
# + id="HLY5zSGlHWNs" colab_type="code" colab={}
# Transformacja do postaci:
# [
# {'key': 'Gender', 'value': ['Men']},
# {'key': 'Shoe Size', 'value': ['M']},
# {'key': 'Shoe Category', 'value': ["Men's Shoes"]},
# {'key': 'Color', 'value': ['Multicolor']},
# {'key': 'Manufacturer Part Number', 'value': ['8190-W-NAVY-7.5']},
# {'key': 'Brand', 'value': ['Josmo']}]
# {
# 'Gender': 'Men',
# 'Shoe Size': 'M'...
# }
# + id="X-8xZNe8WKq7" colab_type="code" colab={}
df['feat_brand_cat'] = df['feat_brand'].factorize()[0]
df['feat_color_cat'] = df['feat_color'].factorize()[0]
df['feat_gender_cat'] = df['feat_gender'].factorize()[0]
df['feat_manufacturer part number_cat'] = df['feat_manufacturer part number'].factorize()[0]
df['feat_material_cat'] = df['feat_material'].factorize()[0]
df['feat_sport_cat'] = df['feat_sport'].factorize()[0]
df['feat_style_cat'] = df['feat_style'].factorize()[0]
for key in keys:
df[get_name_feat(key) + '_cat'] = df[get_name_feat(key)].factorize()[0]
# + id="-Wv2JmZUWhvq" colab_type="code" outputId="8ae2b723-0132-4f67-d8e6-0abc9cb41e58" executionInfo={"status": "ok", "timestamp": 1581694921171, "user_tz": -60, "elapsed": 598, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
# df['brand'] = df['brand'].map(lambda x: str(x).lower())
df[df.brand == df.feat_brand].shape
# + id="45KeyP7TWLiH" colab_type="code" outputId="8b358fd2-c59e-4916-a53b-f2fe32521b41" executionInfo={"status": "ok", "timestamp": 1581695918945, "user_tz": -60, "elapsed": 4778, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
model = RandomForestRegressor(max_depth=5, n_estimators=100)
run_model(['brand_cat'], model)
# + id="WmGGrEr4p5SH" colab_type="code" outputId="e651c850-af49-4540-83b0-497dbd1efb93" executionInfo={"status": "ok", "timestamp": 1581700350497, "user_tz": -60, "elapsed": 893, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 1000}
feats_cat = [x for x in df.columns if '_cat' in x and 'feat_' in x and 'feat_catalog' not in x]
feats_cat
# + id="vHjmTTlKbMpe" colab_type="code" outputId="19d8b83c-9e79-41e9-e8bb-d9c23ff29776" executionInfo={"status": "ok", "timestamp": 1581702398177, "user_tz": -60, "elapsed": 1266, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 187}
# feats = ['brand_cat', 'feat_brand_cat', 'feat_gender_cat', 'feat_material_cat', 'feat_sport_cat', 'feat_style_cat',
# 'feat_metal type_cat', 'feat_is weather-resistant_cat', 'feat_leather grade_cat', 'feat_leather :_cat', 'feat_hood_cat', 'feat_shape_cat', 'feat_metal stamp_cat',
# 'feat_fabric_cat', 'feat_is weather-resistant_cat', 'feat_weather-resistant_cat', 'feat_weather resistant_cat',
# 'feat_is waterproof_cat', 'feat_waterproof_cat', 'feat_heel height_cat', 'feat_boot height_cat', 'feat_shoe height_cat',
# 'feat_height_cat', 'feat_made in_cat', 'feat_best sellers rank_cat', 'feat_fabrication_cat', 'feat_age segment_cat', 'feat_occasion_cat']
feats = ['brand_cat', 'feat_brand_cat', 'feat_gender_cat', 'feat_material_cat', 'feat_sport_cat', 'feat_style_cat',
'feat_shape_cat', 'feat_metal type_cat', 'feat_occasion_cat', 'feat_heel height_cat']
# feats += feats_cat
# feats_full_list = feats
feats = list(set(feats))
feats
# + id="RF3ie-k9uvum" colab_type="code" colab={}
model = RandomForestRegressor(max_depth=5, n_estimators=100)
result = run_model(feats, model)
# + id="C5Y6fVAub--H" colab_type="code" outputId="c3c8e3fa-d9e6-4f4b-9949-a6da962167fc" executionInfo={"status": "ok", "timestamp": 1581702420763, "user_tz": -60, "elapsed": 5913, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 221}
X = df[ feats ].values
y = df['prices_amountmin' ].values
m = RandomForestRegressor(max_depth=5, n_estimators=100, random_state=0)
m.fit(X, y)
print(result)
perm = PermutationImportance(m, random_state=1).fit(X, y);
eli5.show_weights(perm, feature_names=feats)
# + id="ySs9bXAEehzh" colab_type="code" outputId="a723b6cb-fda7-4ef9-e264-1b23a764aff0" executionInfo={"status": "ok", "timestamp": 1581699565754, "user_tz": -60, "elapsed": 665, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 139}
# df['brand'].value_counts(normalize=True)
# df[ df['brand'] == 'nike'].features_parsed.head().values
df[ df['brand'] == 'nike'].features_parsed.sample(5).values
# + id="mwDw3ip_pGHc" colab_type="code" outputId="2a3753a1-d972-4311-bcb5-0c057b514f97" executionInfo={"status": "ok", "timestamp": 1581699633865, "user_tz": -60, "elapsed": 634, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB6WSbkQhxnSPBoeeqVqVci4gePp_xGCNZQZu2Kcg=s64", "userId": "09065008288739507984"}} colab={"base_uri": "https://localhost:8080/", "height": 289}
df['feat_age group'].value_counts()
# + id="0RY9A1Me0T9o" colab_type="code" colab={}
# + id="9_w8IXT60Ocn" colab_type="code" colab={}
# !git add day5.ipynb
# !git config --global user.email "<EMAIL>"
# !git config --global user.name "Wojtek"
# !git commit -m "Add dw matrix day5 file"
# !git push -u origin master
| day5.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [default]
# language: python
# name: python2
# ---
# +
# %run ../Python_files/util_data_storage_and_load.py
# %run ../Python_files/util.py
# %run ../Python_files/load_dicts.py
import numpy as np
# tmc_ref_speed_dict.keys()[0:5]
# tmc_day_speed_dict_Jan_AM = zload('../temp_files/Jan_AM/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Jan_MD = zload('../temp_files/Jan_MD/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Jan_PM = zload('../temp_files/Jan_PM/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Jan_NT = zload('../temp_files/Jan_NT/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Apr_AM = zload('../temp_files/Apr_AM/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Apr_MD = zload('../temp_files/Apr_MD/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Apr_PM = zload('../temp_files/Apr_PM/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Apr_NT = zload('../temp_files/Apr_NT/tmc_day_speed_dict_journal.pkz')
tmc_day_speed_dict_Jul_AM = zload('../temp_files/Jul_AM/tmc_day_speed_dict_journal.pkz')
tmc_day_speed_dict_Jul_MD = zload('../temp_files/Jul_MD/tmc_day_speed_dict_journal.pkz')
tmc_day_speed_dict_Jul_PM = zload('../temp_files/Jul_PM/tmc_day_speed_dict_journal.pkz')
tmc_day_speed_dict_Jul_NT = zload('../temp_files/Jul_NT/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Oct_AM = zload('../temp_files/Oct_AM/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Oct_MD = zload('../temp_files/Oct_MD/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Oct_PM = zload('../temp_files/Oct_PM/tmc_day_speed_dict_journal.pkz')
# tmc_day_speed_dict_Oct_NT = zload('../temp_files/Oct_NT/tmc_day_speed_dict_journal.pkz')
tmc_speed_dict = {}
for tmc in tmc_ref_speed_dict_journal.keys():
speed_list = []
for day in range(32)[1:]:
key = tmc + str(day)
# speed_list.append(tmc_day_speed_dict_Jan_AM[key].speed)
# speed_list.append(tmc_day_speed_dict_Jan_MD[key].speed)
# speed_list.append(tmc_day_speed_dict_Jan_PM[key].speed)
# speed_list.append(tmc_day_speed_dict_Jan_NT[key].speed)
speed_list.append(tmc_day_speed_dict_Jul_AM[key].speed)
speed_list.append(tmc_day_speed_dict_Jul_MD[key].speed)
speed_list.append(tmc_day_speed_dict_Jul_PM[key].speed)
speed_list.append(tmc_day_speed_dict_Jul_NT[key].speed)
# speed_list.append(tmc_day_speed_dict_Oct_AM[key].speed)
# speed_list.append(tmc_day_speed_dict_Oct_MD[key].speed)
# speed_list.append(tmc_day_speed_dict_Oct_PM[key].speed)
# speed_list.append(tmc_day_speed_dict_Oct_NT[key].speed)
# for day in range(31)[1:]:
# key = tmc + str(day)
# speed_list.append(tmc_day_speed_dict_Apr_AM[key].speed)
# speed_list.append(tmc_day_speed_dict_Apr_MD[key].speed)
# speed_list.append(tmc_day_speed_dict_Apr_PM[key].speed)
# speed_list.append(tmc_day_speed_dict_Apr_NT[key].speed)
tmc_speed_dict[tmc] = speed_list
for tmc in tmc_ref_speed_dict_journal.keys():
A = np.array(sum(tmc_speed_dict[tmc], []))
tmc_ref_speed_dict[tmc] = np.percentile(A, 85)
zdump(tmc_ref_speed_dict, '../temp_files/tmc_ref_speed_dict_journal.pkz')
# -
| 01_INRIX_data_preprocessing_journal18/INRIX_data_preprocessing_09_ref_speed_adjust_to_free_speed_journal.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Korteweg–De Vries equation
#
# * Physical space
# \begin{align}
# u_t + u_{xxx}u +6uu_x = 0
# \end{align}
# * Spectral space $\hat{u} = \mathscr{F}\{u\}$
# \begin{align}
# \hat{u_t} = i k_x^3 \hat{u} - 6\mathscr{F} \{ \mathscr{F}^{-1} \{ u \} \mathscr{F}^{-1} \{ ik_x \hat{u}\} \}
# \end{align}
# # Imports
import numpy as np
import matplotlib.pyplot as plt
from rkstiff.grids import construct_x_kx_rfft
from rkstiff.etd34 import ETD34
from rkstiff.etd4 import ETD4
# %matplotlib inline
# # Construct grids
# uniform grid spacing, field assumed to be real-valued -> construct_x_kx_rfft
N = 512
a, b = -150, 150
x,kx = construct_x_kx_rfft(N,a,b)
# # Linear and nonlinear functions for spectral kdV equation
L = 1j*kx**3
def NLfunc(uf):
u = np.fft.irfft(uf)
ux = np.fft.irfft(1j*kx*uf)
return -6*np.fft.rfft(u*ux)
# # Initial values set to a combination of kdV solitons
# +
A0 = np.array([0.6, 0.5, 0.4, 0.3, 0.2]).reshape(1,5)
x0 = np.array([-120, -90, -60, -30, 0]).reshape(1,5)
u0 = 0.5*A0**2/(np.cosh(A0*(x.reshape(N,1)-x0)/2)**2)
u0 = np.sum(u0,axis=1)
u0FFT = np.fft.rfft(u0)
plt.plot(x,u0)
# -
# # Initialize constant-step ETD4 and adaptive-step ETD34 solvers
solverCS = ETD4(linop=L,NLfunc=NLfunc) # Try ETD5 for a 5th order method
solverAS = ETD34(linop=L,NLfunc=NLfunc,epsilon=1e-4)
# # Propagate from time t0 to tf
# store_data -> propagated field stored in solver.u at times solver.t
# store_freq -> propagated field values stored on every store_freq step (default is every step)
uFFT_CS = solverCS.evolve(u0FFT,t0=0,tf=600,h=0.1,store_data=True,store_freq=100)
uFFT_AS = solverAS.evolve(u0FFT,t0=0,tf=600,h_init=0.1,store_data=True,store_freq=25)
# # Graph propagation
T = [solverCS.t,solverAS.t]
U_FFT = [solverCS.u,solverAS.u]
fig = plt.figure(figsize=(16,12))
titles = ['ETD4 : constant-step','ETD34 : adaptive-step']
for i in range(len(T)):
ax = fig.add_subplot(1,2,i+1,projection='3d')
ax.w_xaxis.set_pane_color((0,0,0,0))
ax.w_yaxis.set_pane_color((0,0,0,0))
ax.w_zaxis.set_pane_color((0,0,0,0))
t = np.array(T[i])
for j,snapshot_fft in enumerate(U_FFT[i]):
snapshot = np.fft.irfft(snapshot_fft)
ax.plot(x,t[j]*np.ones_like(x),snapshot,color='black')
ax.set_xlim([x[0],x[-1]])
ax.set_ylim([t[0],t[-1]])
ax.grid(False)
ax.axis(False)
ax.view_init(75,-94)
ax.set_title(titles[i])
plt.tight_layout()
| demos/constant_vs_adaptive.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 bp.section1_video5_data import get_data
from sklearn import model_selection
from xgboost import XGBClassifier
import numpy as np
seed=123
X, Y = get_data('data/video1_diabetes.csv')
X, Y
c = XGBClassifier(random_seed=seed)
results= c.fit(X, Y)
results_kfold_model = model_selection.cross_val_score(c, X, Y, cv=10)
results_kfold_model.mean()*100
new_data=np.array([[0, 148, 72, 0, 0, 33, 0, 50]])
p=c.predict(new_data)
p
pred=c.predict_proba(new_data)
pred
| Section 5/source/s5_v3_classification_using_xgboost.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"}
# # Machine Learning: Practical Application
#
#
# In this tutorial we will build a simple model to predict the if a customer is about to churn.
#
# Goals:
# 1. Explore the dataset
# 2. Build a simple predictive modeling
# 3. Iterate and improve your score
#
# + [markdown] slideshow={"slide_type": "slide"}
# How to follow along:
#
# - install [Anaconda Python](https://www.continuum.io/downloads) (or create conda environment with miniconda)
# - download and unzip `www.dataweekends.com/tdwi`
# - `cd tdwi_machine_learning`
# - `jupyter notebook`
#
#
# + [markdown] slideshow={"slide_type": "slide"}
# We start by importing the necessary libraries:
# + slideshow={"slide_type": "-"}
# %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# + [markdown] slideshow={"slide_type": "slide"}
# ## 1) Explore the dataset
# + [markdown] slideshow={"slide_type": "slide"}
# #### Data exploration
#
# - Load the csv file into memory using Pandas
# - Describe each attribute
# - is it discrete?
# - is it continuous?
# - is it a number?
# - is it text?
# - Identify the target
# + [markdown] slideshow={"slide_type": "slide"}
# Load the csv file into memory using Pandas
# + slideshow={"slide_type": "fragment"}
df = pd.read_csv('churn.csv')
# + [markdown] slideshow={"slide_type": "slide"}
# What's the content of ```df``` ?
# + slideshow={"slide_type": "fragment"}
df.head(3)
# + [markdown] slideshow={"slide_type": "slide"}
# Describe each attribute (is it discrete? is it continuous? is it a number? is it text?)
# + slideshow={"slide_type": "fragment"}
df.info()
# + [markdown] slideshow={"slide_type": "slide"}
# #### Mental notes so far:
#
# - Dataset contains 7043 entries
# - 1 Target column (```Churn```)
# - 19 Features:
# - 4 numerical, 15 text
# - Some features probably binary
# - Some featuers categorical (more than 2 values)
# - No missing data
# + [markdown] slideshow={"slide_type": "slide"}
# Target:
# + slideshow={"slide_type": "fragment"}
df['Churn'].value_counts()
# + [markdown] slideshow={"slide_type": "fragment"}
# Binary variable.
#
# Approximately 1 every 4 customers churns. This is our benchmark.
#
# If we predicted no churns we would be accurate 73.5% of the time.
# + slideshow={"slide_type": "fragment"}
benchmark_accuracy = df['Churn'].value_counts()[0] / len(df)
benchmark_accuracy
# + [markdown] slideshow={"slide_type": "slide"}
# Binary encode target
# + slideshow={"slide_type": "fragment"}
y = (df['Churn'] == 'Yes')
# + slideshow={"slide_type": "fragment"}
y.head(4)
# + slideshow={"slide_type": "fragment"}
y.value_counts()
# + [markdown] slideshow={"slide_type": "slide"}
# Drop churn column from df
# + slideshow={"slide_type": "fragment"}
dfnochurn = df.drop('Churn', axis=1)
# + [markdown] slideshow={"slide_type": "slide"}
# Feature cardinality
# + slideshow={"slide_type": "fragment"}
card = dfnochurn.apply(lambda x:len(x.unique()))
card
# + [markdown] slideshow={"slide_type": "fragment"}
# Some features are numerical, some are binary, some are categorical. Let's start with just the numerical features.
# + [markdown] slideshow={"slide_type": "slide"}
# Copy numerical features to a DataFrame called `X`.
# + slideshow={"slide_type": "fragment"}
X = df[['tenure', 'MonthlyCharges', 'TotalCharges']].copy()
# + [markdown] slideshow={"slide_type": "slide"}
# ## 2) Build a simple model
# + [markdown] slideshow={"slide_type": "slide"}
# Train / Test split
# + slideshow={"slide_type": "fragment"}
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=0)
# + [markdown] slideshow={"slide_type": "slide"}
# Let's use a Decision tree model
# + slideshow={"slide_type": "fragment"}
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(random_state=0)
model
# + [markdown] slideshow={"slide_type": "slide"}
# Train the model
# + slideshow={"slide_type": "fragment"}
model.fit(X_train, y_train)
# + [markdown] slideshow={"slide_type": "slide"}
# Calculate the accuracy score
# + slideshow={"slide_type": "fragment"}
my_score = model.score(X_test, y_test)
print("Classification Score: %0.3f" % my_score)
print("Benchmark Score: %0.3f" % benchmark_accuracy)
# + [markdown] slideshow={"slide_type": "fragment"}
# Very bad!
# + [markdown] slideshow={"slide_type": "slide"}
# Let's try with a Random Forest Classifier
# + slideshow={"slide_type": "fragment"}
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(random_state=0)
model.fit(X_train, y_train)
my_score = model.score(X_test, y_test)
print("Classification Score: %0.3f" % my_score)
print("Benchmark Score: %0.3f" % benchmark_accuracy)
# + [markdown] slideshow={"slide_type": "fragment"}
# Barely better than the benchmark.
# + [markdown] slideshow={"slide_type": "slide"}
# Print the confusion matrix for the decision tree model
# + slideshow={"slide_type": "fragment"}
from sklearn.metrics import confusion_matrix
y_pred = model.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
pd.DataFrame(cm, index=['No Churn', 'Churn'],
columns=['Pred No Churn', 'Pred Churn'])
# + [markdown] slideshow={"slide_type": "slide"}
# ## 3) Iterate and improve
# + [markdown] slideshow={"slide_type": "slide"}
# Now you have a basic pipeline. How can you improve the score? Try:
# - rescale the numerical features:
# - can you use the log of Total Charges?
# - add other features:
# - can you add the binary features to the model? See if you can create auxiliary boolean columns in `X` that reproduce the binary features in `dfnochurn`. For example, you could create a column called `IsMale` that is equal to `True` when `df['gender'] == 'Male'`.
# - can you add the categorical features to the model? To do this you will have to use the function `pd.get_dummies` and to perform 1-hot encoding of the categorical features.
# + [markdown] slideshow={"slide_type": "slide"}
# - visual exploration:
# - can you display the histogram of the numerical features?
# - can you display the relative ratio of binary and categorical variables using pie charts?
#
# - change the parameters of the model.
# - can you change the initialization of the decision tree or the random forest classifier to improve their score? you can check the documentation here:
# - http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html
# - http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html
# + [markdown] slideshow={"slide_type": "slide"}
# - change the model itself. You can find many other models here:
# http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html
#
# Try to get the best score on the test set
# -
# + [markdown] slideshow={"slide_type": "slide"}
# *Copyright © 2017 Dataweekends & CATALIT LLC*
| Machine Learning Practical Application.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 torch
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")
device
# +
import torchvision
from torchvision import models
from torchvision import transforms
import os
import glob
from PIL import Image
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
from torchvision import models
from random import randint
# tensor -> PIL image
unloader = transforms.ToPILImage()
# flip = transforms.RandomHorizontalFlip(p=1)
# +
class ToyDataset(Dataset):
def __init__(self, dark_img_dir, light_img_dir):
self.dark_img_dir = dark_img_dir
self.light_img_dir = light_img_dir
self.n_dark = len(os.listdir(self.dark_img_dir))
self.n_light = len(os.listdir(self.light_img_dir))
def __len__(self):
return min(self.n_dark, self.n_light)
def __getitem__(self, idx):
filename = os.listdir(self.light_img_dir)[idx]
light_img_path = f"{self.light_img_dir}{filename}"
light = Image.open(light_img_path).convert("RGB")
dark_img_path = f"{self.dark_img_dir}{filename}"
dark = Image.open(dark_img_path).convert("RGB")
# if random()>0.5:
# light = transforms.functional.rotate(light, 30)
# dark = transforms.functional.rotate(dark, 30)
# if random()>0.5:
# light = transforms.functional.rotate(light, 330)
# dark = transforms.functional.rotate(dark, 330)
# if random()>0.5:
# light = flip(light)
# dark = flip(dark)
s = randint(600, 700)
transform = transforms.Compose([
transforms.Resize(s),
transforms.CenterCrop(512),
transforms.ToTensor(),
])
light = transform(light)
dark = transform(dark)
return dark, light
batch_size = 1
train_dark_dir = f"./data/train/dark/"
train_light_dir = f"./data/train/light/"
training_set = ToyDataset(train_dark_dir,train_light_dir)
training_generator = DataLoader(training_set, batch_size=batch_size, shuffle=True)
val_dark_dir = f"./data/test/dark/"
val_light_dir = f"./data/test/light/"
validation_set = ToyDataset(val_dark_dir, val_light_dir)
validation_generator = DataLoader(validation_set, batch_size=batch_size, shuffle=True)
# -
# generate training images
n = 1
cycle = 5
dark_save_path = "./data_augment/train/dark/"
light_save_path = "./data_augment/train/light/"
for i in range(cycle):
for item in training_generator:
dark, light = item
dark = unloader(dark[0,])
light = unloader(light[0,])
dark.save(dark_save_path+f"{n}.jpg")
light.save(light_save_path+f"{n}.jpg")
n += 1
# generate testing images
n = 1
cycle = 1
dark_save_path = "./data_augment/test/dark/"
light_save_path = "./data_augment/test/light/"
for i in range(cycle):
for item in validation_generator:
dark, light = item
dark = unloader(dark[0,])
light = unloader(light[0,])
dark.save(dark_save_path+f"{n}.jpg")
light.save(light_save_path+f"{n}.jpg")
n += 1
| image_augmentation.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
# ---
# # RCS Tuples
#
# ## Tuples
#
# * ordered
# * immutable (cannot be changed!)
# * Can be used as a collection of fields
# # Why use Tuples instead of lists ?
# * Can use as keys in dictionaries
# * They are faster than list (faster because of the immutability)
# * There is a bit of safety
# * Generelly use for passing argument groupe
#
# ## Rule
# * List for homogenous data - same data type
# * Tuples for heterogneous data - meaning different types
# declaring
mytuple = 6, 4, 9
print(mytuple)
type(mytuple)
mytuple[2]
mytuple[:2]
mytuple.count(9)
numtuple = tuple(range(10))
numtuple
numtuple[3]
# Tuples are immutable
numtuple[3] = 333
mytuple.index(9)
numtuple.index(9)
333 in numtuple
6 in numtuple
import random
bigtuple = tuple([random.randint(1,6) for _ in range(100)]) # I cast a list comprehension to tuple
bigtuple
tuple("Valdis")
elcountlist = [bigtuple.count(el) for el in range(1,7)]
elcountlist
from collections import Counter # specific type of dictionary
tupcounter = Counter(bigtuple)
tupcounter
mytuple
mylist = list(mytuple)
mylist
dir(mytuple)
bigt = tuple(range(1,11))
bigt
reversedtup = bigt[::-1]
reversedtup
bigt[3] = 33
mlist = list(bigt)
mlist
mlist[3] = 333
mlist
newtup = tuple(mlist)
newtup
# A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
double= 'hello', 'super'
double
# +
empty = () # you do parenthesis for empty tuple
singleton = 'hello', # <-- note trailing comma
double= ('hello', 'super')
triple = (1,2,3) # so parenthesis is not actually necessary
quad = 1,2,3,4
len(empty)
0
len(singleton)
1
print(empty,singleton,double,triple,quad)
#('hello',)
# The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:
# -
bool(empty) # so empty tuple is falsy value
bool(singleton)
lst=list(double)
lst
dir(singleton)
# ## Unpacking tuples
mytuple
a, _, c = mytuple # of course we could just write c = mytuple[2]
print(a, c)
# swapping two values without an explicit temp variable
a, c = c, a
print(a, c)
a, b, c = mytuple
print(a,b,c)
numtup = tuple(range(10))
numtup
x,y, *rest = numtup
x
y
rest # so rest is cast to list, if still needed tuple we'd have to cast it tuple
55
_
mytuple[2]
ytup = ([1,2,3], "Petr", 66)
ytup
ytup[2] = 77
ytup[0]
ytup[0] = [3,555]
ytup[0][2] = "hmmm" # i can modify the list inside the tuple!
ytup
ytup[0].append('new value')
ytup
btup = [1,2], 'Val', 3433, {'a':100, 'b':20}
btup
btup[-1]
# +
# so if the data structure inide tuple is mutable we can modify it
# -
# we can add new key - value pairs to the dictionary inside tuple since dictionaries are mutable
btup[-1]['newkey'] = 'newvalue'
btup
btup[-1].update({'b':500,'c':900})
btup
ytup[1] = 'Valdis'
ytup[2] = 'Valdis'
ytup[0] ='Valdis'
# We can't change tuples, but we can change list items inside tuple
ytup[0][1] = 'Valdis'
ytup
ytup[0].append('something')
ytup
a, b, c = mytuple
print(a, b, c)
55
# Last Value in Memory
_
# +
# More on Tuples
# https://www.datacamp.com/community/tutorials/python-tuples-tutorial
# -
ntup = tuple(range(10))
ntup
ntup[2:6:2]
atup = ntup[:5]+ntup[2:9]
atup
# multiply is overloaded and we can make new longer copies
btup = atup*4
btup
len(btup)
btup.count(2)
btup.index(2)
btup[2]
sum(btup)
min(btup),max(btup)
for n in numtup:
print(n)
# So tuples are a bit faster than lists
# so you can not hash semi mutables tuples,
# so those tuples would not be usable for dictionary keys
hash(numtup)
hash(btup)
a, _, _, b = (1,2,3,4)
a, b
# +
# _ so indicated that we do care about this variable
# -
_
| core/Python Tuples.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] latex_metadata={"author": "<NAME>", "title": "Visual Transformer | Cats&Dogs Edition", "twitter": "@adi_myth"}
# # Visual Transformer with Linformer
#
# Training Visual Transformer on *Lion, Lizard and Toucan dataset*
# + id="s_z7TuN_RIOK"
import sys
# !pip -q install vit_pytorch linformer
# + [markdown] id="IDT1Xwv9RZXb"
# ## Import Libraries
# + id="qq-e52uORIVg"
from __future__ import print_function
import glob
from itertools import chain
import os
import random
import zipfile
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from linformer import Linformer
from PIL import Image
from sklearn.model_selection import train_test_split
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import DataLoader, Dataset
from torchvision import datasets, transforms
from tqdm.notebook import tqdm
import shutil
from vit_pytorch.efficient import ViT
# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="pV-E0IFHRITw" outputId="f4221b45-a2bf-479f-ecdb-8df9e836312a"
print(f"Torch: {torch.__version__}")
# + id="GEoNmg0aQVf9"
# Training settings
batch_size = 32 # was 64
epochs = 10 # was 20
lr = 3e-5
gamma = 0.7
seed = 42
# + id="mSO-6jwwlYzO"
def seed_everything(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
seed_everything(seed)
# + pycharm={"name": "#%%\n"}
device = 'cuda'
# -
# ## Load Data
# + pycharm={"name": "#%%\n"}
# JW: Remove data if exists
shutil.rmtree("data")
os.makedirs('data', exist_ok=True)
os.makedirs('data/train', exist_ok=True)
os.makedirs('data/test', exist_ok=True)
# + pycharm={"name": "#%%\n"}
train_dir = 'data/train'
test_dir = 'data/test'
# + pycharm={"name": "#%%\n"}
# JW: Copy images from chosen dataset to folders, 2/3 train/test split. Add label to train name/path
split = 2/3
dataset = "images-outline"
folders = [x.replace("\\", "/") for x in glob.glob(f"{dataset}/*")]
for folder in folders:
paths = [x.replace("\\", "/") for x in glob.glob(f"{folder}/*.*")]
index = round(split * len(paths))
for path in paths[:index]:
items = path.split('/')
new_name = f"{items[1].lower()}.{items[-1]}"
new_path = f"{train_dir}/{new_name}"
shutil.copy(path, new_path)
for path in paths[index:]:
new_name = path.split('/')[-1]
new_path = f"{test_dir}/{new_name}"
shutil.copy(path, new_path)
# + id="FVD2SEjTRgXh"
train_list = [x.replace("\\", "/") for x in glob.glob(f"{train_dir}/*.*")]
test_list = [x.replace("\\", "/") for x in glob.glob(f"{test_dir}/*.*")]
# + colab={"base_uri": "https://localhost:8080/", "height": 51} id="GwQ01kgtSExB" outputId="50a9ce9b-39d0-4360-e227-cbd155be31fb"
print(f"Train Data: {len(train_list)}")
print(f"Test Data: {len(test_list)}")
# + id="amKHFCu_iwQZ"
labels = [path.split('/')[-1].split('.')[0] for path in train_list]
# + [markdown] id="UxHo4dU8SHcZ"
# ## Split
# + id="YgrHNTpnR6Hl"
train_list, valid_list = train_test_split(train_list,
test_size=0.2,
stratify=labels,
random_state=seed)
# + colab={"base_uri": "https://localhost:8080/", "height": 68} id="UViq3x5yR5-r" outputId="9db06fb4-fb7e-4d07-b316-6619e2f6d030"
print(f"Train Data: {len(train_list)}")
print(f"Validation Data: {len(valid_list)}")
print(f"Test Data: {len(test_list)}")
# + [markdown] id="ZhYDJXk2SRDu"
# ## Image Augmentation
# + id="YKR5RaykR58x"
train_transforms = transforms.Compose(
[
transforms.Resize((224, 224)),
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
]
)
val_transforms = transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
]
)
test_transforms = transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
]
)
# + [markdown] id="b0JAXWWtSXpB"
# ## Load Datasets
# + id="Ds9yt5kHR56R"
class LionLizardToucanDataset(Dataset):
def __init__(self, file_list, transform=None):
self.file_list = file_list
self.transform = transform
def __len__(self):
self.filelength = len(self.file_list)
return self.filelength
def __getitem__(self, idx):
img_path = self.file_list[idx]
img = Image.open(img_path)
img_transformed = self.transform(img)
label = img_path.split("/")[-1].split(".")[0]
if label == "lion":
label = 0
elif label == "lizard":
label = 1
else:
label = 2
return img_transformed, label
# + id="pC-D9a8xSZNd"
train_data = LionLizardToucanDataset(train_list, transform=train_transforms)
valid_data = LionLizardToucanDataset(valid_list, transform=test_transforms)
test_data = LionLizardToucanDataset(test_list, transform=test_transforms)
# + id="-mz9qUsLSZVU"
train_loader = DataLoader(dataset = train_data, batch_size=batch_size, shuffle=True )
valid_loader = DataLoader(dataset = valid_data, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(dataset = test_data, batch_size=batch_size, shuffle=True)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="JiIcaG1zSZLA" outputId="bd4d6e91-6c28-4b42-f242-246250dc55f2"
print(len(train_data), len(train_loader))
# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="hLLq3UCRSZIo" outputId="bc81dd28-197c-4c38-ecd1-7a8cc35d4703"
print(len(valid_data), len(valid_loader))
# + [markdown] id="TF9yMaRrSvmv"
# ## Efficient Attention
# + [markdown] id="XED_6UFASx9r"
# ### Linformer
# + id="EZ6KeBfgSnwg"
efficient_transformer = Linformer(
dim=128,
seq_len=49+1, # 7x7 patches + 1 cls-token
depth=12,
heads=8,
k=64
)
# + [markdown] id="8VCgoZBvovkx"
# ### Visual Transformer
# + id="rFmQvrLXSntZ"
model = ViT(
dim=128,
image_size=224,
patch_size=32,
num_classes=3,
transformer=efficient_transformer,
channels=3,
).to(device)
# + [markdown] id="4u5YZG1eozIv"
# ### Training
# + id="2Go1icggSnrB"
# loss function
criterion = nn.CrossEntropyLoss()
# optimizer
optimizer = optim.Adam(model.parameters(), lr=lr)
# scheduler
scheduler = StepLR(optimizer, step_size=1, gamma=gamma)
# + colab={"base_uri": "https://localhost:8080/", "height": 1000, "referenced_widgets": ["11867da10dc0486ea078f31209581317", "7313e2de08964cb5a7622a190bdfbd4b", "4d3ed025005d4927bf4d620be9c45732", "31b8d6217b8949dfa554b912eed86b57", "<KEY>", "<KEY>", "6c2e22089db945eea9976bf5724e25b1", "<KEY>", "564881ed808b4200be1ea443e89b8d9d", "18d0d3e863eb4681a9dbc81a399b6109", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "3d57e0fd12004a7cb85b1c19956e1f5f", "<KEY>", "8f23349eacd646f3ad2d87dbed40c349", "9919abdccadb4d9db22d4e8b1b72d9ea", "cf0158955a2c49eca2ad4c79101d21a6", "ea494c3b344244fda0d24069c0e7a0d1", "<KEY>", "<KEY>", "16bec98387ac43a982000738d5746699", "182ab780e426419da31a4dc5de213092", "<KEY>", "<KEY>", "c56a4450e3784e86ba91dd3975c60745", "<KEY>", "b0ae2465b90345e19035eabcde635883", "bea5af2eee0b4026b6c74a1851c642d4", "85786d57b43e42db8e05f31d88fa1c22", "<KEY>", "<KEY>", "c2f85a0cdca848f59db65a692b7413a5", "4a13f00f11ef4b4eb3e797e5f57fb2aa", "6d8c09b1aa3f4c4e856f7958200e0cab", "bdac8165176e4ccab62d1d1e180a2bc7", "a669d026327c4113ae5f8151d4ed9e54", "<KEY>", "d14e2a47e6d0471d8c03392ef039e152", "454f2deb19f245e1ac5db5e3968d26a3", "<KEY>", "<KEY>", "<KEY>", "1166efc54747428ab0684e38cf840665", "68621df86e0f4461b176003e414c4a72", "5f725c823796407a9ec98aae36d33d25", "2683595515c04016b77eac45388e8a7e", "f4ac9895b25c4e2f9ae14524f99ac229", "7c801bd8e1ca4aad85b2a53d86aff543", "<KEY>", "<KEY>", "d439ead8b1624645903cff16ec77bf4d", "c247e9b037494995baf719b47223a232", "cbeedabe560a4699b2f964ec984ef9ef", "570452687df04a2787e0d89a31104e00", "d026af39e18243d6a8b13e55d54017ea", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "8d5d9a7f5516458ea9d30f6e65231742", "<KEY>", "3008c90520384917a163ffcfa5be9bb1", "1fd79861d441410693dafbec6ada8134", "548fcdb75e93460a91e4f4b952e4ebdc", "10b780e7baa641f9aeecc58ff054ed19", "67292f3254cc40d79f035c4953e7dd40", "8c7d275a8a33443396982ab7e7a1201d", "<KEY>", "<KEY>", "09e21691d62f421facf39e93d546b6ed", "3392993d89b44c3a9f46b07840c200ce", "2f5b224afcf4454d8d141e125ff7de77", "<KEY>", "<KEY>", "<KEY>", "15641ea864b6449ea0d4fa984e1797e1", "<KEY>", "0f2f1ec1f97748f494bed67cc3ef544f", "5c1e813090f8471b8b3942da946240ed", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "4425cbe1b25547c984b5e525892d3e74", "14cef72569694ffd94a9bac599cf53e2", "<KEY>", "a24aac132e76494dae52f87699c7ad7a", "<KEY>", "dd1d0974e3b04fadbd836682123a1d5a", "676f89c403fd4553a13c6884740ecc09", "524d1408908b40c9ab8a467472cb1462", "<KEY>", "45a3d1840d15446aad3c68392d3e5a64", "6260f7a210df4fe389ef81a8674429ba", "<KEY>", "b9f68ecdcad546e4b642ecea2383538e", "1b91bdcc25c3442e94bb94e95af8bae2", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "1d7ad4ce4d7f4c678b062e34781c2e14", "<KEY>", "fcfd910e3f6e4cbe8f4a9551119c701b", "<KEY>", "71586dd940d64d60873e077857cd89a7", "c248f5f3582a4c13a757203febb2f42a", "438557904d684a48bebb7b7f9eec085c", "a793a66c0e184e43a65f1e1f8eda4f24", "a5781b9efe924be8884c850bfc8c4dac", "<KEY>", "a87fa896655d43a8aab7e89566e756da", "<KEY>", "2dc8c2e5dd3e48c89cadafd715244df4", "<KEY>", "<KEY>", "<KEY>", "2b25eee0ecae4fd1b4edfbc7a8919d7d", "47f9950796d040a09492e2aefbaf7a37", "fc139a3ff6d14f419a7b9d717e86a083", "<KEY>", "6ee0e023f88940ee9e30cc4214740d3a", "f5fa062365b44ab38843fe806c29870b", "<KEY>", "d4a7a84118964bbbafec297e3eedc261", "<KEY>", "bc506ef426f84845bf793175fad5a942", "<KEY>", "3d4f065ed9f241e59a0367909dcac922", "ab2e587ce7974b9ea4d99fcfb526ce55", "0f5dbabbbe6e4e7baa9039e4384acae7", "bc671366114844dc8eded3bbd3e8149b", "385d159046c446389e86f42e3d8d7c4e", "<KEY>", "<KEY>", "04736f2093ef43849d8b6ded15bfed63", "<KEY>", "<KEY>", "<KEY>", "a8d83d522539487aaa0d1407671477da", "<KEY>", "9c47e68a2e5d4a3aadebd3367f07b4ec", "<KEY>", "<KEY>", "e6c7d351d0944e36804d6e1748617520", "<KEY>", "f974ade129f942fbb1548625b41da97e", "<KEY>", "<KEY>", "ea3298ef31234a8bb9dc09259de0d414", "8f9ee556adf24776ac43a9e313548e72", "<KEY>", "fe890270f3fb46c7a9d442992f876863", "<KEY>", "a4bc9978e26440a3851eec78e949fb91", "<KEY>", "1a329d0bc9f047ac8f5d9cd98080aab6"]} id="KDBDOcxeU1eR" outputId="ef6d4d62-e705-4490-90a7-85036ff6ce62" pycharm={"name": "#%%\n"}
for epoch in range(epochs):
epoch_loss = 0
epoch_accuracy = 0
for data, label in tqdm(train_loader):
data = data.to(device)
label = label.to(device)
output = model(data)
loss = criterion(output, label)
optimizer.zero_grad()
loss.backward()
optimizer.step()
acc = (output.argmax(dim=1) == label).float().mean()
epoch_accuracy += acc / len(train_loader)
epoch_loss += loss / len(train_loader)
with torch.no_grad():
epoch_val_accuracy = 0
epoch_val_loss = 0
for data, label in valid_loader:
data = data.to(device)
label = label.to(device)
val_output = model(data)
val_loss = criterion(val_output, label)
acc = (val_output.argmax(dim=1) == label).float().mean()
epoch_val_accuracy += acc / len(valid_loader)
epoch_val_loss += val_loss / len(valid_loader)
print(
f"Epoch : {epoch+1} - loss : {epoch_loss:.4f} - acc: {epoch_accuracy:.4f} - val_loss : {epoch_val_loss:.4f} - val_acc: {epoch_val_accuracy:.4f}\n"
)
| examples/lion_lizard_toucan.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
# ---
# # Support Vector Machines (SVM)
# ---
# As we read earlier, the Support Vector Machine is a type of classification-based, supervised Machine Learning algorithm. In this tutorial, we will learn how to implement a SVM model using Scikit Learn.
#
# ## Importing Project Dependencies
# ---
# Let us first import all the necesary libraries.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# %matplotlib inline
# ## Importing & Pre-Processing the Dataset
# ---
# For this project, we will be working on sklearn's built-in breast cancer dataset. This is a binary classification problem where on the basis of the given features, we want our model to predict whether a given tumore is malignant (cancerous, denoted by 1) or benign (non-cancerous, denoted by 0).
#
# Let us import the dataset now.
# +
# Step 1- Importing the dataset class
from sklearn.datasets import load_breast_cancer
# Step 2- Creating the dataset class object
cancer = load_breast_cancer()
# -
# Now, let us have a look at what all info the breast cancer dataset comes with.
cancer.keys()
# + tags=[]
# printing the dataset description
print(cancer['DESCR'])
# -
# If you go through the description of the dataset, you will find that there are no null values within the dataset, which means it is already cleaned. Now, let us have a look at the features within our dataset.
# features within our dataset
cancer['feature_names']
# Now, we will convert our dataset into a pandas dataframe object that will allow us to manipulate and work with the data in a much better way as compared to a numpy array. We will also have a look at the basic info regarding the data.
# + tags=[]
feature_df = pd.DataFrame(cancer['data'], columns = cancer['feature_names']) # creating the feature dataframe
feature_df.info()
# -
target = cancer['target'] # target values
target
# Now, before we do the modelling, let us have a look at the our data.
feature_df.head()
# If we compare the data in different columns of our feature set, we will notice that the values vary a lot in terms of scale. In order to tackle this data imbalance, we will have to scale/normalize the data. We will be using MinMaxScaler for this, and what it does is that it reduces all the values in the range \[0,1]. Let us see how to implement that.
# +
#Step 1- Importing MinMaxScaler class
from sklearn.preprocessing import MinMaxScaler
# Step 2- Creating class object
scaler = MinMaxScaler()
# Step 3- Fitting and transforming the feature set
X_scaled = scaler.fit_transform(feature_df)
# -
# Now, let us split our dataset into training set and test set.
# +
# Step 1- Importing the test_train_split method from sklearn
from sklearn.model_selection import train_test_split
# Step 2- Performing the split
X_train, X_test, y_train, y_test = train_test_split(X_scaled, target, test_size=0.2, random_state=42)
X_train.shape[0], X_test.shape[0]
# -
# ## Modeling
# ---
# Now that the data is ready and preprocessed, we will now train our SVM model.
# +
# Step 1- Importing the support vector classifier class
from sklearn.svm import SVC
# Step 2- Creating the class object
model = SVC()
# Step 3- Training the model
model.fit(X_train,y_train)
# -
# Now, with the model use our trained model to perform inference on the test set.
# generating predictions on the test set
y_preds = model.predict(X_test)
y_preds
# Now, let us test the evaluate our model on different accuracy measures.
# importing different accuracy metrics
from sklearn.metrics import classification_report,confusion_matrix
# + tags=[]
print(confusion_matrix(y_test, y_preds))
# -
# As we can see, out model performed splendidly, with only 4 false positives and 0 false negative predictions.
pd.DataFrame(classification_report(y_test, y_preds, output_dict = True))
# As we can see, our model has an accuracy of 96.5%, f1 score of 0.97 a precision score of 1 and a recall of 0.9.
#
# __For cases like breast cancer prediction (and other medical uses of machine learning), we generally prefer the precision over other metrics.__ This is because we want our model to have as less false negatives as possible. In other words, telling a patient with cancer that they don't have cancer can be fatal for them. On the other hand, a patient who doesn't have cancer being told that they have cancer is not that big a problem. They can have tests done later to confirm that they don't have cancer.
#
# As we can see, out model had a precision of 1 (100%), hence it performed really well.
#
# With this, we come at the end of this tutorial. Go through the notebook once again before moving on to the quiz in the next step.
| Notebooks/easy_track/algorithms/SVM.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
# ---
# # Assignment 2: Parts-of-Speech Tagging (POS)
#
# Welcome to the second assignment of Course 2 in the Natural Language Processing specialization. This assignment will develop skills in part-of-speech (POS) tagging, the process of assigning a part-of-speech tag (Noun, Verb, Adjective...) to each word in an input text. Tagging is difficult because some words can represent more than one part of speech at different times. They are **Ambiguous**. Let's look at the following example:
#
# - The whole team played **well**. [adverb]
# - You are doing **well** for yourself. [adjective]
# - **Well**, this assignment took me forever to complete. [interjection]
# - The **well** is dry. [noun]
# - Tears were beginning to **well** in her eyes. [verb]
#
# Distinguishing the parts-of-speech of a word in a sentence will help you better understand the meaning of a sentence. This would be critically important in search queries. Identifying the proper noun, the organization, the stock symbol, or anything similar would greatly improve everything ranging from speech recognition to search. By completing this assignment, you will:
#
# - Learn how parts-of-speech tagging works
# - Compute the transition matrix A in a Hidden Markov Model
# - Compute the transition matrix B in a Hidden Markov Model
# - Compute the Viterbi algorithm
# - Compute the accuracy of your own model
#
# ## Outline
#
# - [0 Data Sources](#0)
# - [1 POS Tagging](#1)
# - [1.1 Training](#1.1)
# - [Exercise 01](#ex-01)
# - [1.2 Testing](#1.2)
# - [Exercise 02](#ex-02)
# - [2 Hidden Markov Models](#2)
# - [2.1 Generating Matrices](#2.1)
# - [Exercise 03](#ex-03)
# - [Exercise 04](#ex-04)
# - [3 Viterbi Algorithm](#3)
# - [3.1 Initialization](#3.1)
# - [Exercise 05](#ex-05)
# - [3.2 Viterbi Forward](#3.2)
# - [Exercise 06](#ex-06)
# - [3.3 Viterbi Backward](#3.3)
# - [Exercise 07](#ex-07)
# - [4 Predicting on a data set](#4)
# - [Exercise 08](#ex-08)
# Importing packages and loading in the data set
from utils_pos import get_word_tag, preprocess
import pandas as pd
from collections import defaultdict
import math
import numpy as np
# <a name='0'></a>
# ## Part 0: Data Sources
# This assignment will use two tagged data sets collected from the **Wall Street Journal (WSJ)**.
#
# [Here](http://relearn.be/2015/training-common-sense/sources/software/pattern-2.6-critical-fork/docs/html/mbsp-tags.html) is an example 'tag-set' or Part of Speech designation describing the two or three letter tag and their meaning.
# - One data set (**WSJ-2_21.pos**) will be used for **training**.
# - The other (**WSJ-24.pos**) for **testing**.
# - The tagged training data has been preprocessed to form a vocabulary (**hmm_vocab.txt**).
# - The words in the vocabulary are words from the training set that were used two or more times.
# - The vocabulary is augmented with a set of 'unknown word tokens', described below.
#
# The training set will be used to create the emission, transmission and tag counts.
#
# The test set (WSJ-24.pos) is read in to create `y`.
# - This contains both the test text and the true tag.
# - The test set has also been preprocessed to remove the tags to form **test_words.txt**.
# - This is read in and further processed to identify the end of sentences and handle words not in the vocabulary using functions provided in **utils_pos.py**.
# - This forms the list `prep`, the preprocessed text used to test our POS taggers.
#
# A POS tagger will necessarily encounter words that are not in its datasets.
# - To improve accuracy, these words are further analyzed during preprocessing to extract available hints as to their appropriate tag.
# - For example, the suffix 'ize' is a hint that the word is a verb, as in 'final-ize' or 'character-ize'.
# - A set of unknown-tokens, such as '--unk-verb--' or '--unk-noun--' will replace the unknown words in both the training and test corpus and will appear in the emission, transmission and tag data structures.
#
#
# <img src = "DataSources1.PNG" />
# Implementation note:
#
# - For python 3.6 and beyond, dictionaries retain the insertion order.
# - Furthermore, their hash-based lookup makes them suitable for rapid membership tests.
# - If _di_ is a dictionary, `key in di` will return `True` if _di_ has a key _key_, else `False`.
#
# The dictionary `vocab` will utilize these features.
# +
# load in the training corpus
with open("WSJ_02-21.pos", 'r') as f:
training_corpus = f.readlines()
print(f"A few items of the training corpus list")
print(training_corpus[0:5])
# +
# read the vocabulary data, split by each line of text, and save the list
with open("hmm_vocab.txt", 'r') as f:
voc_l = f.read().split('\n')
print("A few items of the vocabulary list")
print(voc_l[0:50])
print()
print("A few items at the end of the vocabulary list")
print(voc_l[-50:])
# +
# vocab: dictionary that has the index of the corresponding words
vocab = {}
# Get the index of the corresponding words.
for i, word in enumerate(sorted(voc_l)):
vocab[word] = i
print("Vocabulary dictionary, key is the word, value is a unique integer")
cnt = 0
for k,v in vocab.items():
print(f"{k}:{v}")
cnt += 1
if cnt > 20:
break
# +
# load in the test corpus
with open("WSJ_24.pos", 'r') as f:
y = f.readlines()
print("A sample of the test corpus")
print(y[0:10])
# +
#corpus without tags, preprocessed
_, prep = preprocess(vocab, "test.words")
print('The length of the preprocessed test corpus: ', len(prep))
print('This is a sample of the test_corpus: ')
print(prep[0:10])
# -
# <a name='1'></a>
# # Part 1: Parts-of-speech tagging
#
# <a name='1.1'></a>
# ## Part 1.1 - Training
# You will start with the simplest possible parts-of-speech tagger and we will build up to the state of the art.
#
# In this section, you will find the words that are not ambiguous.
# - For example, the word `is` is a verb and it is not ambiguous.
# - In the `WSJ` corpus, $86$% of the token are unambiguous (meaning they have only one tag)
# - About $14\%$ are ambiguous (meaning that they have more than one tag)
#
# <img src = "pos.png" style="width:400px;height:250px;"/>
#
# Before you start predicting the tags of each word, you will need to compute a few dictionaries that will help you to generate the tables.
# #### Transition counts
# - The first dictionary is the `transition_counts` dictionary which computes the number of times each tag happened next to another tag.
#
# This dictionary will be used to compute:
# $$P(t_i |t_{i-1}) \tag{1}$$
#
# This is the probability of a tag at position $i$ given the tag at position $i-1$.
#
# In order for you to compute equation 1, you will create a `transition_counts` dictionary where
# - The keys are `(prev_tag, tag)`
# - The values are the number of times those two tags appeared in that order.
# #### Emission counts
#
# The second dictionary you will compute is the `emission_counts` dictionary. This dictionary will be used to compute:
#
# $$P(w_i|t_i)\tag{2}$$
#
# In other words, you will use it to compute the probability of a word given its tag.
#
# In order for you to compute equation 2, you will create an `emission_counts` dictionary where
# - The keys are `(tag, word)`
# - The values are the number of times that pair showed up in your training set.
# #### Tag counts
#
# The last dictionary you will compute is the `tag_counts` dictionary.
# - The key is the tag
# - The value is the number of times each tag appeared.
# <a name='ex-01'></a>
# ### Exercise 01
#
# **Instructions:** Write a program that takes in the `training_corpus` and returns the three dictionaries mentioned above `transition_counts`, `emission_counts`, and `tag_counts`.
# - `emission_counts`: maps (tag, word) to the number of times it happened.
# - `transition_counts`: maps (prev_tag, tag) to the number of times it has appeared.
# - `tag_counts`: maps (tag) to the number of times it has occured.
#
# Implementation note: This routine utilises *defaultdict*, which is a subclass of *dict*.
# - A standard Python dictionary throws a *KeyError* if you try to access an item with a key that is not currently in the dictionary.
# - In contrast, the *defaultdict* will create an item of the type of the argument, in this case an integer with the default value of 0.
# - See [defaultdict](https://docs.python.org/3.3/library/collections.html#defaultdict-objects).
# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: create_dictionaries
def create_dictionaries(training_corpus, vocab):
"""
Input:
training_corpus: a corpus where each line has a word followed by its tag.
vocab: a dictionary where keys are words in vocabulary and value is an index
Output:
emission_counts: a dictionary where the keys are (tag, word) and the values are the counts
transition_counts: a dictionary where the keys are (prev_tag, tag) and the values are the counts
tag_counts: a dictionary where the keys are the tags and the values are the counts
"""
# initialize the dictionaries using defaultdict
emission_counts = defaultdict(int)
transition_counts = defaultdict(int)
tag_counts = defaultdict(int)
# Initialize "prev_tag" (previous tag) with the start state, denoted by '--s--'
prev_tag = '--s--'
# use 'i' to track the line number in the corpus
i = 0
# Each item in the training corpus contains a word and its POS tag
# Go through each word and its tag in the training corpus
for word_tag in training_corpus:
# Increment the word_tag count
i += 1
# Every 50,000 words, print the word count
if i % 50000 == 0:
print(f"word count = {i}")
### START CODE HERE (Replace instances of 'None' with your code) ###
# get the word and tag using the get_word_tag helper function (imported from utils_pos.py)
word, tag = None
# Increment the transition count for the previous word and tag
transition_counts[(prev_tag, tag)] += None
# Increment the emission count for the tag and word
emission_counts[(tag, word)] += None
# Increment the tag count
tag_counts[tag] += None
# Set the previous tag to this tag (for the next iteration of the loop)
prev_tag = None
### END CODE HERE ###
return emission_counts, transition_counts, tag_counts
emission_counts, transition_counts, tag_counts = create_dictionaries(training_corpus, vocab)
# get all the POS states
states = sorted(tag_counts.keys())
print(f"Number of POS tags (number of 'states'): {len(states)}")
print("View these POS tags (states)")
print(states)
# ##### Expected Output
#
# ```CPP
# Number of POS tags (number of 'states'46
# View these states
# ['#', '$', "''", '(', ')', ',', '--s--', '.', ':', 'CC', 'CD', 'DT', 'EX', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNP', 'NNPS', 'NNS', 'PDT', 'POS', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'SYM', 'TO', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP', 'WP$', 'WRB', '``']
# ```
# The 'states' are the Parts-of-speech designations found in the training data. They will also be referred to as 'tags' or POS in this assignment.
#
# - "NN" is noun, singular,
# - 'NNS' is noun, plural.
# - In addition, there are helpful tags like '--s--' which indicate a start of a sentence.
# - You can get a more complete description at [Penn Treebank II tag set](https://www.clips.uantwerpen.be/pages/mbsp-tags).
# +
print("transition examples: ")
for ex in list(transition_counts.items())[:3]:
print(ex)
print()
print("emission examples: ")
for ex in list(emission_counts.items())[200:203]:
print (ex)
print()
print("ambiguous word example: ")
for tup,cnt in emission_counts.items():
if tup[1] == 'back': print (tup, cnt)
# -
# ##### Expected Output
#
# ```CPP
# transition examples:
# (('--s--', 'IN'), 5050)
# (('IN', 'DT'), 32364)
# (('DT', 'NNP'), 9044)
#
# emission examples:
# (('DT', 'any'), 721)
# (('NN', 'decrease'), 7)
# (('NN', 'insider-trading'), 5)
#
# ambiguous word example:
# ('RB', 'back') 304
# ('VB', 'back') 20
# ('RP', 'back') 84
# ('JJ', 'back') 25
# ('NN', 'back') 29
# ('VBP', 'back') 4
# ```
# <a name='1.2'></a>
# ### Part 1.2 - Testing
#
# Now you will test the accuracy of your parts-of-speech tagger using your `emission_counts` dictionary.
# - Given your preprocessed test corpus `prep`, you will assign a parts-of-speech tag to every word in that corpus.
# - Using the original tagged test corpus `y`, you will then compute what percent of the tags you got correct.
# <a name='ex-02'></a>
# ### Exercise 02
#
# **Instructions:** Implement `predict_pos` that computes the accuracy of your model.
#
# - This is a warm up exercise.
# - To assign a part of speech to a word, assign the most frequent POS for that word in the training set.
# - Then evaluate how well this approach works. Each time you predict based on the most frequent POS for the given word, check whether the actual POS of that word is the same. If so, the prediction was correct!
# - Calculate the accuracy as the number of correct predictions divided by the total number of words for which you predicted the POS tag.
# +
# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: predict_pos
def predict_pos(prep, y, emission_counts, vocab, states):
'''
Input:
prep: a preprocessed version of 'y'. A list with the 'word' component of the tuples.
y: a corpus composed of a list of tuples where each tuple consists of (word, POS)
emission_counts: a dictionary where the keys are (tag,word) tuples and the value is the count
vocab: a dictionary where keys are words in vocabulary and value is an index
states: a sorted list of all possible tags for this assignment
Output:
accuracy: Number of times you classified a word correctly
'''
# Initialize the number of correct predictions to zero
num_correct = 0
# Get the (tag, word) tuples, stored as a set
all_words = set(emission_counts.keys())
# Get the number of (word, POS) tuples in the corpus 'y'
total = len(y)
for word, y_tup in zip(prep, y):
# Split the (word, POS) string into a list of two items
y_tup_l = y_tup.split()
# Verify that y_tup contain both word and POS
if len(y_tup_l) == 2:
# Set the true POS label for this word
true_label = y_tup_l[1]
else:
# If the y_tup didn't contain word and POS, go to next word
continue
count_final = 0
pos_final = ''
# If the word is in the vocabulary...
if word in vocab:
for pos in states:
### START CODE HERE (Replace instances of 'None' with your code) ###
# define the key as the tuple containing the POS and word
key = None
# check if the (pos, word) key exists in the emission_counts dictionary
if key in None: # complete this line
# get the emission count of the (pos,word) tuple
count = None
# keep track of the POS with the largest count
if None: # complete this line
# update the final count (largest count)
count_final = None
# update the final POS
pos_final = None
# If the final POS (with the largest count) matches the true POS:
if None: # complete this line
# Update the number of correct predictions
num_correct += None
### END CODE HERE ###
accuracy = num_correct / total
return accuracy
# -
accuracy_predict_pos = predict_pos(prep, y, emission_counts, vocab, states)
print(f"Accuracy of prediction using predict_pos is {accuracy_predict_pos:.4f}")
# ##### Expected Output
# ```CPP
# Accuracy of prediction using predict_pos is 0.8889
# ```
#
# 88.9% is really good for this warm up exercise. With hidden markov models, you should be able to get **95% accuracy.**
# <a name='2'></a>
# # Part 2: Hidden Markov Models for POS
#
# Now you will build something more context specific. Concretely, you will be implementing a Hidden Markov Model (HMM) with a Viterbi decoder
# - The HMM is one of the most commonly used algorithms in Natural Language Processing, and is a foundation to many deep learning techniques you will see in this specialization.
# - In addition to parts-of-speech tagging, HMM is used in speech recognition, speech synthesis, etc.
# - By completing this part of the assignment you will get a 95% accuracy on the same dataset you used in Part 1.
#
# The Markov Model contains a number of states and the probability of transition between those states.
# - In this case, the states are the parts-of-speech.
# - A Markov Model utilizes a transition matrix, `A`.
# - A Hidden Markov Model adds an observation or emission matrix `B` which describes the probability of a visible observation when we are in a particular state.
# - In this case, the emissions are the words in the corpus
# - The state, which is hidden, is the POS tag of that word.
# <a name='2.1'></a>
# ## Part 2.1 Generating Matrices
#
# ### Creating the 'A' transition probabilities matrix
# Now that you have your `emission_counts`, `transition_counts`, and `tag_counts`, you will start implementing the Hidden Markov Model.
#
# This will allow you to quickly construct the
# - `A` transition probabilities matrix.
# - and the `B` emission probabilities matrix.
#
# You will also use some smoothing when computing these matrices.
#
# Here is an example of what the `A` transition matrix would look like (it is simplified to 5 tags for viewing. It is 46x46 in this assignment.):
#
#
# |**A** |...| RBS | RP | SYM | TO | UH|...
# | --- ||---:-------------| ------------ | ------------ | -------- | ---------- |----
# |**RBS** |...|2.217069e-06 |2.217069e-06 |2.217069e-06 |0.008870 |2.217069e-06|...
# |**RP** |...|3.756509e-07 |7.516775e-04 |3.756509e-07 |0.051089 |3.756509e-07|...
# |**SYM** |...|1.722772e-05 |1.722772e-05 |1.722772e-05 |0.000017 |1.722772e-05|...
# |**TO** |...|4.477336e-05 |4.472863e-08 |4.472863e-08 |0.000090 |4.477336e-05|...
# |**UH** |...|1.030439e-05 |1.030439e-05 |1.030439e-05 |0.061837 |3.092348e-02|...
# | ... |...| ... | ... | ... | ... | ... | ...
#
# Note that the matrix above was computed with smoothing.
#
# Each cell gives you the probability to go from one part of speech to another.
# - In other words, there is a 4.47e-8 chance of going from parts-of-speech `TO` to `RP`.
# - The sum of each row has to equal 1, because we assume that the next POS tag must be one of the available columns in the table.
#
# The smoothing was done as follows:
#
# $$ P(t_i | t_{i-1}) = \frac{C(t_{i-1}, t_{i}) + \alpha }{C(t_{i-1}) +\alpha * N}\tag{3}$$
#
# - $N$ is the total number of tags
# - $C(t_{i-1}, t_{i})$ is the count of the tuple (previous POS, current POS) in `transition_counts` dictionary.
# - $C(t_{i-1})$ is the count of the previous POS in the `tag_counts` dictionary.
# - $\alpha$ is a smoothing parameter.
# <a name='ex-03'></a>
# ### Exercise 03
#
# **Instructions:** Implement the `create_transition_matrix` below for all tags. Your task is to output a matrix that computes equation 3 for each cell in matrix `A`.
# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: create_transition_matrix
def create_transition_matrix(alpha, tag_counts, transition_counts):
'''
Input:
alpha: number used for smoothing
tag_counts: a dictionary mapping each tag to its respective count
transition_counts: transition count for the previous word and tag
Output:
A: matrix of dimension (num_tags,num_tags)
'''
# Get a sorted list of unique POS tags
all_tags = sorted(tag_counts.keys())
# Count the number of unique POS tags
num_tags = len(all_tags)
# Initialize the transition matrix 'A'
A = np.zeros((num_tags,num_tags))
# Get the unique transition tuples (previous POS, current POS)
trans_keys = set(transition_counts.keys())
### START CODE HERE (Return instances of 'None' with your code) ###
# Go through each row of the transition matrix A
for i in range(num_tags):
# Go through each column of the transition matrix A
for j in range(num_tags):
# Initialize the count of the (prev POS, current POS) to zero
count = 0
# Define the tuple (prev POS, current POS)
# Get the tag at position i and tag at position j (from the all_tags list)
key = None
# Check if the (prev POS, current POS) tuple
# exists in the transition counts dictionaory
if None: #complete this line
# Get count from the transition_counts dictionary
# for the (prev POS, current POS) tuple
count = None
# Get the count of the previous tag (index position i) from tag_counts
count_prev_tag = None
# Apply smoothing using count of the tuple, alpha,
# count of previous tag, alpha, and number of total tags
A[i,j] = None
### END CODE HERE ###
return A
# +
alpha = 0.001
A = create_transition_matrix(alpha, tag_counts, transition_counts)
# Testing your function
print(f"A at row 0, col 0: {A[0,0]:.9f}")
print(f"A at row 3, col 1: {A[3,1]:.4f}")
print("View a subset of transition matrix A")
A_sub = pd.DataFrame(A[30:35,30:35], index=states[30:35], columns = states[30:35] )
print(A_sub)
# -
# ##### Expected Output
# ```CPP
# A at row 0, col 0: 0.000007040
# A at row 3, col 1: 0.1691
# View a subset of transition matrix A
# RBS RP SYM TO UH
# RBS 2.217069e-06 2.217069e-06 2.217069e-06 0.008870 2.217069e-06
# RP 3.756509e-07 7.516775e-04 3.756509e-07 0.051089 3.756509e-07
# SYM 1.722772e-05 1.722772e-05 1.722772e-05 0.000017 1.722772e-05
# TO 4.477336e-05 4.472863e-08 4.472863e-08 0.000090 4.477336e-05
# UH 1.030439e-05 1.030439e-05 1.030439e-05 0.061837 3.092348e-02
# ```
# ### Create the 'B' emission probabilities matrix
#
# Now you will create the `B` transition matrix which computes the emission probability.
#
# You will use smoothing as defined below:
#
# $$P(w_i | t_i) = \frac{C(t_i, word_i)+ \alpha}{C(t_{i}) +\alpha * N}\tag{4}$$
#
# - $C(t_i, word_i)$ is the number of times $word_i$ was associated with $tag_i$ in the training data (stored in `emission_counts` dictionary).
# - $C(t_i)$ is the number of times $tag_i$ was in the training data (stored in `tag_counts` dictionary).
# - $N$ is the number of words in the vocabulary
# - $\alpha$ is a smoothing parameter.
#
# The matrix `B` is of dimension (num_tags, N), where num_tags is the number of possible parts-of-speech tags.
#
# Here is an example of the matrix, only a subset of tags and words are shown:
# <p style='text-align: center;'> <b>B Emissions Probability Matrix (subset)</b> </p>
#
# |**B**| ...| 725 | adroitly | engineers | promoted | synergy| ...|
# |----|----|--------------|--------------|--------------|--------------|-------------|----|
# |**CD** | ...| **8.201296e-05** | 2.732854e-08 | 2.732854e-08 | 2.732854e-08 | 2.732854e-08| ...|
# |**NN** | ...| 7.521128e-09 | 7.521128e-09 | 7.521128e-09 | 7.521128e-09 | **2.257091e-05**| ...|
# |**NNS** | ...| 1.670013e-08 | 1.670013e-08 |**4.676203e-04** | 1.670013e-08 | 1.670013e-08| ...|
# |**VB** | ...| 3.779036e-08 | 3.779036e-08 | 3.779036e-08 | 3.779036e-08 | 3.779036e-08| ...|
# |**RB** | ...| 3.226454e-08 | **6.456135e-05** | 3.226454e-08 | 3.226454e-08 | 3.226454e-08| ...|
# |**RP** | ...| 3.723317e-07 | 3.723317e-07 | 3.723317e-07 | **3.723317e-07** | 3.723317e-07| ...|
# | ... | ...| ... | ... | ... | ... | ... | ...|
#
#
# <a name='ex-04'></a>
# ### Exercise 04
# **Instructions:** Implement the `create_emission_matrix` below that computes the `B` emission probabilities matrix. Your function takes in $\alpha$, the smoothing parameter, `tag_counts`, which is a dictionary mapping each tag to its respective count, the `emission_counts` dictionary where the keys are (tag, word) and the values are the counts. Your task is to output a matrix that computes equation 4 for each cell in matrix `B`.
# +
# UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: create_emission_matrix
def create_emission_matrix(alpha, tag_counts, emission_counts, vocab):
'''
Input:
alpha: tuning parameter used in smoothing
tag_counts: a dictionary mapping each tag to its respective count
emission_counts: a dictionary where the keys are (tag, word) and the values are the counts
vocab: a dictionary where keys are words in vocabulary and value is an index
Output:
B: a matrix of dimension (num_tags, len(vocab))
'''
# get the number of POS tag
num_tags = len(tag_counts)
# Get a list of all POS tags
all_tags = sorted(tag_counts.keys())
# Get the total number of unique words in the vocabulary
num_words = len(vocab)
# Initialize the emission matrix B with places for
# tags in the rows and words in the columns
B = np.zeros((num_tags, num_words))
# Get a set of all (POS, word) tuples
# from the keys of the emission_counts dictionary
emis_keys = set(list(emission_counts.keys()))
### START CODE HERE (Replace instances of 'None' with your code) ###
# Go through each row (POS tags)
for i in None: # complete this line
# Go through each column (words)
for j in None: # complete this line
# Initialize the emission count for the (POS tag, word) to zero
count = 0
# Define the (POS tag, word) tuple for this row and column
key = None
# check if the (POS tag, word) tuple exists as a key in emission counts
if None: # complete this line
# Get the count of (POS tag, word) from the emission_counts d
count = None
# Get the count of the POS tag
count_tag = None
# Apply smoothing and store the smoothed value
# into the emission matrix B for this row and column
B[i,j] = None
### END CODE HERE ###
return B
# +
# creating your emission probability matrix. this takes a few minutes to run.
B = create_emission_matrix(alpha, tag_counts, emission_counts, list(vocab))
print(f"View Matrix position at row 0, column 0: {B[0,0]:.9f}")
print(f"View Matrix position at row 3, column 1: {B[3,1]:.9f}")
# Try viewing emissions for a few words in a sample dataframe
cidx = ['725','adroitly','engineers', 'promoted', 'synergy']
# Get the integer ID for each word
cols = [vocab[a] for a in cidx]
# Choose POS tags to show in a sample dataframe
rvals =['CD','NN','NNS', 'VB','RB','RP']
# For each POS tag, get the row number from the 'states' list
rows = [states.index(a) for a in rvals]
# Get the emissions for the sample of words, and the sample of POS tags
B_sub = pd.DataFrame(B[np.ix_(rows,cols)], index=rvals, columns = cidx )
print(B_sub)
# -
# ##### Expected Output
#
# ```CPP
# View Matrix position at row 0, column 0: 0.000006032
# View Matrix position at row 3, column 1: 0.000000720
# 725 adroitly engineers promoted synergy
# CD 8.201296e-05 2.732854e-08 2.732854e-08 2.732854e-08 2.732854e-08
# NN 7.521128e-09 7.521128e-09 7.521128e-09 7.521128e-09 2.257091e-05
# NNS 1.670013e-08 1.670013e-08 4.676203e-04 1.670013e-08 1.670013e-08
# VB 3.779036e-08 3.779036e-08 3.779036e-08 3.779036e-08 3.779036e-08
# RB 3.226454e-08 6.456135e-05 3.226454e-08 3.226454e-08 3.226454e-08
# RP 3.723317e-07 3.723317e-07 3.723317e-07 3.723317e-07 3.723317e-07
# ```
# <a name='3'></a>
# # Part 3: Viterbi Algorithm and Dynamic Programming
#
# In this part of the assignment you will implement the Viterbi algorithm which makes use of dynamic programming. Specifically, you will use your two matrices, `A` and `B` to compute the Viterbi algorithm. We have decomposed this process into three main steps for you.
#
# * **Initialization** - In this part you initialize the `best_paths` and `best_probabilities` matrices that you will be populating in `feed_forward`.
# * **Feed forward** - At each step, you calculate the probability of each path happening and the best paths up to that point.
# * **Feed backward**: This allows you to find the best path with the highest probabilities.
#
# <a name='3.1'></a>
# ## Part 3.1: Initialization
#
# You will start by initializing two matrices of the same dimension.
#
# - best_probs: Each cell contains the probability of going from one POS tag to a word in the corpus.
#
# - best_paths: A matrix that helps you trace through the best possible path in the corpus.
# <a name='ex-05'></a>
# ### Exercise 05
# **Instructions**:
# Write a program below that initializes the `best_probs` and the `best_paths` matrix.
#
# Both matrices will be initialized to zero except for column zero of `best_probs`.
# - Column zero of `best_probs` is initialized with the assumption that the first word of the corpus was preceded by a start token ("--s--").
# - This allows you to reference the **A** matrix for the transition probability
#
# Here is how to initialize column 0 of `best_probs`:
# - The probability of the best path going from the start index to a given POS tag indexed by integer $i$ is denoted by $\textrm{best_probs}[s_{idx}, i]$.
# - This is estimated as the probability that the start tag transitions to the POS denoted by index $i$: $\mathbf{A}[s_{idx}, i]$ AND that the POS tag denoted by $i$ emits the first word of the given corpus, which is $\mathbf{B}[i, vocab[corpus[0]]]$.
# - Note that vocab[corpus[0]] refers to the first word of the corpus (the word at position 0 of the corpus).
# - **vocab** is a dictionary that returns the unique integer that refers to that particular word.
#
# Conceptually, it looks like this:
# $\textrm{best_probs}[s_{idx}, i] = \mathbf{A}[s_{idx}, i] \times \mathbf{B}[i, corpus[0] ]$
#
#
# In order to avoid multiplying and storing small values on the computer, we'll take the log of the product, which becomes the sum of two logs:
#
# $best\_probs[i,0] = log(A[s_{idx}, i]) + log(B[i, vocab[corpus[0]]$
#
# Also, to avoid taking the log of 0 (which is defined as negative infinity), the code itself will just set $best\_probs[i,0] = float('-inf')$ when $A[s_{idx}, i] == 0$
#
#
# So the implementation to initialize $best\_probs$ looks like this:
#
# $ if A[s_{idx}, i] <> 0 : best\_probs[i,0] = log(A[s_{idx}, i]) + log(B[i, vocab[corpus[0]]$
#
# $ if A[s_{idx}, i] == 0 : best\_probs[i,0] = float('-inf')$
#
# Please use [math.log](https://docs.python.org/3/library/math.html) to compute the natural logarithm.
# The example below shows the initialization assuming the corpus starts with the phrase "Loss tracks upward".
#
# <img src = "Initialize4.PNG"/>
# Represent infinity and negative infinity like this:
#
# ```CPP
# float('inf')
# float('-inf')
# ```
# UNQ_C5 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: initialize
def initialize(states, tag_counts, A, B, corpus, vocab):
'''
Input:
states: a list of all possible parts-of-speech
tag_counts: a dictionary mapping each tag to its respective count
A: Transition Matrix of dimension (num_tags, num_tags)
B: Emission Matrix of dimension (num_tags, len(vocab))
corpus: a sequence of words whose POS is to be identified in a list
vocab: a dictionary where keys are words in vocabulary and value is an index
Output:
best_probs: matrix of dimension (num_tags, len(corpus)) of floats
best_paths: matrix of dimension (num_tags, len(corpus)) of integers
'''
# Get the total number of unique POS tags
num_tags = len(tag_counts)
# Initialize best_probs matrix
# POS tags in the rows, number of words in the corpus as the columns
best_probs = np.zeros((num_tags, len(corpus)))
# Initialize best_paths matrix
# POS tags in the rows, number of words in the corpus as columns
best_paths = np.zeros((num_tags, len(corpus)), dtype=int)
# Define the start token
s_idx = states.index("--s--")
### START CODE HERE (Replace instances of 'None' with your code) ###
# Go through each of the POS tags
for i in None: # complete this line
# Handle the special case when the transition from start token to POS tag i is zero
if None: # complete this line
# Initialize best_probs at POS tag 'i', column 0, to negative infinity
best_probs[i,0] = None
# For all other cases when transition from start token to POS tag i is non-zero:
else:
# Initialize best_probs at POS tag 'i', column 0
# Check the formula in the instructions above
best_probs[i,0] = None
### END CODE HERE ###
return best_probs, best_paths
best_probs, best_paths = initialize(states, tag_counts, A, B, prep, vocab)
# Test the function
print(f"best_probs[0,0]: {best_probs[0,0]:.4f}")
print(f"best_paths[2,3]: {best_paths[2,3]:.4f}")
# ##### Expected Output
#
# ```CPP
# best_probs[0,0]: -22.6098
# best_paths[2,3]: 0.0000
# ```
#
# <a name='3.2'></a>
# ## Part 3.2 Viterbi Forward
#
# In this part of the assignment, you will implement the `viterbi_forward` segment. In other words, you will populate your `best_probs` and `best_paths` matrices.
# - Walk forward through the corpus.
# - For each word, compute a probability for each possible tag.
# - Unlike the previous algorithm `predict_pos` (the 'warm-up' exercise), this will include the path up to that (word,tag) combination.
#
# Here is an example with a three-word corpus "Loss tracks upward":
# - Note, in this example, only a subset of states (POS tags) are shown in the diagram below, for easier reading.
# - In the diagram below, the first word "Loss" is already initialized.
# - The algorithm will compute a probability for each of the potential tags in the second and future words.
#
# Compute the probability that the tag of the second work ('tracks') is a verb, 3rd person singular present (VBZ).
# - In the `best_probs` matrix, go to the column of the second word ('tracks'), and row 40 (VBZ), this cell is highlighted in light orange in the diagram below.
# - Examine each of the paths from the tags of the first word ('Loss') and choose the most likely path.
# - An example of the calculation for **one** of those paths is the path from ('Loss', NN) to ('tracks', VBZ).
# - The log of the probability of the path up to and including the first word 'Loss' having POS tag NN is $-14.32$. The `best_probs` matrix contains this value -14.32 in the column for 'Loss' and row for 'NN'.
# - Find the probability that NN transitions to VBZ. To find this probability, go to the `A` transition matrix, and go to the row for 'NN' and the column for 'VBZ'. The value is $4.37e-02$, which is circled in the diagram, so add $-14.32 + log(4.37e-02)$.
# - Find the log of the probability that the tag VBS would 'emit' the word 'tracks'. To find this, look at the 'B' emission matrix in row 'VBZ' and the column for the word 'tracks'. The value $4.61e-04$ is circled in the diagram below. So add $-14.32 + log(4.37e-02) + log(4.61e-04)$.
# - The sum of $-14.32 + log(4.37e-02) + log(4.61e-04)$ is $-25.13$. Store $-25.13$ in the `best_probs` matrix at row 'VBZ' and column 'tracks' (as seen in the cell that is highlighted in light orange in the diagram).
# - All other paths in best_probs are calculated. Notice that $-25.13$ is greater than all of the other values in column 'tracks' of matrix `best_probs`, and so the most likely path to 'VBZ' is from 'NN'. 'NN' is in row 20 of the `best_probs` matrix, so $20$ is the most likely path.
# - Store the most likely path $20$ in the `best_paths` table. This is highlighted in light orange in the diagram below.
# The formula to compute the probability and path for the $i^{th}$ word in the $corpus$, the prior word $i-1$ in the corpus, current POS tag $j$, and previous POS tag $k$ is:
#
# $\mathrm{prob} = \mathbf{best\_prob}_{k, i-1} + \mathrm{log}(\mathbf{A}_{k, j}) + \mathrm{log}(\mathbf{B}_{j, vocab(corpus_{i})})$
#
# where $corpus_{i}$ is the word in the corpus at index $i$, and $vocab$ is the dictionary that gets the unique integer that represents a given word.
#
# $\mathrm{path} = k$
#
# where $k$ is the integer representing the previous POS tag.
#
# <a name='ex-06'></a>
#
# ### Exercise 06
#
# Instructions: Implement the `viterbi_forward` algorithm and store the best_path and best_prob for every possible tag for each word in the matrices `best_probs` and `best_tags` using the pseudo code below.
#
# `for each word in the corpus
#
# for each POS tag type that this word may be
#
# for POS tag type that the previous word could be
#
# compute the probability that the previous word had a given POS tag, that the current word has a given POS tag, and that the POS tag would emit this current word.
#
# retain the highest probability computed for the current word
#
# set best_probs to this highest probability
#
# set best_paths to the index 'k', representing the POS tag of the previous word which produced the highest probability `
#
# Please use [math.log](https://docs.python.org/3/library/math.html) to compute the natural logarithm.
# <img src = "Forward4.PNG"/>
# <details>
# <summary>
# <font size="3" color="darkgreen"><b>Hints</b></font>
# </summary>
# <p>
# <ul>
# <li>Remember that when accessing emission matrix B, the column index is the unique integer ID associated with the word. It can be accessed by using the 'vocab' dictionary, where the key is the word, and the value is the unique integer ID for that word.</li>
# </ul>
# </p>
#
# UNQ_C6 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: viterbi_forward
def viterbi_forward(A, B, test_corpus, best_probs, best_paths, vocab):
'''
Input:
A, B: The transiton and emission matrices respectively
test_corpus: a list containing a preprocessed corpus
best_probs: an initilized matrix of dimension (num_tags, len(corpus))
best_paths: an initilized matrix of dimension (num_tags, len(corpus))
vocab: a dictionary where keys are words in vocabulary and value is an index
Output:
best_probs: a completed matrix of dimension (num_tags, len(corpus))
best_paths: a completed matrix of dimension (num_tags, len(corpus))
'''
# Get the number of unique POS tags (which is the num of rows in best_probs)
num_tags = best_probs.shape[0]
# Go through every word in the corpus starting from word 1
# Recall that word 0 was initialized in `initialize()`
for i in range(1, len(test_corpus)):
# Print number of words processed, every 5000 words
if i % 5000 == 0:
print("Words processed: {:>8}".format(i))
### START CODE HERE (Replace instances of 'None' with your code EXCEPT the first 'best_path_i = None') ###
# For each unique POS tag that the current word can be
for j in None: # complete this line
# Initialize best_prob for word i to negative infinity
best_prob_i = None
# Initialize best_path for current word i to None
best_path_i = None
# For each POS tag that the previous word can be:
for k in None: # complete this line
# Calculate the probability =
# best probs of POS tag k, previous word i-1 +
# log(prob of transition from POS k to POS j) +
# log(prob that emission of POS j is word i)
prob = None
# check if this path's probability is greater than
# the best probability up to and before this point
if None: # complete this line
# Keep track of the best probability
best_prob_i = None
# keep track of the POS tag of the previous word
# that is part of the best path.
# Save the index (integer) associated with
# that previous word's POS tag
best_path_i = None
# Save the best probability for the
# given current word's POS tag
# and the position of the current word inside the corpus
best_probs[j,i] = None
# Save the unique integer ID of the previous POS tag
# into best_paths matrix, for the POS tag of the current word
# and the position of the current word inside the corpus.
best_paths[j,i] = None
### END CODE HERE ###
return best_probs, best_paths
# Run the `viterbi_forward` function to fill in the `best_probs` and `best_paths` matrices.
#
# **Note** that this will take a few minutes to run. There are about 30,000 words to process.
# this will take a few minutes to run => processes ~ 30,000 words
best_probs, best_paths = viterbi_forward(A, B, prep, best_probs, best_paths, vocab)
# Test this function
print(f"best_probs[0,1]: {best_probs[0,1]:.4f}")
print(f"best_probs[0,4]: {best_probs[0,4]:.4f}")
# ##### Expected Output
#
# ```CPP
# best_probs[0,1]: -24.7822
# best_probs[0,4]: -49.5601
# ```
# <a name='3.3'></a>
# ## Part 3.3 Viterbi backward
#
# Now you will implement the Viterbi backward algorithm.
# - The Viterbi backward algorithm gets the predictions of the POS tags for each word in the corpus using the `best_paths` and the `best_probs` matrices.
#
# The example below shows how to walk backwards through the best_paths matrix to get the POS tags of each word in the corpus. Recall that this example corpus has three words: "Loss tracks upward".
#
# POS tag for 'upward' is `RB`
# - Select the the most likely POS tag for the last word in the corpus, 'upward' in the `best_prob` table.
# - Look for the row in the column for 'upward' that has the largest probability.
# - Notice that in row 28 of `best_probs`, the estimated probability is -34.99, which is larger than the other values in the column. So the most likely POS tag for 'upward' is `RB` an adverb, at row 28 of `best_prob`.
# - The variable `z` is an array that stores the unique integer ID of the predicted POS tags for each word in the corpus. In array z, at position 2, store the value 28 to indicate that the word 'upward' (at index 2 in the corpus), most likely has the POS tag associated with unique ID 28 (which is `RB`).
# - The variable `pred` contains the POS tags in string form. So `pred` at index 2 stores the string `RB`.
#
#
# POS tag for 'tracks' is `VBZ`
# - The next step is to go backward one word in the corpus ('tracks'). Since the most likely POS tag for 'upward' is `RB`, which is uniquely identified by integer ID 28, go to the `best_paths` matrix in column 2, row 28. The value stored in `best_paths`, column 2, row 28 indicates the unique ID of the POS tag of the previous word. In this case, the value stored here is 40, which is the unique ID for POS tag `VBZ` (verb, 3rd person singular present).
# - So the previous word at index 1 of the corpus ('tracks'), most likely has the POS tag with unique ID 40, which is `VBZ`.
# - In array `z`, store the value 40 at position 1, and for array `pred`, store the string `VBZ` to indicate that the word 'tracks' most likely has POS tag `VBZ`.
#
# POS tag for 'Loss' is `NN`
# - In `best_paths` at column 1, the unique ID stored at row 40 is 20. 20 is the unique ID for POS tag `NN`.
# - In array `z` at position 0, store 20. In array `pred` at position 0, store `NN`.
# <img src = "Backwards5.PNG"/>
# <a name='ex-07'></a>
# ### Exercise 07
# Implement the `viterbi_backward` algorithm, which returns a list of predicted POS tags for each word in the corpus.
#
# - Note that the numbering of the index positions starts at 0 and not 1.
# - `m` is the number of words in the corpus.
# - So the indexing into the corpus goes from `0` to `m - 1`.
# - Also, the columns in `best_probs` and `best_paths` are indexed from `0` to `m - 1`
#
#
# **In Step 1:**
# Loop through all the rows (POS tags) in the last entry of `best_probs` and find the row (POS tag) with the maximum value.
# Convert the unique integer ID to a tag (a string representation) using the dictionary `states`.
#
# Referring to the three-word corpus described above:
# - `z[2] = 28`: For the word 'upward' at position 2 in the corpus, the POS tag ID is 28. Store 28 in `z` at position 2.
# - states(28) is 'RB': The POS tag ID 28 refers to the POS tag 'RB'.
# - `pred[2] = 'RB'`: In array `pred`, store the POS tag for the word 'upward'.
#
# **In Step 2:**
# - Starting at the last column of best_paths, use `best_probs` to find the most likely POS tag for the last word in the corpus.
# - Then use `best_paths` to find the most likely POS tag for the previous word.
# - Update the POS tag for each word in `z` and in `preds`.
#
# Referring to the three-word example from above, read best_paths at column 2 and fill in z at position 1.
# `z[1] = best_paths[z[2],2]`
#
# The small test following the routine prints the last few words of the corpus and their states to aid in debug.
# UNQ_C7 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: viterbi_backward
def viterbi_backward(best_probs, best_paths, corpus, states):
'''
This function returns the best path.
'''
# Get the number of words in the corpus
# which is also the number of columns in best_probs, best_paths
m = best_paths.shape[1]
# Initialize array z, same length as the corpus
z = [None] * m
# Get the number of unique POS tags
num_tags = best_probs.shape[0]
# Initialize the best probability for the last word
best_prob_for_last_word = float('-inf')
# Initialize pred array, same length as corpus
pred = [None] * m
### START CODE HERE (Replace instances of 'None' with your code) ###
## Step 1 ##
# Go through each POS tag for the last word (last column of best_probs)
# in order to find the row (POS tag integer ID)
# with highest probability for the last word
for k in None: # complete this line
# If the probability of POS tag at row k
# is better than the previosly best probability for the last word:
if None: # complete this line
# Store the new best probability for the lsat word
best_prob_for_last_word = None
# Store the unique integer ID of the POS tag
# which is also the row number in best_probs
z[m - 1] = None
# Convert the last word's predicted POS tag
# from its unique integer ID into the string representation
# using the 'states' dictionary
# store this in the 'pred' array for the last word
pred[m - 1] = None
## Step 2 ##
# Find the best POS tags by walking backward through the best_paths
# From the last word in the corpus to the 0th word in the corpus
for i in reversed(range(m-1)): # complete this line
# Retrieve the unique integer ID of
# the POS tag for the word at position 'i' in the corpus
pos_tag_for_word_i = z[i]
# In best_paths, go to the row representing the POS tag of word i
# and the column representing the word's position in the corpus
# to retrieve the predicted POS for the word at position i-1 in the corpus
z[i - 1] = best_paths[pos_tag_for_word_i,i]
# Get the previous word's POS tag in string form
# Use the 'states' dictionary,
# where the key is the unique integer ID of the POS tag,
# and the value is the string representation of that POS tag
pred[i - 1] = states[z[i-1]]
### END CODE HERE ###
return pred
# Run and test your function
pred = viterbi_backward(best_probs, best_paths, prep, states)
m=len(pred)
print('The prediction for pred[-7:m-1] is: \n', prep[-7:m-1], "\n", pred[-7:m-1], "\n")
print('The prediction for pred[0:8] is: \n', pred[0:7], "\n", prep[0:7])
# **Expected Output:**
#
# ```CPP
# The prediction for prep[-7:m-1] is:
# ['see', 'them', 'here', 'with', 'us', '.']
# ['VB', 'PRP', 'RB', 'IN', 'PRP', '.']
# The prediction for pred[0:8] is:
# ['DT', 'NN', 'POS', 'NN', 'MD', 'VB', 'VBN']
# ['The', 'economy', "'s", 'temperature', 'will', 'be', 'taken']
# ```
#
# Now you just have to compare the predicted labels to the true labels to evaluate your model on the accuracy metric!
# <a name='4'></a>
# # Part 4: Predicting on a data set
#
# Compute the accuracy of your prediction by comparing it with the true `y` labels.
# - `pred` is a list of predicted POS tags corresponding to the words of the `test_corpus`.
print('The third word is:', prep[3])
print('Your prediction is:', pred[3])
print('Your corresponding label y is: ', y[3])
# <a name='ex-08'></a>
# ### Exercise 08
#
# Implement a function to compute the accuracy of the viterbi algorithm's POS tag predictions.
# - To split y into the word and its tag you can use `y.split()`.
# UNQ_C8 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: compute_accuracy
def compute_accuracy(pred, y):
'''
Input:
pred: a list of the predicted parts-of-speech
y: a list of lines where each word is separated by a '\t' (i.e. word \t tag)
Output:
'''
num_correct = 0
total = 0
# Zip together the prediction and the labels
for prediction, y in zip(pred, y):
### START CODE HERE (Replace instances of 'None' with your code) ###
# Split the label into the word and the POS tag
word_tag_tuple = None
# Check that there is actually a word and a tag
# no more and no less than 2 items
if None: # complete this line
continue
# store the word and tag separately
word, tag = None
# Check if the POS tag label matches the prediction
if None: # complete this line
# count the number of times that the prediction
# and label match
num_correct += None
# keep track of the total number of examples (that have valid labels)
total += None
### END CODE HERE ###
return num_correct/total
print(f"Accuracy of the Viterbi algorithm is {compute_accuracy(pred, y):.4f}")
# ##### Expected Output
#
# ```CPP
# Accuracy of the Viterbi algorithm is 0.9531
# ```
#
# Congratulations you were able to classify the parts-of-speech with 95% accuracy.
# ### Key Points and overview
#
# In this assignment you learned about parts-of-speech tagging.
# - In this assignment, you predicted POS tags by walking forward through a corpus and knowing the previous word.
# - There are other implementations that use bidirectional POS tagging.
# - Bidirectional POS tagging requires knowing the previous word and the next word in the corpus when predicting the current word's POS tag.
# - Bidirectional POS tagging would tell you more about the POS instead of just knowing the previous word.
# - Since you have learned to implement the unidirectional approach, you have the foundation to implement other POS taggers used in industry.
# ### References
#
# - ["Speech and Language Processing", <NAME> and <NAME>](https://web.stanford.edu/~jurafsky/slp3/)
# - We would like to thank <NAME> for her help and inspiration
| week 2/.ipynb_checkpoints/utf-8''C2_W2_Assignment-Copy1-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
# ---
# # Project 1: Driving Licenses, Traffic Accidents and Casualties Analysis
# ## Problem Statment
#
# Craft your problem statement here using the prompt from the README and other sources you find during your investigation.
#
# ## Executive Summary
# Write an executive summary that summarizes the problem and your key findings.
#
# ### Contents:
# - [Datasets Description](#Datasets-Description)
# - [Data Import & Cleaning](#Data-Import-and-Cleaning)
# - [Exploratory Data Analysis](#Exploratory-Data-Analysis)
# - [Data Visualization](#Visualize-the-data)
# - [Descriptive and Inferential Statistics](#Descriptive-and-Inferential-Statistics)
# - [Outside Research](#Outside-Research)
# - [Conclusions and Recommendations](#Conclusions-and-Recommendations)
# **If you combine your problem statement, executive summary, data dictionary, and conclusions/recommendations, you have an amazing README.md file that quickly aligns your audience to the contents of your project.** Don't forget to cite your data sources!
# *All libraries used should be added here, including any Jupyter magic commands*
# +
# library imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
# %matplotlib inline
#Setting display format to retina in matplotlib for better quality images.
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('retina')
# +
# df.head() # show first 5 rows
# df.tail() # last 5 rows
# df.columns # list all column names
# df.shape # get number of rows and columns
# df.info() # additional info about dataframe
# df.describe() # statistical description, only for numeric values
# df['col_name'].value_counts(dropna=False) # count unique values in a column
# -
# ## Datasets Description
#
# [Driving Licenses](https://datasource.kapsarc.org/explore/dataset/saudi-arabia-driving-licenses-issued-in-the-kingdom-2004-2008/information/?disjunctive.administritive_area&sort=time_period&location=5,24.37495,45.08024&basemap=jawg.streets)
# This dataset contains Saudi Arabia Driving Licenses Issued By Administrative Area for 1993 - 2016. Data from General Authority for Statistics . Follow datasource.kapsarc.org for timely data to advance energy economics research.
#
# [Traffic Accidents and Casualties](https://datasource.kapsarc.org/explore/dataset/saudi-arabia-traffic-accidents-and-casualties-injured-dead-2008/export/?disjunctive.region&disjunctive.indicator&sort=time_period)
# This dataset contains Saudi Arabia Traffic Accidents and Casualties by Region for 2016. Data from General Authority for Statistics. Follow datasource.kapsarc.org for timely data to advance energy economics research.
#
# ## Data Import and Cleaning
# #### 1. Read In Driving Licenses & Traffic Accidents Data
# Read in the `saudi-arabia-traffic-accidents-2008.csv` and `saudi-arabia-driving-licenses-2004-2008.csv` files and assign them to appropriately named pandas dataframes.
# +
#Code
accidents_df = pd.read_csv('../data/saudi-arabia-traffic-accidents-2008.csv',sep=';')
licenses_df = pd.read_csv('../data/saudi-arabia-driving-licenses-2004-2008.csv',sep = ';')
# -
# delete
print(accidents_df.shape)
#
print(licenses_df.shape)
# #### 2. Display data
#
# Print the first 10 rows of each dataframe to your jupyter notebook
# +
#Code
accidents_df.head(10)
# -
licenses_df.head(10)
# #### 3. Briefly describe the data
#
# Take your time looking through the data and briefly describe the data in the markdown cell below. Note things about what the columns might mean, and the general information that is conveyed in the dataframe.
# Answer:
#
# 1. Traffic accidents dataframe:
#
# Dataframe exists in .csv format. The dimensions of the dataframe are (84 rows, 7 columns).
# Each row represents traffic accident features as follows:
#
# unnamed 0:seems to serve as index for df
# unnamed 0.1: has same values as unnamed 0
# year: describes the year of traffic accident
# region: describes area of traffic accident
# indicator: describes result of traffic accident as injured or dead
# value: corresponds to number of traffic accidents
# geo_point_2d: describes geographical location of traffic accidents
#
# 2. Driving licenses dataframe:
#
# Dataframe exists in .csv format. The dimensions of the dataframe are (350 rows, 5 columns).
# Each row represents driving license features as follows:
#
# nnamed 0:seems to serve as index for df
# year:describes the year of issued driving licenses
# administritive area: describes issuing area
# driving licenses: number of issued licenses
# geo_point_2d:describes geographical location of issuing area
#
#
# #### 4a. How complete is the data?
#
# Investigate missing values etc.
# +
print(accidents_df.isnull().sum()) # there are 6 missing values in accidents_df['geo_point_2d']
print('-----------------')
print(licenses_df.isnull().sum() ) # there are 25 missing values in accidents_df['geo_point_2d']
#
print('-----------------')
print(accidents_df.shape)
print(licenses_df.shape)
# +
# dropping missing values from both dataframes
accidents_df.dropna(how='any', inplace=True)
licenses_df.dropna(how='any', inplace=True)
# +
# missing values re-check
print(accidents_df.isnull().sum())
print('-----------------')
print(licenses_df.isnull().sum())
print('-----------------')
print(accidents_df.shape)
print(licenses_df.shape)
# -
# #### 4b. Are there any obvious issues with the observations?
#
# yes,
#
#
# - There are unnamed columns and dublicate columns serving as index numbers.
#
# - geo_point column has missing values in both dataframes and were subsequently dropped.
#
# - geo_point column in both dataframes need to be separated on (',')into two additional cloumns.
#
# - Driving licenses column in the licenses_df contains string of numbers follwed by letter n. n needs to be removed and numbers within the same column need to be converted into integer type.
#
# - Values for Indicator column in accidents_df each contain No.of Casualties - injured/dead. This will have to be trimed to just injured or dead.
#
# **What is the minimum *possible* value for each dataset? What is the maximum *possible* value?**
# +
# double check this with an AI. is this what the question is asking???
# checking max and min for accidents_df
print(accidents_df.max(axis = 0, skipna = True));
print('------------')
print(accidents_df.min(axis = 0, skipna = True));
# +
# checking max and min for licenses_df
print(licenses_df.max(axis = 0, skipna = True));
print('-----------')
print(licenses_df.min(axis = 0, skipna = True));
# -
# #### 5. What are your data types?
# Display the data types of each feature.
# +
#displying datatype for each feature for both dataframes
print(licenses_df.dtypes)
print('------------------')
print(accidents_df.dtypes)
# +
# DataFrame.astype : Cast argument to a specified dtype.
# to_datetime : Convert argument to datetime.
# to_timedelta : Convert argument to timedelta.
# numpy.ndarray.astype : Cast a numpy array to a specified type.
# DataFrame.convert_dtypes : Convert dtypes.
# +
# trying to fix Year from str to int
#method 1: using pd.to_numeric
#accidents_df['Year'] = pd.to_numeric(accidents_df['Year']) #not working. Unable to parse string "(2016)" at position 0
#method 2 df.astype()
# accidents_df.Year.astype(int) # not working base 10 issue
# method 3
#ccidents_df.convert_dtypes hold up!
# -
# What did you learn?
# - Do any of them seem odd?
# - Which ones are not as they should be?
# Answer:
#
#
# yes,
#
# - features: Unnamed :0 and Unnamed: 0.1 are represented as integers while the rest of features are in object str format.
#
# - the following features will have to be converted:
#
# Year -> convert to int
#
# Value -> remove 'n' and conver to int
# geopoint -> separate at (,) and conver to float
# #### 6. Fix incorrect data types
# Based on what you discovered above, use appropriate methods to re-type incorrectly typed data.
# - Define a function that will allow you to convert numerical columns to an appropriate numeric type. Use `map` or `apply` to change these columns in each dataframe.
# +
# using one-line function to convert ['Year'] object str to integer type. and omitting ()
accidents_df['Year'] = accidents_df['Year'].apply(lambda x: x.replace('(', '').replace(')', '')).astype('int')
licenses_df['Year'] = licenses_df['Year'].apply(lambda x: x.replace('(', '').replace(')', '')).astype('int')
#
print(accidents_df.dtypes)
print('--------------')
print(licenses_df.dtypes)
# -
# - Make new columns `x` and `y` using `geo_point_2d`
# +
# accidents_df['x'] = accidents_df.geo_point_2d.str[0:,]
# accidents_df['y'] = accidents_df.geo_point_2d.str[:]
# +
# creating new x,y columns using geo_point_2d and splitting on (',')
accidents_df[['x','y']] = accidents_df.geo_point_2d.str.split(",",expand=True,)
licenses_df[['x','y']] = licenses_df.geo_point_2d.str.split(",",expand=True,)
# -
type(accidents_df.x.loc[10]) #checking type of random value in x column
# +
# converting x and y cols to floats instead of object str for both dataframes
accidents_df[['x','y']] = accidents_df[['x','y']].astype('float')
licenses_df[['x','y']] = licenses_df[['x','y']].astype('float')
# -
type(accidents_df.x.loc[10]) # re-checking type of the same value in x column
# - Fix any individual values preventing other columns from being the appropriate type.
# +
# using .apply lambda to omit letter n from columns ['Value'] and ['Driving Licenses']
# and converting column value types into integers
accidents_df['Value'] = accidents_df['Value'].apply(lambda x: x.replace('n', '')).astype('int')
licenses_df['Driving Liceses'] = licenses_df['Driving Liceses'].apply(lambda x: x.replace('n', '')).astype('int')
# +
# Keep this for ref
# licenses_df['Driving Liceses'] =licenses_df['Driving Liceses'].map(lambda x: x.lstrip('n').rstrip('n'))
# licenses_df.head(50)
# +
# I will try to replace n and convert str to int in one go like before. let hack!
#keep 2 lines below for ref
# accidents_df['Value'] = accidents_df['Value'].apply(lambda x: x.replace('n', '').replace('n', '')).astype('int')
# licenses_df['Driving Liceses'] = licenses_df['Driving Liceses'].apply(lambda x: x.replace('n', '').replace('n', '')).astype('int')
##below code was used above. delete this when confident
# # using .apply lambda to omit letter n from columns and convert column values from object str into integers
# accidents_df['Value'] = accidents_df['Value'].apply(lambda x: x.replace('n', '')).astype('int')
# licenses_df['Driving Liceses'] = licenses_df['Driving Liceses'].apply(lambda x: x.replace('n', '')).astype('int')
# +
#keep the line below for ref
#licenses_df['Driving Liceses'] =licenses_df['Driving Liceses'].map(lambda x: x.lstrip('n').rstrip('n'))
###
#removing 'n' from licenses_df['DrivingLicenses']
#removing 'n' from accidents_df['Value']
# licenses_df['Driving Liceses'] =licenses_df['Driving Liceses'].map(lambda x: x.rstrip('n'))#####DONE using .replace above
# accidents_df['Value'] =accidents_df['Value'].map(lambda x: x.rstrip('n')) #####DONE using .replace above
# +
### next, change [value] and [Drvinglicenses] cols into int ##########DONE
# +
# #removing '()' from licenses_df['Year']
# licenses_df['Year'] =licenses_df['Year'].map(lambda x: x.lstrip('()').rstrip('()')) #####DONE using .replace above
# licenses_df.head() #####DONE using .replace above
#removing 'n' from accidents_df['Value']
# accidents_df['Value'] =accidents_df['Value'].map(lambda x: x.lstrip('n').rstrip('n')) #####DONE using .replace above
# accidents_df.head() #####DONE using .replace above
# +
# most likely delete this
#removing 'No.of Casualities' from licenses_df['Indicator']
# accidents_df['Indicator'] =accidents_df['Indicator'].map(lambda x: x.lstrip('No.ofCasualties -').rstrip())
# accidents_df.head()
# -
# - Finish your data modifications by making sure the columns are now typed appropriately.
accidents_df.head(1)
licenses_df.head(1)
# dropping unnecessary columns goint forward
accidents_df = accidents_df.drop(['Unnamed: 0','Unnamed: 0.1','geo_point_2d'], axis=1)
licenses_df = licenses_df.drop(['Unnamed: 0','geo_point_2d'], axis=1)
accidents_df.head()
licenses_df.head()
# +
# re-check of null values
print(licenses_df.isnull().sum())
print('-----------------')
print(accidents_df.isnull().sum())
# +
#checking dublicates
print(licenses_df.duplicated().sum())
print(accidents_df.duplicated().sum())
# -
# - Display the data types again to confirm they are correct.
print(accidents_df.dtypes)
print('---------------')
print(licenses_df.dtypes)
# #### 7. Rename columns
# Change the names of the columns to more expressive names so that you can tell the difference the Driving Licenses columns and the & Traffic Accidents columns. Your solution should map all column names being changed at once (no repeated singular name-changes). **We will be combining these two datasets, and so you should name columns in an appropriate way**.
#
# **Guidelines**:
# - Column names should be all lowercase (you will thank yourself when you start pushing data to SQL later in the course)
# - Column names should not contain spaces (underscores will suffice--this allows for using the `df.column_name` method to access columns in addition to `df['column_name']`.
# - Column names should be unique and informative (the only feature that we actually share between dataframes is the state).
# - Please also fix any typos you see in the column names.
# displaying origina column names in licenses_df
licenses_df.columns
# +
# renaming columns in licenses_df using the dictionary method:
licenses_df.rename(columns={
'Year':'year', # year == license year
'Administritive Area':'region', # region == license region
'Driving Liceses':'license_count', # count == licneses count
'x':'x_point', # geo_x == license geo location x
'y':'y_point' # geo_y == license geo location y
}, inplace = True)
# -
# displaying new column names in licenses_df
licenses_df.head()
licenses_df.shape
# displaying a list of original column names in accidnets_df
accidents_df.columns
# +
# renaming columns in accidents_df using the dictionary method:
accidents_df.rename(columns={
'Year':'year', # a_year == accidents year
'Region':'region', # a_region == accidents region
'Indicator':'accident_outcome', # Indicator == accident outcome
'Value':'accident_count', # a_count == accidents count
'x':'x_point', # geo_x == accidents geo location x
'y':'y_point' # geo_y == accidents geo location y
}, inplace=True)
# -
# displaying new column names in accidents_df
accidents_df.head()
accidents_df.shape
# +
inner_join = pd.merge(accidents_df,licenses_df,on=[['year']], how='inner')
inner_join.head(50)
# -
inner_join.shape
# #### 8. Create a data dictionary
#
# Now that we've fixed our data, and given it appropriate names, let's create a [data dictionary](http://library.ucmerced.edu/node/10249).
#
# A data dictionary provides a quick overview of features/variables/columns, alongside data types and descriptions. The more descriptive you can be, the more useful this document is.
#
# Example of a Fictional Data Dictionary Entry:
#
# |Feature|Type|Dataset|Description|
# |---|---|---|---|
# |**county_pop**|*integer*|2010 census|The population of the county (units in thousands, where 2.5 represents 2500 people).|
# |**per_poverty**|*float*|2010 census|The percent of the county over the age of 18 living below the 200% of official US poverty rate (units percent to two decimal places 98.10 means 98.1%)|
#
# [Here's a quick link to a short guide for formatting markdown in Jupyter notebooks](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html).
#
# Provided is the skeleton for formatting a markdown table, with columns headers that will help you create a data dictionary to quickly summarize your data, as well as some examples. **This would be a great thing to copy and paste into your custom README for this project.**
#the code in this cell left aligns the table below.
# %%html
<style>
table {float:left}
</style>
# |Feature|Type|Dataset|Description|
# |:-|:-|:-|:------------:|
# |a_year|*int*|accidents_df|year in which traffict accidents occurred|
# |a_region|*object*|accidents_df|region where traffict accidents occurred|
# |a_casualties|*object*|accidents_df|outcome of accidents - dead/injured|
# |a_count|*int*|accidents_df|number of resulting casualties from accidents|
# |a_geoloc_x|*float*|accidents_df|x coordinate location of accidents|
# |a_geoloc_y|*float*|accidents_df|y coordinate location of accidents|
# |---|---|---|---|
# |l_year|*int*|licenses_df|year of issued driving licenses|
# |l_region|*object*|licenses_df|region of issuded driving licenses|
# |l_count|*int*|licenses_df|number of issued driving licenses|
# |l_geoloc_x|*float*|licenses_df|x coordinate location of driving licenses issuing region|
# |l_geoloc_y|*float*|licenses_df|y coordinate location of driving licenses issuing region|
#
#
#
#
# #### 9. Drop unnecessary rows
#
# This study concerns accident and license in regions/area. Please do the followings:
# 0. Which rows are not associated with regions?
# 1. Confirm the numbers of all regions add up to total.
# 2. Remove the rows that are not associated with regions
# #Answer
#
# - unnecessary rows correspond to value == Total instead of a particular region/area
# - the same rows (with Total instead of region) also lack geo_point_2d values (nulls)
#
# These rows were droped earlier using:
#
# accidents_df.dropna(how='any', inplace=True)
# licenses_df.dropna(how='any', inplace=True)
#
# +
# renaming regions to be the same across both dataframes
licenses_df['region'].replace({'Makkah':'Makkah',
'Eastern':'Eastern Region',
'Tabouk':'Tabouk',
'Hail':'Hail',
'Northern Boarder':'Northern Boarder',
'Jazan':'Jazan',
'Al-Jouf':'Al-Jouf',
'Al-Baaha':'Al-Baha',
'Riyadh':'Riyadh',
'Madinah':'Madinah',
'Al-Qaseem':'Qassim',
'Najran':'Najran',
'Assir':'Asir'},inplace=True) # inplace = True to update original df
# +
# renaming regions to be the same across both dataframes
accidents_df['region'].replace({'Mecca':'Makkah',
'Eastern Region':'Eastern Region',
'Tabouk':'Tabouk',
'Hail':'Hail',
'Northern Boarder':'Northern Boarder',
'Jazan':'Jazan',
'Al-Jouf':'Al-Jouf',
'Al-Baaha':'Al-Baha',
'Riyadh':'Riyadh',
'Madinah':'Madinah',
'Qassim':'Qassim',
'Najran':'Najran',
'Asir':'Asir'},inplace=True) # inplace = True to update original df
# -
# checking updated region names in accidents_df
accidents_df['region'].unique()
#checking updated region names in licenses_df
licenses_df['region'].unique()
# +
print(accidents_df['region'].value_counts()) #getting value counts for each region in region column
print('---------------')
print(accidents_df['region'].value_counts().sum()) #adding regions
print('---------------')
print(accidents_df.shape) # confirming number of regions add up to total
# we have 6 enteries per region.
# 3 enteries per each year (2016 or 2017)
# each entry corresponds to outcome (injured, dead, total num of accidents)
# -
print(licenses_df['region'].value_counts()) #getting value counts for each region in region column
print('---------------')
print(licenses_df['region'].value_counts().sum()) #adding regions
print('---------------')
print(licenses_df.shape) # confirming number of regions add up to total
# #### 10a. Data formats
# Is the License data in long or wide format? How about the Accident data? And why?
# +
#both are in long format since each row contains one measure for the given variable or subject.
# -
# #### 10b. Changing formats
# Which format would work best for both dataframes? Transform the datasets to the same format before merging in the next task.
# +
# wide format would work best. this way, each row will contain all mesures for a particular subject
# update: long format will be suitable for flexibility obtainin statistical data and plotting
# -
# #### 11. Merge dataframes
#
# Join the Driving Licenses & Traffic Accidents dataframes using the **region** and **year** in each dataframe as the key. Assign this to a new variable. Which join should you use to preserve the most data?
#display license_df before merge
licenses_df.head()
#display accidents_df before merge
accidents_df.head()
# +
#performing an inner join to preserve most data
combined_datasets = pd.merge(licenses_df,accidents_df,on=['region','x_point','y_point'], how='inner')
combined_datasets.head()
# -
print(f'accidents_df: {accidents_df.shape}\nlicenses_df: {licenses_df.shape}\ncombined_datasets: {combined_datasets.shape}')
print(combined_datasets.duplicated().sum())
print(combined_datasets.isnull().sum())
# #### 12. Save your cleaned, merged dataframe
#
# Use a relative path to save out your data as `combined_datasets.csv`.
combined_datasets.to_csv('../data/combined_datasets.csv')
licenses_df.to_csv('../data/licenses_df.csv') #remove
accidents_df.to_csv('../data/accidents_df.csv') #remove
# ## Exploratory Data Analysis
#
#
# ### Summary Statistics
# Transpose the output of pandas `describe` method to create a quick overview of each numeric feature.
combined_datasets.describe()
combined_datasets.dtypes
# #### Manually calculate standard deviation
#
# $$\sigma = \sqrt{\frac{1}{n}\sum_{i=1}^n(x_i - \mu)^2}$$
#
# - Write a function to calculate standard deviation using the formula above
# importing libraries
#=================
import math
import sys
#=================
# defining standard dev function as stdev_cal
def stdev_cal(data):
n = len(data)
if n <= 1:
return 0.0
mean, sd = mean_cal(data), 0.0
# calculating standard dev
for el in data:
sd += (int(el) - mean)**2
sd = math.sqrt(sd / int(n-1))
return sd
#================================
# defining function to calculate mean as mean_cal
def mean_cal (ls):
n, mean = len(ls), 0.0
if n <= 1:
return ls[0]
# calculating mean
for el in ls:
mean = mean + int(el)
mean = mean / int(n)
return mean
# testing function
stdev_cal(combined_datasets['license_count'])
# testing function
stdev_cal(combined_datasets['accident_count'])
# - Use a **dictionary comprehension** to apply your standard deviation function to each numeric column in the dataframe. **No loops**
# - Assign the output to variable `sd` as a dictionary where:
# - Each column name is now a key
# - That standard deviation of the column is the value
#
# *Example Output :* `{'Driving_Licenses_x': 120, 'Traffic_Accidents_x': 120, ...}`
combined_datasets.columns
# +
# my_dict_2 = {'l_year':combined_datasets['l_year'],
# 'license_count':combined_datasets['license_count'],
# 'geo_x':combined_datasets['geo_x'],
# 'geo_y':combined_datasets['geo_y'],
# 'a_year':combined_datasets['a_year'],
# 'accident_outcome':combined_datasets['accident_outcome'],
# 'accident_count':combined_datasets['accident_count']}
# +
#Code:
# -
# Do your manually calculated standard deviations match up with the output from pandas `describe`? What about numpy's `std` method?
# +
# Answer: yes
# testing manual function:
print('manula standard dev:',stdev_cal(combined_datasets['license_count']))
# testing via numpy:
import numpy as np
print('numpy std:',np.std(combined_datasets['license_count']))
# -
# confirming license count standard dev == manual and numpy standard dev output
combined_datasets.describe()
# +
######fix typo in license_year
# -
# #### Investigate trends in the data
# Using sorting and/or masking (along with the `.head` method to not print our entire dataframe), consider the following questions:
#
# - Which regions have the highest and lowest Driving Licenses based on years (1993 - 2017)
# - Which regions have the highest and lowest mean Traffic Accidents numbers for years (2016 - 2017)
# - What are the regions that have more Driving Licenses issued in each year than the year average?
# - What are the regions that have more Traffic Accidents happened in each year than the year average?
#
# Based on what you've just observed, have you identified any regions that you're especially interested in? **Make a note of these and state *why* you think they're interesting**.
#
# **You should comment on your findings at each step in a markdown cell below your code block**. Make sure you include at least one example of sorting your dataframe by a column, and one example of using boolean filtering (i.e., masking) to select a subset of the dataframe.
# +
# 1.A
#Which regions have the highest and lowest Driving Licenses based on years (1993 - 2017)?
# Using .sort_values() and obtaining 1st row via iloc[]
combined_datasets.sort_values(['license_count']).iloc[[0]]
#===============
#this can also be used on license_df for cleaner output:
#licenses_df.sort_values('license_count').iloc[[0]]
# +
# 1.B
# Using .sort_values(), ascend=False and obtaining 1st row via iloc[]
combined_datasets.sort_values(['license_count'],ascending=False).iloc[[0]]
#=============
#this can also be used on license_df for cleaner output:
#licenses_df.sort_values(['license_count'],ascending=False).iloc[[0]]
# -
# **Which regions have the highest and lowest Driving Licenses based on years (1993 - 2017)?**
#
# Answer:
#
# - The highest number of driving licenses was in Riyadh in 2017. license count:495307
# - The lowest number of driving licenses was in Tabouk in 2015. license count: 915
# +
# 2.A
#Which regions have the highest and lowest mean Traffic Accidents numbers for years (2016 - 2017)?
# using filtering logic to access columns of interest.
# and sorting by accident count column, ascending=false
combined_datasets[(combined_datasets['accident_count']>1)
&(combined_datasets['accident_year']>=2016)].sort_values('accident_count',ascending=True).head(1)
#=============
#this can also be used on accident_df for cleaner output:
#accidents_df[(accidents_df['accident_count']>1)&(accidents_df['accident_year']>=2016)].sort_values('accident_count',ascending=True).head(1)
# +
#2.B
combined_datasets[(combined_datasets['accident_count']>1)
&(combined_datasets['accident_year']>=2016)].sort_values('accident_count',ascending=False).head(1)
#=============
#this can also be used on accident_df for cleaner output:
#accidents_df[(accidents_df['accident_count']>1)&(accidents_df['accident_year']>=2016)].sort_values('accident_count',ascending=False).head(1)
# -
# **Which regions have the highest and lowest mean Traffic Accidents numbers for years (2016 - 2017)?**
#
# Answer:
#
# The highest number of traffic accidents was in Makkah in 2017. accidents count:145541
# The lowest number of traffic accidents was in Northern Boarder in 2017. accident count: 112
# +
# 3. What are the regions that have more Driving Licenses issued in each year than the year average?
# obtaining mean license count and assigning variable
lice_year_ave = np.mean(combined_datasets['license_count'])
# flitering license_count for elements > lice_year_ave and assigning variable
lice_above_ave = combined_datasets[(combined_datasets['license_count']>lice_year_ave)]
#obtaining unique regions
print('Regions above annual average licenses count:\n', lice_above_ave['region'].unique())
# -
lice_above_ave = licenses_df[(licenses_df['license_count']>lice_year_ave)]
print(lice_above_ave.region.value_counts())
# Side note: It appears Makkah, ER and Riyadh beat the annual average for issued licenses by a big margin. However, this is expeced given the magnitude of population per these areas
# +
# 4. What are the regions that have more Traffic Accidents happened in each year than the year average?
# obtaining mean accident count and assigning variable
acci_year_ave = np.mean(combined_datasets['accident_count'])
# flitering accident_count for elements > acci_year_ave and assigning variable
acci_above_ave = combined_datasets[(combined_datasets['accident_count']>acci_year_ave)]
#obtaining unique regions
print('Regions above annual average accident count:\n', acci_above_ave['region'].unique())
# -
acci_above_ave = accidents_df[(accidents_df['accident_count']>acci_year_ave)]
print(acci_above_ave.region.value_counts())
# Side note: Makkah, ER and Riyadh in addition to others, exceed the annual average for number of accidents (13868 accidents) in both 2016 and 2017.
# ## Visualize the data
#
# There's not a magic bullet recommendation for the right number of plots to understand a given dataset, but visualizing your data is *always* a good idea. Not only does it allow you to quickly convey your findings (even if you have a non-technical audience), it will often reveal trends in your data that escaped you when you were looking only at numbers.
#
# Some recommendations on plotting:
# - Plots have titles
# - Plots have axis labels
# - Plots have appropriate tick labels
# - All text is legible in a plot
# - Plots demonstrate meaningful and valid relationships
# - Plots are interpreted to aid understanding
#
# There is such a thing as too many plots, and there are a *lot* of bad plots. You might make some! (But hopefully not with the guided prompts below).
# #### Use Seaborn's heatmap with pandas `.corr()` to visualize correlations between all numeric features
#
# Heatmaps are generally not appropriate for presentations, and should often be excluded from reports as they can be visually overwhelming. **However**, they can be extremely useful in identify relationships of potential interest (as well as identifying potential collinearity before modeling).
#
# *example*:
# ```python
# sns.heatmap(df.corr())
# ```
#
# Please take time to format your output, adding a title. Look through some of the additional arguments and options. (Axis labels aren't really necessary, as long as the title is informative).
plt.figure(figsize = (10,7))
sns.heatmap(combined_datasets.corr(), annot=True,linecolor='black'
,linewidths=.1,cbar=True,cmap="Blues")
sns.set(font_scale=1)
ax = plt.axes()
ax.set_title('licenses issued vs accident counts - Saudi Arabia')
plt.show();
# #### Define a custom function to subplot histograms
#
# We should write a function that will take the names of 2+ columns and subplot histograms. While you can use pandas plotting or Seaborn here, matplotlib gives you greater control over all aspects of your plots.
#
# [Helpful Link for Plotting Multiple Figures](https://matplotlib.org/users/pyplot_tutorial.html#working-with-multiple-figures-and-axes)
#
# Here's some starter code:
def subplot_histograms(dataframe, list_of_columns, list_of_titles, list_of_xlabels):
nrows = int(np.ceil(len(list_of_columns)/2) # Makes sure you have enough rows
fig, ax = plt.subplots(nrow s=nrows, ncols=2) # You'll want to specify your figsize
ax = ax.ravel() # Ravel turns a matrix into a vector, which is easier to iterate
for i, column in enumerate(list_of_columns): # Gives us an index value to get into all our lists
ax[i].hist(dataframe[column]) # feel free to add more settings
# Set titles, labels, etc here for each subplot
# #### Plot and interpret histograms
# For each of the following:
# - Driving Licenses number
# - Traffic Accidents number
#
# Please plot two additional histograms that will help with your understanding of the data
# +
sns.set_style('whitegrid')
# %matplotlib inline
font = {'size':10}
plt.rc('font', **font)
plt.figure(figsize=(5,6))
plt.hist(accidents_df.accident_count, bins=15,range=[10000,150000], facecolor='grey', align='mid')
plt.xticks(rotation='vertical')
plt.xlabel('Number of accidents')
plt.ylabel('Frequency');
# -
# - The histogram for number of accidents is rightly skewed. ie. the mode is higher than the mean.
# - The most frequently occurring range of accidents is approximately between 10000 - 30000 accidents.
#
font = {'size':10}
plt.rc('font', **font)
plt.figure(figsize=(5,7))
plt.hist(accidents_df.region, bins=15,facecolor='grey', align='mid')
plt.xticks(rotation='vertical')
plt.ylabel('Frequency')
plt.xlabel('Regions');
# The frequency of regions in our data is uniformly distributed.
# ie. the frequency of all regions is approximately equal
font = {'size':10}
plt.rc('font', **font)
plt.figure(figsize=(5,7))
plt.hist(licenses_df.license_count, bins=15, range=[20000,200000], facecolor='green', align='mid')
plt.xticks(rotation='vertical')
plt.xlabel('Dirving licenses')
plt.ylabel('Frequency')
# The histogram for number of issued driving licenses is rightly skewed. ie. the mode is higher than the mean.
# The most frequent amount of issued licenses is approximately 25000 licenses.
font = {'size':10}
plt.rc('font', **font)
plt.figure(figsize=(5,7))
plt.hist(licenses_df.licese_year, bins=30,range=[1993,2017],facecolor='green', align='mid')
plt.xticks(rotation='vertical')
plt.xlabel('years of issued licenses')
The frequency of years for issued licenses in our data is uniformly distributed.
ie. the frequency of all years is approximately equal (each year represented 13 times)
# #### Plot and interpret scatter plots
#
# For each of the following:
# - Driving Licenses vs. Traffic Accidents for 2017
# - Driving Licenses vs. Traffic Accidents for 2016
# - Driving Licenses for 2016 vs 2017
# - Traffic Accidents for 2016 vs 2017
#
# Plot the two variables against each other using matplotlib or Seaborn
#
# Your plots should show:
# - Two clearly labeled axes
# - A proper title
# - Using colors and symbols that are clear and unmistakable
#
# **Feel free to write a custom function, and subplot if you'd like.** Functions save both time and space.
#
make new df for 2017 and another for 2016
plt.scatter(licenses_df.license_count, accidents_df.accident_count)
plt.xlabel('GRE')
plt.ylabel('GPA');
plt.title('My plotting Example');
# #### Plot and interpret boxplots
#
# For each numeric variable in the dataframe create a boxplot using Seaborn. Boxplots demonstrate central tendency and spread in variables. In a certain sense, these are somewhat redundant with histograms, but you may be better able to identify clear outliers or differences in IQR, etc.
#
# Multiple values can be plotted to a single boxplot as long as they are of the same relative scale (meaning they have similar min/max values).
#
# Each boxplot should:
# - Only include variables of a similar scale
# - Have clear labels for each variable
# - Have appropriate titles and labels
# +
# Code
# -
# #### Feel free to do additional plots below
# *(do research and choose your own chart types & variables)*
#
# Are there any additional trends or relationships you haven't explored? Was there something interesting you saw that you'd like to dive further into? It's likely that there are a few more plots you might want to generate to support your narrative and recommendations that you are building toward. **As always, make sure you're interpreting your plots as you go**.
# ## Descriptive and Inferential Statistics
# #### Summarizing Distributions
#
# Above, we used pandas `describe` to provide quick summary statistics of our numeric columns. We also demonstrated many visual relationships.
#
# As data scientists, having a complete understanding of data is imperative prior to modeling.
#
# While we will continue to build our analytic tools, we know that measures of *central tendency*, *spread*, and *shape/skewness* provide a quick summary of distributions.
#
# For each variable in your data, summarize the underlying distributions (in words & statistics)
# - Be thorough in your verbal description of these distributions.
# - Be sure to back up these summaries with statistics.
# Answers:
# #### We generally assuming that data we sample from a population will be normally distributed. Do we observe this trend?
# Answer:
# Does This Assumption Hold for:
# - Driving Licenses
# - Traffic Accidents
# Explain your answers for each distribution and how you think this will affect estimates made from these data.
# Answer:
# #### Statistical Evaluation of Distributions
#
# **If you feel it's appropriate**, using methods we discussed in class, run hypothesis tests to compare variables of interest in our dataset.
# +
# Code
# -
# ## Outside Research
# Based upon your observations, choose **three** regions that demonstrate interesting trends in the number of driving licenses and traffic accidents. Spend some time doing outside research on provincial and central policies that might influence these rates, and summarize your findings below. **Feel free to go back and create new plots that highlight these states of interest**. If you bring in any outside tables or charts, make sure you are explicit about having borrowed them. If you quote any text, make sure that it renders as being quoted. (Make sure that you cite your sources -- check with you local instructor for citation preferences).
# Answer:
# ## Conclusions and Recommendations
# - Based on your exploration of the data, what are you key takeaways and recommendations?
# - Are there additional data you desire that would better inform your investigations?
# Answer:
| code/personal_practice_space/starter-code-practice_Copy1-Copy1-scaterplot .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
# ---
# # Exporting data to NetCDF files <img align="right" src="../Supplementary_data/dea_logo.jpg">
#
# * **Compatability:** Notebook currently compatible with both the `NCI` and `DEA Sandbox` environments
# * **Products used:**
# [ls8_nbart_geomedian_annual](https://explorer.sandbox.dea.ga.gov.au/ls8_nbart_geomedian_annual)
# ## Background
# NetCDF is a file format for storing multidimensional scientific data.
# This file format supports datasets containing multiple observation dates, as well as multiple bands.
# It is a native format for storing the `xarray` datasets that are produced by Open Data Cube, i.e. by `dc.load` commands.
#
# NetCDF files should follow [Climate and Forecast (CF) metadata conventions](http://cfconventions.org/) for the description of Earth sciences data.
# By providing metadata such as geospatial coordinates and sensor information in the same file as the data, CF conventions allow NetCDF files to be "self-describing".
# This makes CF-compliant NetCDFs a useful way to save multidimensional data loaded from Digital Earth Australia, as the data can later be loaded with all the information required for further analysis.
#
# The `xarray` library which underlies the Open Data Cube (and hence Digital Earth Australia) was specifically designed for representing NetCDF files in Python.
# However, some geospatial metadata is represented quite differently between the NetCDF-CF conventions versus the GDAL (or proj4) model that is common to most geospatial software (including ODC, e.g. for reprojecting raster data when necessary).
# The main difference between `to_netcdf` (in `xarray` natively) and `write_dataset_to_netcdf` (provided by `datacube`) is that the latter is able to appropriately serialise the *coordinate reference system* object which is associated to the dataset.
#
# ## Description
# In this notebook we will load some data from Digital Earth Australia and then write it to a (CF-compliant) NetCDF file using the `write_dataset_to_netcdf` function provided by `datacube`.
# We will then verify the file was saved correctly, and (optionally) clean up.
#
# ---
# ## Getting started
#
# To run this analysis, run all the cells in the notebook, starting with the "Load packages" cell.
#
# ### Load packages
# +
# %matplotlib inline
import datacube
import xarray as xr
from datacube.drivers.netcdf import write_dataset_to_netcdf
# -
# ### Connect to the datacube
dc = datacube.Datacube(app='Exporting_NetCDFs')
# ## Load data from the datacube
# Here we load a sample dataset from the DEA Landsat-8 Annual Geomedian product (`ls8_nbart_geomedian_annual`).
# The loaded data is multidimensional, and contains two time-steps (2015, 2016) and six satellite bands (`blue`, `green`, `red`, `nir`, `swir1`, `swir2`).
# +
lat, lon = -35.282052, 149.128667 # City Hill, Canberra
radius = 0.01 # Approx. 1km
# Load data from the datacube
ds = dc.load(product='ls8_nbart_geomedian_annual',
lat=(lat - radius, lat + radius),
lon=(lon - radius, lon + radius),
time=('2015', '2016'))
# Print output data
print(ds)
# -
# ## Export to a NetCDF file
# To export a CF-compliant NetCDF file, we use the `write_dataset_to_netcdf` function:
write_dataset_to_netcdf(ds, 'output_netcdf.nc')
# That's all.
# The file has now been produced, and stored in the current working directory.
# ## Reading back from saved NetCDF
# Let's start just by confirming the file now exists.
# We can use the special `!` command to run command line tools directly within a Jupyter notebook.
# In the example below, `! ls *.nc` runs the `ls` shell command, which will give us a list of any files in the NetCDF file format (i.e. with file names ending with `.nc`).
#
# > For an introduction to using shell commands in Jupyter, [see the guide here](https://jakevdp.github.io/PythonDataScienceHandbook/01.05-ipython-and-shell-commands.html).
# ! ls *.nc
# We could inspect this file using external utilities such as `gdalinfo` or `ncdump`, or open it for visualisation e.g. in `QGIS`.
#
# We can also load the file back into Python using `xarray`:
# +
# Load the NetCDF from file
reloaded_ds = xr.open_dataset('output_netcdf.nc')
# Print loaded data
print(reloaded_ds)
# -
# We can now use this reloaded dataset just like the original dataset, for example by plotting one of its colour bands:
reloaded_ds.red.plot(col='time')
# ### Clean-up
# To remove the saved NetCDF file that we created, run the cell below. This is optional.
# ! rm output_netcdf.nc
# ---
#
# ## Additional information
#
# **License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0).
# Digital Earth Australia data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license.
#
# **Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)).
# If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/GeoscienceAustralia/dea-notebooks).
#
# **Last modified:** December 2019
#
# **Compatible datacube version:**
print(datacube.__version__)
# ## Tags
# Browse all available tags on the DEA User Guide's [Tags Index](https://docs.dea.ga.gov.au/genindex.html)
# + raw_mimetype="text/restructuredtext" active=""
# **Tags**: :index:`sandbox compatible`, :index:`NCI compatible`, :index:`annual geomedian`, :index:`NetCDF`, :index:`write_dataset_to_netcdf`, :index:`exporting data`, :index:`metadata`, :index:`shell commands`
| Frequently_used_code/Exporting_NetCDFs.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
# ---
"""
WARNING: This tutorial and MegatronBERT are not supported as part of NeMo release 1.5.0.
Please use version 1.4.0 https://github.com/NVIDIA/NeMo/tree/r1.4.0
You can download the 1.4.0 NeMo container with the command:
docker pull nvcr.io/nvidia/nemo:1.4.0
or make sure BRANCH is set to r1.4.0 when using this notebook on Google Colab
"""
BRANCH = 'r1.5.1'
# +
"""
You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.
Instructions for setting up Colab are as follows:
1. Open a new Python 3 notebook.
2. Import this notebook from GitHub (File -> Upload Notebook -> "GITHUB" tab -> copy/paste GitHub URL)
3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select "GPU" for hardware accelerator)
4. Run this cell to set up dependencies.
"""
# If you're using Google Colab and not running locally, run this cell
# install NeMo
# !python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]
# +
# If you're not using Colab, you might need to upgrade jupyter notebook to avoid the following error:
# 'ImportError: IProgress not found. Please update jupyter and ipywidgets.'
# ! pip install ipywidgets
# ! jupyter nbextension enable --py widgetsnbextension
# Please restart the kernel after running this cell
# +
from nemo.collections import nlp as nemo_nlp
from nemo.utils.exp_manager import exp_manager
import os
import wget
import torch
import pytorch_lightning as pl
from omegaconf import OmegaConf
# -
# In this tutorial, we are going to describe how to finetune BioMegatron - a [BERT](https://arxiv.org/abs/1810.04805)-like [Megatron-LM](https://arxiv.org/pdf/1909.08053.pdf) model pre-trained on large biomedical text corpus ([PubMed](https://pubmed.ncbi.nlm.nih.gov/) abstracts and full-text commercial use collection) - on the [NCBI Disease Dataset](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3951655/) for Named Entity Recognition.
#
# The model size of Megatron-LM can be larger than BERT, up to multi-billion parameters, compared to 345 million parameters of BERT-large.
# There are some alternatives of BioMegatron, most notably [BioBERT](https://arxiv.org/abs/1901.08746). Compared to BioBERT BioMegatron is larger by model size and pre-trained on larger text corpus.
#
# A more general tutorial of using BERT-based models, including Megatron-LM, for downstream natural language processing tasks can be found [here](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/nlp/01_Pretrained_Language_Models_for_Downstream_Tasks.ipynb).
#
# # Task Description
# **Named entity recognition (NER)**, also referred to as entity chunking, identification or extraction, is the task of detecting and classifying key information (entities) in text.
#
# For instance, **given sentences from medical abstracts, what diseases are mentioned?**<br>
# In this case, our data input is sentences from the abstracts, and our labels are the precise locations of the named disease entities. Take a look at the information provided for the dataset.
#
# For more details and general examples on Named Entity Recognition, please refer to the [Token Classification and Named Entity Recognition tutorial notebook](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/nlp/Token_Classification_Named_Entity_Recognition.ipynb).
#
# # Dataset
#
# The [NCBI-disease corpus](https://www.ncbi.nlm.nih.gov/CBBresearch/Dogan/DISEASE/) is a set of 793 PubMed abstracts, annotated by 14 annotators. The annotations take the form of HTML-style tags inserted into the abstract text using the clearly defined rules. The annotations identify named diseases, and can be used to fine-tune a language model to identify disease mentions in future abstracts, *whether those diseases were part of the original training set or not*.
#
# Here's an example of what an annotated abstract from the corpus looks like:
#
# ```html
# 10021369 Identification of APC2, a homologue of the <category="Modifier">adenomatous polyposis coli tumour</category> suppressor . The <category="Modifier">adenomatous polyposis coli ( APC ) tumour</category>-suppressor protein controls the Wnt signalling pathway by forming a complex with glycogen synthase kinase 3beta ( GSK-3beta ) , axin / conductin and betacatenin . Complex formation induces the rapid degradation of betacatenin . In <category="Modifier">colon carcinoma</category> cells , loss of APC leads to the accumulation of betacatenin in the nucleus , where it binds to and activates the Tcf-4 transcription factor ( reviewed in [ 1 ] [ 2 ] ) . Here , we report the identification and genomic structure of APC homologues . Mammalian APC2 , which closely resembles APC in overall domain structure , was functionally analyzed and shown to contain two SAMP domains , both of which are required for binding to conductin . Like APC , APC2 regulates the formation of active betacatenin-Tcf complexes , as demonstrated using transient transcriptional activation assays in APC - / - <category="Modifier">colon carcinoma</category> cells . Human APC2 maps to chromosome 19p13 . 3 . APC and APC2 may therefore have comparable functions in development and <category="SpecificDisease">cancer</category> .
# ```
#
# In this example, we see the following tags within the abstract:
# ```html
# <category="Modifier">adenomatous polyposis coli tumour</category>
# <category="Modifier">adenomatous polyposis coli ( APC ) tumour</category>
# <category="Modifier">colon carcinoma</category>
# <category="Modifier">colon carcinoma</category>
# <category="SpecificDisease">cancer</category>
# ```
#
# For our purposes, we will consider any identified category (such as "Modifier", "Specific Disease", and a few others) to generally be a "disease".
#
# Let's download the dataset.
DATA_DIR = "DATA_DIR"
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(os.path.join(DATA_DIR, 'NER'), exist_ok=True)
print('Downloading NCBI data...')
wget.download('https://www.ncbi.nlm.nih.gov/CBBresearch/Dogan/DISEASE/NCBI_corpus.zip', DATA_DIR)
# ! unzip -o {DATA_DIR}/NCBI_corpus.zip -d {DATA_DIR}
# +
# If you want to see more examples, you can explore the text of the corpus using the file browser to the left, or open files directly, for example typing a command like the following in a code-cell:
# ! head -1 $DATA_DIR/NCBI_corpus_testing.txt
# -
# We have two datasets derived from this corpus: a text classification dataset and a named entity recognition (NER) dataset. The text classification dataset labels the abstracts among three broad disease groupings. We'll use this simple split to demonstrate the NLP text classification task. The NER dataset labels individual words as diseases. This dataset will be used for the NLP NER task.
# ## Pre-process dataset
# A pre-processed NCBI-disease dataset for NER can be found [here](https://github.com/spyysalo/ncbi-disease/tree/master/conll) or [here](https://github.com/dmis-lab/biobert#datasets).<br>
# We download the files under {DATA_DIR/NER} directory.
NER_DATA_DIR = f'{DATA_DIR}/NER'
wget.download('https://raw.githubusercontent.com/spyysalo/ncbi-disease/master/conll/train.tsv', NER_DATA_DIR)
wget.download('https://raw.githubusercontent.com/spyysalo/ncbi-disease/master/conll/devel.tsv', NER_DATA_DIR)
wget.download('https://raw.githubusercontent.com/spyysalo/ncbi-disease/master/conll/test.tsv', NER_DATA_DIR)
# !ls -lh $NER_DATA_DIR
# Convert these to a format that is compatible with [NeMo Token Classification module](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/token_classification_train.py), using the [conversion script](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/data/import_from_iob_format.py).
# ! mv $NER_DATA_DIR/devel.tsv $NER_DATA_DIR/dev.tsv
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/data/import_from_iob_format.py')
# ! python import_from_iob_format.py --data_file=$NER_DATA_DIR/train.tsv
# ! python import_from_iob_format.py --data_file=$NER_DATA_DIR/dev.tsv
# ! python import_from_iob_format.py --data_file=$NER_DATA_DIR/test.tsv
# The NER task requires two files: the text sentences, and the labels. Run the next two cells to see a sample of the two files.
# !head $NER_DATA_DIR/text_train.txt
# !head $NER_DATA_DIR/labels_train.txt
# ### IOB Tagging
# We can see that the abstract has been broken into sentences. Each sentence is then further parsed into words with labels that correspond to the original HTML-style tags in the corpus.
#
# The sentences and labels in the NER dataset map to each other with _inside, outside, beginning (IOB)_ tagging. Anything separated by white space is a word, including punctuation. For the first sentence we have the following mapping:
#
# ```text
# Identification of APC2 , a homologue of the adenomatous polyposis coli tumour suppressor .
# O O O O O O O O B I I I O O
# ```
#
# Recall the original corpus tags:
# ```html
# Identification of APC2, a homologue of the <category="Modifier">adenomatous polyposis coli tumour</category> suppressor .
# ```
# The beginning word of the tagged text, "adenomatous", is now IOB-tagged with a <span style="font-family:verdana;font-size:110%;">B</span> (beginning) tag, the other parts of the disease, "polyposis coli tumour" tagged with <span style="font-family:verdana;font-size:110%;">I</span> (inside) tags, and everything else tagged as <span style="font-family:verdana;font-size:110%;">O</span> (outside).
#
# # Model configuration
#
# Our Named Entity Recognition model is comprised of the pretrained [BERT](https://arxiv.org/pdf/1810.04805.pdf) model followed by a Token Classification layer.
#
# The model is defined in a config file which declares multiple important sections. They are:
# - **model**: All arguments that are related to the Model - language model, token classifier, optimizer and schedulers, datasets and any other related information
#
# - **trainer**: Any argument to be passed to PyTorch Lightning
WORK_DIR = "WORK_DIR"
os.makedirs(WORK_DIR, exist_ok=True)
MODEL_CONFIG = "token_classification_config.yaml"
# download the model's configuration file
config_dir = WORK_DIR + '/configs/'
os.makedirs(config_dir, exist_ok=True)
if not os.path.exists(config_dir + MODEL_CONFIG):
print('Downloading config file...')
wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG, config_dir)
else:
print ('config file is already exists')
# this line will print the entire config of the model
config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'
print(config_path)
config = OmegaConf.load(config_path)
# Note: these are small batch-sizes - increase as appropriate to available GPU capacity
config.model.train_ds.batch_size=8
config.model.validation_ds.batch_size=8
print(OmegaConf.to_yaml(config))
# # Model Training
# ## Setting up Data within the config
#
# Among other things, the config file contains dictionaries called dataset, train_ds and validation_ds. These are configurations used to setup the Dataset and DataLoaders of the corresponding config.
#
# We assume that both training and evaluation files are located in the same directory, and use the default names mentioned during the data download step.
# So, to start model training, we simply need to specify `model.dataset.data_dir`, like we are going to do below.
#
# Also notice that some config lines, including `model.dataset.data_dir`, have `???` in place of paths, this means that values for these fields are required to be specified by the user.
#
# Let's now add the data directory path to the config.
# +
# in this tutorial train and dev datasets are located in the same folder, so it is enought to add the path of the data directory to the config
config.model.dataset.data_dir = os.path.join(DATA_DIR, 'NER')
# if you want to decrease the size of your datasets, uncomment the lines below:
# NUM_SAMPLES = 1000
# config.model.train_ds.num_samples = NUM_SAMPLES
# config.model.validation_ds.num_samples = NUM_SAMPLES
# -
# ## Building the PyTorch Lightning Trainer
#
# NeMo models are primarily PyTorch Lightning modules - and therefore are entirely compatible with the PyTorch Lightning ecosystem.
#
# Let's first instantiate a Trainer object
print("Trainer config - \n")
print(OmegaConf.to_yaml(config.trainer))
# +
# lets modify some trainer configs
# checks if we have GPU available and uses it
cuda = 1 if torch.cuda.is_available() else 0
config.trainer.gpus = cuda
# for PyTorch Native AMP set precision=16
config.trainer.precision = 16 if torch.cuda.is_available() else 32
# remove distributed training flags
config.trainer.accelerator = None
trainer = pl.Trainer(**config.trainer)
# -
# ## Setting up a NeMo Experiment
#
# NeMo has an experiment manager that handles logging and checkpointing for us, so let's use it:
# +
exp_dir = exp_manager(trainer, config.get("exp_manager", None))
# the exp_dir provides a path to the current experiment for easy access
exp_dir = str(exp_dir)
exp_dir
# +
# complete list of supported BERT-like models
print(nemo_nlp.modules.get_pretrained_lm_models_list())
# specify BERT-like model, you want to use
PRETRAINED_BERT_MODEL = "biomegatron-bert-345m-cased"
# -
# add the specified above model parameters to the config
config.model.language_model.pretrained_model_name = PRETRAINED_BERT_MODEL
# Now, we are ready to initialize our model. During the model initialization call, the dataset and data loaders we'll be prepared for training and evaluation.
# Also, the pretrained BERT model will be downloaded, note it can take up to a few minutes depending on the size of the chosen BERT model.
model_ner = nemo_nlp.models.TokenClassificationModel(cfg=config.model, trainer=trainer)
# ## Monitoring training progress
# Optionally, you can create a Tensorboard visualization to monitor training progress.
# If you're not using Colab, refer to [https://www.tensorflow.org/tensorboard/tensorboard_in_notebooks](https://www.tensorflow.org/tensorboard/tensorboard_in_notebooks) if you're facing issues with running the cell below.
# +
try:
from google import colab
COLAB_ENV = True
except (ImportError, ModuleNotFoundError):
COLAB_ENV = False
# Load the TensorBoard notebook extension
if COLAB_ENV:
# %load_ext tensorboard
# %tensorboard --logdir {exp_dir}
else:
print("To use tensorboard, please use this notebook in a Google Colab environment.")
# -
# start model training
trainer.fit(model_ner)
# # Inference
#
# To see how the model performs, we can run generate prediction similar to the way we did it earlier
# let's first create a subset of our dev data
# ! head -n 100 $NER_DATA_DIR/text_dev.txt > $NER_DATA_DIR/sample_text_dev.txt
# ! head -n 100 $NER_DATA_DIR/labels_dev.txt > $NER_DATA_DIR/sample_labels_dev.txt
# Now, let's generate predictions for the provided text file.
# If labels file is also specified, the model will evaluate the predictions and plot confusion matrix.
model_ner.evaluate_from_file(
text_file=os.path.join(NER_DATA_DIR, 'sample_text_dev.txt'),
labels_file=os.path.join(NER_DATA_DIR, 'sample_labels_dev.txt'),
output_dir=exp_dir,
add_confusion_matrix=False,
normalize_confusion_matrix=True,
batch_size=1
)
# Please check matplotlib version if encountering any error plotting confusion matrix:
# https://stackoverflow.com/questions/63212347/importerror-cannot-import-name-png-from-matplotlib
# ## Training Script
#
# If you have NeMo installed locally, you can also train the model with `nlp/token_classification/token_classification_train.py.`
#
# To run training script, use:
#
# `python token_classification_train.py model.dataset.data_dir=PATH_TO_DATA_DIR PRETRAINED_BERT_MODEL=biomegatron-bert-345m-cased`
# The training could take several minutes and the result should look something like
# ```
# [NeMo I 2020-05-22 17:13:48 token_classification_callback:82] Accuracy: 0.9882348032875798
# [NeMo I 2020-05-22 17:13:48 token_classification_callback:86] F1 weighted: 98.82
# [NeMo I 2020-05-22 17:13:48 token_classification_callback:86] F1 macro: 93.74
# [NeMo I 2020-05-22 17:13:48 token_classification_callback:86] F1 micro: 98.82
# [NeMo I 2020-05-22 17:13:49 token_classification_callback:89] precision recall f1-score support
#
# O (label id: 0) 0.9938 0.9957 0.9947 22092
# B (label id: 1) 0.8843 0.9034 0.8938 787
# I (label id: 2) 0.9505 0.8982 0.9236 1090
#
# accuracy 0.9882 23969
# macro avg 0.9429 0.9324 0.9374 23969
# weighted avg 0.9882 0.9882 0.9882 23969
# ```
| tutorials/nlp/Token_Classification-BioMegatron.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
from sklearn.datasets import make_blobs
X, y= make_blobs(centers=2)
from sklearn.preprocessing import MinMaxScaler
mmsX = MinMaxScaler()
mmsY = MinMaxScaler()
x = mmsX.fit_transform(X)
Y = mmsY.fit_transform(y.reshape(-1, 1))
def optimize(X, y, epochs, rate):
w = np.random.random((X.shape[1], 1))
b = np.random.randn(1)[0]
for i in range(epochs):
z = np.dot(X, w) + b
a = sigmoid(z)
j = -((np.dot(y.T , np.log(a)) + np.dot((1 - y).T ,np.log(1 - a))))/len(y)
df = (a - y.reshape((100 ,1)))
err = np.sum(df)/len(y)
w = w - rate*np.dot(X.T, df)
b = b - rate*sum(df)
print("Loss: " , j)
return w , b
w , b = optimize(x, Y, 5000 ,0.05)
def sigmoid(X):
return 1/(1 + np.exp(-X))
w
x[0]
sigmoid(np.dot(x[3] , w) + b)
y[3]
| Logistic_Regression/Logistic_Regression - Vectorization.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %matplotlib notebook
#dependencies
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# +
mouse_df = pd.read_csv('/Users/edwardkohn/Desktop/mouse_drug_data.csv')
clinical_df = pd.read_csv('/Users/edwardkohn/Desktop/clinicaltrial_data.csv')
#merged table
mouse_clinical_comb = pd.merge(clinical_df,mouse_df,on='Mouse ID',how='left')
#rename columns for easy access
mouse_clinical_comb_df = mouse_clinical_comb.rename(columns={'Mouse ID':'Mouse_ID','Tumor Volume (mm3)':'Tumor_Volume_mm3',
'Metastatic Sites':'Metastatic_Sites'})
# -
# # Tumor Response to Treatment
#select only columns we want for this graph
tumor_response_df = mouse_clinical_comb_df[['Drug', 'Timepoint', 'Tumor_Volume_mm3']]
#filter only by drugs we want to use
tumor_response_df_select=tumor_response_df.loc[tumor_response_df['Drug'].isin(['Capomulin','Infubinol','Ketapril','Placebo'])]
# +
#create pivot tables and apply the mean to tumor volume values
mean_values = pd.pivot_table(tumor_response_df_select,index='Timepoint',columns='Drug',values='Tumor_Volume_mm3',aggfunc='mean')
print(mean_values)
#apply sem to each of the drugs in the pivot table to then use them in the graph as error bars data.
capomulin_sem = mean_values['Capomulin'].sem()
infubinol_sem = mean_values['Infubinol'].sem()
ketapril_sem = mean_values['Ketapril'].sem()
placebo_sem = mean_values['Placebo'].sem()
print(capomulin_sem,infubinol_sem,ketapril_sem,placebo_sem)
# +
#plot with errors graph
fig,ax = plt.subplots()
ax.errorbar(mean_values.index,mean_values['Capomulin'],yerr=capomulin_sem,label='Capomulin',marker='d',linestyle='-.',markersize=5,capsize=5)
ax.errorbar(mean_values.index,mean_values['Infubinol'],yerr=infubinol_sem,label='Infubinol',marker='.',linestyle=':',markersize=8,capsize=5)
ax.errorbar(mean_values.index,mean_values['Ketapril'],yerr=ketapril_sem,label='Ketapril',marker='.',linestyle='-.',markersize=8,capsize=5)
ax.errorbar(mean_values.index,mean_values['Placebo'],yerr=placebo_sem,label='Placebo',marker='d',linestyle=':',markersize=5,capsize=5)
ax.legend(loc='best')
ax.set_xlim(-0.5, 50)
ax.set_ylim(30, 75)
ax.set_xlabel('Time (Days)')
ax.set_ylabel('Tumor Volume (mm3)')
ax.grid(alpha=0.25)
plt.title('Tumor Volume Response to Treatment')
plt.show()
fig.savefig("Figure1.png")
# -
# # Metastatic Response to Treatment
# +
metastatic_response_df = mouse_clinical_comb_df[['Drug', 'Timepoint','Metastatic_Sites']]
metastatic_response_df.head()
# +
#filter only by drugs we want to use
metastatic_response_df_select = metastatic_response_df[metastatic_response_df['Drug'].isin(['Capomulin','Infubinol','Ketapril','Placebo'])]
#create pivot tables and apply the mean to metastatic values
metastic_mean_values = pd.pivot_table(metastatic_response_df_select,index='Timepoint',columns='Drug',values='Metastatic_Sites',aggfunc='mean')
#apply sem to each of the drugs in the pivot table to then use them in the graph as error bars data.
metastic_capomulin_sem = metastic_mean_values['Capomulin'].sem()
metastic_infubinol_sem = metastic_mean_values['Infubinol'].sem()
metastic_ketapril_sem = metastic_mean_values['Ketapril'].sem()
metastic_placebo_sem = metastic_mean_values['Placebo'].sem()
metastic_mean_values
# +
#plot with errors graph
fig2,ax2 = plt.subplots()
ax2.errorbar(metastic_mean_values.index,metastic_mean_values['Capomulin'],yerr=metastic_capomulin_sem,label='Capomulin',marker='d',linestyle='--',markersize=4,capsize=1)
ax2.errorbar(metastic_mean_values.index,metastic_mean_values['Infubinol'],yerr=metastic_infubinol_sem,label='Infubinol',marker='o',linestyle='dashdot',markersize=4,capsize=5)
ax2.errorbar(metastic_mean_values.index,metastic_mean_values['Ketapril'],yerr=metastic_ketapril_sem,label='Ketapril',marker='d',linestyle=':',markersize=4,capsize=3)
ax2.errorbar(metastic_mean_values.index,metastic_mean_values['Placebo'],yerr=metastic_placebo_sem,label='Placebo',marker='o',linestyle='--',markersize=4,capsize=7)
ax2.legend(loc='best')
ax2.grid(alpha=0.25)
ax2.set_xlabel('Time (Days)')
ax2.set_ylabel('Metastatic Sites')
plt.title(' Metastatic Response to Treatment')
plt.show()
fig2.savefig("Figure2.png")
# -
# # Survival Rates For Each Treatment
# Survival Rates
mouse_sr_df = mouse_clinical_comb_df[['Drug', 'Timepoint', 'Mouse_ID']]
#filter only by drugs we want to use
mouse_sr_drugs_select_df = mouse_sr_df[mouse_sr_df['Drug'].isin(['Capomulin','Infubinol','Ketapril','Placebo'])]
# +
#create pivot tables and apply count to mouse_id
mouse_sr_pivot_df = pd.pivot_table(mouse_sr_drugs_select_df,index='Timepoint',columns='Drug',values='Mouse_ID',aggfunc='count')
#add percentages columns
mouse_sr_pivot_df['Capomulin_percent']=mouse_sr_pivot_df['Capomulin']/mouse_sr_pivot_df['Capomulin'].iloc[0] *100
mouse_sr_pivot_df['Infubinol_percent']= mouse_sr_pivot_df['Infubinol']/mouse_sr_pivot_df['Infubinol'].iloc[0] *100
mouse_sr_pivot_df['Ketapril_percent']= mouse_sr_pivot_df['Ketapril']/mouse_sr_pivot_df['Ketapril'].iloc[0] *100
mouse_sr_pivot_df['Placebo_percent']= mouse_sr_pivot_df['Placebo']/mouse_sr_pivot_df['Placebo'].iloc[0] *100
mouse_sr_pivot_df
# +
fig3,ax3 = plt.subplots()
ax3.plot(mouse_sr_pivot_df.index,mouse_sr_pivot_df['Capomulin_percent'],label='Capomulin_percent',marker='d',linestyle='-.',markersize=5)
ax3.plot(mouse_sr_pivot_df.index,mouse_sr_pivot_df['Infubinol_percent'],label='Infubinol_percent',marker='.',linestyle=':',markersize=8)
ax3.plot(mouse_sr_pivot_df.index,mouse_sr_pivot_df['Ketapril_percent'],label='Ketapril_percent',marker='.',linestyle='-.',markersize=8)
ax3.plot(mouse_sr_pivot_df.index,mouse_sr_pivot_df['Placebo_percent'],label='Placebo_percent',marker='d',linestyle=':',markersize=5)
ax3.legend(loc='best')
ax3.set_xlabel('Time (Days)')
ax3.set_ylabel('Survival Rates Percent(%)')
ax3.grid(alpha=0.25)
plt.title('Survival Rate For Each Treatment')
plt.show()
fig3.savefig("Figure3.png")
# -
# # bar graph that compares the total % tumor volume change for each drug across the full 45 days
#
# +
bar_graphdata_df = mouse_clinical_comb_df[['Drug', 'Timepoint', 'Tumor_Volume_mm3']]
#filter only by drugs we want to use
bar_graphdata_df_select = bar_graphdata_df[bar_graphdata_df['Drug'].isin(['Capomulin','Infubinol','Ketapril','Placebo'])]
bar_graphdata_df_pivot = pd.pivot_table(bar_graphdata_df_select,index='Timepoint',columns='Drug',values='Tumor_Volume_mm3')
bar_graphdata_df_pivot
# +
list_of_percentage_change = []
for key,value in bar_graphdata_df_pivot.items():
percent_changes_to_append=round((value.iloc[9] - value.iloc[0])/value.iloc[0]*100,6)
list_of_percentage_change.append(percent_changes_to_append)
percentage_change_volume = {'Capomulin':list_of_percentage_change[0],'Infubinol':list_of_percentage_change[1],
'Ketapril':list_of_percentage_change[2],'Placebo':list_of_percentage_change[3]}
percentage_change_volume=pd.Series(percentage_change_volume)
percentage_change_volume
# +
fig5,ax5 = plt.subplots(figsize=(4,4))
x_axis = np.arange(len(list_of_percentage_change))
labels = percentage_change_volume.keys()
y_axis = list_of_percentage_change
xticks = [value for value in range(len(list_of_percentage_change))]
plt.xticks(xticks,labels)
colors = []
for value in list_of_percentage_change:
if value >= 0:
colors.append('g')
else:
colors.append('r')
texts = [list_of_percentage_change]
ax5.bar(x_axis,y_axis,label=labels,color=colors,width=0.5)
plt.grid(alpha=0.30)
plt.title("Tumor Volume Change Over 45 Days (%)")
plt.xlabel("Drug Name")
plt.ylabel("Tumor Volume Change (%)")
plt.tight_layout()
plt.show()
fig5.savefig("Figure5.png")
# -
# # Conclusions:
# +
1) After analyzing the data between the drugs applied to the mice in the study (Capomulin, Infubinol, Ketapril and Placebo). It can be concluded that the most effective drug is the Capomulin which was the only drug to reduce the volume of the tumor from 45(mm3) to ~36.2(mm3) accounting for ~ 19.5% reduction during the 45-day trial. Also, out all of the drugs it also had the lowest standard deviation giving us the most reliable result. On the other hand, Ketrapril was the least effective drug increasing the tumor size by ~57% and also had the highest standard deviation.
2) All of the drugs had metastic sites increase. However, Capoulim was the most effective had the lowest metastic spread while Ketapril and Placebo had the highest spread.
3) In the survival rate graph, we see that Capomulin has the highest rate of survival specially during the first days of the trial. Over the long rung specially after day 15 we can observe that is when the survival rate starts to slump. Another particular observation is that Infubinol survival rate is in line with Capomulin during the first 5 days then the drug has the sharpest decline out all of the drugs.
Final Thoughts:
Out of the study made the most effective drug is the Capomulin since it was the only drug that reduced the volume of the tumor, prevented a larger spread of the metastic sites and had the highest survival rate during the 45-day trial.
| Pymaceuticals/matplotlib hm .ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: finance
# language: python
# name: finance
# ---
# # NIR photography for snowpit (Finse)
#
# Assess usability of NIR photography for extracting SSA from NIR images taken from the Sony QX1/2.8 - 20mm pancake lens
#
# See the paper by [<NAME> Schneebeli 2016](https://www.cambridge.org/core/journals/journal-of-glaciology/article/measuring-specific-surface-area-of-snow-by-nearinfrared-photography/C99FD080CFF5CC76EF77E5C85E4731AC) for more info
#
# A calibration profile was derived from the camera with Micmac. This calibration profile is for correcting vigneting.
#
# 1. correct image for vignetting (calib profile is of the size of Raw images. Crop from center to use with jpegs
# 2. detrend if needed the luminosity, as it can vary linearly from top to bottom of the snowpit
# 3. sample targets for absolute reflectance calibration (white= 99%, and grey=50%). Fit a linear model $r=a+bi$, with $r$ being the reflectance, and $i$ the pixel intensity.
# 4. Convert reflectance image to SSA with the conversion equation $SSA = Ae^{r/t}$ with $A=0.017 mm^{-1}$ and $t=12.222$. An optical diameter image can also be computed with: $d=6/SSA$ (d in mm).
# 5. Finally, use the ruler (or other object of know size) in image to scale image dimension to metric system.
#
#
# TODO:
# - write functions for all steps
# - wrap all in a python package/class
# - write function to extract profiles, and maybe later identify layers using reflectance/SSA, and contrast enhanced image
# - write function to extract SSA profile to import in [niviz.org](www.niviz.org)
# - include class to compute
#
# - Raw images are in 12 bit. Find a way to convert to BW from original while maintaining the 12bit resolution. [Rawpy](https://github.com/letmaik/rawpy) might be useful. Then make sure the processing pipeline can accept 12bit data (*i.e.* all skimage functions)
# - wrap micmac function to extract profile 'mm3d vodka'. At least provide the method on how to do it.
#
import skimage as sk
import matplotlib.pyplot as plt
import numpy as np
# +
fname = '/home/arcticsnow/github/nirpy/data/DSC01343.JPG'
fname_calib = '/home/arcticsnow/github/nirpy/data/SONY_QX1_SONY_28_20mm.tif'
img = sk.io.imread(fname)
calib = sk.io.imread(fname_calib).T
img_v = sk.color.rgb2hsv(img)[:,:,2]
# Crop calib profile, using center of matrix as cropping reference
def crop_center(img,crop_shape):
y,x = img.shape
startx = x//2 - crop_shape[1]//2
starty = y//2 - crop_shape[0]//2
return img[starty:starty+crop_shape[0], startx:startx+crop_shape[1]]
calib = crop_center(calib, img_v.shape)
# -
# #%matplotlib
fig, axs = plt.subplots(1,2,sharex=True, sharey=True)
axs[0].imshow(img_v)
axs[1].imshow(img_v*calib)
# +
# Compute linear trend of luminosty from top to bottom
means = np.mean(img_v*calib, axis=1)
trend = np.polyfit(np.arange(0,means.shape[0]),means,1)
trendpoly = np.poly1d(trend)
# +
# Compute corrected and detrended image
img_cor = img_v*calib- np.repeat(trendpoly(np.arange(0,means.shape[0])),img_v.shape[1], axis=0).reshape(img_v.shape)
fig, axs = plt.subplots(1,1, sharey=True)
axs.imshow(img_cor)
axs.plot([2000,2000], [0, img_v.shape[0]], 'k')
axs.plot(img_cor[:,2000]*5000+2000, np.arange(0,img_v.shape[0]), 'r')
plt.grid(linestyle=':', c='k')
# +
# Show possibility to use contrast enhancement for visualization purpose
img_eq = sk.exposure.equalize_hist(img_cor)
fig, axs = plt.subplots(1,1, sharey=True)
axs.imshow(img_eq)
axs.plot([2000,2000], [0, img_v.shape[0]], 'k')
axs.plot(img_eq[:,2000]*1000+1000, np.arange(0,img_v.shape[0]), 'r')
plt.grid(linestyle=':', c='k')
# -
# ## Calibrate Vignetting Method with Micmac
#
# Micmac method to remove vignetting from an image. This calibration process provides a matrix of the size of the camera sensor, that is used by element-wise multiplication with the images. The calibration is camera/lens/focal lens dependend.
#
# 1. take multiple images of a none shiny surface in diffuse light
# 2. find tie points of with tapioca
# ```
# mm3d Tapioca All .*ARW 2750
# ```
# 3. compute calibration matrix with vodka
# ```
# mm3d Vodka .*ARW
# ```
# 4. If you want to apply the calibration directly:
# ```
# mm3d Vodka .*ARW DoCor=1
# ```
#
| SSA_retrieval.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
# ---
# +
# 워드 파일에 뉴스 내용을 복사
# 파일을 html.htm 으로 저장
# safelink를 제거하기 위해 아래 수행
# 생성된 result 파일 열고 복붙
from urllib.parse import unquote
filename = 'html.htm'
res_name = 'result.htm'
pattern = 'nam06.safelinks.protection.outlook.com'
matching_lines = []
def replace_str(line):
left_str = line.split("?url=",1)[1]
right_str = left_str.split("&data=",1)[0]
url = unquote(right_str)
print(url)
return url
# -
lst = []
for line in open(filename).readlines():
if pattern in line:
lst.append(line)
lst
# +
text_file = open(filename, "r")
fin = text_file.read()
fin
# +
fileout = open(res_name, "wt")
for line in lst:
left_str = line.split("?url=",1)[1]
right_str = left_str.split("&data=",1)[0]
url = unquote(right_str)
fin = fin.replace(line, 'href="' + url + '"')
fileout.write(fin)
fileout.close()
# -
| ebadak_news.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
# ---
# # Normalização com percentil
#
# ## Definição da função a ser feita e testada
#
# Escrever um programa que faça a normalização dos pixels da imagem ``f`` para a faixa ``[0, 255]``, porém com um
# parâmetro de percentil indicando qual valor mínimo e máximo de ``f`` que será normalizado dentro da faixa. O percentil
# é um valor de percentagem variando de 0 a 100. Um percentil de valor ``p`` é o nível de cinza ``v`` em que existem ``p`` porcento
# de pixels de valor menor que ``v``.
#
# A função portanto deve ter o seguinte comportamento, dado imagem ``f`` e percentil ``p``:
#
# - pixels com nível de cinza abaixo do valor de pixel dado pelo percentil ``p`` são atribuídos o valor 0;
# - pixels com nível de cinza acima do valor de pixel dado pelo percentil ``100 - p`` são atribuídos valor 255;
# - demais pixels são normalizados linearmente entre os valores 0 e 255.
#
# A função de normalização sem percentil está implementada em
#
# - [ia898:normalize](../src/normalize.ipynb)
#
# A proposta aqui é fazer outra função de
# normalização com a opção do parâmetro adicional ``p`` percentil. A vantagem desta função é que se consegue melhorar o
# contraste da imagem passando um valor de ``p``, o que não é possível de se fazer com a função ``normalize``.
#
# ## Referências:
#
# - [Percentil](http://pt.wikipedia.org/wiki/Percentil Wikipedia)
# - [NumPy:percentile](http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.percentile.html)
# - [ia898:percentile] Cálculo do percentil a partir da imagem (**ainda não está feita**)
# - [ia636:h2percentile](../src/h2percentile.ipynb) Cálculo do percentil a partir do histograma da imagem
# ## Implementação das funções
#
# Implemente aqui as suas funções:
def nperc_clip(f, p):
# coloque a sua solução editando esta parte
import numpy as np
return f
# ### Testando as funções
# ### Caso numérico
# ### Com imagens
| deliver/Normalizacao_com_percentil.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=Mathematics/OrderOfOperations/order-of-operations.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>
from IPython.display import HTML
hide_me = ''
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show) {
$('div.input').each(function(id) {
el = $(this).find('.cm-variable:first');
if (id == 0 || el.text() == 'hide_me') {
$(this).hide();
}
});
$('div.output_prompt').css('opacity', 0);
} else {
$('div.input').each(function(id) {
$(this).show();
});
$('div.output_prompt').css('opacity', 1);
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input style="opacity:1" type="submit" value="Click here to show the code."></form>''')
# # Order of Operations
#
# #### Grade 9 curriculum
#
# A Jupyter notebook to explore order of operations conventions for arithmetic operations.
# ## Introduction
#
# In elementary mathematics, we have two basic operations: addition and multiplication. Each of these operations comes with an "opposite" (or, as a mathematician might say, an *inverse*) operation. The opposite of addition is subtraction, and the opposite of multiplication is division.
#
# When there is a single operation to perform, we all know what to do, including the computer. For example, we could have the computer calculate the sum $3+7$ or the product $9\times 3$:
3+7
9*3
# If you want to type your expressions into an input box, the operators are:
# * Brackets: `(` and `)`
# * Exponents: `**`
# * Division: `/`
# * Multiplication: `*`
# * Addition: `+`
# * Subtraction: `-`
# **Note:** all code in Jupyter is *live*, and *editable*. Feel free to go back to the last two lines and change the numbers. To get the computer to do the calculation, press `Shift`+`Enter` on your keyboard.
#
# If we wanted to undo either the addition or the multiplication, we can use their opposites:
10-7
27/3
# *You might be wondering why there is a decimal in the last output. Whenever the computer does division, it uses [floating point arithmetic](https://en.wikipedia.org/wiki/Floating-point_arithmetic), and it is allowing for the fact that division doesn't always return a whole number.*
#
#
# Now, if we need to add up a whole bunch of numbers (or multiply them), we don't have to worry about doing it wrong, thanks to a property of arithmetic called **associativity**. Basically, it means if we want to compute a sum like $5+9+7$, it doesn't matter if we first do $5+9$, and then add 7, or if we do $9+7$ and then add 5. In other words, it doesn't matter if we first *associate* 5 with 9, or *associate* 9 with 7—both ways give us the same result. (Because of this, we say addition is *associative*.) To distinguish between the two associations, we use parentheses like this:
#
# $$(5+9)+7 = 5+(9+7)$$
#
# In mathematics, using brackets (or parentheses) is a way of saying, "Do this first!"
#
# Go ahead and try this for yourself. Then, let the computer confirm it for you. We've entered the left-hand side of the above equality for you. To try the right-hand side, click on the $+$ sign in the tool bar at the top to add a new cell. Type in the right-hand side yourself, and press `Shift`+`Enter` to confirm the result.
(5+9)+7
# The same thing works for multiplication. For example, $(2\cdot 4)\cdot 5 = 40 = 2\cdot (4\cdot 5)$. And of course, as well as being able to put brackets wherever we want, we can also change the order of the numbers without affecting the answer.
#
# Things get more complicated if we want to do both addition and multiplication in a single calculation, or if we want to bring subtraction or division into the picture. Consider this expression:
#
# $$3+7\times 4$$
#
# Which operation should we do first? The addition, or the multiplication? Or does it matter? Let's try both ways using parentheses; as noted above, any operation in parentheses is always done first. We see the results in the two cells below:
(3+7)*4
3+(7*4)
# Interesting! Order *doesn't* matter when there's only addition or only multiplication involved, but as soon as we combine the two, the order (and hence, the placement of brackets) *does* make a difference.
#
# ## Exercise
#
# Does order matter for subtraction or division? Let's see by using brackets again. In the code cells below, try a few examples to see what happens. We've done a couple for you to show you how they're written. Note that you can do more than one calculation in a cell by using a comma to separate them.
(10-3)-5, 10-(3-5)
(12/6)/2, 12/(6/2)
# ## The Problem
#
# How do we (or a computer) figure out the answer to a really complicated expression like this?
#
# $$8 + 5/3^{2} \times (7 - 4)/(6 + 9)$$
#
# The answer is the same for both humans and computers: we need to
#
# 1. Break the problem down into simpler steps, and
# 2. Determine the order in which those steps should be performed.
#
# We know what the simpler steps should be; these are the individual arithmetic operations. How do we determine the order? The short answer is that there is an agreed-upon convention. In other words, everybody agrees to do operations in the same order so that they always get the same answer. This order is called (conveniently) the **order of operations**.
#
# ### The Order of Operations is:
#
# * **B**rackets
# * **E**xponents
# * **D**ivision
# * **M**ultiplication
# * **A**ddition
# * **S**ubtraction
#
# This is commonly remembered by the acronym **BEDMAS**, or **PEMDAS** (if we use the word "parentheses" instead of "brackets") or even **BODMAS** (if we use "orders" instead of "exponents"). Some people remember this order by the phrase **P**lease **E**xcuse **M**y **D**ear **A**unt **S**ally.
#
# *Did you notice? the **D** and **M** in **PEMDAS** are switched around! Doesn't that change things? (The answer is coming up!)*
#
# Here's a way to visualize the order of operations. Higher operations are done first.
#
# 
# #### What happens if there are multiple operations on the same level of the pyramid?
#
# This means they have the same amount of importance, and so they're treated as if they were the same operation. (Technically, it means they *are* the same operation—ask your teacher why!) In other words, we do **m**ultiplication and **d**ivision at the same time, left-to-right, then we do **a**ddition and **s**ubtraction at the same time, left-to-right.
# ### But why do we have the order of operations? And why not a different order?
#
# The short answer is because all operations boil down to addition and subtraction. It's true: exponents are repeated multiplication, and multiplication itself is repeated addition. So we want to do the most complex operations first before moving on to the simpler ones. Brackets are used to show associations that might break this order, which is why they must be done first.
#
# The long answer can be found here: http://mathforum.org/library/drmath/view/52582.html
# Let's try a simple calculation with two operations. If we want to explicitly tell the computer which operation to perform first, we can use brackets. First, we try doing the addition first:
(3 + 5) * 6
# Next, let's see what we get if we do the multiplication first:
3 + (5 * 6)
# Finally, let's input the expression without any brackets, and let the computer take care of the order.
3 + 5 * 6
# What was the result? Did it match either of the calcuations above it? Based on this example, does it appear as though the computer is following the order of operations?
#
# *******
# Are all computer programs created equal? Here are two calculators, from the same company, with the same input, but different outputs! Based on the BEDMAS order, which answer is right?
#
# *Note: 2(2+1) is the same as 2x(2+1), it's just a different way to write it.*<br>
#
# <div style="width: 300px;"> <img src="https://saravanderwerf.com/wp-content/uploads/2018/04/order-of-operations-on-calc.jpg"></div>
#
# Can you figure out how to add additional brackets to reproduce each result?
# ## Example
#
# How do we evaluate the expression $2^3 \times (4 + 8)$?
#
# ### Solution
#
# Here is a step-by-step walk-through of the calculation:
#
# $$\begin{align*}
# 2^3 \times \mathbf{(4+8)} & = 2^3\times 12 \tag{Brackets first!}\\
# \mathbf{2^3}\times 12 & = 8\times 12 \tag{Exponents come next}\\
# \mathbf{8\times 12} & = 96 \tag{Finally, the multiplication}
# \end{align*}$$
#
# On the computer, we expect the following steps to be carried out:
#
# >2^3 $\times$ **(4 $+$ 8)**
# >
# >**2^3** $\times$ 12
# >
# > **8 $\times$ 12**
# >
# > 96
# Let's check to see if it works:
2**3 * (4 + 8)
# Want to see another example? Watch this and try to solve it before they get to the solution!
# + tags=["hide-input"] active=""
# hide_me
#
# from IPython.display import HTML
#
# # Youtube
# HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/Y3CZ_JBQ0do?rel=0&start=17" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>')
# + tags=["hide-input"] language="html"
# <iframe width="560" height="315" src="https://www.youtube.com/embed/Y3CZ_JBQ0do?rel=0&start=17" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
# -
# *****
#
# ### Mixing things up
#
# Let's start with a number and 3 operations that can be applied to the number:
#
# >5
# >
# >_ `x` 4
# >
# >_ `+` 7
# >
# >_ `^` 2
# Let's say we want to do the addition, then the exponent, then the multiplication. What's the answer?
#
# 5 + 7 = <font color='green'>12</font>
# <font color='green'>12</font>^2 = <font color='blue'>144</font>
# <font color='blue'>144</font> x 4 = 576
#
# The answer is 576. But if we type the same series of operations into the computer, what do we get?
5+7**2*4
# That's not what we want! But we shouldn't expect it to be: order of operations requires that the addition be performed last, not first!
#
# ### Exercise:
# Re-enter the above expression in the cell below, and then add brackets as needed to get the correct order of operations. Be sure that your output matches the correct answer!
# What output do we get by doing the exponent, then the addition, then the mulitplication?
#
# 5^2 = <font color='green'>25</font>
# <font color='green'>25</font> + 7 = <font color='blue'>32</font>
# <font color='blue'>32</font> x 4 = 128
#
# How can we write these expressions in one line to get this output?
# Were you able to get 128 as your answer? Again, we see that the brackets are necessary. If we leave them out, then the computer follows the order of operations convention, and we get:
5**2+7*4
# Can you think of another order to write these operations in that gives a different output?
# *********
#
# ### Practice Questions
# ### Try solving this:
# + tags=["hide-input"]
hide_me
import ipywidgets as widgets
import IPython
answer = widgets.FloatText(value = 0, description='Your Answer')
op1 = widgets.Dropdown(value='', options={'Addition', 'Multiplication', 'Division', 'Brackets',''},
style={'description_width': 'initial'}, description='First Operation:',)
op2 = widgets.Dropdown(value='', options={'Addition', 'Multiplication', 'Division',''},
style={'description_width': 'initial'}, description='Second Operation:',)
op3 = widgets.Dropdown(value='', options={'Addition', 'Division',''},
style={'description_width': 'initial'}, description='Third Operation:',)
def display():
print("Solve 7 * (9 - 4)/2 + 3 using the order of operations and write your answer below:")
IPython.display.display(answer)
def check2(b):
if op1.value =='':
pass
if op1.value == 'Brackets':
print("Great! What did you do next?")
IPython.display.display(op2)
else:
print("Remember the B in BEDMAS is for brackets, try the question again.")
def check3(c):
if op2.value == '':
pass
if op2.value == 'Multiplication':
print("Awesome! What did you do next?")
IPython.display.display(op3)
else:
print("Remember division and multiplication are done left to right when there's no brackets and before addition and subtraction.\nTry the question again.")
def check4(d):
if op3.value == '':
pass
if op3.value == 'Division':
print("Well done! If you did not get 20.5, it must have been a calculation error, try each step again.")
else:
print("Remember division and multiplication are done before addition and subtraction, try the question again.")
def check(a):
op1.value = ''
op2.value = ''
op3.value = ''
IPython.display.clear_output(wait=False)
display()
if answer.value == 20.5:
print("You are correct!")
else:
print("Sorry, that's not the right answer. Which operation did you do first?")
IPython.display.display(op1)
display()
answer.observe(check, 'value')
op1.observe(check2, 'value')
op2.observe(check3, 'value')
op3.observe(check4, 'value')
# -
# ### A few more questions
# + tags=["hide-input"]
hide_me
import ipywidgets as widgets
import IPython
# + tags=["hide-input"]
hide_me
choice = widgets.Dropdown(
options={'Easy', 'Medium', 'Hard'},
description='Difficulty:',
)
Start = widgets.Button(description = "Start")
ans = widgets.Button(description = "Answer")
def reveal(choice):
click = False
if choice=='Easy':
print("2*5+3")
print("10+3")
print("13")
else:
if choice=='Medium':
print("(1+6)*5+3")
print("(7)*5+3")
print("35+3")
print("38")
else:
print("(4^2-2)/2*3^2")
print("(16-2)/2*3^2")
print("(14)/2*3^2")
print("(14)/2*9")
print("7*9")
print("63")
def create(choice):
#click = True
if choice=='Easy':
print("2*5+3")
else:
if choice=='Medium':
print("(1+6)*5+3")
else:
print("(4^2-2)/2*3^2")
def on_button(a):
IPython.display.clear_output(wait=False)
IPython.display.display(choice, Start, ans)
reveal(choice.value)
def display2(b):
IPython.display.clear_output(wait=False)
IPython.display.display(choice, Start)
create(choice.value)
IPython.display.display(ans)
ans.on_click(on_button)
IPython.display.display(choice, Start)
Start.on_click(display2)
# -
# ### Back to our first Problem
#
# Now that you have some examples under your belt, let's go back to the hard expression we saw earlier:
#
# $$8 + 5/3^{2} \times (7 - 4)/(6 + 9)$$
#
# What part of this problem do we do first?
#
# Can you write all the steps to solve this problem in order?
#
# What was your final answer?
# ## What did we learn?
# In this notebook, we learned:
#
# * There is a logical order to the operations
# * The order is:
# * **B**rackets
# * **E**xponents
# * **D**ivision
# * **M**ultiplication
# * **A**ddition
# * **S**ubtraction
# * Division and multiplication have the same priority
# * Addition and subtraction do too
# [](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
| _build/jupyter_execute/curriculum-notebooks/Mathematics/OrderOfOperations/order-of-operations.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.7.2
# language: julia
# name: julia-1.7
# ---
# # IMEC2201 Herramientas Computacionales
# ## Semana 2: Gráficas y Visualizaciones
# ### Clase 4: Ajuste de Datos e Incertidumbre
#
# Universidad de los Andes — Abril 6, 2022.
#
# ---
#
# ## TABLA DE CONTENIDO
#
# ### Sección 1: Ajuste de Datos (Regresión OLS) [→](#section1)
# - 1.1. Cargar Librerías
# - 1.2. Mínimos Cuadrados Ordinarios (OLS)
# - 1.2.1. Gráfica MBHP vs Masa
# - 1.2.2. Ajuste Lineal
# - 1.2.3. Coeficiente de Correlación
# - 1.2.4. Caso Práctico
# - 1.3. Histogramas
#
# ### Sección 2: Incertidumbre [→](#section2)
# - 2.1. Error Aleatorio
# - 2.2. Barras de Error
# - 2.3. Librería Measurements.jl
# - 2.3.1. Barras de Error
# - 2.3.2. Propagación de Error
# ___
# **¡Importante!** Note que la carpeta **week2** contiene dos archivos: `Project.toml` y `Manifest.toml`. Estos configuran el <font color="#FF5733">*ambiente de trabajo*</font> y facilitan el manejo de <font color="#FF5733">librerías</font>.
#
# Para inicializar el ambiente desde Julia REPL, dentro de la carpeta **week2**, ejecute lo siguiente:
#
# ```shell
# $ (v1.7) pkg > activate .
# $ (week2) pkg> instantiate
# ```
#
# **Nota:** Para acceder al Pkg REPL, escriba el corchete derecho `]` en el Julia REPL. Note que el REPL cambie de color de verde (Julia REPL) a azul (Pkg REPL). Una vez ejecutado el código `activate .`, el prefijo entre paréntesis indica el ambiente activo: cambia de `v1.7` a `week2`.
#
# O, desde Jupyter Notebook, ejecute:
#
# ```julia
# $ using Pkg
# $ Pkg.activate()
# $ Pkg.instantiate()
# ```
#
# **Nota:** La activación del ambiente <font color="#FF5733">*precompila*</font> las librerías por lo que puede tardar un momento su ejecución completa.
#
# <div class="alert alert-block alert-info">
#
# <i class="fa fa-info-circle" aria-hidden="true"></i>
# Puede obtener más información en la documentación oficial de la librería [`Pkg.jl`](https://pkgdocs.julialang.org/v1/environments/) y en el documento dando clic [aquí](https://towardsdatascience.com/how-to-setup-project-environments-in-julia-ec8ae73afe9c).
# </div>
using Pkg
Pkg.activate(pwd())
Pkg.instantiate()
Pkg.status()
# <a id="section1"></a>
# # Sección 1: Ajuste de Datos (Regresión OLS)
# ## 1.1. Cargar Librerías
import CSV
import XLSX
import Plots
import Statistics
import DataFrames
import LinearAlgebra
# ## 1.2. Mínimos Cuadrados Ordinarios (OLS)
#
# Un ajuste (o <font color="#FF5733">regresión</font>) es una función $f(x)$ que se aproxima a unos datos sin que necesariamente pase sobre ellos (Vidal, 2017). Ahora bien, un ajuste lineal (o <font color="#FF5733">regresión lineal</font>) busca la determinación de la ecuación de la **recta** que mejor ajusta a una distribución bidimensional (i.e., $x$ y $y$) de datos (Franco, 2016).
#
# $$
# Y = aX + b
# $$
#
# Siendo $Y$ la variable dependiente, $X$ la variable independiente, $a$ la pendiente y $b$ el intercepto con el eje vertical (i.e., eje $Y$).
#
# El método de **mínimos cuadrados ordinarios** (OLS, por sus siglas en inglés) es un ejercicio de optimización del error cuadrático $e^2$. Es decir, se minimiza la suma de cuadrados de las diferencias (llamados residuos) entre los puntos generados por la función y los correspondientes valores en los datos medidos (Wikipedia, 2021).
#
# $$
# \sum_{i=1}^{n} e_i^2 = \sum_{i=1}^{n} \left( y_i - \hat{y}_i \right )^2
# $$
#
# <img src='./img/OLS.png' width='350'/>
# Figura tomada de [Cuemath - Least Squares](https://www.cuemath.com/data/least-squares/).
# +
df_orig = DataFrames.DataFrame(XLSX.readtable("./data/engines.xlsx", "Data", header=true)...) # ./ es pwd()
df = copy(df_orig)
println("El DataFrame tiene $(size(df)[1]) filas y $(size(df)[2]) columnas.")
first(df, 5)
# -
# Algunas Métricas Estadísticas
DataFrames.describe(df)
# ### 1.2.1. Gráfica MBHP vs Masa
Plots.plot(df."Mass (Kg)",
df."Maximum Brake Horsepower (BHP)",
seriestype = :scatter,
title="Relación MBHP y Masa",
xlabel="Masa (kg)",
ylabel="MBHP",
xrotation=0,
legend=false,
m=:circle,
ms=4,
mc=:dodgerblue,
alpha=0.5,
dpi=500,
frame=:origin)
# Al observar la gráfica anterior, se evidencia poca linealidad entre los datos. Por ende, para conseguir una buena interpretación, se procede a obtener la respectiva relación logarítimica, es decir $log \: \text{MBHP}$ vs. $log \: \text{Masa}$.
#
# En este caso (ambos ejes con valores logarítmicos), tenemos que la pendiente $a$ y el intercepto $b$ es:
#
# $$
# Y = aX + log(b)
# $$
# +
eje_x = log.(df."Mass (Kg)")
eje_y = log.(df."Maximum Brake Horsepower (BHP)")
Plots.plot(eje_x,
eje_y,
seriestype = :scatter,
title="Relación log MBHP y log Masa",
xlabel="Masa (kg)",
ylabel="MBHP",
label="Medidas",
legend=:outertopright,
m=:circle,
ms=4,
mc=:dodgerblue,
alpha=0.5,
dpi=500,
frame=:origin)
# -
# ¡Perfecto! Con esta transformación, ahora podemos ver que efectivamente hay una relación lineal entre las variables $\texttt{Masa}$ y $\texttt{MBHP}$.
# ### 1.2.2. Ajuste Lineal
#
# Una librería que nos permite realizar un ajuste lineal con el método OLS es `GLM` (*Generalized Linear Models*).
#
# La librería `GLM` tiene una función llamada `lm` para los ajustes lineales. Esta tiene los siguientes parámetros de entrada principales:
#
# - `formula`: Usa nombre de columnas del DataFrame (e.g., `names(df) = [:Y,:X1,:X2]`) y una fórmula válida con la sintaxis (e.g., `@formula(Y ~ X1 + X2)`).
# - `data`: El DataFrame que contiene los valores.
#
# Más info [aquí](https://juliastats.org/GLM.jl/v0.11/).
#
# Pero... ¿qué es un modelo lineal (o ecuación lineal)?
#
#
# <div class="alert alert-block alert-success">
# > Es una ecuación de primer grado (es decir, involucra una o más variables a la primera potencia) y no contiene productos entre las variables, es decir, la ecuación solo involucra sumas y restas de una variable a la primera potencia.
# </div>
# +
df_ols = DataFrames.DataFrame(X = log.(df."Mass (Kg)"),
Y = log.(df."Maximum Brake Horsepower (BHP)"))
DataFrames.first(df_ols, 5)
# +
using GLM
ols = lm(@formula(Y ~ X), df_ols)
ols
# -
# La columna $\texttt{Coef.}$ nos da la información que necesitamos:
# - **Pendiente $a$**: 0.858983
# - **Intercepto $b$**: 0.910096
#
# Para visualizar la información, hacemos uso de la función `predict()` que me evalúa el ajuste lineal hecho.
# ### 1.2.3. Coeficiente de Correlación
#
# El coeficiente de correlación $R^2$ de determina a partir de la función `r2` de la librería `StatsBase`.
# +
import StatsBase
R² = round(StatsBase.r2(ols), digits=2)
R²
# +
using GLM
a = round(coef(ols)[1], digits=2) # ¿Qué obtenemos con 'coef()'?
b = round(coef(ols)[2], digits=2) # ¿Qué obtenemos con 'coef()'?
Plots.plot!(df_ols."X", predict(ols), color=:red, alpha=0.5, label="Y = $(a)X + $(b)\nR² = $(R²)")
# -
# ### 1.2.4. Caso Práctico
#
# Queremos obtener el ajuste lineal al correlacionar las variables `Mass (Kg)` y `Displacement (cm3)`. Esta relación también es $log-log$.
#
# El paso a paso que debemos hacer es:
# 1. Transformar los datos al valor logaritmo.
# 2. Crear el DataFrame únicamente con las columnas de interés.
# 3. Usar la librería `GLM` con la sintaxis adecuada (i.e., `GLM.lm(@formula(Y ~ X), df)`).
# 4. Estimar el valor de $R^2$.
# 4. Crear la gráfica base.
# 5. Agregar la línea de tendencia con `predict(ols)`.
# +
df_ols = DataFrames.DataFrame(X = log.(df."Mass (Kg)"),
Y = log.(df."Displacement (cm3)"))
DataFrames.first(df_ols, 5)
# +
using GLM
ols = lm(@formula(Y ~ X), df_ols)
ols
# +
import StatsBase
R² = round(StatsBase.r2(ols), digits=2)
R²
# +
eje_x = df_ols."X"
eje_y = df_ols."Y"
Plots.plot(eje_x,
eje_y,
seriestype = :scatter,
title="Relación log Desplazamiento y log Masa",
xlabel="Masa (kg)",
ylabel="Desplazamiento (cm3)",
label="Medidas",
legend=:outertopright,
m=:circle,
ms=4,
mc=:dodgerblue,
alpha=0.5,
dpi=500,
frame=:origin)
# +
using GLM
a = round(coef(ols)[1], digits=2) # ¿Qué obtenemos con 'coef()'?
b = round(coef(ols)[2], digits=2) # ¿Qué obtenemos con 'coef()'?
Plots.plot!(df_ols."X", predict(ols), color=:green, alpha=0.5, label="Y = $(a)X + $(b)\nR² = $(R²)")
# -
# ## 1.3. Histogramas
#
# Los histogramas permiten visualizar la distribución de un conjunto de datos a partir de la frecuencia de los valores representados en un rango específico. Para este caso, haremos uso de la función `fit` de la librería `StatsBase` para crear nuestro gráfico.
# +
# Estimamos el número de bins con la Regla de Sturge
K = Int(round(1 + 3.322 * log(length(df_ols."Y"))))
# Histograma
using StatsBase
h = fit(Histogram, df_ols."Y", nbins=K)
# -
# Para graficar esta información, hacemos uso de la función `bar` de la librería `Plots`.
hist = Plots.bar(h.edges, h.weights,
xlabel = "Mediciones (Y)",
ylabel = "Frecuencia",
title = "Histograma",
legend = false,
color = :dodgerblue,
alpha = 0.5)
# Podemos agregar líneas de medidas de tendencia central como promedio y desviaciones estándar.
# +
avg = Statistics.mean(df_ols."Y")
desv = Statistics.std(df_ols."Y")
Plots.vline!([avg - desv, avg, avg + desv],
linestyle=:dash,
color=:green)
# -
# <a id="section2"></a>
# # Sección 2: Incertidumbre
# ## 2.1. Error Aleatorio
#
# Típicamente nos encontramos lo siguiente en una guía de laboratorio:
#
# > **Estimación de Incertidumbre**: Las variables observadas se verán afectadas por la incertidumbre de medición, y aquellas
# obtenidas a partir de ecuaciones matemáticas se verán afectadas por el error propagado.
# Para estimar las incertidumbres de medición, es importante distinguir entre las fuentes
# sistemáticas y aleatorias de error a medida que se realiza el experimento. Para las fuentes
# de error aleatorias, **se debe estimar un intervalo de confianza del 95% según la distribución
# de probabilidad correspondiente (e.g., t-Student o Normal)**. Debe documentar en el informe
# cómo se estimó la incertidumbre de medición y cómo se calculó la propagación de error.
#
# ¿Cómo lo podemos hacer en Julia?
#
#
# Recordemos que, para la distribución Normal (también llamada Gaussiana):
#
# $$
# z = \frac{x - \mu}{\sigma_x}
# $$
#
# Donde:
#
# $$
# \sigma_x = \frac{\sigma}{\sqrt{n}}
# $$
#
# Con estos datos, obtenemos el intervalor de confianza:
#
# $$
# \mu = x \pm z \sigma_x
# $$
#
#
# Este ejercicio es facilitado con las librerías `Distributions` e `HypothesisTests`.
# +
using Distributions, HypothesisTests
μ = round(Statistics.mean(df_ols."X"), digits=2)
println("Promedio Masa ~ μ = $μ\n")
println( OneSampleTTest(df_ols."X") )
println("\nIntervalo de Confianza (95%): $(confint(OneSampleTTest(df_ols."X")))") # Intervalo de Confianza del 95%
# -
# ## 2.2. Barras de Error
#
# Conocido el error de cada dato, `Plots` nos permite agregar las barras de error de manera sencilla a partir del parámetro `yerror`.
# +
error = Array(randn(DataFrames.nrow(df_ols), 1))
df_ols."error" .= error
DataFrames.first(df_ols, 5)
# +
eje_x = log.(df."Mass (Kg)")
eje_y = log.(df."Maximum Brake Horsepower (BHP)")
Plots.plot(eje_x,
eje_y,
seriestype = :scatter,
title="Relación log MBHP y log Masa",
xlabel="Masa (kg)",
ylabel="MBHP",
label="Medidas",
legend=:outertopright,
m=:circle,
ms=4,
mc=:dodgerblue,
alpha=0.5,
dpi=500,
frame=:origin,
yerror=df_ols."error")
# -
# ## 2.3. Librería `Measurements.jl`
#
# La librería `Measurements` también permite agregar barras de error con una sintaxis más clara y ¡es útil para ejercicios de <font color="#FF5733">propagación de error</font> de manera sencilla!.
#
# Más info [aquí](https://juliaphysics.github.io/Measurements.jl/stable/).
# ### 2.3.1. Barras de Error
# +
using Measurements
eje_x = df_ols."X"
eje_y = df_ols."Y"
err = df_ols."error"
eff_y = eje_y .± err # Note el término '.±'
Plots.plot(eje_x,
eff_y,
seriestype = :scatter,
title="Relación log MBHP y log Masa",
xlabel="Masa (kg)",
ylabel="MBHP",
label="Medidas",
legend=:outertopright,
m=:circle,
ms=4,
mc=:dodgerblue,
alpha=0.5,
dpi=500,
frame=:origin,
yerror=df_ols."error")
# -
# ### 2.3.2. Propagación de Error
#
# Un péndulo simple se describe a partir de la siguiente ecuación:
#
# $$
# T = 2\pi \sqrt{\frac{L}{g}}
# $$
#
# Al despejar para la gravedad $g$, obtenemos:
#
# $$
# g = \frac{4 \pi^2 L}{T^2}
# $$
#
# Ahora, el error propagado para esta ecuación es:
#
# $$
# e = \sqrt{ \left( \frac{\partial g}{\partial L} \right)^2 \cdot e_L^2 + \left( \frac{\partial g}{\partial T} \right)^2 \cdot e_T^2}
# $$
#
# Luego:
#
# $$
# e = \sqrt{ \left( \frac{4 \pi^2}{T^2} \right)^2 \cdot e_L^2 + \left( \frac{-8 \pi^2 L}{T^3} \right)^2 \cdot e_T^2}
# $$
# +
# Definimos las variables con su error
L = measurement(0.936, 1e-3); # Forma 1
T = 1.942 ± 4e-3; # Forma 2
# +
# El error, de forma manual, es
termino1 = ((4*pi^2 / (1.942)^2)^2) * (1e-3)^2
termino2 = ((-8*pi^2*(0.936) / (1.942)^3)^2) * (4e-3)^2
e = √(termino1 + termino2) # √ es igual a la función 'sqrt()'
# -
g = 4pi^2*L / T^2 # Notemos la propagación de error con `Measurements.jl`
| content/week2/C4_ajustedatos.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 itertools
import logging
import numpy as np
from pandas import DataFrame
from sklearn.linear_model import ElasticNet
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
logger = logging.getLogger(__name__)
# -
from dbnd import band, task, output, log_metric, project_path
from dbnd_examples.data import data_repo
from targets import DataTarget
def calculate_metrics(actual, pred):
rmse = np.sqrt(mean_squared_error(actual, pred))
mae = mean_absolute_error(actual, pred)
r2 = r2_score(actual, pred)
return rmse, mae, r2
# Tasks are where computation is done. Tasks produce targets as outputs and consume targets as inputs. Targets can be a S3 path, a local file or a database record.
#
# If we'll express PredictWineQuality as tasks and targets, it will look like this:
# 
# +
@task(result=output.csv)
def validate_model(model: ElasticNet, validation_dataset: DataFrame) -> str:
logger.info("Running validate model demo: %s", validation_dataset)
# support for py3 parqeut
validation_dataset = validation_dataset.rename(str, axis="columns")
validation_x = validation_dataset.drop(["quality"], 1)
validation_y = validation_dataset[["quality"]]
prediction = model.predict(validation_x)
(rmse, mae, r2) = calculate_metrics(validation_y, prediction)
log_metric("rmse", rmse)
log_metric("mae", rmse)
log_metric("r2", r2)
return ["%s,%s,%s" % (rmse, mae, r2)]
# -
# Every task can be configurable, and it can be done by using parameters. For example, we can add alpha or l1_ratio parameter to train_model. It might look like this
# +
@task
def train_model(
test_set: DataFrame,
training_set: DataFrame,
alpha: float = 0.5,
l1_ratio: float = 0.5,
) -> ElasticNet:
lr = ElasticNet(alpha=alpha, l1_ratio=l1_ratio)
lr.fit(training_set.drop(["quality"], 1), training_set[["quality"]])
prediction = lr.predict(test_set.drop(["quality"], 1))
(rmse, mae, r2) = calculate_metrics(test_set[["quality"]], prediction)
log_metric("alpha", alpha)
log_metric("rmse", rmse)
log_metric("mae", rmse)
log_metric("r2", r2)
logging.info(
"Elasticnet model (alpha=%f, l1_ratio=%f): rmse = %f, mae = %f, r2 = %f",
alpha,
l1_ratio,
rmse,
mae,
r2,
)
return lr
# -
# The first thing we'll do is creating a task that split the data into separate train, test and validation sets.
# +
@task( result=("training_set", "test_set", "validation_set"))
def prepare_data(raw_data: DataFrame):
train_df, test_df = train_test_split(raw_data)
test_df, validation_df = train_test_split(test_df, test_size=0.5)
return train_df, test_df, validation_df
@task
def calculate_alpha(alpha: float = 0.5):
alpha += 0.1
return alpha
# -
# Now, we can put all tasks together. We need to define tha output of the @band (model and validation) and assign them
# That's all :)
@band(result=("model", "validation"))
def predict_wine_quality(
data: DataTarget = data_repo.wines,
alpha: float = 0.5,
l1_ratio: float = 0.5,
good_alpha: bool = False,
):
training_set, test_set, validation_set = prepare_data(raw_data=data)
if good_alpha:
alpha = calculate_alpha(alpha)
model = train_model(
test_set=test_set,
training_set=training_set,
alpha=alpha,
l1_ratio=l1_ratio,
)
validation = validate_model(
model=model, validation_dataset=validation_set
)
return model, validation
#run pipeline
wine = predict_wine_quality.t(alpha=0.4, data=data_repo.wines)
wine.dbnd_run()
# +
#run pipeline with defferent alpha
wine = predict_wine_quality.t(alpha=0.3, data=data_repo.wines)
wine.dbnd_run()
# -
@band
def predict_wine_quality_parameter_search(
data: DataTarget = data_repo.wines,
alpha_step: float = 0.3,
l1_ratio_step: float = 0.4,
):
result = {}
variants = list(
itertools.product(np.arange(0, 1, alpha_step), np.arange(0, 1, l1_ratio_step))
)
logger.info("All Variants: %s", variants)
for alpha_value, l1_ratio in variants:
exp_name = "Predict_%f_l1_ratio_%f" % (alpha_value, l1_ratio)
model, validation = predict_wine_quality(
data=data, alpha=alpha_value, l1_ratio=l1_ratio, task_name=exp_name
)
result[exp_name] = (model, validation)
return result
#run pipeline with defferent alpha
wine_search = predict_wine_quality_parameter_search.t(data=data_repo.wines)
wine_search.dbnd_run()
| examples/src/dbnd_examples/pipelines/wine_quality/predict_wine_quality_tutorial.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
# ---
# # Widgets
# + hide_input=true
from fastai import *
from fastai.vision import *
from fastai.widgets import DatasetFormatter, ImageDeleter, ImageRelabeler
# -
# fastai offers several widgets to support the workflow of a deep learning practitioner. The purpose of the widgets are to help you organize, clean, and prepare your data for your model. Widgets are separated by data type.
# ## Images
# ### DatasetFormatter
# The [`DatasetFormatter`](/widgets.image_cleaner.html#DatasetFormatter) class prepares your image dataset for widgets by returning a formatted [`DatasetTfm`](/vision.data.html#DatasetTfm) based on the [`DatasetType`](/basic_data.html#DatasetType) specified. Use `from_toplosses` to grab the most problematic images directly from your learner. Optionally, you can restrict the formatted dataset returned to `n_imgs`.
#
# Specify the [`DatasetType`](/basic_data.html#DatasetType) you'd like to process:
# - DatasetType.Train
# - DatasetType.Valid
# - DatasetType.Test
path = untar_data(URLs.MNIST_SAMPLE)
data = ImageDataBunch.from_folder(path)
learner = create_cnn(data, models.resnet18, metrics=[accuracy])
ds, idxs = DatasetFormatter().from_toplosses(learner, ds_type=DatasetType.Valid)
# ### ImageDeleter
# [`ImageDeleter`](/widgets.image_cleaner.html#ImageDeleter) is for cleaning up images that don't belong in your dataset. It renders images in a row and gives you the opportunity to delete the file from your file system.
ImageDeleter(ds, idxs)
# ### ImageRelabeler
# [`ImageRelabeler`](/widgets.image_cleaner.html#ImageRelabeler) helps you find mis-categorized images in your data directory.
#
# > NOTE: ImageRelabeler currently only works with files where labels were created from the names of their parent directory (i.e. with .from_folder()). The widget moves mislabeled photos from the incorrect parent directory to the properly-labeled parent directory.
#
# To relabel an image, just click the proper label in the widget dropdown.
ImageRelabeler(ds, idxs)
| docs_src/widgets.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
# # !pip install gensim
import numpy as np
import gensim
import os
import string
import re
import pprint
from gensim import corpora, models, similarities
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.manifold import TSNE
import nltk
from nltk import word_tokenize, tokenize
nltk.download('punkt')
# %matplotlib inline
from matplotlib import pyplot as plt
# #!pip install vaderSentiment
import datetime
from collections import Counter
from tqdm import tqdm
tqdm.pandas(desc='progress-bar')
from gensim.models.doc2vec import LabeledSentence
import operator
from nltk.stem.porter import *
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score
# -
# ### Getting dataframes from cleaned csvs
trump_df = pd.read_csv('../data/clean_trump.csv').drop(columns = ['Unnamed: 0'])
print(trump_df.shape)
trump_df.head()
biden_df = pd.read_csv('../data/clean_biden.csv').drop(columns = ['Unnamed: 0'])
print(biden_df.shape)
biden_df.head()
# +
trump_df['hashtag'] = 'trump'
biden_df['hashtag'] = 'biden'
full_df = pd.concat([trump_df, biden_df], ignore_index=True)
full_df = full_df.drop_duplicates(subset='tweet', keep=False)
display(full_df.head())
trump_df=full_df[full_df['hashtag']=='trump']
biden_df=full_df[full_df['hashtag']=='biden']
print(trump_df.shape)
print(biden_df.shape)
display(trump_df.head())
display(biden_df.head())
len(set(full_df['tweet']))
og_tweet=full_df['tweet']
# -
# ### Further tweet cleaning - get rid of @user and simplify words for word2vec, doc2vec using Porter Stemmer
def remove_mentions(df):
pattern = r"@[\w]*"
tweets = df['tweet']
clean_tweets = []
for tweet in tweets:
r = re.findall(pattern, tweet)
for i in r:
tweet = re.sub(i, '', tweet)
clean_tweets.append(tweet)
return clean_tweets
# +
trump_df['og_tweet'] = trump_df['tweet']
trump_df['tweet'] = remove_mentions(trump_df)
trump_df['tweet'] = trump_df['tweet'].str.replace("[^a-zA-Z#]", " ")
trump_df['tweet'] = trump_df['tweet'].apply(lambda x: ' '.join([w for w in x.split() if len(w) > 3]))
trump_tokens = trump_df['tweet'].apply(lambda x: x.split())
trump_tokens[:5]
trump_df.head()
# -
biden_df['og_tweet']=biden_df['tweet']
biden_df['tweet'] = remove_mentions(biden_df)
biden_df['tweet'] = biden_df['tweet'].str.replace("[^a-zA-Z#]", " ")
biden_df['tweet'] = biden_df['tweet'].apply(lambda x: ' '.join([w for w in x.split() if len(w) > 3]))
biden_tokens = biden_df['tweet'].apply(lambda x: x.split())
biden_tokens[:5]
stemmer = PorterStemmer()
trump_tokens = trump_tokens.apply(lambda x: [stemmer.stem(i) for i in x])
trump_tokens[:5]
biden_tokens = biden_tokens.apply(lambda x: [stemmer.stem(i) for i in x])
biden_tokens[:5]
trump_tokens_list = trump_tokens.tolist()
for i in range(len(trump_tokens)):
trump_tokens_list[i] = ' '.join(trump_tokens_list[i])
trump_df['tweet'] = trump_tokens_list
trump_df.head()
# +
biden_tokens_list=biden_tokens.tolist()
for i in range(len(biden_tokens)):
biden_tokens_list[i] = ' '.join(biden_tokens_list[i])
biden_df['tweet'] = biden_tokens_list
biden_df.head()
# -
# ### Splitting data into training and testing sets, applying labels based on `avg_polarity`
# ##### Using threshold of 0.05 as 'undecided' from previous VADER and textblod analyses. Maintaining absolute netural polarity with those who scored near 0.0 for polarity.
# +
threshold = 0.05
train_trump_df = trump_df[(trump_df['avg_polarity'] < -threshold) | (trump_df['avg_polarity'] > threshold) | (trump_df['avg_polarity'] == 0)]
test_trump_df = trump_df[((trump_df['avg_polarity'] >= -threshold) & (trump_df['avg_polarity'] <= threshold)) & (trump_df['avg_polarity'] != 0)]
print("Training size: ", train_trump_df.shape)
print("Training negatives: ", train_trump_df[train_trump_df['avg_polarity']<-threshold].shape)
print("Training positives: ", train_trump_df[train_trump_df['avg_polarity']>threshold].shape)
print("Training neutrals: ", train_trump_df[train_trump_df['avg_polarity']==0.0].shape)
print("Testing size: ", test_trump_df.shape)
# +
labels=[]
for index, row in train_trump_df.iterrows():
if row['avg_polarity'] == 0:
labels.append(0)
elif row['avg_polarity'] < 0:
labels.append(1)
else:
labels.append(-1)
train_trump_df['label'] = labels
test_trump_df.head()
# +
train_biden_df = biden_df[(biden_df['avg_polarity'] < -threshold) | (biden_df['avg_polarity'] > threshold) | (biden_df['avg_polarity'] == 0.0)]
test_biden_df = biden_df[((biden_df['avg_polarity'] >= -threshold) & (biden_df['avg_polarity'] <= threshold)) & (biden_df['avg_polarity'] != 0)]
print("Training size: ", train_biden_df.shape)
print("Training negatives: ", train_biden_df[train_biden_df['avg_polarity']<-threshold].shape)
print("Training positives: ", train_biden_df[train_biden_df['avg_polarity']>threshold].shape)
print("Training neutrals: ", train_biden_df[train_biden_df['avg_polarity']==0.0].shape)
print("Testing size: ", test_biden_df.shape)
test_biden_df.head()
biden_df.shape
# +
labels=[]
for index, row in train_biden_df.iterrows():
if row['avg_polarity'] == 0:
labels.append(0)
elif row['avg_polarity'] < 0:
labels.append(-1)
else:
labels.append(1)
train_biden_df['label'] = labels
train_biden_df.head()
# -
#combine labeled trump and biden datasets
train_df = pd.concat([train_trump_df, train_biden_df], ignore_index=True)
test_df = pd.concat([test_trump_df, test_biden_df], ignore_index=True)
display(train_df.head())
print(train_df.shape)
display(test_df.head())
print(test_df.shape)
def add_label(tweet):
output = []
for i, s in zip(tweet.index, tweet):
output.append(LabeledSentence(s, ['tweet_', str(i)]))
return output
train_labeled_tweets = add_label(train_df['tweet'])
test_labeled_tweets = add_label(test_df['tweet'])
# ### Doc2Vec model creation
feature_size=200
d2v = gensim.models.Doc2Vec(dm=1, dm_mean=1, vector_size=feature_size, window=5, min_count=3, workers=32, alpha=0.1, seed=0)
d2v.build_vocab([i for i in tqdm(train_labeled_tweets)])
d2v.train(train_labeled_tweets, total_examples=len(train_df['tweet']), epochs=30)
# +
d2v_vectors = np.zeros((len(train_labeled_tweets), feature_size))
for i in range(len(train_df['tweet'])):
d2v_vectors[i, :] = d2v.docvecs[i].reshape((1, feature_size))
d2v_df = pd.DataFrame(d2v_vectors)
print(d2v_df.shape)
d2v_df.head()
# -
# ### Word2Vec model creation
split_tokens = train_df['tweet'].apply(lambda x: x.split())
w2v = gensim.models.Word2Vec(split_tokens, size=feature_size, window=5, min_count=3, sg=1, workers=32, seed=0)
w2v.train(split_tokens, total_examples=len(train_df['tweet']), epochs=30)
# ##### Represent tweet using average of vectors of words in the tweet
def avg_vector(w2v, tweet_tokens, size):
vec_sum = np.zeros(size).reshape((1, size))
num_tokens=0
for token in tweet_tokens:
try:
vec_sum += w2v[token].reshape((1, size))
num_tokens+=1;
except KeyError:
continue
if num_tokens>0:
vec_sum = vec_sum/num_tokens
return vec_sum
w2v_vectors = np.zeros((len(split_tokens), feature_size))
for i in range(len(split_tokens)):
w2v_vectors[i, :]=avg_vector(w2v, split_tokens[i], feature_size)
w2v_df = pd.DataFrame(w2v_vectors)
print(w2v_df.shape)
w2v_df.head()
# +
#splitting xtrain and ytrain, xvaild, yvalid
w2v_xtrain = w2v_df.iloc[:140000, :]
w2v_xvalid = w2v_df.iloc[140000:, :]
# d2v_xtrain = d2v_df.iloc[:140000, :]
# d2v_xvalid = d2v_df.iloc[140000:, :]
yvalid = train_df.iloc[140000:, :]['label']
ytrain = train_df.iloc[:140000, :]['label']
set(ytrain)
# -
d2v_full_df = d2v_df
d2v_full_df['label'] = train_df['label']
d2v_full_df.to_csv('d2v_df.csv', index=False)
w2v_full_df = w2v_df
w2v_full_df['label'] = train_df['label']
w2v_full_df.to_csv('w2v_df.csv', index=False)
# ### SVM attempt
# +
# svc = svm.SVC(kernel='poly', C=1, probability=True).fit(w2v_xtrain, ytrain)
# prediction = svc.predict_proba(w2v_xvalid)
# prediction_int = prediction[:,1] >= 0.3
# prediction_int = prediction_int.astype(np.int)
# f1_score(yvalid, prediction_int)
# +
# svc = svm.SVC(kernel='poly', C=1, probability=True).fit(d2v_xtrain, ytrain)
# prediction = svc.predict_proba(d2v_xvalid)
# prediction_int = prediction[:,1] >= 0.3
# prediction_int = prediction_int.astype(np.int)
# f1_score(yvalid, prediction_int)
# -
# ### Random Tree Attempt
# +
# w2v_rf = RandomForestClassifier(n_estimators=500, random_state=0).fit(w2v_xtrain, ytrain)
# w2v_prediction = w2v_rf.predict(w2v_xvalid)
# f1_score(yvalid, w2v_prediction)
# +
# d2v_rf = RandomForestClassifier(n_estimators=500, random_state=11).fit(w2v_xtrain, ytrain)
# d2v_prediction = d2v_rf.predict(d2v_xvalid)
# f1_score(yvalid, d2v_prediction)
# -
# ### XGBoost attempt
# !pip install xgboost
from xgboost import XGBClassifier
w2v_xgb = XGBClassifier(max_depth=5, n_estimators=1000, nthread=3).fit(w2v_xtrain, ytrain)
w2v_prediction = w2v_xgb.predict(w2v_xvalid)
f1_score(yvalid, w2v_prediction, average='weighted')
d2v_xgb = XGBClassifier(max_depth=5, n_estimators=1000, nthread=3).fit(d2v_xtrain, ytrain)
d2v_prediction = d2v_xgb.predict(d2v_xvalid)
f1_score(yvalid, d2v_prediction, average='weighted')
# +
# no need because d2v f1score is bad
#d2v = gensim.models.Doc2Vec(dm=1, dm_mean=1, vector_size=feature_size, window=5, min_count=3, workers=32, alpha=0.1, seed=0)
# d2v.build_vocab([i for i in tqdm(test_labeled_tweets)])
# d2v.train(test_labeled_tweets, total_examples=len(train_df['tweet']), epochs=30)
# d2v_vectors = np.zeros((len(test_labeled_tweets), feature_size))
# for i in range(len(test_df['tweet'])):
# d2v_vectors[i, :] = d2v.docvecs[i].reshape((1, feature_size))
# test_d2v_df = pd.DataFrame(d2v_vectors)
# print(test_d2v_df.shape)
# test_d2v_df.head()
# +
split_tokens = test_df['tweet'].apply(lambda x: x.split())
w2v = gensim.models.Word2Vec(split_tokens, size=feature_size, window=5, min_count=3, sg=1, workers=32, seed=0)
w2v.train(split_tokens, total_examples=len(test_df['tweet']), epochs=30)
w2v_vectors = np.zeros((len(split_tokens), feature_size))
for i in range(len(split_tokens)):
w2v_vectors[i, :]=avg_vector(w2v, split_tokens[i], feature_size)
test_w2v_df = pd.DataFrame(w2v_vectors)
print(test_w2v_df.shape)
test_w2v_df.head()
# -
import xgboost as xgb
ytrain=ytrain +1
yvalid=yvalid +1
dtrain = xgb.DMatrix(w2v_xtrain, label=ytrain)
dvalid = xgb.DMatrix(w2v_xvalid, label=yvalid)
dtest = xgb.DMatrix(test_w2v_df)
params={
'objective': 'multi:softprob',
'max_depth': '5',
'min_child_weight': 1,
'eta': 0.3,
'subsample': 1,
'colsample': 1,
'num_class': 3
}
# +
def custom_eval(preds, dtrain):
labels = dtrain.get_label().astype(np.int)
preds = np.argmax(preds, axis=1)
return [('f1_score', f1_score(labels, preds, average='weighted'))]
gridsearch_params = [
(max_depth, min_child_weight)
for max_depth in range(6,8)
for min_child_weight in range(5,8)
]
max_f1 = 0.
best_params = None
for max_depth, min_child_weight in gridsearch_params:
params['max_depth'] = max_depth
params['min_child_weight'] = min_child_weight
cv_results = xgb.cv(
params,
dtrain,
feval= custom_eval,
num_boost_round=200,
seed=16,
nfold=5,
)
mean_f1 = cv_results['test-f1_score-mean'].max()
boost_rounds = cv_results['test-f1_score-mean'].idxmax()
if mean_f1 > max_f1:
max_f1 = mean_f1
best_params = (max_depth,min_child_weight)
print("Best max depth: ", best_params[0])
print("Best min_child_weight: ", best_params[1])
print("f1_score", max_f1)
# +
gridsearch_params = [
(subsample)
for subsample in [i/10. for i in range(8,11)]
]
max_f1 = 0.
best_params = None
for subsample in gridsearch_params:
params['subsample'] = subsample
cv_results = xgb.cv(
params,
dtrain,
feval= custom_eval,
num_boost_round=200,
maximize=True,
seed=16,
nfold=5,
early_stopping_rounds=10
)
mean_f1 = cv_results['test-f1_score-mean'].max()
boost_rounds = cv_results['test-f1_score-mean'].idxmax()
if mean_f1 > max_f1:
max_f1 = mean_f1
best_params = (subsample)
print("best subsample ", best_params)
# +
best_params = None
for eta in [.3, .2, .1, .05]:
params['eta'] = eta
cv_results = xgb.cv(
params,
dtrain,
feval= custom_eval,
num_boost_round=1000,
maximize=True,
seed=16,
nfold=5,
early_stopping_rounds=10
)
mean_f1 = cv_results['test-f1_score-mean'].max()
boost_rounds = cv_results['test-f1_score-mean'].idxmax()
if mean_f1 > max_f1:
max_f1 = mean_f1
best_params = eta
print("Best eta: ", best_params)
# -
params={
'objective': 'multi:softprob',
'max_depth': '7',
'min_child_weight': 6,
'eta': 0.3,
'subsample': 1,
'num_class': 3
}
# +
xgb_w2v = xgb.train(params, dtrain, num_boost_round=1000, maximize=True, evals=[(dvalid, "Validation")], early_stopping_rounds=10)
# -
test_pred = xgb_w2v.predict(dtest)
test_label = []
for pred in test_pred:
test_label.append(np.argmax(pred) - 1)
len(test_label)
test_df['label'] = test_label
test_df.head()
fin_full_df = pd.concat([train_df, test_df], ignore_index=True)
fin_full_df.shape
fin_full_df.head()
final_df = fin_full_df[['user_id','og_tweet', 'state', 'likes', 'retweet_count', 'avg_polarity', 'label', 'hashtag']]
final_df.columns = ['user_id', 'tweet', 'state', 'likes', 'retweet_count', 'avg_polarity', 'label', 'hashtag']
print(final_df.shape)
print(full_df.shape)
final_df.tail(20)
fin_full_df.shape
fin_full_df = fin_full_df.drop(columns=['tweet', 'hashtag'])
fin_full_df['tweet'] = og_tweet
full_df['label']=fin_full_df['label']
final_df.to_csv('combined_labeled_df.csv', index=False)
| exploration/word2vec_analysis_claudia.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/priyanshgupta1998/Image_Processing/blob/master/OnedriveAssignment.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + id="g-_WprmFA8OV" colab_type="code" colab={}
# + id="ie-oi1BsCdO6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 122} outputId="116a5d70-0bed-445d-8fa5-b661e7903704"
from google.colab import drive
drive.mount('/content/drive')
# + id="BstFMCL7DlTD" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="776656d6-ef0e-4010-dc26-7d397270e114"
# cd /content/drive/My Drive/onedrive_assign/
# + id="esHMvIkCEFw0" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="e45feae1-5b79-4fb8-81e1-2a0d712ed166"
import os
print(os.listdir())
# + id="MvyEehtSCcYo" colab_type="code" colab={}
# !unzip 'train.zip'
# + id="bnB6790xCcW4" colab_type="code" colab={}
# !unzip 'test.zip'
# + id="nRmW5TAfCcVG" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 80} outputId="c4b714b8-483e-4be4-b092-889b344aa274"
import tensorflow.keras.layers as Layers
import tensorflow.keras.activations as Actications
import tensorflow.keras.models as Models
import tensorflow.keras.optimizers as Optimizer
import tensorflow.keras.metrics as Metrics
import tensorflow.keras.utils as Utils
from keras.utils.vis_utils import model_to_dot
import os
import matplotlib.pyplot as plot
import cv2
import numpy as np
from sklearn.utils import shuffle
from sklearn.metrics import confusion_matrix as CM
from random import randint
from IPython.display import SVG
import matplotlib.gridspec as gridspec
# + id="q2FR5MEHCcTS" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="11065afe-f03c-4a66-ce90-a2ae6e0ec522"
print(os.listdir())
# + id="G14gVDCvCcR5" colab_type="code" colab={}
# + id="tKmz1lMlCcQM" colab_type="code" colab={}
# + id="fG5d138oCcK6" colab_type="code" colab={}
# + id="e8FpD49pA8T0" colab_type="code" colab={}
# + id="nHwmuvD0A8gP" colab_type="code" colab={}
# + id="17BgAMDDA8oL" colab_type="code" colab={}
# + id="916j7qhxA8tV" colab_type="code" colab={}
# + id="E_eLqgjuA8yZ" colab_type="code" colab={}
# + id="0-2XjlVPA8-I" colab_type="code" colab={}
# + id="XJeL_FWfA9Dr" colab_type="code" colab={}
# + id="w3fzfVywA87i" colab_type="code" colab={}
# + id="v_7uNwEZA85k" colab_type="code" colab={}
# + id="sn7GaylRA83f" colab_type="code" colab={}
# + id="2bpL3UOxA81_" colab_type="code" colab={}
# + id="991xHeXgA8wb" colab_type="code" colab={}
# + id="8orN8HTDA8ls" colab_type="code" colab={}
# + id="3RE6YABTA8jQ" colab_type="code" colab={}
# + id="C2rt4TXDA8d8" colab_type="code" colab={}
# + id="toKolLXoA8ba" colab_type="code" colab={}
# + id="dksVacC3A8ZF" colab_type="code" colab={}
# + id="UY_Fjfk1A8XL" colab_type="code" colab={}
# + id="P8_xK9JNA8R5" colab_type="code" colab={}
# + id="TGsv3pBJA8MO" colab_type="code" colab={}
| OnedriveAssignment.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: mcvine
# language: python
# name: mcvine
# ---
import os, sys
# import mcvine modules
from instrument.geometry.pml import weave
from instrument.geometry import operations
thisdir = os.path.abspath(os.path.dirname("__file__"))
libpath = os.path.join(thisdir, '../c3dp_source')
if not libpath in sys.path:
sys.path.insert(0, libpath)
import collimator_support as colli_original
import SCADGen.Parser
from create_collimator_geometry import Collimator_geom
from clampcell_geo import Clampcell
from DAC_geo import DAC
# +
clampcell=Clampcell(total_height=True)
outer_body=clampcell.outer_body()
inner_sleeve=clampcell.inner_sleeve()
sample=clampcell.sample()
cell_sample_assembly=operations.unite(operations.unite(outer_body, sample), inner_sleeve)
# +
scad_flag = True ########CHANGE CAD FLAG HERE
if scad_flag is True:
samplepath = os.path.join(thisdir, '../figures')
else:
samplepath = os.path.join(thisdir, '../sample')
# +
for coll_length in [195.]: #100, 230,380
channel_length=195. #32, 17
min_channel_wall_thickness=1.
# coll = colli_original.Collimator_geom()
coll = Collimator_geom()
coll.set_constraints(max_coll_height_detector=230., max_coll_width_detector=230.,
min_channel_wall_thickness=min_channel_wall_thickness,
max_coll_length=coll_length, min_channel_size=3.,
truss_base_thickness=30., trass_final_height_factor=0.45,
touch_to_halfcircle=6 ,SNAP_acceptance_angle=False)
coll.set_parameters(number_channels=3.,channel_length =channel_length)
filename = 'coll_geometry_{coll_length}_{coll_height}_{coll_width}_{channel_length}_{wall_thickness}.xml'.\
format(coll_length=coll_length, coll_height=coll.max_coll_height_detector, coll_width=coll.max_coll_height_detector, channel_length=channel_length, wall_thickness=min_channel_wall_thickness)
outputfile = os.path.join(samplepath, filename)
supports=coll.support()
truss=coll.support_design()
coli = coll.gen_one_col(collimator_Nosupport=False)
# collimator=coll.gen_collimators_xml(multiple_collimator=False, scad_flag=scad_flag,detector_angles=[0], collimator_Nosupport=False, coll_file=outputfile)
both=operations.unite(cell_sample_assembly, coli)
# both= truss
# both=supports
file='colli_anvil'
filename='%s.xml'%(file)
outputfile=os.path.join(samplepath, filename)
with open (outputfile,'wt') as file_h:
weave(both,file_h, print_docs = False)
# -
p = SCADGen.Parser.Parser(outputfile)
p.createSCAD()
test = p.rootelems[0]
cadFile_name='%s.scad'%(file)
cad_file_path=os.path.abspath(os.path.join(samplepath, cadFile_name))
cad_file_path
# !vglrun openscad {cad_file_path}
import cadquery as cq
from cq_jupyter import Assembly, Part, Edges, Faces, display, exportSTL
| notebooks/collimator_geometry_creation.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
# ---
print('Simple neural network sprint 1')
from dataclasses import dataclass # for neural network construction
import pickle
import gzip
import random # to initialize weights and biases
import numpy as np # for all needed math
from PIL import Image, ImageOps
from time import time
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def sigmoid_prime(z):
return sigmoid(z) * (1 - sigmoid(z))
def cost_derivative(output_activations, y):
return (output_activations - y)
#Lets move to the nueral network
# +
@dataclass
class Network:
num_layers: int
biases: list
weights: list
def init_network(layers):
return Network(
len(layers),
# input layer doesn't have biases
[np.random.randn(y, 1) for y in layers[1:]],
# there are no (weighted) connections into input layer or out of the output layer
[np.random.randn(y, x) for x, y in zip(layers[:-1], layers[1:])]
)
# +
#Forward propagation function
#Calculates activation vector for each layer and returns the last activation vector as ndarray.
# -
def feedforward(nn, a):
for b, w in zip(nn.biases, nn.weights):
a = sigmoid(np.dot(w, a) + b)
return a
def evaluate(nn, test_data):
test_results = [(np.argmax(feedforward(nn, x)), y) for (x, y) in test_data]
return sum(int(x == y) for (x, y) in test_results) # This function is used to evaluate
def learn(nn, training_data, epochs, mini_batch_size, learning_rate, test_data = None):
n = len(training_data)
for j in range(epochs):
random.shuffle(training_data) #stochastic
mini_batches = [
training_data[k: k + mini_batch_size] for k in range(0, n, mini_batch_size)
]
for mini_batch in mini_batches:
stochastic_gradient_descent(nn, mini_batch, learning_rate) # that's where learning really happes
if test_data:
print('Epoch {0}: accuracy {1}%'.format(f'{j + 1:2}', 100.0 * evaluate(nn, test_data) / len(test_data)))
else:
print('Epoch {0} complete.'.format(f'{j + 1:2}'))
# +
# epoch is the number of times model passes thepugh training dataset.
# +
# now lets build the worker function
# -
def stochastic_gradient_descent(nn, mini_batch, eta):
# gradient symbol nabla
nabla_b = [np.zeros(b.shape) for b in nn.biases]
nabla_w = [np.zeros(w.shape) for w in nn.weights]
for x, y in mini_batch:
delta_nabla_b, delta_nabla_w = backprop(nn, x, y)
nabla_b = [nb + dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw + dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
nn.weights = [w - (eta / len(mini_batch)) * nw for w, nw in zip(nn.weights, nabla_w)]
nn.biases = [b - (eta / len(mini_batch)) * nb for b, nb in zip(nn.biases, nabla_b)]
# +
# BACKPROPOGATION
# -
def backprop(nn, x, y):
nabla_b = [np.zeros(b.shape) for b in nn.biases]
nabla_w = [np.zeros(w.shape) for w in nn.weights]
# feedforward
activation = x # first layer activation is just its input
activations = [x] # list to store all activations, layer by layer
zs = [] # list to store all z vectors, layer by layer
for b, w in zip(nn.biases, nn.weights):
z = np.dot(w, activation) + b # calculate z for the current layer
zs.append(z) # store
activation = sigmoid(z) # layer output
activations.append(activation) # store
# backward pass
# 1. starting from the output layer
delta = cost_derivative(activations[-1], y) * sigmoid_prime(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
# 2. continue back to the input layer (i is the layer index, we're using i instead of l
# to improve readability -- l looks too much like 1)
for i in range(2, nn.num_layers): # starting from the next-to-last layer
z = zs[-i]
sp = sigmoid_prime(z)
delta = np.dot(nn.weights[-i + 1].transpose(), delta) * sp
nabla_b[-i] = delta
nabla_w[-i] = np.dot(delta, activations[-i - 1].transpose())
return (nabla_b, nabla_w)
# +
# Now this model is ready to be fed with model data generated by other team members.
# -
| Nueral_network.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
# ---
# + deletable=false run_control={"frozen": true} dc={"key": "4"} editable=false tags=["context"]
# ## 1. Where are the old left-handed people?
# <p><img src="https://assets.datacamp.com/production/project_479/img/Obama_signs_health_care-20100323.jpg" alt="Barack Obama signs the Patient Protection and Affordable Care Act at the White House, March 23, 2010"></p>
# <p>Barack Obama is left-handed. So are <NAME> and <NAME>; so were <NAME> and <NAME>. A <a href="https://www.nejm.org/doi/full/10.1056/NEJM199104043241418">1991 study</a> reported that left-handed people die on average nine years earlier than right-handed people. Nine years! Could this really be true? </p>
# <p>In this notebook, we will explore this phenomenon using age distribution data to see if we can reproduce a difference in average age at death purely from the changing rates of left-handedness over time, refuting the claim of early death for left-handers. This notebook uses <code>pandas</code> and Bayesian statistics to analyze the probability of being a certain age at death given that you are reported as left-handed or right-handed.</p>
# <p>A National Geographic survey in 1986 resulted in over a million responses that included age, sex, and hand preference for throwing and writing. Researchers <NAME> and <NAME> analyzed this data and noticed that rates of left-handedness were around 13% for people younger than 40 but decreased with age to about 5% by the age of 80. They concluded based on analysis of a subgroup of people who throw left-handed but write right-handed that this age-dependence was primarily due to changing social acceptability of left-handedness. This means that the rates aren't a factor of <em>age</em> specifically but rather of the <em>year you were born</em>, and if the same study was done today, we should expect a shifted version of the same distribution as a function of age. Ultimately, we'll see what effect this changing rate has on the apparent mean age of death of left-handed people, but let's start by plotting the rates of left-handedness as a function of age.</p>
# <p>This notebook uses two datasets: <a href="https://www.cdc.gov/nchs/data/statab/vs00199_table310.pdf">death distribution data</a> for the United States from the year 1999 (source website <a href="https://www.cdc.gov/nchs/nvss/mortality_tables.htm">here</a>) and rates of left-handedness digitized from a figure in this <a href="https://www.ncbi.nlm.nih.gov/pubmed/1528408">1992 paper by <NAME> Wysocki</a>. </p>
# + tags=["sample_code"] dc={"key": "4"}
# import libraries
import pandas as pd
import matplotlib.pyplot as plt
# load the data
data_url_1 = "https://gist.githubusercontent.com/mbonsma/8da0990b71ba9a09f7de395574e54df1/raw/aec88b30af87fad8d45da7e774223f91dad09e88/lh_data.csv"
lefthanded_data = pd.read_csv(data_url_1)
# plot male and female left-handedness rates vs. age
# %matplotlib inline
fig, ax = plt.subplots() # create figure and axis objects
ax.plot(lefthanded_data['Age'], lefthanded_data['Female'], marker = 'o') # plot "Female" vs. "Age"
ax.plot(lefthanded_data['Age'], lefthanded_data['Male'], marker = 'x') # plot "Male" vs. "Age"
ax.legend() # add a legend
ax.set_xlabel('Age')
ax.set_ylabel('Number of deaths')
# + deletable=false run_control={"frozen": true} dc={"key": "11"} editable=false tags=["context"]
# ## 2. Rates of left-handedness over time
# <p>Let's convert this data into a plot of the rates of left-handedness as a function of the year of birth, and average over male and female to get a single rate for both sexes. </p>
# <p>Since the study was done in 1986, the data after this conversion will be the percentage of people alive in 1986 who are left-handed as a function of the year they were born. </p>
# + tags=["sample_code"] dc={"key": "11"}
# create a new column for birth year of each age
lefthanded_data['Birth_year'] = 1986 - lefthanded_data['Age']
# create a new column for the average of male and female
lefthanded_data['Mean_lh'] = lefthanded_data[['Male', 'Female']].mean(axis=1)
# create a plot of the 'Mean_lh' column vs. 'Birth_year'
fig, ax = plt.subplots()
ax.plot(lefthanded_data['Birth_year'], lefthanded_data['Mean_lh'], marker='o') # plot 'Mean_lh' vs. 'Birth_year'
ax.set_xlabel('Birth year') # set the x label for the plot
ax.set_ylabel('Mean') # set the y label for the plot
# + deletable=false run_control={"frozen": true} dc={"key": "18"} editable=false tags=["context"]
# ## 3. Applying Bayes' rule
# <p>The probability of dying at a certain age given that you're left-handed is <strong>not</strong> equal to the probability of being left-handed given that you died at a certain age. This inequality is why we need <strong>Bayes' theorem</strong>, a statement about conditional probability which allows us to update our beliefs after seeing evidence. </p>
# <p>We want to calculate the probability of dying at age A given that you're left-handed. Let's write this in shorthand as P(A | LH). We also want the same quantity for right-handers: P(A | RH). </p>
# <p>Here's Bayes' theorem for the two events we care about: left-handedness (LH) and dying at age A.</p>
# <p>$$P(A | LH) = \frac{P(LH|A) P(A)}{P(LH)}$$</p>
# <p>P(LH | A) is the probability that you are left-handed <em>given that</em> you died at age A. P(A) is the overall probability of dying at age A, and P(LH) is the overall probability of being left-handed. We will now calculate each of these three quantities, beginning with P(LH | A).</p>
# <p>To calculate P(LH | A) for ages that might fall outside the original data, we will need to extrapolate the data to earlier and later years. Since the rates flatten out in the early 1900s and late 1900s, we'll use a few points at each end and take the mean to extrapolate the rates on each end. The number of points used for this is arbitrary, but we'll pick 10 since the data looks flat-ish until about 1910. </p>
# + tags=["sample_code"] dc={"key": "18"}
# import library
import numpy as np
# create a function for P(LH | A)
def P_lh_given_A(ages_of_death, study_year = 1990):
""" P(Left-handed | ages of death), calculated based on the reported rates of left-handedness.
Inputs: numpy array of ages of death, study_year
Returns: probability of left-handedness given that subjects died in `study_year` at ages `ages_of_death` """
# Use the mean of the 10 last and 10 first points for left-handedness rates before and after the start
early_1900s_rate = lefthanded_data.tail(10)['Mean_lh'].mean()
late_1900s_rate = lefthanded_data.head(10)['Mean_lh'].mean()
middle_rates = lefthanded_data.loc[lefthanded_data['Birth_year'].isin(study_year - ages_of_death)]['Mean_lh']
youngest_age = study_year - 1986 + 10 # the youngest age is 10
oldest_age = study_year - 1986 + 86 # the oldest age is 86
P_return = np.zeros(ages_of_death.shape) # create an empty array to store the results
# extract rate of left-handedness for people of ages 'ages_of_death'
P_return[ages_of_death > oldest_age] = early_1900s_rate / 100
P_return[ages_of_death < youngest_age] = late_1900s_rate / 100
P_return[np.logical_and((ages_of_death <= oldest_age), (ages_of_death >= youngest_age))] = middle_rates / 100
return P_return
# + deletable=false run_control={"frozen": true} dc={"key": "25"} editable=false tags=["context"]
# ## 4. When do people normally die?
# <p>To estimate the probability of living to an age A, we can use data that gives the number of people who died in a given year and how old they were to create a distribution of ages of death. If we normalize the numbers to the total number of people who died, we can think of this data as a probability distribution that gives the probability of dying at age A. The data we'll use for this is from the entire US for the year 1999 - the closest I could find for the time range we're interested in. </p>
# <p>In this block, we'll load in the death distribution data and plot it. The first column is the age, and the other columns are the number of people who died at that age. </p>
# + tags=["sample_code"] dc={"key": "25"}
# Death distribution data for the United States in 1999
data_url_2 = "https://gist.githubusercontent.com/mbonsma/2f4076aab6820ca1807f4e29f75f18ec/raw/62f3ec07514c7e31f5979beeca86f19991540796/cdc_vs00199_table310.tsv"
# load death distribution data
death_distribution_data = pd.read_csv(data_url_2, sep='\t', skiprows=[1])
# drop NaN values from the `Both Sexes` column
death_distribution_data.dropna(subset=['Both Sexes'], inplace=True)
# plot number of people who died as a function of age
fig, ax = plt.subplots()
ax.plot('Age', 'Both Sexes', data=death_distribution_data, marker='o') # plot 'Both Sexes' vs. 'Age'
ax.set_xlabel('Age')
ax.set_ylabel('Death distribution')
# + deletable=false run_control={"frozen": true} dc={"key": "32"} editable=false tags=["context"]
# ## 5. The overall probability of left-handedness
# <p>In the previous code block we loaded data to give us P(A), and now we need P(LH). P(LH) is the probability that a person who died in our particular study year is left-handed, assuming we know nothing else about them. This is the average left-handedness in the population of deceased people, and we can calculate it by summing up all of the left-handedness probabilities for each age, weighted with the number of deceased people at each age, then divided by the total number of deceased people to get a probability. In equation form, this is what we're calculating, where N(A) is the number of people who died at age A (given by the dataframe <code>death_distribution_data</code>):</p>
# <p><img src="https://i.imgur.com/gBIWykY.png" alt="equation" width="220"></p>
# <!--- $$P(LH) = \frac{\sum_{\text{A}} P(LH | A) N(A)}{\sum_{\text{A}} N(A)}$$ -->
# + tags=["sample_code"] dc={"key": "32"}
def P_lh(death_distribution_data, study_year = 1990): # sum over P_lh for each age group
""" Overall probability of being left-handed if you died in the study year
Input: dataframe of death distribution data, study year
Output: P(LH), a single floating point number """
p_list = death_distribution_data['Both Sexes'] * P_lh_given_A(
death_distribution_data['Age'], study_year
)
p = p_list.sum() # calculate the sum of p_list
return p / death_distribution_data['Both Sexes'].sum()
print(P_lh(death_distribution_data))
# + deletable=false run_control={"frozen": true} dc={"key": "39"} editable=false tags=["context"]
# ## 6. Putting it all together: dying while left-handed (i)
# <p>Now we have the means of calculating all three quantities we need: P(A), P(LH), and P(LH | A). We can combine all three using Bayes' rule to get P(A | LH), the probability of being age A at death (in the study year) given that you're left-handed. To make this answer meaningful, though, we also want to compare it to P(A | RH), the probability of being age A at death given that you're right-handed. </p>
# <p>We're calculating the following quantity twice, once for left-handers and once for right-handers.</p>
# <p>$$P(A | LH) = \frac{P(LH|A) P(A)}{P(LH)}$$</p>
# <p>First, for left-handers.</p>
# <!--Notice that I was careful not to call these "probability of dying at age A", since that's not actually what we're calculating: we use the exact same death distribution data for each. -->
# + tags=["sample_code"] dc={"key": "39"}
def P_A_given_lh(ages_of_death, death_distribution_data, study_year = 1990):
""" The overall probability of being a particular `age_of_death` given that you're left-handed """
P_A = death_distribution_data['Both Sexes'][ages_of_death] / death_distribution_data['Both Sexes'].sum()
P_left = P_lh(death_distribution_data, study_year) # use P_lh function to get probability of left-handedness overall
P_lh_A = P_lh_given_A(ages_of_death, study_year) # use P_lh_given_A to get probability of left-handedness for a certain age
return P_lh_A*P_A/P_left
# + deletable=false run_control={"frozen": true} dc={"key": "46"} editable=false tags=["context"]
# ## 7. Putting it all together: dying while left-handed (ii)
# <p>And now for right-handers.</p>
# + tags=["sample_code"] dc={"key": "46"}
def P_A_given_rh(ages_of_death, death_distribution_data, study_year = 1990):
""" The overall probability of being a particular `age_of_death` given that you're right-handed """
P_A = death_distribution_data['Both Sexes'][ages_of_death] / death_distribution_data['Both Sexes'].sum()
P_right = 1 - P_lh(death_distribution_data, study_year=study_year)
P_rh_A = 1 - P_lh_given_A(ages_of_death, study_year=study_year)
return P_rh_A*P_A/P_right
# + deletable=false run_control={"frozen": true} dc={"key": "53"} editable=false tags=["context"]
# ## 8. Plotting the distributions of conditional probabilities
# <p>Now that we have functions to calculate the probability of being age A at death given that you're left-handed or right-handed, let's plot these probabilities for a range of ages of death from 6 to 120. </p>
# <p>Notice that the left-handed distribution has a bump below age 70: of the pool of deceased people, left-handed people are more likely to be younger. </p>
# + tags=["sample_code"] dc={"key": "53"}
ages = np.arange(6, 115, 1) # make a list of ages of death to plot
# calculate the probability of being left- or right-handed for each
left_handed_probability = P_A_given_lh(ages, death_distribution_data)
right_handed_probability = P_A_given_rh(ages, death_distribution_data)
# create a plot of the two probabilities vs. age
fig, ax = plt.subplots() # create figure and axis objects
ax.plot(ages, left_handed_probability, label = "Left-handed")
ax.plot(ages, right_handed_probability, label = 'Right-handed')
ax.legend() # add a legend
ax.set_xlabel("Age at death")
ax.set_ylabel(r"Probability of being age A at death")
# + deletable=false run_control={"frozen": true} dc={"key": "60"} editable=false tags=["context"]
# ## 9. Moment of truth: age of left and right-handers at death
# <p>Finally, let's compare our results with the original study that found that left-handed people were nine years younger at death on average. We can do this by calculating the mean of these probability distributions in the same way we calculated P(LH) earlier, weighting the probability distribution by age and summing over the result.</p>
# <p>$$\text{Average age of left-handed people at death} = \sum_A A P(A | LH)$$</p>
# <p>$$\text{Average age of right-handed people at death} = \sum_A A P(A | RH)$$</p>
# + tags=["sample_code"] dc={"key": "60"}
# calculate average ages for left-handed and right-handed groups
# use np.array so that two arrays can be multiplied
average_lh_age = np.nansum(ages*np.array(left_handed_probability))
average_rh_age = np.nansum(ages*np.array(right_handed_probability))
# print the average ages for each group
print(average_lh_age, average_rh_age)
# print the difference between the average ages
print("The difference in average ages is " + str(round(average_lh_age - average_rh_age, 1)) + " years.")
# + deletable=false run_control={"frozen": true} dc={"key": "67"} editable=false tags=["context"]
# ## 10. Final comments
# <p>We got a pretty big age gap between left-handed and right-handed people purely as a result of the changing rates of left-handedness in the population, which is good news for left-handers: you probably won't die young because of your sinisterness. The reported rates of left-handedness have increased from just 3% in the early 1900s to about 11% today, which means that older people are much more likely to be reported as right-handed than left-handed, and so looking at a sample of recently deceased people will have more old right-handers.</p>
# <p>Our number is still less than the 9-year gap measured in the study. It's possible that some of the approximations we made are the cause: </p>
# <ol>
# <li>We used death distribution data from almost ten years after the study (1999 instead of 1991), and we used death data from the entire United States instead of California alone (which was the original study). </li>
# <li>We extrapolated the left-handedness survey results to older and younger age groups, but it's possible our extrapolation wasn't close enough to the true rates for those ages. </li>
# </ol>
# <p>One thing we could do next is figure out how much variability we would expect to encounter in the age difference purely because of random sampling: if you take a smaller sample of recently deceased people and assign handedness with the probabilities of the survey, what does that distribution look like? How often would we encounter an age gap of nine years using the same data and assumptions? We won't do that here, but it's possible with this data and the tools of random sampling. </p>
# <!-- I did do this if we want to add more tasks - it would probably take three more blocks.-->
# <p>To finish off, let's calculate the age gap we'd expect if we did the study in 2018 instead of in 1990. The gap turns out to be much smaller since rates of left-handedness haven't increased for people born after about 1960. Both the National Geographic study and the 1990 study happened at a unique time - the rates of left-handedness had been changing across the lifetimes of most people alive, and the difference in handedness between old and young was at its most striking. </p>
# + tags=["sample_code"] dc={"key": "67"}
# Calculate the probability of being left- or right-handed for all ages
left_handed_probability_2018 = P_A_given_lh(ages, death_distribution_data, study_year=2018)
right_handed_probability_2018 = P_A_given_rh(ages, death_distribution_data, study_year=2018)
# calculate average ages for left-handed and right-handed groups
average_lh_age_2018 = np.nansum(ages*np.array(left_handed_probability_2018))
average_rh_age_2018 = np.nansum(ages*np.array(right_handed_probability_2018))
print("The difference in average ages is " +
str(round(average_rh_age_2018 - average_lh_age_2018, 1)) + " years.")
| DataCamp/Do Left-handed People Really Die Young?/notebook.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import torch
import random
import numpy as np
random.seed(0)
np.random.seed(0)
torch.manual_seed(0)
torch.cuda.manual_seed(0)
torch.backends.cudnn.deterministic = True
# -
import sklearn.datasets
wine = sklearn.datasets.load_wine()
wine.data.shape
# +
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
wine.data[:, :2],
wine.target,
test_size=0.3,
shuffle=True)
X_train = torch.FloatTensor(X_train)
X_test = torch.FloatTensor(X_test)
y_train = torch.LongTensor(y_train)
y_test = torch.LongTensor(y_test)
# +
class WineNet(torch.nn.Module):
def __init__(self, n_hidden_neurons):
super(WineNet, self).__init__()
self.fc1 = torch.nn.Linear(2, n_hidden_neurons)
self.activ1 = torch.nn.Sigmoid()
self.fc2 = torch.nn.Linear(n_hidden_neurons, n_hidden_neurons)
self.activ2 = torch.nn.Sigmoid()
self.fc2_2 = torch.nn.Linear(n_hidden_neurons, n_hidden_neurons)
self.activ2_2 = torch.nn.Sigmoid()
self.fc3 = torch.nn.Linear(n_hidden_neurons, 3)
self.sm = torch.nn.Softmax(dim=1)
def forward(self, x):
x = self.fc1(x)
x = self.activ1(x)
x = self.fc2(x)
x = self.activ2(x)
x = self.fc2_2(x)
x = self.activ2_2(x)
x = self.fc3(x)
return x
def inference(self, x):
x = self.forward(x)
x = self.sm(x)
return x
wine_net = WineNet(5)
# +
loss = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(wine_net.parameters(),
lr=1.0e-3)
# -
np.random.permutation(5)
# +
batch_size = 10
for epoch in range(5000):
order = np.random.permutation(len(X_train))
for start_index in range(0, len(X_train), batch_size):
optimizer.zero_grad()
batch_indexes = order[start_index:start_index+batch_size]
x_batch = X_train[batch_indexes]
y_batch = y_train[batch_indexes]
preds = wine_net.forward(x_batch)
loss_value = loss(preds, y_batch)
loss_value.backward()
optimizer.step()
if epoch % 100 == 0:
test_preds = wine_net.forward(X_test)
test_preds = test_preds.argmax(dim=1)
print((test_preds == y_test).float().mean())
# +
import matplotlib.pyplot as plt
# %matplotlib inline
plt.rcParams['figure.figsize'] = (10, 8)
n_classes = 3
plot_colors = ['g', 'orange', 'black']
plot_step = 0.02
x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1
xx, yy = torch.meshgrid(torch.arange(x_min, x_max, plot_step),
torch.arange(y_min, y_max, plot_step))
preds = wine_net.inference(
torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1)], dim=1))
preds_class = preds.data.numpy().argmax(axis=1)
preds_class = preds_class.reshape(xx.shape)
plt.contourf(xx, yy, preds_class, cmap='Accent')
for i, color in zip(range(n_classes), plot_colors):
indexes = np.where(y_train == i)
plt.scatter(X_train[indexes, 0],
X_train[indexes, 1],
c=color,
label=wine.target_names[i],
cmap='Accent')
plt.xlabel(wine.feature_names[0])
plt.ylabel(wine.feature_names[1])
plt.legend()
# -
| notebooks/pytorch_trainin_wine.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import matplotlib.pyplot as plt
import numpy as np
# find out at which point the car starts to find the red label
def calculate_start_point(dis, after):
for i in range(after, len(dis) - 1):
if dis[i] > dis[i+1]:
return i
return -1
def visualize(k, start_pos, is_average=False):
num_of_points = 900
dis = []
for i in range(1, 6):
cur = np.load('./2-13/2-13-k' + str(k) + '-car2-' + str(i) + '.npy')[:,0]
sp = calculate_start_point(cur, start_pos[i-1])
cur_dis = cur[sp:sp+num_of_points]
dis.append(cur_dis)
# plt.plot(cur_dis)
mean_list = np.mean(dis, axis=0)
max_list = np.max(dis, axis=0)
min_list = np.min(dis, axis=0)
plt.xlabel('time step')
plt.ylabel('distance to the previous car')
plt.plot(mean_list, label='K = ' + str(int(k)))
x = np.arange(0, 900, 1)
if not is_average:
plt.title('Mean Case')
baseline = [70] * num_of_points
plt.fill_between(x, max_list, min_list, color='grey', alpha='0.5')
plt.plot(baseline, 'y', label='baseline')
else:
plt.title('K = ' + str(int(k)))
plt.legend()
def export_data(k, start_pos):
num_of_points = 900
for i in range(1, 6):
cur = np.load('./2-13/2-13-k' + str(k) + '-car2-' + str(i) + '.npy')[:,0]
sp = calculate_start_point(cur, start_pos[i-1])
cur_dis = cur[sp:sp+num_of_points]
np.save('./2-13-cleaned/2-13-k' + str(k) + '-car2-' + str(i) + '-clearned', cur_dis)
export_data('01', [150, 150, 30, 5, 40])
export_data('05', [20, 50, 50, 70, 20])
export_data('07', [55, 30, 50, 75, 40])
export_data('08', [180, 30, 80, 20, 80])
export_data('09', [130, 90, 110, 50, 80])
export_data('10', [80, 90, 30, 60, 280])
visualize('01', [150, 150, 30, 5, 40], True)
visualize('05', [20, 50, 50, 70, 20], True)
visualize('07', [55, 30, 50, 75, 40], True)
visualize('08', [180, 30, 80, 20, 80], True)
visualize('09', [130, 90, 110, 50, 80], True)
visualize('10', [80, 90, 30, 60, 280], True)
# K = 0.1
visualize('01', [150, 150, 30, 5, 40])
# K = 0.5
visualize('05', [20, 50, 50, 70, 20])
# K = 0.7
visualize('07', [55, 30, 50, 75, 40])
# K = 0.8
visualize('08', [180, 30, 80, 20, 80])
# K = 0.9
visualize('09', [130, 90, 110, 50, 80])
# K = 1.0
visualize('10', [80, 90, 30, 60, 280])
| record/car-following/.ipynb_checkpoints/car-following-visualization-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
# ---
# Write a program that uses the input function to ask the user for their name and then prints the name on the screen. You can add to the end of the print function given to you.
name = input('What is your name: ')
print('Hello,', name)
| 1.2_codeHS.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
# ---
# # RF model with max_depth=12 (limited, unlike before) - including SHAP value, ALE, Gini, LOCO, etc...
# ## Initialisation
# +
import logging
import os
import re
import sys
import warnings
from collections import namedtuple
from functools import reduce
from itertools import combinations
from operator import mul
import cloudpickle
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
import shap
from joblib import Memory, Parallel, delayed
from loguru import logger as loguru_logger
from matplotlib.patches import Rectangle
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score, train_test_split
from tqdm import tqdm
import wildfires.analysis
from alepython import ale_plot
from alepython.ale import _second_order_ale_quant
from wildfires.analysis import *
from wildfires.dask_cx1 import get_parallel_backend
from wildfires.data import *
from wildfires.logging_config import enable_logging
from wildfires.qstat import get_ncpus
from wildfires.utils import *
loguru_logger.enable("alepython")
loguru_logger.remove()
loguru_logger.add(sys.stderr, level="WARNING")
logger = logging.getLogger(__name__)
enable_logging("jupyter")
warnings.filterwarnings("ignore", ".*Collapsing a non-contiguous coordinate.*")
warnings.filterwarnings("ignore", ".*DEFAULT_SPHERICAL_EARTH_RADIUS*")
warnings.filterwarnings("ignore", ".*guessing contiguous bounds*")
normal_coast_linewidth = 0.5
mpl.rc("figure", figsize=(14, 6))
mpl.rc("font", size=9.0)
figure_saver = FigureSaver(
directories=os.path.join(
"~", "tmp", "analysis_time_lags_explain_pdp_ale_lower_max_depth"
),
debug=True,
dpi=500,
)
memory = get_memory("analysis_time_lags_explain_pdp_ale_lower_max_depth", verbose=100)
CACHE_DIR = os.path.join(
DATA_DIR, ".pickle", "time_lags_explain_pdp_ale_lower_max_depth"
)
# -
# ## Overwrite wildfires get_data with our own personalised version
from get_time_lag_data import get_data
value = "symlog"
linthres = 1e-2
subs = [2, 3, 4, 5, 6, 7, 8, 9]
log_xscale_kwargs = dict(value=value, linthreshx=linthres, subsx=subs)
log_yscale_kwargs = dict(value=value, linthreshy=linthres, subsy=subs)
log_vars = (
"dry day period",
"popd",
"agb tree",
"cape x precip",
"lai",
"shruball",
"pftherb",
"pftcrop",
"treeall",
)
# ## Creating the Data Structures used for Fitting
# +
shift_months = [1, 3, 6, 9, 12, 18, 24]
# selection_variables = (
# "VOD Ku-band -3 Month",
# # "SIF", # Fix regridding!!
# "VOD Ku-band -1 Month",
# "Dry Day Period -3 Month",
# "FAPAR",
# "pftHerb",
# "LAI -1 Month",
# "popd",
# "Dry Day Period -24 Month",
# "pftCrop",
# "FAPAR -1 Month",
# "FAPAR -24 Month",
# "Max Temp",
# "Dry Day Period -6 Month",
# "VOD Ku-band -6 Month",
# )
# ext_selection_variables = selection_variables + (
# "Dry Day Period -1 Month",
# "FAPAR -6 Month",
# "ShrubAll",
# "SWI(1)",
# "TreeAll",
# )
from ipdb import launch_ipdb_on_exception
with launch_ipdb_on_exception():
(
e_s_endog_data,
e_s_exog_data,
e_s_master_mask,
e_s_filled_datasets,
e_s_masked_datasets,
e_s_land_mask,
) = get_data(shift_months=shift_months, selection_variables=None)
# -
# ### Offset data from 12 or more months before the current month in order to ease analysis (interpretability).
# We are interested in the trends in these properties, not their absolute values, therefore we subtract a recent 'seasonal cycle' analogue.
# This hopefully avoids capturing the same relationships for a variable and its 12 month counterpart due to their high correlation.
to_delete = []
for column in e_s_exog_data:
match = re.search(r"-\d{1,2}", column)
if match:
span = match.span()
# Change the string to reflect the shift.
original_offset = int(column[slice(*span)])
if original_offset > -12:
# Only shift months that are 12 or more months before the current month.
continue
comp = -(-original_offset % 12)
new_column = " ".join(
(
column[: span[0] - 1],
f"{original_offset} - {comp}",
column[span[1] + 1 :],
)
)
if comp == 0:
comp_column = column[: span[0] - 1]
else:
comp_column = " ".join(
(column[: span[0] - 1], f"{comp}", column[span[1] + 1 :])
)
print(column, comp_column)
e_s_exog_data[new_column] = e_s_exog_data[column] - e_s_exog_data[comp_column]
to_delete.append(column)
for column in to_delete:
del e_s_exog_data[column]
# ## Cached Model Fitting
# If anything regarding the data changes above, the cache has to be refreshed using memory.clear()!
# +
ModelResults = namedtuple(
"ModelResults",
("X_train", "X_test", "y_train", "y_test", "r2_test", "r2_train", "model"),
)
model_cache = SimpleCache("rf_model", cache_dir=CACHE_DIR)
# model_cache.clear()
@model_cache
def get_time_lags_model():
"""Get a RF model trained on the extended shifted data.
Returns:
ModelResults: A namedtuple with the fields 'X_train', 'X_test', 'y_train', 'y_test',
'r2_test', 'r2_train', and 'model'.
"""
# Split the data.
X_train, X_test, y_train, y_test = train_test_split(
e_s_exog_data, e_s_endog_data, random_state=1, shuffle=True, test_size=0.3
)
# Define and train the model.
rf = RandomForestRegressor(n_estimators=500, max_depth=12, random_state=1)
rf.fit(X_train, y_train)
r2_test = rf.score(X_test, y_test)
r2_train = rf.score(X_train, y_train)
return ModelResults(X_train, X_test, y_train, y_test, r2_test, r2_train, rf)
from wildfires.dask_cx1 import *
# with get_parallel_backend(fallback=False):
with parallel_backend("threading", n_jobs=get_ncpus()):
model_results = get_time_lags_model()
# Take advantage of all cores available to our job.
model_results.model.n_jobs = get_ncpus()
# -
# ## R2 Scores
print("R2 train:", model_results.r2_train)
print("R2 test:", model_results.r2_test)
# +
from sklearn.metrics import mean_squared_error, r2_score
print(
"mse train:",
mean_squared_error(
model_results.model.predict(model_results.X_train), model_results.y_train
),
)
print(
"mse test:",
mean_squared_error(
model_results.model.predict(model_results.X_test), model_results.y_test
),
)
# -
# ## Mapping
# +
# e_s_endog_data,
# e_s_exog_data,
# e_s_master_mask,
# e_s_filled_datasets,
# e_s_masked_datasets,
# e_s_land_mask,
# Want dry day period > 12 AND FAPAR > 0.35 - the boundary of a 'strange' quadrant.
# Shape of the raw array - shape of master_mask.
FAPAR_lim = 0.39
DRY_DAY_lim = 20
fapar_data = np.ma.MaskedArray(
np.zeros_like(e_s_master_mask, dtype=np.float64),
mask=np.ones_like(e_s_master_mask, dtype=np.float64),
)
fapar_data[~e_s_master_mask] = e_s_exog_data["FAPAR"].values
fapar_data.mask |= fapar_data < FAPAR_lim
dry_day_data = np.ma.MaskedArray(
np.zeros_like(e_s_master_mask, dtype=np.float64),
mask=np.ones_like(e_s_master_mask, dtype=np.float64),
)
dry_day_data[~e_s_master_mask] = e_s_exog_data["Dry Day Period"].values
dry_day_data.mask |= dry_day_data < DRY_DAY_lim
combined_mask = fapar_data.mask | dry_day_data.mask
# -
from wildfires.data import dummy_lat_lon_cube
# +
# _ = cube_plotting(~fapar_data.mask, title=f"FAPAR > {FAPAR_lim}")
# _ = cube_plotting(~dry_day_data.mask, title=f"Dry Day Period > {DRY_DAY_lim}")
# _ = cube_plotting(~combined_mask, title=f"Combined FAPAR > {FAPAR_lim} & Dry Day Period > {DRY_DAY_lim}")
mpl.rc("figure", figsize=(9, 3.8), dpi=900)
selection = match_shape(np.any(~combined_mask, axis=0), combined_mask.shape)
new_fapar_data = fapar_data.copy()
new_fapar_data.mask = ~selection
new_fapar = dummy_lat_lon_cube(new_fapar_data)
_ = cube_plotting(
new_fapar[:, 130:-130, 280:-150],
title=f"FAPAR > {FAPAR_lim} & Dry Day Period > {DRY_DAY_lim}",
label="Mean FAPAR",
coastline_kwargs={"linewidth": 0.3},
)
# -
# ## SHAP Values
# Using dask to parallelise the SHAP value calculations is possible, but avoid loky (and dask depending on its setup)
model_results.model
[tree.get_n_leaves() for tree in model_results.model.estimators_]
# +
model_results.model.n_jobs = get_ncpus()
N = 10
background_data = model_results.X_train[-200:]
def get_shap_values():
print(os.getpid(), "starting shap")
explainer = shap.TreeExplainer(model_results.model, data=background_data)
shap_values = explainer.shap_values(model_results.X_train[:N])
return shap_values
with get_client(fallback=True, fallback_threaded=False) as client:
shap_values = np.vstack
with Time(f"shap {N}"):
with get_parallel_backend():
shap_values = np.vstack(
Parallel()(delayed(get_shap_values)() for i in range(10))
)
# +
import matplotlib as mpl
mpl.rc("figure", dpi=1000)
shap.summary_plot(
shap_values, model_results.X_train[:N], title="SHAP Feature Importances"
)
# -
# ### SHAP Interaction Values
explainer = shap.TreeExplainer(model_results.model)
N = 10
with Time(f"shap interaction, {N}"):
shap_interaction_values = explainer.shap_interaction_values(
model_results.X_train[:N]
)
explainer = shap.TreeExplainer(model_results.model)
N = 20
with Time(f"shap interaction, {N}"):
shap_interaction_values = explainer.shap_interaction_values(
model_results.X_train[:N]
)
shap.summary_plot(shap_interaction_values, model_results.X_train[:N])
gini_mean = pd.Series(
model_results.model.feature_importances_, index=model_results.X_train.columns
).sort_values(ascending=False)
# ## ELI5 Permutation Importances (PFI)
# +
import cloudpickle
import eli5
from eli5.sklearn import PermutationImportance
from joblib import Parallel, delayed, parallel_backend
from wildfires.dask_cx1 import get_parallel_backend
perm_importance_cache = SimpleCache(
"perm_importance", cache_dir=CACHE_DIR, pickler=cloudpickle
)
# Does not seem to work with the dask parallel backend - it gets bypassed and every available core on the machine is used up
# if attempted.
@perm_importance_cache
def get_perm_importance():
with parallel_backend("threading", n_jobs=get_ncpus()):
return PermutationImportance(model_results.model).fit(
model_results.X_train, model_results.y_train
)
perm_importance = get_perm_importance()
perm_df = eli5.explain_weights_df(
perm_importance, feature_names=list(model_results.X_train.columns)
)
# -
# ### Brute Force LOCO (leave one column out) by retraining the model with the relevant column(s) removed
# +
import sklearn.base
from sklearn.metrics import mean_squared_error
from wildfires.dask_cx1 import *
# XXX: This uses subsampled data for now!!!!
N = int(2e5)
loco_cache = SimpleCache("loco_mses", cache_dir=CACHE_DIR)
######### !!!!!!!!!!!!!!!!!1! ####################
# loco_cache.clear()
def simple_loco(est, X_train, y_train, leave_out=()):
"""Simple LOCO feature importances.
Args:
est: Estimator object with `fit()` and `predict()` methods.
train_X (pandas DataFrame): DataFrame containing the training data.
train_y (pandas Series or array-like): Target data.
leave_out (iterable of column names): Column names to exclude.
Returns:
mse: Mean squared error of the training set predictions.
"""
# Get a new instance with the same parameters.
est = sklearn.base.clone(est)
# Fit on the reduced dataset.
X_train = X_train.copy()
for column in leave_out:
del X_train[column]
est.fit(X_train[:N], y_train[:N])
# Get MSE.
mse = mean_squared_error(y_true=y_train, y_pred=est.predict(X_train))
return mse
@loco_cache
def get_loco_mses():
# Baseline prediction will be the empty list (first entry here).
leave_out_columns = [[]]
for column in model_results.X_train.columns:
leave_out_columns.append([column])
model_clone = sklearn.base.clone(model_results.model)
with get_parallel_backend(False):
mse_values = Parallel(verbose=10)(
delayed(simple_loco)(
model_clone, model_results.X_train, model_results.y_train, columns
)
for columns in tqdm(leave_out_columns, desc="Prefetch LOCO columns")
)
return leave_out_columns, mse_values
leave_out_columns, mse_values = get_loco_mses()
# +
from warnings import warn
mse_values = np.asarray(mse_values)
assert leave_out_columns[0] == []
loco_columns = ["baseline"] + ["_".join(columns) for columns in leave_out_columns[1:]]
baseline_mse = mse_values[0]
loco_importances = pd.Series(
mse_values[1:] - baseline_mse, index=loco_columns[1:]
).sort_values(ascending=False)
if np.any(loco_importances < 0):
warn("MSE values without some features were lower than baseline.")
# -
# ### Comparing the three measures - Gini vs PFI vs LOCO
# +
import seaborn as sns
loco = False
comp_import_df = pd.DataFrame(
np.hstack(
(
gini_mean.index.values[:, np.newaxis],
gini_mean.values[:, np.newaxis],
perm_df["feature"].values[:, np.newaxis],
perm_df["weight"].values[:, np.newaxis],
*(
(
loco_importances.index.values[:, np.newaxis],
loco_importances.values[:, np.newaxis],
)
if loco
else ()
),
)
),
columns=[
["Gini"] * 2 + ["PFI"] * 2 + (["LOCO"] if loco else []) * 2,
["Feature", "Importance"] * (3 if loco else 2),
],
)
fig, axes = plt.subplots(1, 3 if loco else 2, figsize=(23 if loco else 15.3, 15))
for ax, measure in zip(axes, ("Gini", "PFI", "LOCO")):
features = list(comp_import_df[(measure, "Feature")])[::-1]
importances = np.asarray(comp_import_df[(measure, "Importance")])[::-1]
importances /= np.sum(importances)
ax.set_title(measure)
ax.barh(
range(len(features)),
importances,
align="center",
color=sns.color_palette("husl", len(features), desat=0.5)[::-1],
)
ax.set_yticks(range(len(features)))
ax.set_yticklabels(features)
ax.set_xlabel(f"Relative {measure} Importance")
ax.margins(y=0.008, tight=True)
plt.subplots_adjust(wspace=0.45)
# -
# ## Individual Tree Importances - Gini vs PFI
# +
N_col = 20
fig, (ax, ax2) = plt.subplots(2, 1, sharex=True, figsize=(7, 6))
# Gini values.
ind_trees_gini = pd.DataFrame(
[tree.feature_importances_ for tree in model_results.model],
columns=model_results.X_train.columns,
)
mean_importances = ind_trees_gini.mean().sort_values(ascending=False)
ind_trees_gini = ind_trees_gini.reindex(mean_importances.index, axis=1)
sns.boxplot(data=ind_trees_gini.iloc[:, :N_col], ax=ax)
ax.set(
# title="Gini Importances",
ylabel="Gini Importance (MSE)\n"
)
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha="right")
# PFI values.
pfi_ind = pd.DataFrame(perm_importance.results_, columns=model_results.X_train.columns)
# Re-index according to the same ordering as for the Gini importances!
pfi_ind = pfi_ind.reindex(mean_importances.index, axis=1)
sns.boxplot(data=pfi_ind.iloc[:, :N_col], ax=ax2)
ax2.set(
# title="PFI Importances",
ylabel="PFI Importance\n"
)
_ = ax2.set_xticklabels(ax2.get_xticklabels(), rotation=45, ha="right")
for _ax in (ax, ax2):
_ax.grid(which="major", alpha=0.3)
_ax.tick_params(labelleft=False)
fig.suptitle("Gini and PFI Importances")
plt.tight_layout()
plt.subplots_adjust(top=0.91)
# -
# ## Correlation Plot
# +
from functools import partial
import matplotlib.colors as colors
class MidpointNormalize(colors.Normalize):
def __init__(self, *args, midpoint=None, **kwargs):
self.midpoint = midpoint
super().__init__(*args, **kwargs)
def __call__(self, value, clip=None):
# Simple mapping between the color range halves and the data halves.
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
def corr_plot(exog_data):
columns = list(map(map_name, exog_data.columns))
def trim(string, n=10, cont_str="..."):
if len(string) > n:
string = string[: n - len(cont_str)]
string += cont_str
return string
n = len(columns)
fig, ax = plt.subplots(figsize=(12, 8))
corr_arr = np.ma.MaskedArray(exog_data.corr().values)
corr_arr.mask = np.zeros_like(corr_arr)
# Ignore diagnals, since they will all be 1 anyway!
np.fill_diagonal(corr_arr.mask, True)
im = ax.matshow(
corr_arr,
interpolation="none",
cmap="RdYlBu_r",
norm=MidpointNormalize(midpoint=0.0),
)
fig.colorbar(im, pad=0.02, shrink=0.8, aspect=40, label="Pearson Correlation")
ax.set_xticks(np.arange(n))
ax.set_xticklabels(map(partial(trim, n=15), columns))
ax.set_yticks(np.arange(n))
ax.set_yticklabels(columns)
# Activate ticks on top of axes.
ax.tick_params(axis="x", bottom=False, top=True, labelbottom=False, labeltop=True)
# Rotate and align top ticklabels
plt.setp(
[tick.label2 for tick in ax.xaxis.get_major_ticks()],
rotation=45,
ha="left",
va="center",
rotation_mode="anchor",
)
fig.tight_layout()
corr_plot(model_results.X_train[model_results.X_train.columns[:-12]])
print("Excluded columns:", model_results.X_train.columns[-12:])
# -
# ## PDP Plots
from pdpbox import pdp
dry_day_isolate = pdp.pdp_isolate(
model_results.model,
model_results.X_train,
model_results.X_train.columns,
feature="Dry Day Period",
num_grid_points=20,
percentile_range=(5, 95),
)
value = "symlog"
linthres = 1e-2
subs = [2, 3, 4, 5, 6, 7, 8, 9]
log_xscale_kwargs = dict(value=value, linthreshx=linthres, subsx=subs)
log_yscale_kwargs = dict(value=value, linthreshy=linthres, subsy=subs)
log_vars = (
"dry day period",
"popd",
"agb tree",
"cape x precip",
"lai",
"shruball",
"pftherb",
"pftcrop",
"treeall",
)
# ## ALE Plotting
# +
from functools import partial
import matplotlib.colors as colors
class MidpointNormalize(colors.Normalize):
def __init__(self, *args, midpoint=None, **kwargs):
self.midpoint = midpoint
super().__init__(*args, **kwargs)
def __call__(self, value, clip=None):
# Simple mapping between the color range halves and the data halves.
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
def ale_2d(predictor, train_set, features, bins=40, coverage=1):
if coverage < 1:
# This should be ok if `train_set` is randomised, as it usually is.
train_set = train_set[: int(train_set.shape[0] * coverage)]
ale, quantiles_list, samples_grid = _second_order_ale_quant(
predictor, train_set, features, bins=bins, return_samples_grid=True
)
fig, ax = plt.subplots(figsize=(7.5, 4.5))
centres_list = [get_centres(quantiles) for quantiles in quantiles_list]
n_x, n_y = 50, 50
x = np.linspace(centres_list[0][0], centres_list[0][-1], n_x)
y = np.linspace(centres_list[1][0], centres_list[1][-1], n_y)
X, Y = np.meshgrid(x, y, indexing="xy")
ale_interp = scipy.interpolate.interp2d(centres_list[0], centres_list[1], ale.T)
CF = ax.contourf(
X,
Y,
ale_interp(x, y),
cmap="bwr",
levels=30,
alpha=0.7,
norm=MidpointNormalize(midpoint=0.0),
)
# Do not autoscale, so that boxes at the edges (contourf only plots the bin
# centres, not their edges) don't enlarge the plot. Such boxes include markings for
# invalid cells, or hatched boxes for valid cells.
plt.autoscale(False)
# Add hatching for the significant cells. These have at least `min_samples` samples.
# By default, calculate this as the number of samples in each bin if everything was equally distributed, divided by 10.
min_samples = (train_set.shape[0] / reduce(mul, map(len, centres_list))) / 10
for i, j in zip(*np.where(samples_grid >= min_samples)):
ax.add_patch(
Rectangle(
[quantiles_list[0][i], quantiles_list[1][j]],
quantiles_list[0][i + 1] - quantiles_list[0][i],
quantiles_list[1][j + 1] - quantiles_list[1][j],
linewidth=0,
fill=None,
hatch=".",
alpha=0.4,
)
)
if np.any(ale.mask):
# Add rectangles to indicate cells without samples.
for i, j in zip(*np.where(ale.mask)):
ax.add_patch(
Rectangle(
[quantiles_list[0][i], quantiles_list[1][j]],
quantiles_list[0][i + 1] - quantiles_list[0][i],
quantiles_list[1][j + 1] - quantiles_list[1][j],
linewidth=1,
edgecolor="k",
facecolor="none",
alpha=0.4,
)
)
fig.colorbar(CF, format="%.0e", pad=0.03, aspect=32, shrink=0.85)
ax.set_xlabel(features[0])
ax.set_ylabel(features[1])
nbins_str = "x".join([str(len(centres)) for centres in centres_list])
fig.suptitle(
f"Second-order ALE of {features[0]} and {features[1]}\n"
f"Bins: {nbins_str} (Hatching: Sig., Boxes: Missing)"
)
plt.subplots_adjust(top=0.89)
if any(log_var.lower() in features[0].lower() for log_var in log_vars):
ax.set_xscale(**log_xscale_kwargs)
if any(log_var.lower() in features[1].lower() for log_var in log_vars):
ax.set_yscale(**log_yscale_kwargs)
figure_saver.save_figure(fig, "__".join(features), sub_directory="2d_ale_new")
return ale, quantiles_list, samples_grid
# -
_ = ale_2d(
model_results.model.predict,
model_results.X_train,
["Dry Day Period", "FAPAR"],
bins=40,
coverage=1,
)
# +
import matplotlib as mpl
mpl.rc("figure", figsize=(7.5, 4.5), dpi=600)
feature = "Dry Day Period"
with figure_saver(feature, sub_directory="1d_ale_new"):
ale_plot(
model_results.model,
model_results.X_train,
feature,
bins=40,
monte_carlo=True, # XXX: !!!
monte_carlo_rep=100,
monte_carlo_ratio=0.01,
plot_quantiles=False,
)
plt.gcf().axes[0].lines[-1].set_marker(".")
plt.gcf().axes[0].set_xscale(
value="symlog", linthres=1e-2, subs=[2, 3, 4, 5, 6, 7, 8, 9]
)
# +
import matplotlib as mpl
mpl.rc("figure", figsize=(7.5, 4.5), dpi=600)
feature = "FAPAR"
with figure_saver(feature, sub_directory="1d_ale_new"):
ale_plot(
model_results.model,
model_results.X_train,
feature,
bins=40,
monte_carlo=True, # XXX: !!!
monte_carlo_rep=100,
monte_carlo_ratio=0.01,
plot_quantiles=False,
)
plt.gcf().axes[0].lines[-1].set_marker(".")
# -
# ## Worldwide
# +
def save_ale_plot_1d(model, X_train, column):
with figure_saver(column, sub_directory="ale"):
ale_plot(
model,
X_train,
column,
bins=40,
monte_carlo=False, # XXX: !!!
monte_carlo_rep=100,
monte_carlo_ratio=0.01,
plot_quantiles=False,
)
plt.gcf().axes[0].lines[-1].set_marker(".")
if any(feature.lower() in column.lower() for feature in log_vars):
plt.gcf().axes[0].set_xscale(**log_xscale_kwargs)
target_func = save_ale_plot_1d
model_params = (model_results.model, model_results.X_train[:100])
with get_parallel_backend(fallback="none") as (backend, client):
if client is not None:
print("Using Dask", client)
# A Dask scheduler was found, so we need to scatter large pieces of data (if any).
model_params = [client.scatter(param, broadcast=True) for param in model_params]
def func(param_iter):
return client.gather(client.map(target_func, *list(zip(*(param_iter)))))
else:
print("Not using any backend")
def func(param_iter):
return [target_func(*params) for params in param_iter]
func(
(*model_params, column)
for column in tqdm(model_results.X_train.columns, desc="ALE plotting")
if column == "lightning"
)
# -
# ### 2D ALE interaction plots
# +
coverage = 0.02
def plot_ale_and_get_importance(columns, model, train_set):
model.n_jobs = get_ncpus()
ale, quantiles_list, samples_grid = ale_2d(
model.predict, train_set, columns, bins=20, coverage=coverage,
)
min_samples = (
train_set.shape[0] / reduce(mul, map(lambda x: len(x) - 1, quantiles_list))
) / 10
try:
return np.ma.max(ale[samples_grid > min_samples]) - np.ma.min(
ale[samples_grid > min_samples]
)
except:
return None
# -
ptp_values = {}
columns_list = list(combinations(model_results.X_train.columns, 2))
for columns in tqdm(columns_list, desc="Calculating 2D ALE plots"):
ptp_values[columns] = plot_ale_and_get_importance(
columns, model_results.model, model_results.X_train
)
# +
# Ignore and count None values, then plot a histogram of the ptp values.
filtered_columns_list = []
filtered_ptp_values = []
for columns, ptp in ptp_values.items():
if ptp is not None:
filtered_columns_list.append(columns)
filtered_ptp_values.append(ptp)
np.asarray([ptp for ptp in ptp_values if ptp is not None])
_ = plt.hist(filtered_ptp_values, bins=20)
# -
pdp_results = pd.Series(filtered_ptp_values, index=filtered_columns_list)
pdp_results.sort_values(inplace=True, ascending=False)
print(pdp_results.head(20))
# ## Subset the original DataFrame to analyse specific regions only
def subset_dataframe(data, original_mask, additional_mask, suffix=""):
"""Sub-set results based on an additional mask.
Args:
data (pandas.core.frame.DataFrame): Data to select.
orig_mask (array-like): Original mask that was used to transform the data into the column representation in `data`. This mask should be False where data should be selected.
additional_mask (array-like): After conversion of columns in `data` back to a lat-lon grid, this mask will be used in addition to `orig_mask` to return a subset of the data to the column format. This mask should be False where data should be selected.
suffix (str): Suffix to add to column labels. An empty space will be added to the beginning of `suffix` if this is not already present.
Returns:
pandas.core.frame.DataFrame: Selected data.
"""
additional_mask = match_shape(additional_mask, original_mask.shape)
if suffix:
if suffix[0] != " ":
suffix = " " + suffix
new_data = {}
for column in tqdm(data.columns, desc="Selecting data"):
# Create a blank lat-lon grid.
lat_lon_data = np.empty_like(original_mask, dtype=np.float64)
# Convert data from the dense column representation to the sparse lat-lon grid.
lat_lon_data[~original_mask] = data[column]
# Use the original and the new mask to create new columns.
new_data[column + suffix] = lat_lon_data[
((~original_mask) & (~additional_mask))
]
return pd.DataFrame(new_data)
# ### SE Asia
# +
# Create new mask.
region_mask = ~box_mask(lats=(-10, 10), lons=(95, 150))
cube_plotting(region_mask)
# XXX: This only allows subsetting the original data (both training and test!) since otherwise the original mask does not apply.
# Apply new mask.
sub_X = subset_dataframe(e_s_exog_data, e_s_master_mask, region_mask, "SE ASIA")
print("Original size:", e_s_exog_data.shape)
print("Selected size:", sub_X.shape)
# Plot ALE plots for only this region.
for column in tqdm(sub_X.columns, desc="Calculating ALE plots"):
with figure_saver(column, sub_directory="ale_se_asia"):
ale_plot(
model_results.model,
sub_X,
column,
bins=40,
monte_carlo=True,
monte_carlo_rep=30,
monte_carlo_ratio=0.1,
verbose=False,
log="x"
if any(
feature.lower() in column.lower()
for feature in ("dry day period", "popd",)
)
else None,
)
# -
# ### Brazilian Amazon
# +
# Create new mask.
region_mask = ~box_mask(lats=(-15, 1), lons=(-72, -46))
cube_plotting(region_mask)
# XXX: This only allows subsetting the original data (both training and test!) since otherwise the original mask does not apply.
# Apply new mask.
sub_X = subset_dataframe(e_s_exog_data, e_s_master_mask, region_mask, "BRAZ AMAZ")
print("Original size:", e_s_exog_data.shape)
print("Selected size:", sub_X.shape)
# Plot ALE plots for only this region.
for column in tqdm(sub_X.columns, desc="Calculating ALE plots"):
with figure_saver(column, sub_directory="ale_braz_amaz"):
ale_plot(
model_results.model,
sub_X,
column,
bins=40,
monte_carlo=True,
monte_carlo_rep=30,
monte_carlo_ratio=0.1,
verbose=False,
log="x"
if any(
feature.lower() in column.lower()
for feature in ("dry day period", "popd",)
)
else None,
)
# -
# ### Europe
# +
# Create new mask.
region_mask = ~box_mask(lats=(33, 73), lons=(-11, 29))
cube_plotting(region_mask)
# XXX: This only allows subsetting the original data (both training and test!) since otherwise the original mask does not apply.
# Apply new mask.
sub_X = subset_dataframe(e_s_exog_data, e_s_master_mask, region_mask, "EUROPE")
print("Original size:", e_s_exog_data.shape)
print("Selected size:", sub_X.shape)
# Plot ALE plots for only this region.
for column in tqdm(sub_X.columns, desc="Calculating ALE plots"):
with figure_saver(column, sub_directory="ale_europe"):
ale_plot(
model_results.model,
sub_X,
column,
bins=40,
monte_carlo=True,
monte_carlo_rep=30,
monte_carlo_ratio=0.1,
verbose=False,
log="x"
if any(
feature.lower() in column.lower()
for feature in ("dry day period", "popd",)
)
else None,
)
| analyses/time_lags_explain_pdp_ale_lower_max_depth.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
# ---
# <table style="float:left; border:none">
# <tr style="border:none; background-color: #ffffff">
# <td style="border:none">
# <a href="http://bokeh.pydata.org/">
# <img
# src="assets/bokeh-transparent.png"
# style="width:50px"
# >
# </a>
# </td>
# <td style="border:none">
# <h1>Bokeh Tutorial</h1>
# </td>
# </tr>
# </table>
#
# <div style="float:right;"><h2>11. Running Bokeh Applications</h2></div>
# The architecture of Bokeh is such that high-level “model objects” (representing things like plots, ranges, axes, glyphs, etc.) are created in Python, and then converted to a JSON format that is consumed by the client library, BokehJS. Using the Bokeh Server, it is possible to keep the “model objects” in python and in the browser in sync with one another, creating powerful capabilities:
#
# * respond to UI and tool events generated in a browser with computations or queries using the full power of python
# * automatically push updates the UI (i.e. widgets or plots), in a browser
# * use periodic, timeout, and asychronous callbacks drive streaming updates
#
# ***This capability to synchronize between python and the browser is the main purpose of the Bokeh Server.***
from bokeh.io import output_notebook, show
output_notebook()
# ## Bokeh Apps in Notebooks
#
# The easiest way to embed a Bokeh application in a notebook is to make a function `modify_doc(doc)` that creates Bokeh content, and adds it to the document. This function can be passed to `show`, and the app defined by the function will be displayed inline. A short complete example is below
# +
from bokeh.layouts import column
from bokeh.models.widgets import TextInput, Button, Paragraph
def modify_doc(doc):
# create some widgets
button = Button(label="Say HI")
input = TextInput(value="Bokeh")
output = Paragraph()
# add a callback to a widget
def update():
output.text = "Hello, " + input.value
button.on_click(update)
# create a layout for everything
layout = column(button, input, output)
# add the layout to curdoc
doc.add_root(layout)
# In the notebook, just pass the function that defines the app to show
# You may need to supply notebook_url, e.g notebook_url="http://localhost:8889"
show(modify_doc)
# +
# EXERCISE: add a Select widget to this example that offers several different greetings
# -
# ## Bokeh Apps with `bokeh serve`
#
# It's also possible to define Bokeh applications by creating a standard Python script. In this case, there is no need to make a function like `modify_doc`. Typically, the script should simply create all the bokeh cotent, then add it to the doc with a line like
# ```python
# curdoc().add_root(layout)
# ```
#
# To try out the example below, copy the code into a file ``hello.py`` and then execute:
# ```bash
# bokeh serve --show hello.py
# ```
#
# <center><div style="font-size: 14pt;color: firebrick;"> NOTE: The exercise below require work outside the notebook <div></center>
# ```python
# # hello.py
#
# from bokeh.io import curdoc
# from bokeh.layouts import column
# from bokeh.models.widgets import TextInput, Button, Paragraph
#
# # create some widgets
# button = Button(label="Say HI")
# input = TextInput(value="Bokeh")
# output = Paragraph()
#
# # add a callback to a widget
# def update():
# output.text = "Hello, " + input.value
# button.on_click(update)
#
# # create a layout for everything
# layout = column(button, input, output)
#
# # add the layout to curdoc
# curdoc().add_root(layout)
# ```
# Copy this code to a script `hello.py` and run it with the Bokeh server.
# ## Linking Plots and Widgets
#
# Lets take a look at a more involved example that links several widgets to a plot.
# +
from numpy.random import random
from bokeh.layouts import column, row
from bokeh.plotting import figure
from bokeh.models.widgets import Select, TextInput
def get_data(N):
return dict(x=random(size=N), y=random(size=N), r=random(size=N) * 0.03)
COLORS = ["black", "firebrick", "navy", "olive", "goldenrod"]
def modify_doc(doc):
source = ColumnDataSource(data=get_data(200))
p = figure(tools="", toolbar_location=None)
r = p.circle(x='x', y='y', radius='r', source=source,
color="navy", alpha=0.6, line_color="white")
select = Select(title="Color", value="navy", options=COLORS)
input = TextInput(title="Number of points", value="200")
def update_color(attrname, old, new):
r.glyph.fill_color = select.value
select.on_change('value', update_color)
def update_points(attrname, old, new):
N = int(input.value)
source.data = get_data(N)
input.on_change('value', update_points)
layout = column(row(select, input, width=400), row(p))
doc.add_root(layout)
show(modify_doc)
# -
# EXERCISE: add more widgets to change more aspects of this plot
# # Streaming Data
#
# It is possible to efficiently stream new data to column data sources by using the ``stream`` method. This method accepts two argmuments:
# * ``new_data`` — a dictionary with the same structure as the column data source
# * ``rollover`` — a maximum column length on the client (earlier data is dropped) *[optional]*
#
# If no ``rollover`` is specified, data is never dropped on the client and columns grow without bound.
#
# It is often useful to use periodic callbacks in conjuction with streaming data The ``add_periodic_callback`` method of ``curdoc()`` accepts a callback function, and a time interval (in ms) to repeatedly execute the callback.
#
# +
from math import cos, sin
def modify_doc(doc):
p = figure(match_aspect=True)
p.circle(x=0, y=0, radius=1, fill_color=None, line_width=2)
# this is just to help the auto-datarange
p.rect(0, 0, 2, 2, alpha=0)
# this is the data source we will stream to
source = ColumnDataSource(data=dict(x=[1], y=[0]))
p.circle(x='x', y='y', size=12, fill_color='white', source=source)
def update():
x, y = source.data['x'][-1], source.data['y'][-1]
# construct the new values for all columns, and pass to stream
new_data = dict(x=[x*cos(0.1) - y*sin(0.1)], y=[x*sin(0.1) + y*cos(0.1)])
source.stream(new_data, rollover=8)
doc.add_periodic_callback(update, 150)
doc.add_root(p)
show(modify_doc)
# -
### EXERCISE: starting with the above example, create your own streaming plot
# Bokeh column data sources also support a `patch` method that can be used to efficiently update subsets of data.
# ## Directory Format Apps and Templates
#
# Bokeh apps can also be defined with a directory format. This format affords the use of extra modules, data files, templates, theme files, and other features. The directory should contain a `main.py` which is the "entry point" for the app, but ay contain extra parts:
# ```
# myapp
# |
# +---main.py
# +---server_lifecycle.py
# +---static
# +---theme.yaml
# +---templates
# +---index.html
# ```
# The [Directory Format](https://bokeh.pydata.org/en/latest/docs/user_guide/server.html#directory-format) section of the User's Guide has more information.
#
# See a complete sophisticated example at: https://github.com/bokeh/bokeh/tree/master/examples/app/dash
#
# <img src="https://bokeh.github.io/blog/2018/6/13/release-0-13-0/dash.png">
# ## Tips and Tricks
#
#
# * Real Python callbacks *require* a Bokeh server application. They cannot work with `output_file`, `components` or other functions that generate standalone output. Standalone content can only use `CustomJS` callbacks.
#
#
# * Try to update data sources "all at once" whenever possible, i.e. prefer this:
# ```python
# source.data = new_data_dict # GOOD
# ```
# rather then updating individual columns sequentially:
# ```python
# # LESS GOOD
# source.data['foo'] = new_foo_column
# source.data['bar'] = new_bar_column
# ```
# If the new columns are exactly the same length as the old ones, then updating sequentially, but will trigger extra updates, and may result in bad visual effects.
# If the new columns a different length than the old ones, then updating "all at once" is **mandatory**.
#
#
# * Each time a session is started, the Bokeh server runs the script (or `modify_doc`) function, and the code that is run ***must return completely new Bokeh objects every time***. It is not possible to share Bokeh objects between sessions. As a concrete example, this is what NOT to do:
# ```python
# source = ColumnDataSource(data) # VERY BAD - global outside modify_doc
#
# def modify_doc(doc):
# p = figure()
# p.circle('x', 'y', source=source)
# doc.add_root(p)
#
# ```
# The analogous situation would occur with a script if the script imports a global Bokeh object from a separate module (due to the way Python caches imports).
| bokeh/tutorial/11 - Running Bokeh Applictions.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
# ---
# +
# Imports
import numpy as np
import pandas as pd
# +
# Reading in csv file
df = pd.read_csv('weekly_prices.csv')
# +
# Checking the shape of the data
df.shape
# +
# Checking to see what the data looks like
# There appears to be some NaN values
df.head(10)
# +
# Drop the NaN values
df = df.dropna()
# +
# Check to make sure they were removed
df['dollars_per_gallon'].isnull().any()
# -
df
| notebooks/gas_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
# ---
# + [markdown] nbgrader={"grade": false, "grade_id": "hw4_instructions", "locked": true, "schema_version": 1, "solution": false}
# # Homework: lecture 1 (x points)
#
#
# To begin, answer the questions below:
#
# -
# Packages and code used to make the grading work
# Do not edit this, just execute it
from ipywidgets import widgets
from grading.ok import check
#import autograde.notebook as nb
#import matplotlib.pyplot as plt
# ## Question 1
# What is the best fruit? (Select one answer)
# + tags=["q1"]
# A multiple choice question. Students select one of the replies
# the value they select will be available as `q1.value`
# There are many more widgets https://ipywidgets.readthedocs.io/en/stable/index.html
# that we could use to build simple questions that aren't code
# We'd probably want to make a helper in one of the earthpy libraries
# that removes some of the boilerplate?
q1 = widgets.Select(
options=['Apples', 'Oranges', 'Pears', 'Banana', 'Chocolate'],
description='The best fruit is',
style={'description_width': 'initial'}
)
q1
# + tags=["public", "q1"]
# this will be a public test of the answer
assert q1.value, "You need to select one reply"
# + tags=["private", "q1"]
# this will be a private test of the answer
# Students won't be able to see this
assert 'Chocolate' in q1.value, "The best fruit is chocolate"
# -
# ## Question 2
#
# We discussed sports at great length in the lecture. Select the best sports from the list below. (select one or more replies)
# + tags=["q2"]
# A multiple choice question. Students select one or more of the replies
# the value(s) they select will be available as `q1.value`
q2 = widgets.SelectMultiple(
options=['Eating', 'Running', 'Swimming', 'Cycling'],
description='The best sports are',
style={'description_width': 'initial'}
)
q2
# + tags=["public", "q2"]
assert q2.value, "You need to select at least one reply"
# + tags=["private", "q2"]
# to compute credit that isn't 0/1 create a function
# that returns a number, the credit achieved.
# XXX is this the best way of doing this?
def check_q2():
score = 0
if 'Cycling' not in q2.value:
print("Cycling is one of the best sports")
else:
score += 1
if 'Running' not in q2.value:
print("Running is one of the best sports")
else:
score += 1
if 'Swimming' not in q2.value:
print("Swimming is one of the best sports")
else:
score += 1
return score
# + [markdown] tags=["marks=10", "q3"]
# ## Question 3
#
# In the cell below answer the following question: Why should you combine chocolate with exercise?
#
# ### BEGIN ANSWER
#
# The model answer is written here. In the student notebook everything between the ### BEGIN and ### END tags will be removed and replaced by "YOUR ANSWER HERE"
#
# We have to tag this cell to specify how many marks the question is worth. This will be used during the manual grading somehow.
#
# ### END ANSWER
# -
# ## Plot 1: Roads Map and Legend (x points)
#
# Create a map of California roads:
#
# Use the `madera-county-roads/tl_2013_06039_roads.shp` layer (located in your `spatial-vector-lidar` data folder that you downloaded for class) to create a map that shows:
#
# 1. the madera roads layer (`madera-county-roads/tl_2013_06039_roads.shp`),
# 2. sjer plot locations (`vector_data/SJER_plot_centroids.shp`) and the
# 3. sjer_aoi boundary (`sjer_crop.shp`)
#
# Create a map of California roads:
#
# 1. Import the `madera-county-roads/tl_2013_06039_roads.shp` layer located in your `week_04` data download.
# 2. Create a map that shows the madera roads layer, sjer plot locations and the sjer_aoi boundary (sjer_crop.shp).
# 3. Plot the roads so different **road types** (using the RTTYP field) are represented using unique symbology. Use the `RTTYP` field to plot unique road types.
# 4. Map the plot locations by the attribute **plot type** using unique symbology for each "type".
# 4. Add a **title** to your plot.
# 5. Adjust your plot legend so that the full name for each `RTTYP` name is clearly represented in your legend. HINT: You will need to consult the metadata for that layer to determine what each `RTTYP` type represents.
# 6. Be sure that your plot legend is not covering your data.
#
# **IMPORTANT:** be sure that all of the data are within the same `EXTENT` and `crs` of the `sjer_aoi` layer. This means that you may have to crop and reproject your data prior to plotting it!
# + nbgrader={"grade": false, "grade_id": "import_ans", "locked": false, "schema_version": 1, "solution": true}
# Import the libraries that you will need
# The contents between the ### BEGIN and ### END tags will be removed
# and replaced by `# Your code here`
# no grading happens here
### BEGIN SOLUTION
import os
import earthpy as et
import numpy as np
import pandas as pd
import geopandas as gpd
import matplotlib
from shapely.geometry import box
from matplotlib.colors import ListedColormap, BoundaryNorm
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import shapely
### END SOLUTION
# -
# The chunk above contains packages required for grading
# The chunk below is an example student answer. notice that here we have several different ways that a student may opt to plot. this is used to test how we grade different approaches to plottin.
# + nbgrader={"grade": false, "grade_id": "p1_ans", "locked": false, "schema_version": 1, "solution": true} tags=["q4", "answer"]
# Cell's tagged as "answer" are removed from the student version, they will not
# form part of what the autograder adds to a student's notebook during
# the grading process. They will be visible to a manual grader
# set home directory and download data
os.chdir(os.path.join(et.io.HOME, 'earth-analytics'))
path_data = et.data.get_data('spatial-vector-lidar')
# Import data
sjer_aoi = gpd.read_file(
'data/spatial-vector-lidar/california/neon-sjer-site/vector_data/SJER_crop.shp')
sjer_roads = gpd.read_file(
'data/spatial-vector-lidar/california/madera-county-roads/tl_2013_06039_roads.shp')
sjer_plots = gpd.read_file(
'data/spatial-vector-lidar/california/neon-sjer-site/vector_data/SJER_plot_centroids.shp')
# replace roads with a missing RTTYP value with "Unknown"
sjer_roads = sjer_roads.replace(
{'RTTYP': {'': "Unknown", 'C': 'County', 'S': 'State Recognized', 'M': 'Common Name'}})
# reproject roads and plot data
sjer_roads = sjer_roads.to_crs(sjer_aoi.crs)
# crop the data
sjer_roads['geometry'] = sjer_roads.geometry.intersection(
box(*sjer_aoi.total_bounds))
sjer_roads = sjer_roads[sjer_roads['geometry'].is_empty == False].reset_index(drop=True)
# VARIOUS WAYS TO PLOT DATA
fig, ax = plt.subplots(figsize=(10, 10))
ax.set_axis_off()
case = 1
if case == 1:
# set colors and label names
roadPalette = {'Common Name': 'black', 'State Recognized': 'blue',
'County': 'grey', 'Unknown': 'lightgrey'}
linestyle_dict = {'Common Name': ':', 'State Recognized': '--',
'Unknown': '-.'}
pointsPalette = {'trees': 'chartreuse',
'grass': 'darkgreen', 'soil': 'burlywood'}
marker_dict = {'trees': '+', 'grass': '*', 'soil': 'o'}
# plot data
for plot_type, data in sjer_plots.groupby('plot_type'):
data.plot(color=pointsPalette[plot_type], ax=ax, label=plot_type,
markersize=50, marker=marker_dict[plot_type])
for road_type, data in sjer_roads.groupby('RTTYP'):
data.plot(color=roadPalette[road_type], ax=ax,
label=road_type, linestyle = linestyle_dict[road_type])
#ax.legend(loc=(1.1, .1),prop={'size': 16}, frameon=False)
if case == 2:
# set colors and label names
point_colors = ['darkgreen', 'burlywood', 'chartreuse']
point_labels = ['grass', 'soil', 'trees']
line_colors = ['black', 'blue', 'lightgrey']
line_labels = ['Common Name', 'State Recognized', 'Unknown']
# plot points and roads
sjer_plots.plot(ax=ax, column='plot_type', cmap=ListedColormap(point_colors), legend = True)
sjer_roads.plot(ax=ax, column='RTTYP', cmap=ListedColormap(line_colors), linestyle = 'None', legend = True)
# create legend
point_types = [Line2D([0], [0], marker = 'o', color=c, linestyle = 'None',
markersize=10) for c in point_colors]
line_types = [Line2D([0], [0], color=c) for c in line_colors]
leg1 = ax.legend(point_types, point_labels, loc=(1.1, .3), title='Plot Type', prop={'size': 16}, frameon=False)
leg2 = ax.legend(line_types, line_labels, loc=(1.1, .1), title='Road Type', prop={'size': 16}, frameon=False)
ax.add_artist(leg1)
plt.setp(leg2.get_title(), fontsize='15')
plt.setp(leg1.get_title(), fontsize='15')
# add title and legend details
ax.set(title= 'Homework Plot 1: \nMadera County Roads and study plot locations')
# + nbgrader={"grade": false, "grade_id": "p1_ans", "locked": false, "schema_version": 1, "solution": true}
### DO NOT REMOVE LINE BELOW ###
# all results have to be assigned to a variable that has a
# unique name and does not get reused in the notebook.
q4_ax1 = nb.convert_axes(plt)
# + nbgrader={"grade": true, "grade_id": "p1_tests", "locked": true, "points": 1, "schema_version": 1, "solution": false} tags=["q4", "private"]
# Test Suite for Plot 1
# currently i want more verbose but also cleaner feedback.
# note that above i commented out the legend. and the legend tests thus failed.
# i'd like a very user friendly feedback block with the tests that passed vs failed.
# below is ugly and scary but it does work!
# this test has to be private as it depends on code from `earthanalytics`
# which is a private package
from earthanalytics.hw4_tests import homework4_tests
hw4t = homework4_tests()
results = unittest.TextTestRunner().run(hw4t.p1_tests(q4_ax1))
| master/01-lecture.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
# ---
# # Understanding Fishing Vessel's Authorization and Parameters
#
# This notebook is a short exercise for us to understand parameters associated with a fishing vessel, and how is each type of fishing vessel registered. In general, we noticed that there are several fishing licensing authorities, such as CLAV, CCSBT, IOTC, etc.. Also, as indicated in the CLAV sample table below, not all vessels are registered with the same authorization body and each authorization body has a different requirement in terms of required parameters. To obtain a table with mmsi and gear type, we would have to merge the tables using the vessel's unique ID.
import pandas as pd
import numpy as np
# ## CLAV Registered Vessels datasets
#
# This is a consolidated vessel dataset with all fishing authorities (but only for certain types of fish). This dataset does not come with mmsi as the identifier. The most unique ID of the vessel is the "callsign" assigned to each table.
clav_fleet_registration = pd.read_csv('../data/clav_vessel_registry.csv', error_bad_lines=False)
clav_fleet_registration.head(5)
# ## Merging Other Authorization Body's Datasets to Obtain MMSI/Vessels
#
# To get the mmsi of each vessel. We used several registration authorities' vessels list to merge and obtain a general list of fishing vessel mmsi numbers. Moreover, vessel tracking sites that provide data on all fishing vessels such as Marinetraffic do not provide the general fishing gear type/ fishing vessel registration type (maybe with paid option).
#
# The range of the mmsi data is using 2013 and 2016 as the benchmark, which corresponds to our AIS training data from 2012 to 2016.
europe_fleet_registration_2016 = pd.read_csv('../data/vesselRegistryListResults_2016.csv', sep=';', error_bad_lines=False)
europe_fleet_registration_2016 = europe_fleet_registration_2016[['Name of vessel','IRCS', 'MMSI', 'Vessel Type', 'Main fishing gear', 'Subsidiary fishing gear 1']]
europe_fleet_registration_2013 = pd.read_csv('../data/vesselRegistryListResults_2013.csv', sep=';', error_bad_lines=False)
europe_fleet_registration_2013 = europe_fleet_registration_2013[['Name of vessel','IRCS', 'MMSI', 'Vessel Type', 'Main fishing gear', 'Subsidiary fishing gear 1']]
europe_fleet_registration = pd.concat([europe_fleet_registration_2013, europe_fleet_registration_2016])
europe_fleet_registration = europe_fleet_registration.dropna()
europe_fleet_registration.head(5)
CCSBT_fleet_registration = pd.read_csv('../data/authorised_vessel_record.csv', error_bad_lines=False)
CCSBT_fleet_registration = CCSBT_fleet_registration[['Callsign', 'Vessel Type', 'Gear Type']]
CCSBT_fleet_registration.head(5)
IOTC_fleet_registration = pd.read_csv('../data/IOTC_authorized_vessels.csv', error_bad_lines=False)
IOTC_fleet_registration = IOTC_fleet_registration[['IRCS', 'Type', 'Gear']]
IOTC_fleet_registration.head(5)
fleet_all = pd.merge(europe_fleet_registration, CCSBT_fleet_registration, left_on='IRCS', right_on='Callsign', how='outer')
fleet_all = pd.merge(fleet_all, IOTC_fleet_registration, on='IRCS', how='outer')
fleet_all.drop_duplicates().dropna().head(5)
# ## Vessel Registration Dataset References
#
# https://webgate.ec.europa.eu/fleet-europa/search_en
#
# https://iotc.org/vessels/current
#
# http://clav.iotc.org/browser/search/#.YFPZxp1Kjb0
#
# https://www.iattc.org/VesselRegister/VesselList.aspx?Lang=en#Venezuela
| eda/eda_mmsi.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
import json
import pandas as pd
# +
# local url
url = 'http://127.0.0.1:5000/'
# sample data
data = {
'accommodates': 2,
'bedrooms': 1.0,
'cleaning_fee': 60.0,
'extra_people': 15.0,
'guests_included': 2,
'minimum_nights': 10,
'neighbourhood_group_cleansed_Mitte': 1,
'neighbourhood_group_cleansed_Pankow': 0,
'neighbourhood_group_cleansed_Tempelhof - Schöneberg': 0,
'neighbourhood_group_cleansed_Friedrichshain-Kreuzberg': 0,
'neighbourhood_group_cleansed_Neukölln': 0,
'neighbourhood_group_cleansed_Charlottenburg-Wilm.': 0,
'neighbourhood_group_cleansed_Treptow - Köpenick': 0,
'neighbourhood_group_cleansed_Steglitz - Zehlendorf': 0,
'neighbourhood_group_cleansed_Reinickendorf': 0,
'neighbourhood_group_cleansed_Lichtenberg': 0,
'neighbourhood_group_cleansed_Marzahn - Hellersdorf': 0,
'neighbourhood_group_cleansed_Spandau': 0,
'property_type_Guesthouse': 1,
'property_type_Apartment': 0,
'property_type_Condominium': 0,
'property_type_Loft': 0,
'property_type_House': 0,
'property_type_Serviced apartment': 0,
'property_type_Townhouse': 0,
'property_type_Other': 0,
'property_type_Bed and breakfast': 0,
'property_type_Guest suite': 0,
'property_type_Hostel': 0,
'room_type_Entire home/apt': 1,
'room_type_Private room': 0,
'room_type_Shared room': 0,
'bed_type_Real Bed': 1,
'bed_type_Sofa\Other': 0,
'instant_bookable_f': 1,
'instant_bookable_t': 0,
'cancellation_policy_strict': 1,
'cancellation_policy_flexible': 0,
'cancellation_policy_moderate': 0
}
# -
data = json.dumps(data)
# +
# A response of 200 means everything went alright
post_request = requests.post(url, data)
print(post_request)
# -
print(post_request.json())
| .ipynb_checkpoints/airbnb_sample_test-checkpoint.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:exercises]
# language: python
# name: conda-env-exercises-py
# ---
# # Constraint Satisfaction Problems
#
# ## 1. Kartenfärbungsprobleme als CSP
# Gegeben sei die folgende Karte von Mecklenburg-Vorpommern-
# 
# * Spezifizieren Sie, analog zur Vorlesung, das zugehörige Kartenfärbungsproblem für 3 Farben als Constraint Satisfaction Problem. Geben Sie für alle Variablen die Domänen und alle notwendigen Bedingungen an.
# * Bestimmen Sie eine Lösung für dieses Problem über Suche mit Backtracking! Benutzen Sie dabei die Heuristik Minimum remaining values und geben Sie für jeden Zwischenschritt und jedes Land die möglichen Farben an!
#
#
# ## 2. Backtracking-Suche implementieren
# * Implementieren Sie die Funktion `backtrackcsp`.
# * Modellieren Sie die Karte aus Aufgabe 1 als CSP in Python, und verwenden Sie `backtrackcsp` zum Lösen.
# +
#csp
#set of variables, domain of each variable, constraints
#can have only inequality constraints (sufficient for map coloring problems)
class CSP():
def __init__(self,domains,constraints):
self.domains=domains
self.constraints=constraints
self.assignments={}
for k in domains.keys():
self.assignments[k]=None
self.unassigned=domains.keys()
def getNVar(self):
return len(self.domains.keys())
def isConsistent(self):
consistent = True
for k in self.constraints.keys():
co = self.constraints[k]
for c in co:
if (self.assignments[k] is not None) and (self.assignments[c] is not None):
consistent = consistent and (self.assignments[k] != self.assignments[c])
return consistent
def getDomain(self,var):
return self.domains[var]
def assign(self,var,value):
self.assignments[var]=value
def unassign(self,var):
self.assignments[var]=None
def getAssignments(self):
return self.assignments
def getNextAssignableVar(self):
#get the next var that is unassigned AND has non-empty domain
for u in self.assignments.keys():
if (self.assignments[u] is None) and self.domains[u] != []:
return u
def isSolved(self):
solved=True
for a in self.assignments.values():
solved = solved and (a is not None)
return (solved and self.isConsistent())
#backtracking search algorithm
def backtrackcsp(csp,depth):
#select d-th variable. iterate over domain. for each element, iteratively call backtrackscp
#return None when no solution possible, or the csp with the solution
if not (csp.getNVar() > depth):
return None
else:
#iterate over domain of d-th variable
var = csp.getNextAssignableVar()
dom = csp.getDomain(var)
for d in dom:
#bind var to d
csp.assign(var,d)
#test whether this is a solution (then return solution), or go deeper
if csp.isSolved():
return csp
#when this is consistent, go deeper. if not consistent, we do not need to consider this
#any further
if csp.isConsistent():
#go deeper
ret = backtrackcsp(csp,depth+1)
#if ret is a solution, return this, if not, go to next iteration
if ret is not None:
return ret
#else: (this is not a valid assignment, we do not need to test this any further)
#when we get here, no assignment lead to a solution, i.e. there is no solution
#remove the assignments of var
csp.unassign(var)
return None
#very simple example: A={1,2,3}, B={1,2,3}, C={1,2,3}. A!=B, B!=C
examplecsp = CSP({'A':[1,2,3],'B':[1,2,3],'C':[1,2,3]},{'A':['B'],'B':['C']})
print(backtrackcsp(examplecsp,0).getAssignments())
#definition of map
places = {'LUP':[1,2,3],'MSE':[1,2,3],'NWM':[1,2,3],'HRO':[1,2,3],'LRO':[1,2,3],'SN':[1,2,3],
'VG':[1,2,3],'VR':[1,2,3]}
borders = {'NWM':['SN','LUP','LRO'], 'SN':['LUP'], 'LUP':['LRO','MSE'], 'LRO':['MSE','HRO','VR'],
'MSE':['VR','VG'], 'VG':['VR']}
mvmap = CSP(places,borders)
print(backtrackcsp(mvmap,0).getAssignments())
| 04-csp_lsg.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/Tyred/TimeSeries_OCC-PUL/blob/main/Notebooks/IsolationForest.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="Emi8F7ZFdSrK"
# ## Imports
# + id="Ut4w1hMDsE7S"
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest
from sklearn.metrics import precision_score, accuracy_score, recall_score, f1_score
import tensorflow as tf
from tensorflow import keras
from sklearn.decomposition import PCA
from sklearn.manifold import MDS
# + [markdown] id="6y-sBkgCb8GM"
# ## Reading the dataset from Google Drive
#
# + colab={"base_uri": "https://localhost:8080/"} id="jUip5vSwsFet" outputId="2b778b00-f318-419d-81b4-1f413b8b203c"
path = 'drive/My Drive/UFSCar/FAPESP/IC/Data/UCRArchive_2018'
dataset = input('Dataset: ')
tr_data = np.genfromtxt(path + "/" + dataset + "/" + dataset + "_TRAIN.tsv", delimiter="\t",)
te_data = np.genfromtxt(path + "/" + dataset + "/" + dataset + "_TEST.tsv", delimiter="\t",)
labels = te_data[:, 0]
print("Labels:", np.unique(labels))
# + [markdown] id="R0l2RpHUcHaB"
# ## Splitting in Train-Test data
# + colab={"base_uri": "https://localhost:8080/"} id="DvCT8FllsJBY" outputId="046794a9-00ab-44e6-d952-26075c0771c3"
class_label = int(input('Positive class label: '))
train_data = tr_data[tr_data[:, 0] == class_label, 1:] # train
test_data = te_data[:, 1:] # test
print("Train data shape:", train_data.shape)
print("Test data shape:", test_data.shape)
# + [markdown] id="UcC1Ru1McR5b"
# ## Labeling for OCC Task
# <li> Label 1 for positive class </li>
# <li> Label -1 for other class(es) </li>
# + colab={"base_uri": "https://localhost:8080/"} id="wO1RyvvYsMsM" outputId="77e2994c-399c-4ce9-8fed-bd8c0c0ce567"
occ_labels = [1 if x == class_label else -1 for x in labels]
print("Positive samples:", occ_labels.count(1))
print("Negative samples:", occ_labels.count(-1))
# + [markdown] id="nbY1evUb-hX4"
# ## Results
#
# + id="ZlURfjmMsimF"
clf = IsolationForest(random_state=0).fit(train_data)
# + colab={"base_uri": "https://localhost:8080/"} id="sBqciP5dslRy" outputId="b525ae05-f660-4c37-a2b1-dadc14ade18f"
result_labels = clf.predict(test_data)
acc = accuracy_score(occ_labels, result_labels)
precision = precision_score(occ_labels, result_labels)
recall = recall_score(occ_labels, result_labels)
f1 = f1_score(occ_labels, result_labels)
print("Accuracy: %.2f" % (acc*100) + "%")
print("Precision: %.2f" % (precision*100) + "%")
print("Recall: %.2f" % (recall*100) + "%")
print("F1-Score: %.2f" % (f1*100) + "%")
| Notebooks/algorithms/IsolationForest.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
from tensorflow import keras
import tensorflow as tf
from tensorflow.keras import layers
from keras.layers import Input, Dense, Activation
import matplotlib.pyplot as plt
from keras.models import Model
# +
# tag list
tag_file=pd.read_csv("tags.csv")
tag=tag_file["tagID"]
tag=list(tag)
# user_code
user_tag_file=pd.read_csv("user_tags.csv")
company_tag_file=pd.read_csv("job_tags.csv")
# user_code 작성
list_of_user=list(set(user_tag_file["userID"]))
user_code={}
for user in list_of_user:
user_code[user]=[0 for i in range(887)]
sizeOfUserTag=len(user_tag_file)
for i in range(sizeOfUserTag):
tag_id_of_user=user_tag_file["tagID"][i]
index_of_tag_user=tag.index(tag_id_of_user)
user_code[user_tag_file["userID"][i]][index_of_tag_user]=1
# company_code 작성
list_of_company=list(set(company_tag_file["jobID"]))
company_code={}
for company in list_of_company:
company_code[company]=[0 for i in range(887)]
sizeOfCompanyTag=len(company_tag_file)
for i in range(sizeOfCompanyTag):
tag_id_of_company=company_tag_file["tagID"][i]
index_of_tag_company=tag.index(tag_id_of_company)
company_code[company_tag_file["jobID"][i]][index_of_tag_company]=1
#d company_size 작성
job_file=pd.read_csv("job_companies.csv")
# [nan, '51-100', '101-200', '11-50', '201-500', '501-1000', '1000 이상', '1-10']
sizeList=list(set(job_file["companySize"]))
company_size={}
sizeOfCompanySize=len(job_file)
for i in range(sizeOfCompanySize):
company_size[job_file["jobID"][i]]=[0 for _ in range(8)]
comSize=job_file["companySize"][i]
company_size[job_file["jobID"][i]][sizeList.index(comSize)]=1
# -
#모델 불러오기
from tensorflow.python.keras.models import load_model
model = load_model("donghyun_model2.h5")
# +
# x_test 입력
test_file=pd.read_csv("test_job.csv")
size_input_test=len(test_file)
X_test=[]
for i in range(size_input_test):
userL=user_code[test_file["userID"][i]]
companyL=company_code[test_file["jobID"][i]]
tempL=[]
for j in range(887):
if userL[j]==1 and companyL[j]==1:
tempL.append(0.7)
elif userL[j]==1 and companyL[j]==0:
tempL.append(0.5)
elif userL[j]==0 and companyL[j]==1:
tempL.append(0.3)
else:
tempL.append(0.1)
tempL.extend(company_size[test_file["jobID"][i]])
X_test.append(tempL)
X_test=np.array(X_test)
# -
y_prob=model.predict(X_test)
y_class=[]
for i in range(len(y_prob)):
if y_prob[i][0]>=0.5:
y_class.append(1)
else:
y_class.append(0)
print(y_class)
df=pd.DataFrame(data=y_class,columns=['applied'])
df.to_csv("result.csv",mode='w',index=False)
| test2.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
# ---
# # Вероятность в Python
# > Вероятность — степень (относительная мера, количественная оценка) возможности наступления некоторого события. В теории вероятностей вероятность принимает значения от 0 до 1. Значение 1 соответствует достоверному событию, невозможное событие имеет вероятность 0. Чем выше значение, тем больше вероятность события
#
# **Вероятность** как область научного знания важна, потому что неопределенность и случайность встречаются повсеместно, соответственно, знание о вероятности помогает принимать более информированные решения и осмыслять неопределенности.
#
#
# ## Факториал
#
# **Факториал** — функция, определённая на множестве неотрицательных целых чисел. Факториал натурального числа n определяется как произведение всех натуральных чисел от 1 до n включительно
#
# Факториал вычисляется по следующей формуле:
#
# $$ n! = n \times (n-1) \times (n-2)\times \ldots \times 2 \times 1 $$
#
# Пример:
# $$ 5! = 5 \times 4 \times 3 \times 2 \times 1 = 120 $$
#
# А как это выглядит в python
def factorial(n):
if n == 1: return 1
else: return n * factorial(n-1)
factorial(5)
# Хорошо, но где факториалы используются в реальном мире?
#
# Скажем, в гонке участвуют пять машин F1, и вы хотите узнать количество способов, по которым эти пять могут финишировать первыми, вторыми или третьими. Можно взять листок бумаги и просто записать все возможные варианты, но зачем? Что если машин F1 больше 20?
#
# Вот как эта задача решается с помощью факториалов:
#
# $$ \frac{5!}{(5-3)!} = \frac{5!}{2!} = \frac{5 \times 4 \times 3 \times 2 \times 1}{2 \times 1} = 5 \times 4 \times 3 = 60 $$
#
# Это называется перестановка
factorial(22)/factorial(22-3)
# ## Перестановки
#
#
#
# > В математике **перестановка** — это упорядочение членов набора в последовательность или, если последовательность уже определена, перестановка (изменение порядка) ее элементов.
#
#
# Существует два способа вычисления перестановок. Выбор способа зависит от того, разрешается повторение или нет. Давайте рассмотрим на примере.
#
# У вас есть веб-сайт, на котором могут регистрироваться пользователи. Им нужно вводить пароль длиной строго в 8 символов, которые не должны повторяться. Сперва нужно определить, сколько букв и цифр в английском алфавите:
#
# - количество букв: 26
# - количество цифр: 10
#
# То есть всего 36. Тогда `n = 36`, а `r = 8`, потому что пароль должен быть длиной в 8 символов. Зная это, мы легко можем рассчитать количество уникальных паролей, используя формулу:
#
#
# $$ \frac{n!}{(n-r)!} $$
#
# Если вручную:
#
# $$ \frac{36!}{(36-8)!} = 1220096908800 $$
def permutattion_without_repetition(n, r):
return factorial(n)/factorial(n-r)
permutattion_without_repetition(36,8)
# Здорово, но я хочу разрешить пользователям повторно использовать символы. Нет проблем, в данном случае это перестановки с повторениями, формула еще проще:
#
# $$ n^r $$
def permutattion_with_repetition(n, r):
return n**r
permutattion_with_repetition(36, 8)
# ## Сочетания
#
# > Сочетание— это выбор значений из набора, в котором (в отличие от перестановок) порядок выбора не имеет значения.
#
# Чтобы понять это определение, разберем следующий пример: **группа людей, выбранных в команду — это та же самая группа, независимо от порядка участников**. Вот и вся идея сочетаний. Если выбрать 5 членов команды, можно упорядочить их по имени, росту или другому параметру, но команда останется прежней — порядок не имеет значения.
#
# Давайте запишем это формулой. Количество сочетаний `C` набора из `n` объектов, взятых по `r`, рассчитывается так:
#
# $$ C(n,r) = \frac{n!}{r!(n-r)!} $$
#
# С этим уравнением мы можем решить следующую задачу: **сколькими способами можно выбрать в футбольную команду 5 человек из 10?**
#
# Группа будет той же, порядок значения не имеет. Значит, `n = 10`, а `r = 5`:
#
# $$ C(n,r) = \frac{10!}{5!(10-5)!} = 252 $$
#
def combination_without_repetition(n, r):
return factorial(n)/ (factorial(r) * factorial(n-r))
combination_without_repetition(10,5)
# Великолепно! Но интересно, существует ли версия сочетаний с повторениями? Да!
#
# Представьте, что готовите сэндвич и по какой-то причине вам нужно использовать только 4 ингредиента из 10. Однако ингредиенты не должны быть уникальны, например, можно положить 3 куска сыра и 1 кусок салями. Как это здорово, я тоже обожаю сыр, вот спасибо!
#
# Но как сформулировать эту идею математически? Ответ снова прост:
#
# $$ \frac{(n+r-1)!}{r!(n-1)} $$
#
# Давайте применим формулу к примеру выше. n снова равно 10 (потому что 10 возможных ингредиентов), а r = 4 (потому что выбрать можно только 4):
#
# $$ \frac{(10+4-1)!}{4!(10-1)} = 715 $$
def combination_with_repetition(n, r):
return factorial(n+r-1)/ (factorial(r) * factorial(n-1))
combination_with_repetition(10,4)
# ## Вероятность
#
# Здесь я расскажу о том, что такое:
# - пространство элементарных событий («sample space»)
# - случайных величин («outcome»);
#
# Приведем понятие эксперимента и то, как я его понимаю; вероятность («probability»), интерпретация вероятности и дискретных случайных величин.
#
#
# Пожалуй, одним из основополагающих понятий, благодаря которому можно понять, что речь идёт о теории вероятностей, а не о другой области исследования является **выборка («sample»)** (1) и **пространство элементарных событий («sample space»)** (2). Я воспринимаю (1) как некоторый список сущностей (или событий), которые может захватить глаз человека и представить его на бумаге.
#
# Есть второй вариант интерпретации определения (1) – это могут быть выдуманные значения (числа, символы), которые можно представить на бумаге. Эти данные являются исходными значениями для эксперимента (о нём будет сказано чуть позже). Выборку мы получаем из пространства элементарных событий (2). По сути своей это абстрактное понятие, определяющее множество выборок в пространстве.
#
#
# Чуть выше мы затронули понятие эксперимента. Поскольку выше было определено, что выборка может быть, как выдуманной, так и нет, то соответственно, эксперимент я воспринимаю как некий процесс манипуляции либо с настоящими данными, либо с вымышленными. В качестве примера можно привести программный код на языке Python.
# +
import random
data = []
while len(data) != 5:
data.append(random.randint(1, 10))
print(data)
# -
# Данный пример определяет любое событие в пространстве элементарных событий. В нашем случае пространство элементарных событий – это случайное число в промежутке от 1 до 10 `(random.randint(1, 10))`, которое добавляет эти значения в список data, пока его длина `(len)` не будет равняться 5.
#
# Ниже представлен пример с неслучайными данными. Давайте представим, что мы с вами работаем в некоторой фирме и для того, чтобы провести эксперимент, требуется узнать возраст людей (клиентов) по их имени. Вот код.
birth_date ={'Bob': 10, 'Alice':16, 'Ann':15}
print(birth_date)
# Он представляет собой словарь, в качестве ключа выступает имя человека, а значения – его возраст.
#
# > Представленное событие не является выдуманным (исходя из условия задачи), поскольку в первой задаче мы не знали какое число нам достанется для помещения его в список, а во втором значения данные заранее известны.
#
#
# После того, как мы получили данные, необходимо их оценить. Оценка может быть либо экспериментальная (её ещё называют «грубой»), либо теоретической. Логично понимать, что экспериментальная получена в результате проведения эксперимента, а теоретическая без проведения эксперимента.
#
# В качестве примера можно привести всеми известную задачу подбрасывания кубика, у которого на каждой грани написаны цифры от 1 до 6. И нам необходимо определить вероятность выпадения числа на каждой грани.
#
#
# Вот пример теоретического определения вероятности:
#
# Допустим кубик подбрасывается бесконечное количество раз, тогда в теории вероятность выпадения каждого числа стремится к
#
# $$ Pr = \frac{1}{6} = 0.17 $$
#
# Проблема в том, что на практике мы не можем подбрасывать кубик бесконечное количество раз. Это утомительно и не нужно, поэтому мы проводим реальный эксперимент с ограничениями.
#
#
# Например, нам нужно подбросить кубик 10 раз. Для этого я написал функцию, которая носит название «кубик».
def kubik(n):
"""
:param n: Количество подбрасываний
:return: Список слкучайных подюрасываний кубика
"""
data = []
while len(data) <n:
data.append(random.randint(1,6))
return data
# Она при помощи метода `(random.randint(1,6))` определяет количество выпаданий случайной грани от 1 до 6. Результат случайного числа он описывает в переменную data. Если мы выполним 10 подбрасываний, то результатом будет являться список из этих значений. Значения в списке могут быть любыми.
kub_data = kubik(100)
print(kub_data)
# Чтобы получить вероятность выпадения каждой грани, необходимо определить количество граней в выборке. Я реализовал это при помощи следующей функции:
def count_rate(kub_data):
"""
Возвращает частоту выпадания значений кубика,
согласно полученным данным
:param kub_data: данные эксперимента
:return:
"""
kub_rate = {}
for i in kub_data:
if i in kub_rate:
continue
else:
kub_rate[i] = kub_data.count(i)
for i in range(1, 7):
if i not in kub_rate:
kub_rate[i] = 0
return kub_rate
rate = count_rate(kub_data)
print(rate)
# Результатом функции служит словарь, который считает количество выпадений от 1 до 6. Пример реализует два цикла, первый цикл считает текущие случайные значения в полученной выборке, но поскольку у нас некоторые значения могут не выпасть, то мы их добавляем в конец словаря.
#
# Данные, конечно, я получил, но мне не нравится формат их вывода. Поэтому необходимо их отсортировать:
def sort_rate(counted_rate):
"""
Возвращает отсортированную частоту по ключу
:param counted_rate: Наша неотсортированная частота
:return:
"""
sorted_rate = {}
for key in sorted(counted_rate.keys()):
sorted_rate[key] = counted_rate[key]
return sorted_rate
srt_rate = sort_rate(rate)
print(srt_rate)
# Для сортировки хорошо подойдёт метод sorted. В официальной документации написано, что она возвращает отсортированный список, полученный из итерируемого объекта, который передан как аргумент. В моём случае итерируемый объект – это наш словарь, который мы сортируем по ключу `(sorted(counted_rate.keys()))`.
# Следующий шаг, преобразование данного словаря в `dataframe`. DataFrame представляет собой табличную структуру представления данных для удобного их структурирования. Для преобразования служит библиотека pandas (ссылка на официальную документацию (для тех, кто не знает): https://pandas.pydata.org/docs/ ). Она очень популярна в Python сообществе, имеет очень много интересных плюшек, о плюсах можно много говорить, об этом много написано в том числе на Хабре, поэтому перечислять их не буду. Вот реализация функции:
# +
import pandas as pd
def crate_dataframe(sorted_date):
"""
Создание и преобразование данных в Pandas dataframe
:param sorted_date: dict
:return: pd.Dataframe
"""
df = pd.DataFrame(sorted_date, index=[0])
df = df.T
df = df.rename(columns={0: 'Частота'})
df.insert(0, 'Количество выпаданий', range(1, 1 + len(df)))
return df
# -
df = crate_dataframe(srt_rate)
df
# Теперь самое время определить вероятности. Для того, чтобы это сделать, нужно ещё раз убедиться, что мы подбрасывали кубик ровно 10 раз и затем полученное значение разделить на частоту. Ниже опишу общую формулу:
#
#
# $$ \text{Вероятность(Pr)} = \frac{\text{Количество подбрасований}}{\text{Частота выпадения грани куба}} $$
def probability_solving(dataframe):
"""
Вычисление вероятности полученных результатов
:param dataframe:
:return:
"""
sum_rate = dataframe['Частота'].sum()
probability = []
for i in dataframe['Частота']:
probability.append(i / sum_rate)
dataframe['Вероятность'] = probability
return dataframe
df = probability_solving(df)
# Суммарное количество бросков описывается переменной sum_rate, для вычисления вероятности служит цикл, который берёт значения из столбца Частота (`dataframe['Частота']`) и вычисляет её вероятность, путём создания нового столбца (`dataframe['Вероятность']`).
import matplotlib.pyplot as plt
a = df['Вероятность'].plot(kind='bar', legend=True)
# # Домашнее задание
# 1. Один самолет вылетел из Москвы, и должен совершить посадку в 5 городах. Необходимо узнать, количество городов, в котрых может приземлиться в первый, второй, третий город.
# +
# Начните писать код тут
# -
# 2. Осьминог Пауль 16 раз пробовал угадать победителя футбольного матча. 14 раз он угадал правильно, 2 раза ошибся. Проверьте гипотезу H0: Пауль выбирает победителя футбольного матча случайно. Сделайте вывод. (сложная задача)
# +
# Начните писать код тут
| ds/probability.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
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
DATA_CONTAINER = "data/"
# -
# loading data
def load_csv_data(file_name, data_container=DATA_CONTAINER):
csv_path = os.path.join(data_container, file_name)
return pd.read_csv(csv_path)
def plot_boxplox(data_time, data_temp, labels, title):
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
bp = ax1.boxplot(data_time, labels=labels, notch=True, bootstrap=10000)
ax1.set_ylabel('time to find all solutions (s)', color='b')
ax1.tick_params('y', colors='b')
for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
plt.setp(bp[element], color='b')
ax2 = ax2.twinx()
bp = ax2.boxplot(data_temp, labels=labels, notch=True, bootstrap=10000)
ax2.set_ylabel('temperature (°C)', color='r', )
ax2.tick_params('y', colors='r')
for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
plt.setp(bp[element], color='r')
plt.show()
def plot_data(timestamp, time, temp, limits, title):
fig, ax1 = plt.subplots()
maxtime = timestamp[-1:]
ymin1 = limits[0]
ymax1 = limits[1]
ax1.plot(timestamp, time, 'b-')
ax1.set_xlabel('experiment time (min) - (duration: %.2f min)' %(maxtime))
ax1.set_ylabel('time to find all solutions (s)', color='b')
ax1.tick_params('y', colors='b')
ax1.set_ylim([ymin1, ymax1])
ymin2 = limits[2]
ymax2 = limits[3]
ax2 = ax1.twinx()
ax2.plot(timestamp, temp, 'r')
ax2.set_ylabel('temperature (°C)', color='r')
ax2.tick_params('y', colors='r')
ax2.set_ylim([ymin2, ymax2])
ax1.set_title(title)
plt.show()
def plot_barh(y_pos, performance, error, labels, title, color, xlabel):
fig, ax = plt.subplots()
plt.grid()
# Example data
people = labels
ax.barh(y_pos, performance, xerr=error, align='center', color=color, ecolor='black', height=0.1)
ax.set_yticks(y_pos)
ax.set_yticklabels(labels)
ax.invert_yaxis()
ax.set_xlabel(xlabel)
ax.set_title(title)
plt.show()
def plot_barh(y_pos, performance, error, labels, title, color, xlabel):
fig, ax = plt.subplots()
plt.grid()
# Example data
people = labels
ax.barh(y_pos, performance, xerr=error, align='center', color=color, ecolor='black', height=0.1)
ax.set_yticks(y_pos)
ax.set_yticklabels(labels)
ax.invert_yaxis()
ax.set_xlabel(xlabel)
ax.set_title(title)
plt.show()
path_4b = "data/performance/raspberry_pi/buster/4B"
# **Standard Raspbian Kernel with active ICE cooling**
# +
# rPi 4B std - loading data standard raspbian kernel
#kernel_std_4b_mt_active = load_csv_data("std_kernel_4B_multithread_output_cooling.csv", path_4b)
#kernel_std_4b_mt_active = load_csv_data("std_kernel_4B_multithread_output_cooling_external_5v.csv", path_4b)
#kernel_std_4b_mt_active = load_csv_data("std_kernel_4B_multithread_output_cooling_capacitor_air.csv", path_4b)
#kernel_std_4b_mt_active = load_csv_data("std_kernel_4B_multithread_output_cooling_capacitor_ice_gel.csv", path_4b)
kernel_std_4b_mt_active = load_csv_data("std_kernel_4B_multithread_output_cooling_capacitor_firmware.csv", path_4b)
kernel_std_4b_mt_active['time'] -= kernel_std_4b_mt_active['time'][0]
kernel_std_4b_st_active = load_csv_data("std_kernel_4B_singlethread_output_cooling.csv", path_4b)
kernel_std_4b_st_active['time'] -= kernel_std_4b_st_active['time'][0]
# -
# **Standard Raspbian Kernel with passive ICE cooling**
# +
# rPi 4B - loading data preempt-rt raspbian kernel
kernel_std_4b_mt_passive = load_csv_data("std_kernel_4B_multithread_output_cooling_pasive.csv", path_4b)
kernel_std_4b_mt_passive['time'] -= kernel_std_4b_mt_passive['time'][0]
kernel_std_4b_st_passive = load_csv_data("std_kernel_4B_singlethread_output_cooling_passive.csv", path_4b)
kernel_std_4b_st_passive['time'] -= kernel_std_4b_st_passive['time'][0]
# -
# **Multithread - Standard Raspbian Kernel 4.19.80-v7l+**
# +
# rPi 4B MT - plotting standard raspbian kernel - passive cooling
timestamp_std_4b_mt_passive = kernel_std_4b_mt_passive.time/60
time_std_4b_mt_passive = kernel_std_4b_mt_passive.seconds + kernel_std_4b_mt_passive.microseconds/1000000
temp_std_4b_mt_passive = (kernel_std_4b_mt_passive.cpu_temp + kernel_std_4b_mt_passive.gpu_temp)/2
title = "Raspberry Pi 4 Model B\nusing Stardard Raspbian Kernel 4.19.80-v7l+\nICE Tower Cooling Fan - Passive\n(Queens: 12, Threads: 4, Iterations: 100)"
plot_data(timestamp_std_4b_mt_passive[:99], time_std_4b_mt_passive[:99], temp_std_4b_mt_passive[:99], (17, 25, 30, 80), title)
# -
print("Time to 45 iterations: %.2f s" %timestamp_std_4b_mt_passive[44])
# +
# rPi 4B MT - plotting standard raspbian kernel - active cooling
timestamp_std_4b_mt_active = kernel_std_4b_mt_active.time/60
time_std_4b_mt_active = kernel_std_4b_mt_active.seconds + kernel_std_4b_mt_active.microseconds/1000000
temp_std_4b_mt_active = (kernel_std_4b_mt_active.cpu_temp + kernel_std_4b_mt_active.gpu_temp)/2
#title = "Raspberry Pi 4 Model B\nusing Stardard Raspbian Kernel 4.19.80-v7l+\nICE Tower Cooling Fan - Active\n(Queens: 12, Threads: 4, Iterations: 100)"
#title = "Raspberry Pi 4 Model B\nusing Stardard Raspbian Kernel 4.19.80-v7l+\nICE Tower Cooling Fan - Active - Ext. 5V\n(Queens: 12, Threads: 4, Iterations: 100)"
#title = "Raspberry Pi 4 Model B\nusing Stardard Raspbian Kernel 4.19.80-v7l+\nICE Tower Cooling Fan - Active - Capacitor & Air blocked\n(Queens: 12, Threads: 4, Iterations: 100)"
#title = "Raspberry Pi 4 Model B\nusing Stardard Raspbian Kernel 4.19.80-v7l+\nICE Tower Cooling Fan - Active - Capacitor & Gel Pack\n(Queens: 12, Threads: 4, Iterations: 100)"
title = "Raspberry Pi 4 Model B\nusing Stardard Raspbian Kernel 4.19.80-v7l+\nICE Tower Cooling Fan - Active - Capacitor & New Firmware\n(Queens: 12, Threads: 4, Iterations: 100)"
#plot_data(timestamp_std_4b_mt_active[:99], time_std_4b_mt_active[:99], temp_std_4b_mt_active[:99], (17, 25, 30, 80), title)
plot_data(timestamp_std_4b_mt_active[:99], time_std_4b_mt_active[:99], temp_std_4b_mt_active[:99], (17, 20.5, 30, 45), title)
# -
print("Time to 45 iterations: %.2f s" %timestamp_std_4b_mt_active[44])
# **Singple - Standard Raspbian Kernel 4.19.80-v7l+**
# +
# rPi 4B ST - plotting standard raspbian kernel - passive cooling
timestamp_std_4b_st_passive = kernel_std_4b_st_passive.time/60
time_std_4b_st_passive = kernel_std_4b_st_passive.seconds + kernel_std_4b_st_passive.microseconds/1000000
temp_std_4b_st_passive = (kernel_std_4b_st_passive.cpu_temp + kernel_std_4b_st_passive.gpu_temp)/2
title = "Raspberry Pi 4 Model B\nusing Stardard Raspbian Kernel 4.19.80-v7l+\nICE Tower Cooling Fan - Passive\n(Queens: 12, Threads: 1, Iterations: 50)"
plot_data(timestamp_std_4b_st_passive[:49], time_std_4b_st_passive[:49], temp_std_4b_st_passive[:49], (17, 75, 30, 65 ), title)
# -
print("Time to 45 iterations: %.2f s" %timestamp_std_4b_st_passive[44])
# +
# rPi 4B ST - plotting standard raspbian kernel - active cooling
timestamp_std_4b_st_active = kernel_std_4b_st_active.time/60
time_std_4b_st_active = kernel_std_4b_st_active.seconds + kernel_std_4b_st_active.microseconds/1000000
temp_std_4b_st_active = (kernel_std_4b_st_active.cpu_temp + kernel_std_4b_st_active.gpu_temp)/2
title = "Raspberry Pi 4 Model B\nusing Stardard Raspbian Kernel 4.19.80-v7l+\nICE Tower Cooling Fan - Active\n(Queens: 12, Threads: 1, Iterations: 50)"
plot_data(timestamp_std_4b_st_active[:49], time_std_4b_st_active[:49], temp_std_4b_st_active[:49], (17, 75, 30, 65 ), title)
# -
print("Time to 45 iterations: %.2f s" %timestamp_std_4b_st_active[44])
print("Multi-thread 4B (A): %.2f | Multi-thread 4B (P): %.2f" % (np.mean(time_std_4b_mt_active), np.mean(time_std_4b_mt_passive)))
print("Single-thread 4B (A): %.2f | Single-thread 4B (P): %.2f" % (np.mean(time_std_4b_st_active), np.mean(time_std_4b_st_passive)))
print("Max. temp. (MT-A) %.2f | Max. temp. (MT-P) %.2f" % (np.max(temp_std_4b_mt_active), np.max(temp_std_4b_mt_passive)))
print("Max. temp. (ST-A) %.2f | Max. temp. (ST-P) %.2f" % (np.max(temp_std_4b_st_active), np.max(temp_std_4b_st_passive)))
| performance_test_standard_kernel_cooling_rpi_4B.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
# ---
# # Pricing a life insurance product
# Statistics Probability Theory Expected Value
#
# Suppose you're working for a life insurance company that is trying to price a one year policy for a 24-year old male.
#
# If the individual has a .99972 probability of surviving the year, and the payout is `$300,000`, what should the company price the policy at if they want to target an expected value of `$150`?
#
# +
p = .99972
payout = 300000
payout_expectation = (1-p)*payout
target_ev = 150
policy_price = target_ev + payout_expectation
print(f'payout_expectation: {round(payout_expectation)}')
print(f'policy_price: {round(policy_price)}')
# -
| interviewq_exercises/q125_stats_insurance_policy_price_expectation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .r
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: R
# language: R
# name: ir
# ---
# # Testing with apply, foreach and for loops in R
#
# Similar to programs like C or C++, in R you can do looping to do some sort of iteration using for, apply and foreach functions.
#
# 1. for: like any other programming, this loops user defined n time to do something
# 2. apply: similar to for, apply can iterate over row or column to do a user defined task
# 3. foreach: this function is like for function but, on steroids. Here, we can use parallel computing to perform for loops in parallel.
#
# To test out the performance of each of the functions, we will use different data sizes to see which performs better.
# getRes() function will basically look at a row to see it it meets constraints like if number of '1' in a row is less than or equal to something and if it is then it return 1 else 0. We can use this function against a dataframe to compare the results.
#
library(dplyr)
library(microbenchmark)
getRes = function(combinations) {
row = combinations
one = length(which(row==1))
two = length(which(row==2))
three = length(which(row==3))
if(one <= 6)
{
if(two <= 5)
{
if(three == 1)
{
return(1)
}
else {return(0)}
}
else {return(0)}
}
else {return(0)}
}
# ## Apply
# Create an apply loop function to run the getRes function.
apply_loop = function (combinations){
x1= as.POSIXct(Sys.time())
res = NULL
res = apply(combinations,1,getRes)
x2= as.POSIXct(Sys.time())
#return(res)
return(as.difftime(x2-x1, units = "secs"))
}
# ## Foreach
# Create an foreach loop function to run the getRes function.
# +
library(foreach)
library(doParallel)
library(parallel)
foreach_loop = function (combinations){
cl <- makeCluster(16)
clusterExport(cl, c("getRes"))
registerDoParallel(cl)
x1= as.POSIXct(Sys.time())
res = NULL
res = foreach(i = 1:nrow(combinations), .combine = rbind) %dopar% {
getRes(combinations[i,])
}
x2= as.POSIXct(Sys.time())
stopCluster(cl)
#return(res)
return(as.difftime(x2-x1, units = "secs"))
}
# -
# ## For
# Create an for loop function to run the getRes function.
for_loop = function (combinations){
x1= as.POSIXct(Sys.time())
res=NULL
for(i in 1:nrow(combinations)) {
res[i] = getRes(combinations[i,])
}
x2= as.POSIXct(Sys.time())
#return(res)
return(as.difftime(x2-x1, units = "secs"))
}
# ## Microbenchmark
# Do a microbench study to run all different loops and get some statistics. Microbench will perform 5 iterations. Dplyr package is used to group and summarize the data.
# +
mbLoops1 = NULL
combinations = expand.grid(c(1:3))
mbLoops = function(combinations) {
res = microbenchmark(apply_loop(combinations), foreach_loop(combinations), for_loop(combinations), times=5)
res1 = res
res1$time = res1$time/1000000000
mb = res1 %>% group_by(expr) %>% summarise (mean = mean(time)
,sd = sd(time)
,min = min(time)
,max = max(time)
)
mb$size = nrow(combinations)
return(data.frame(mb))
}
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
mbLoops1
# -
# Increase the data size and run different loops.
# +
combinations = expand.grid(c(1:3), c(1:3))
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
# +
combinations = expand.grid(c(1:3), c(1:3), c(1:3))
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
# +
combinations = expand.grid(c(1:3), c(1:3), c(1:3), c(1:3))
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
# +
combinations = expand.grid(c(1:3), c(1:3), c(1:3), c(1:3), c(1:3))
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
# +
combinations = expand.grid(c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3))
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
# +
combinations = expand.grid(c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3))
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
# +
combinations = expand.grid(c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3))
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
# +
combinations = expand.grid(c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3))
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
# +
combinations = expand.grid(c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3))
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
# +
combinations = expand.grid(c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3), c(1:3))
mbLoops1 = rbind(mbLoops(combinations), mbLoops1)
# -
# View summarized data metrics. Although its hard to make out the difference we can tell apply method was consistently faster compared to the rest of the function loops.
mbLoops1
# Let's plot the data to better visualize how everything looks like.
# +
#Adjust plot sizes
options(repr.plot.width=10, repr.plot.height=6)
plot(subset(mbLoops1, expr =='apply_loop(combinations)')$size
, subset(mbLoops1, expr =='apply_loop(combinations)')$mean
, type='o'
, col='red'
, pch=19
, ylim = c(0,180)
, ylab="Seconds"
, xlab = "Data Size"
, main = "Mean of Different Loops Comparison"
)
lines(subset(mbLoops1, expr =='apply_loop(combinations)')$size
, subset(mbLoops1, expr =='foreach_loop(combinations)')$mean
, type='o'
, col='green'
, pch=19
)
lines(subset(mbLoops1, expr =='apply_loop(combinations)')$size
, subset(mbLoops1, expr =='for_loop(combinations)')$mean
, type='o'
, col='blue'
, pch=19
)
legend("topleft", c("apply", "foreach", "for"), col = c("red", "green","blue"), lty=1, cex=0.8 )
# +
#Adjust plot sizes
options(repr.plot.width=10, repr.plot.height=6)
plot(subset(mbLoops1, expr =='apply_loop(combinations)')$size
, subset(mbLoops1, expr =='apply_loop(combinations)')$sd
, type='o'
, col='red'
, pch=19
, ylim = c(0,15)
, ylab="Seconds"
, xlab = "Data Size"
, main = "SD of Different Loops Comparison"
)
lines(subset(mbLoops1, expr =='apply_loop(combinations)')$size
, subset(mbLoops1, expr =='foreach_loop(combinations)')$sd
, type='o'
, col='green'
, pch=19
)
lines(subset(mbLoops1, expr =='apply_loop(combinations)')$size
, subset(mbLoops1, expr =='for_loop(combinations)')$sd
, type='o'
, col='blue'
, pch=19
)
legend("topleft", c("apply", "foreach", "for"), col = c("red", "green","blue"), lty=1, cex=0.8 )
# -
# From the above study, we can observe that apply loop was consistently much faster compared to either for or foreach loop. As the data size increases, the time to run also increased linearly in for and foreach loop. On the other hand for apply, there was almost no change in time to run apply loop.
sessionInfo()
| loops.ipynb |
# ##### Copyright 2020 Google LLC.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# # send_more_money_any_base
# <table align="left">
# <td>
# <a href="https://colab.research.google.com/github/google/or-tools/blob/master/examples/notebook/contrib/send_more_money_any_base.ipynb"><img src="https://raw.githubusercontent.com/google/or-tools/master/tools/colab_32px.png"/>Run in Google Colab</a>
# </td>
# <td>
# <a href="https://github.com/google/or-tools/blob/master/examples/contrib/send_more_money_any_base.py"><img src="https://raw.githubusercontent.com/google/or-tools/master/tools/github_32px.png"/>View source on GitHub</a>
# </td>
# </table>
# First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab.
# !pip install ortools
# +
# Copyright 2010 <NAME> <EMAIL>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
SEND+MORE=MONEY in 'any' base in Google CP Solver.
Alphametic problem SEND+MORE=MONEY in any base.
Examples:
Base 10 has one solution:
{9, 5, 6, 7, 1, 0, 8, 2}
Base 11 has three soltutions:
{10, 5, 6, 8, 1, 0, 9, 2}
{10, 6, 7, 8, 1, 0, 9, 3}
{10, 7, 8, 6, 1, 0, 9, 2}
Also, compare with the following models:
* Comet : http://www.hakank.org/comet/send_more_money_any_base.co
* ECLiPSE : http://www.hakank.org/eclipse/send_more_money_any_base.ecl
* Essence : http://www.hakank.org/tailor/send_more_money_any_base.eprime
* Gecode : http://www.hakank.org/gecode/send_more_money_any_base.cpp
* Gecode/R: http://www.hakank.org/gecode_r/send_more_money_any_base.rb
* MiniZinc: http://www.hakank.org/minizinc/send_more_money_any_base.mzn
* Zinc: http://www.hakank.org/minizinc/send_more_money_any_base.zinc
* SICStus: http://www.hakank.org/sicstus/send_more_money_any_base.pl
This model was created by <NAME> (<EMAIL>)
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.constraint_solver import pywrapcp
# Create the solver.
solver = pywrapcp.Solver('Send most money')
# data
print('base:', base)
# declare variables
s = solver.IntVar(0, base - 1, 's')
e = solver.IntVar(0, base - 1, 'e')
n = solver.IntVar(0, base - 1, 'n')
d = solver.IntVar(0, base - 1, 'd')
m = solver.IntVar(0, base - 1, 'm')
o = solver.IntVar(0, base - 1, 'o')
r = solver.IntVar(0, base - 1, 'r')
y = solver.IntVar(0, base - 1, 'y')
x = [s, e, n, d, m, o, r, y]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
solver.Add(
s * base**3 + e * base**2 + n * base + d + m * base**3 + o * base**2 +
r * base + e == m * base**4 + o * base**3 + n * base**2 + e * base + y,)
solver.Add(s > 0)
solver.Add(m > 0)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
collector = solver.AllSolutionCollector(solution)
solver.Solve(
solver.Phase(x, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MAX_VALUE),
[collector])
num_solutions = collector.SolutionCount()
money_val = 0
for s in range(num_solutions):
print('x:', [collector.Value(s, x[i]) for i in range(len(x))])
print()
print('num_solutions:', num_solutions)
print('failures:', solver.Failures())
print('branches:', solver.Branches())
print('WallTime:', solver.WallTime())
print()
base = 10
| examples/notebook/contrib/send_more_money_any_base.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
# ---
# # GPU Simulator
#
# ## GPU Qiskit Aer Simulator Backends and Methods
#
# Following Qiskit Aer backends currently support GPU acceleration:
# * `QasmSimulator`
# * `StatevectorSimulator`
# * `UnitarySimulator`
#
# To check the availability of GPU support on these backends, `available_method()` returns methods with gpu suports.
# ## Introduction
#
# This notebook shows how to accelerate Qiskit Aer simulators by using GPUs.
#
# To install GPU support in Qiskit Aer, please install GPU version of Qiskit Aer by
#
# `pip install qiskit-aer-gpu`
#
# ### Note
#
# Qiskit Aer only supports NVIDIA's GPUs and requires CUDA toolkit installed on the system.
from qiskit import *
from qiskit.circuit.library import *
from qiskit.providers.aer import *
qasm_sim = QasmSimulator()
print(qasm_sim.available_methods())
# If Qiskit Aer with GPU support is installed correctly, you can see `statevector_gpu` and `density_matrix_gpu`
st_sim = StatevectorSimulator()
print(st_sim.available_methods())
u_sim = UnitarySimulator()
print(u_sim.available_methods())
# ### Simulation with GPU
#
# Here is a simple example to run quantum volume circuit with 20 qubits by using `QasmSimulator` backend.
# Setting the simulation method `statevector_gpu` in `backend_options` parameter passed to `QasmSimulator.run` method to use GPU for the simulaiton.
# +
shots = 64
qubit = 20
depth=10
qv20 = QuantumVolume(qubit, depth, seed = 0)
qv20 = transpile(qv20, backend=qasm_sim, optimization_level=0)
qv20.measure_all()
qobj = assemble(qv20, shots=shots, memory=True)
if 'statevector_gpu' in qasm_sim.available_methods():
result = qasm_sim.run(qobj, backend_options={"method" : "statevector_gpu"}).result()
else:
print('There is no GPU simulator installed, so using CPU simulator')
result = qasm_sim.run(qobj, backend_options={"method" : "statevector"}).result()
counts = result.get_counts(qv20)
print(counts)
# -
# The following sample shows an example using `density_matrix_gpu` mthod in `QasmSimulator`.
# +
qubit = 10
depth = 10
qv10 = QuantumVolume(qubit, depth, seed = 0)
qv10 = transpile(qv10, backend=qasm_sim, optimization_level=0)
qv10.measure_all()
qobj = assemble(qv10, shots=shots, memory=True)
if 'density_matrix_gpu' in qasm_sim.available_methods():
result = qasm_sim.run(qobj, backend_options={"method" : "density_matrix_gpu"}).result()
else:
print('There is no GPU simulator installed, so using CPU simulator')
result = qasm_sim.run(qobj, backend_options={"method" : "density_matrix"}).result()
counts = result.get_counts(qv10)
print(counts)
# -
# ## Parallelizing Simulaiton by Using Multiple GPUs
#
# In general GPU has less memory size than CPU, and the largest number of qubits is depending on the memory size. For example, if a GPU has 16 GB of memory, Qiskit Aer can simulate up to 29 qubits by using `statevector_gpu` method in `QasmSimulator` and `StatevectorSimulator` backends or up to 14 qubits by using `density_matrix_gpu` method in `QasmSimulator` backend and `unitary_gpu` method in `UnitarySimulator` backend in double precision.
#
# To simulate with more larger nnumber of qubits, multiple GPUs can be used to parallelize the simulation or also parallel simulation can accelerate the simulation speed.
#
# To use multi-GPUs, following options should be set in the `backend_options` parameter passed to `run` method. In the parallel simulator, the vector of quantum states are divided into sub-vectors called chunk and chunks are distributed to memory of multiple-GPUs.
#
# Following 2 options should be passed:
# * `blocking_enable` : Set `True` to enable parallelization
# * `blocking_qubits` : This option sets the size of chunk that is distributed to parallel memory space. Set this parameter to satisfy `16*(2^(blocking_qubits+4)) < smallest memory size on the system (in byte)` for double precision. (`8*` for single precision).
#
# The parameter `blocking_qubits` will be varied in different environment, so this parameter is optimized by using some benchmarks before running actual applications. Usually setting 20 to 23 will be good for many environments.
#
# Here is an example of Quantum Volume of 30 qubits with multiple GPUs by using `QasmSimulator` backend and `statevector_gpu` method.
qubit = 30
depth = 10
qv30 = QuantumVolume(qubit, depth, seed = 0)
qv30 = transpile(qv30, backend=qasm_sim, optimization_level=0)
qv30.measure_all()
qobj = assemble(qv30, shots=shots, memory=True)
if 'statevector_gpu' in qasm_sim.available_methods():
result = qasm_sim.run(qobj, backend_options={"method" : "statevector_gpu", "blocking_enable" : True, "blocking_qubits" : 23 }).result()
counts = result.get_counts(qv30)
print(counts)
else:
print('There is no GPU simulator installed')
# ### Note
#
# Note that only `QasmSimulator` can be applied for large qubit circuits because `StatevectorSimulator` and `UnitarySimulator` backends currently returns snapshots of state that will require large memory space. If CPU has enough memory to store snapshots these 2 backends can be used with GPUs.
# ## Distribution of Shots by Using Multiple GPUs
#
# Also GPUs can be used to accelerate simulating multiple shots with noise models. If the system has multiple GPUs, shots are automatically distributed to GPUs if there is enough memory to simulate one shot on single GPU. Also if there is only one GPU on the system, multiple shots can be parallelized on threads of GPU.
#
# Note multiple shots distribution on GPU is slower than running on CPU when number of qubits to be simulated is small because of large overheads of GPU kernel launch.
#
# Following example shows running 1000 shots of quantum volume circuit with noise on GPU.
# +
from qiskit.providers.aer.noise import *
noise_model = NoiseModel()
error = depolarizing_error(0.05, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
shots = 1000
qobj = assemble(qv10, shots=shots, memory=True)
if 'statevector_gpu' in qasm_sim.available_methods():
result = qasm_sim.run(qobj, noise_model = noise_model, backend_options={"method" : "statevector_gpu"}).result()
else:
print('There is no GPU simulator installed, so using CPU simulator')
result = qasm_sim.run(qobj, noise_model = noise_model, backend_options={"method" : "statevector"}).result()
rdict = result.to_dict()
print("simulation time = {0}".format(rdict['time_taken']))
# -
import qiskit.tools.jupyter
# %qiskit_version_table
# %qiskit_copyright
| tutorials/simulators/8_gpu_simulator.ipynb |
// ---
// jupyter:
// jupytext:
// text_representation:
// extension: .scala
// format_name: light
// format_version: '1.5'
// jupytext_version: 1.14.4
// kernelspec:
// display_name: 0904 - Scala
// language: scala
// name: 0904_scala
// ---
// # Introduction to XGBoost Spark with GPU
//
// Mortgage is an example of xgboost classifier. In this notebook, we will show you how to load data, train the xgboost model and use this model to predict if someone is "deliquency". Comparing to original XGBoost Spark codes, there're only two API differences.
//
//
// ## Load libraries
// First we load some common libraries that both GPU version and CPU version xgboost will use:
import ml.dmlc.xgboost4j.scala.spark.{XGBoostClassifier, XGBoostClassificationModel}
import org.apache.spark.sql.SparkSession
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
import org.apache.spark.sql.types.{DoubleType, IntegerType, StructField, StructType}
// what is new to xgboost-spark users is only `rapids.GpuDataReader`
import ml.dmlc.xgboost4j.scala.spark.rapids.{GpuDataReader, GpuDataset}
// Some libraries needed for CPU version are not needed in GPU version any more. The extra libraries needed for CPU are like below:
//
// ```scala
// import org.apache.spark.ml.feature.VectorAssembler
// import org.apache.spark.sql.DataFrame
// import org.apache.spark.sql.functions._
// import org.apache.spark.sql.types.FloatType
// ```
// ## Set your dataset path
// Set the paths of datasets for training and prediction
// You need to update them to your real paths!
val trainPath = "/data/mortgage/csv/train/"
val trainWithEvalPath = "/data/mortgage/csv/trainWithEval/"
val evalPath = "/data/mortgage/csv/eval/"
// ## Set the schema of the dataset
// for mortgage example, the data has 27 columns: 26 features and 1 label. "deinquency_12" is set as label column. The schema will be used to help load data in the future. We also defined some key parameters used in xgboost training process. We also set some basic xgboost parameters here.
// +
val labelColName = "delinquency_12"
val schema = StructType(List(
StructField("orig_channel", DoubleType),
StructField("first_home_buyer", DoubleType),
StructField("loan_purpose", DoubleType),
StructField("property_type", DoubleType),
StructField("occupancy_status", DoubleType),
StructField("property_state", DoubleType),
StructField("product_type", DoubleType),
StructField("relocation_mortgage_indicator", DoubleType),
StructField("seller_name", DoubleType),
StructField("mod_flag", DoubleType),
StructField("orig_interest_rate", DoubleType),
StructField("orig_upb", IntegerType),
StructField("orig_loan_term", IntegerType),
StructField("orig_ltv", DoubleType),
StructField("orig_cltv", DoubleType),
StructField("num_borrowers", DoubleType),
StructField("dti", DoubleType),
StructField("borrower_credit_score", DoubleType),
StructField("num_units", IntegerType),
StructField("zip", IntegerType),
StructField("mortgage_insurance_percent", DoubleType),
StructField("current_loan_delinquency_status", IntegerType),
StructField("current_actual_upb", DoubleType),
StructField("interest_rate", DoubleType),
StructField("loan_age", DoubleType),
StructField("msa", DoubleType),
StructField("non_interest_bearing_upb", DoubleType),
StructField(labelColName, IntegerType)))
val commParamMap = Map(
"eta" -> 0.1,
"gamma" -> 0.1,
"missing" -> 0.0,
"max_depth" -> 10,
"max_leaves" -> 256,
"grow_policy" -> "depthwise",
"objective" -> "binary:logistic",
"min_child_weight" -> 30,
"lambda" -> 1,
"scale_pos_weight" -> 2,
"subsample" -> 1,
"nthread" -> 1,
"num_round" -> 100)
// -
// ## Create a new spark session and load data
// we must create a new spark session to continue all spark operations. It will also be used to initilize the `GpuDataReader` which is a data reader powered by GPU.
//
// Here's the first API difference, we now use GpuDataReader to load dataset. Similar to original Spark data loading API, GpuDataReader also uses chaining call of "option", "schema","csv". For CPU verions data reader, the code is like below:
//
// ```scala
// val dataReader = spark.read
// ```
//
// NOTE: in this notebook, we have uploaded dependency jars when installing toree kernel. If we don't upload them at installation time, we can also upload in notebook by [%AddJar magic](https://toree.incubator.apache.org/docs/current/user/faq/). However, there's one restriction for `%AddJar`: the jar uploaded can only be available when `AddJar` is called after a new spark session is created. We must use it as below:
//
// ```scala
// import org.apache.spark.sql.SparkSession
// val spark = SparkSession.builder().appName("mortgage-GPU").getOrCreate
// // %AddJar file:/data/libs/cudf-0.9.2-cuda10.jar
// // %AddJar file:/data/libs/xgboost4j_2.x-1.0.0-Beta5.jar
// // %AddJar file:/data/libs/xgboost4j-spark_2.x-1.0.0-Beta5.jar
// // ...
// ```
val spark = SparkSession.builder().appName("mortgage-gpu").getOrCreate
// Here's the first API difference, we now use `GpuDataReader` to load dataset. Similar to original Spark data loading API, `GpuDataReader` also uses chaining call of "option", "schema","csv". For `CPU` verion data reader, the code is like below:
//
// ```scala
// val dataReader = spark.read
// ```
//
// `featureNames` is used to tell xgboost which columns are `feature` and while column is `label`
val reader = new GpuDataReader(spark).option("header", true).schema(schema)
val featureNames = schema.filter(_.name != labelColName).map(_.name)
// Now we can use `dataReader` to read data directly. However, in CPU version, we have to use `VectorAssembler` to assemble all feature columns into one column. The reason will be explained later. the CPU version code is as below:
//
// ```scala
// object Vectorize {
// def apply(df: DataFrame, featureNames: Seq[String], labelName: String): DataFrame = {
// val toFloat = df.schema.map(f => col(f.name).cast(FloatType))
// new VectorAssembler()
// .setInputCols(featureNames.toArray)
// .setOutputCol("features")
// .transform(df.select(toFloat:_*))
// .select(col("features"), col(labelName))
// }
// }
//
// val trainSet = reader.csv(trainPath)
// val evalSet = reader.csv(evalPath)
// trainSet = Vectorize(trainSet, featureCols, labelName)
// evalSet = Vectorize(evalSet, featureCols, labelName)
//
// ```
//
// While with GpuDataReader, `VectorAssembler` is not needed any more. We can simply read data by:
val trainSet = reader.csv(trainPath)
val trainWithEvalSet = reader.csv(trainWithEvalPath)
val evalSet = reader.csv(evalPath)
// ## Add XGBoost parameters for GPU version
//
// Another modification is `num_workers` should be set to the number of machines with GPU in Spark cluster, while it can be set to the number of your CPU cores in CPU version. CPU version parameters:
//
// ```scala
// // difference in parameters
// "tree_method" -> "hist",
// "num_workers" -> 12
// ```
val xgbParamFinal = commParamMap ++ Map("tree_method" -> "gpu_hist", "num_workers" -> 1)
val xgbClassifier = new XGBoostClassifier(xgbParamFinal)
.setLabelCol(labelColName)
// === diff ===
.setFeaturesCols(featureNames)
// ## Benchmark and train
// The benchmark object is for calculating training time. We will use it to compare with xgboost in CPU version.
//
// We also support training with evaluation sets in 2 ways as same as CPU version behavior:
//
// * API `setEvalSets` after initializing an XGBoostClassifier
//
// ```scala
// xgbClassifier.setEvalSets(Map("eval" -> evalSet))
//
// ```
//
// * parameter `eval_sets` when initializing an XGBoostClassifier
//
// ```scala
// val paramMapWithEval = paramMap + ("eval_sets" -> Map("eval" -> evalSet))
// val xgbClassifierWithEval = new XGBoostClassifier(paramMapWithEval)
// ```
//
// in this notebook, we use API method to set evaluation sets.
xgbClassifier.setEvalSets(Map("eval" -> trainWithEvalSet))
// +
object Benchmark {
def time[R](phase: String)(block: => R): (R, Float) = {
val t0 = System.currentTimeMillis
val result = block // call-by-name
val t1 = System.currentTimeMillis
println("Elapsed time [" + phase + "]: " + ((t1 - t0).toFloat / 1000) + "s")
(result, (t1 - t0).toFloat / 1000)
}
}
// Start training
println("\n------ Training ------")
val (xgbClassificationModel, _) = Benchmark.time("train") {
xgbClassifier.fit(trainSet)
}
// -
// ## Transformation and evaluation
// We use `evalSet` to evaluate our model and use some key columns to show our predictions. Finally we use `MulticlassClassificationEvaluator` to calculate an overall accuracy of our predictions.
// +
println("\n------ Transforming ------")
val (results, _) = Benchmark.time("transform") {
val ret = xgbClassificationModel.transform(evalSet).cache()
ret.foreachPartition(_ => ())
ret
}
results.select("orig_channel", labelColName,"rawPrediction","probability","prediction").show(10)
println("\n------Accuracy of Evaluation------")
val evaluator = new MulticlassClassificationEvaluator().setLabelCol(labelColName)
val accuracy = evaluator.evaluate(results)
println(accuracy)
// -
// ## Save the model to disk and load model
// We save the model to disk and then load it to memory. We can use the loaded model to do a new prediction.
// +
xgbClassificationModel.write.overwrite.save("/data/model/mortgage")
val modelFromDisk = XGBoostClassificationModel.load("/data/model/mortgage")
val (results2, _) = Benchmark.time("transform2") {
modelFromDisk.transform(evalSet)
}
results2.show(10)
// -
spark.close()
| examples/notebooks/scala/mortgage-gpu.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 Functions
#
# If you're running the exact same chunk of code once or twice you can probably just copy and paste as needed, however, if you find yourself copy and pasting more than three times, it is probably in your best interest to instead write a <i>function</i> (sometimes called <i>method</i>) that you can just call instead.
#
# We'll start with a silly (to me at least) example and work up our function competence from there.
# +
## To write a function you start with def function_name() then have a colon
## all code you want included as a part of the function should be
## properly indented!
# def function_name():
def hello_there():
# Then on an indented block write the code you want executed
print("Hello there.")
# -
## To call the function, just type the functions name
## with parantheses
hello_there()
# +
## You code
## Write your own function called general_kenobi
## When called it should print the string "General Kenobi."
def general_kenobi():
print("General Kenobi.")
# +
## You code
# call general_kenobi then hello_there
general_kenobi()
hello_there()
# -
# ## Wanting something in `return`
#
# We'll surely want functions that do more than just print Star Wars prequel references. In fact we'll probably want functions that give us some kind of output, that's the point of the `return` statement.
#
# `return`s end the function code chunk, and, as the name suggests, they return some output when called. Let's do an example.
## here's a simple example
def make_two():
return 2
## A 2 should be returned
make_two()
# +
## You code
## Write a function that returns the number 3
## call it make_three
def make_three():
return 3
make_three()
# -
# ## Adding Arguments
#
# Sometimes we'll want our function to take in some kind of input, do something with it, then return the results. Inputs to python functions are called arguments, let's write a function that has some arguments.
## Here we take in a number, x, and
## decide if it is divisible by 2
## if it is, we return x/2
## if it isn't we return (x+1)/2
def weird_division(x):
if x%2 == 0:
# double indent
# note that if we hit this return statement
# we exit the function and don't run
# any of the remaining code
return x/2
else:
return (x+1)/2
# +
## You code
## run weird_divison a few times
## and see what happens
weird_division(7)
# -
## You code
## write a function that takes in an integer
## and returns the string
## "even" or "odd" depending on whether it is
## even or odd
def even_or_odd(x):
if type(x) == int:
if x%2 == 0:
return "even"
else:
return "odd"
else:
return "Not an 'int'"
even_or_odd(8.14)
# #### Arguments with Default Arguments
#
# Sometimes we'll want to make a function that has an argument with a default value that can be altered by the user. This can be done!
#
# In order to do this you first place all the arguments that must be entered by the user, and then follow it by all the arguments that have a default value. Let's see
## x will need to be entered each time it is called
## y has a default value of 2, but can be changed
def divisible_by(x,y=2):
if x%y == 0:
print("Yes.",x,"is divisible by",y)
else:
print("No.",x,"is not divisble by",y)
# +
## let's first call divisible_by using any integer for x
## and keeping y at the default value of 2
divisible_by(3)
## Now let's change the argument for y
## both of the following work
divisible_by(3, y=3)
divisible_by(3, 3)
## but it is good practice to use the variable name
## so people who read your code, know what you're doing
# +
## You code
## write a function that can take in three numbers x, y, and z
## and multiply them
## have z default to 17
def weird_multiply(x, y, z=17):
return x*y*z
# -
## You code
## now call that function and use the default value for z
weird_multiply(1,2)
## You code
## now call that function and change the value of z
weird_multiply(1,2,z=16)
# #### An Aside on Variable Scope
#
# Maybe you're sitting at your computer worried about what might go wrong if the variable name used in your function is the same as a variable name outside of your function. Well worry no longer.
#
# Variables created in a normal non-function code chunk are known as `global variables`. Let's look at an example.
## running this makes apple a global variable
apple = 10
apple
# After you run the above code chunk `apple` becomes a global variable.
#
# Variables defined within a function are known as `local variables`. Let's look at another example.
## Within dumb_function 'apple' is a local variable
def dumb_function(apple):
print(apple)
# In python local variables take precedence over global variables. This means that when we call `dumb_function` the value that gets printed is whatever you input as the `apple` argument.
## STOP
## Before running this, what do you think the output will be?
## only run once you have thought of the answer
dumb_function("peanut butter")
apple
# ### Anonymous (or Lambda) Functions
#
# In some settings it will be useful to use a function without having to store it in memory. In these settings you would want to write an "anonymous function", so called because it is not stored within a named variable. In python it is more common to call anonymous functions "lambda functions". Let's see why right now.
## The syntax of a lambda function is
## lambda arguments: expression
## here x is the argument, the expression is x times 2
lambda x: x * 2
## We can abuse this to quickly define a function
## without a def or return statement
double = lambda x: x * 2
double
# +
## You code
## call double using any number you'd like
double(83)
# +
## You code
## Write a lambda function for multiplying a number by 5
times_five = lambda x: x * 5
times_five(5)
# -
# You might be wondering why lambda functions exist, or why they might be useful. That's fair!
#
# Their true use comes later when you've learned a little more python. For example, sometimes we may wish to apply a certain operation to a collection of items all at once, there are ways in python for doing this, and lambda functions can be used quite frequently to help.
# ## That's it for Functions!
#
# That's all we'll touch on for functions in this prereq, this was not a comprehensive tour of functions in python, but it is all you'll need to know to utilize them in the boot camp.
# This notebook was written for the Erdős Institute Cőde Data Science Boot Camp by <NAME>, Ph. D., 2021.
#
# Redistribution of the material contained in this repository is conditional on acknowledgement of <NAME>, Ph.D.'s original authorship and sponsorship of the Erdős Institute as subject to the license (see License.md)
| python prep/3. Writing Functions - Complete.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
# ---
# ## 0. Utility
import random
from timeit import default_timer as timer
import matplotlib.pyplot as plt
# %matplotlib inline
def check_fun(ref_fun, fun, input_gen, ntimes=10, **kwargs):
"Check fun with reference implementation."
for _ in range(ntimes):
input_ = input_gen(**kwargs)
assert(fun(*input_) == ref_fun(*input_))
print("Tests passed")
def generate_shuffle_array(n=1000):
"Generate a shuffled array [0...n)"
array = list(range(n))
random.shuffle(array)
return (array, )
def scaling_analyze(fun, input_gen, max_exp=4):
"Do scaling analysis on fun from 10**0 to 10**max_exp."
ns, times = [], []
for e in range(max_exp + 1):
n = 10 ** e
ns.append(n)
input_ = input_gen(n)
start = timer()
_ = fun(input_)
end = timer()
times.append(end - start)
return ns, times
# +
# ns, times = scaling_analyze(sorted, generate_shuffle_array, max_exp=6)
# plt.loglog(ns, times, 'bo')
# -
# ## 1. Selection Sort
# 
def selection_sort(array):
"Implement selection sort to sort an array."
A = list(array)
n = len(A)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if A[j] < A[min_idx]:
min_idx = j
A[min_idx], A[i] = A[i], A[min_idx]
return A
check_fun(sorted, selection_sort, generate_shuffle_array, n = 500, ntimes=10)
# +
# ns, times = scaling_analyze(selection_sort, generate_shuffle_array, max_exp=4)
# +
# plt.loglog(ns, times, 'bo')
# -
# ## 2. Insertion Sort
#
# 
def insertion_sort(array):
"Implement insertion sort to sort an array."
A = list(array)
n = len(A)
for k in range(n - 1):
i = k + 1
while i > 0 and A[i - 1] > A[i]:
A[i - 1], A[i] = A[i], A[i - 1]
i -= 1
return A
check_fun(sorted, insertion_sort, generate_shuffle_array, n=500, ntimes=10)
# ## 3. Bubble Sort
# 
def bubble_sort(array):
"Implement bubble sort to sort an array."
A = list(array)
n = len(A)
for s in range(n - 1):
for k in range(n - 1 - s):
if A[k] > A[k + 1]:
A[k], A[k + 1] = A[k + 1], A[k]
return A
check_fun(sorted, bubble_sort, generate_shuffle_array, n=500, ntimes=10)
# ## 4. Merge Sort
# 
def merge_sort(array):
"Implement merge sort to sort an array."
A = list(array)
def merge_sort_helper(A):
"helper function of merge sort"
n = len(A)
if n == 1:
return A
else:
m = n // 2
L = merge_sort_helper(A[:m])
R = merge_sort_helper(A[m:])
i, l, r = 0, 0, 0
nL, nR = len(L), len(R)
while l < nL and r < nR:
if L[l] < R[r]:
A[i] = L[l]
l += 1
else:
A[i] = R[r]
r += 1
i += 1
for j in range(l, nL):
A[i] = L[j]
i += 1
for j in range(r, nR):
A[i] = R[j]
i += 1
return A
return merge_sort_helper(A)
check_fun(sorted, merge_sort, generate_shuffle_array, n=500, ntimes=10)
# +
# ns, times = scaling_analyze(sorted, generate_shuffle_array, max_exp=7)
# plt.loglog(ns, times, 'bo')
# -
# ## 5. Quick Sort
# 
def quick_sort(array):
"Implement quick sort to sort an array."
A = list(array)
def partition(A, lo, hi):
"partition function."
i = lo - 1
pivot = A[hi]
for j in range(lo, hi):
if A[j] <= pivot:
i = i + 1
A[i], A[j] = A[j], A[i]
A[i + 1], A[hi] = A[hi], A[i + 1]
return i + 1
def quick_sort_helper(A, lo, hi):
"quick sort helper function."
if lo < hi:
i = partition(A, lo, hi)
quick_sort_helper(A, lo, i - 1)
quick_sort_helper(A, i + 1, hi)
quick_sort_helper(A, 0, len(A) - 1)
return A
check_fun(sorted, quick_sort, generate_shuffle_array, n=500, ntimes=10)
ns, times = scaling_analyze(sorted, generate_shuffle_array, max_exp=7)
plt.loglog(ns, times, 'bo')
# ## 6. Bucket Sort
# 
def bucket_sort(array):
"Implement Bucket sort of an array."
A = list(array)
mn, mx = min(A), max(A)
C = [0] * (mx - mn + 1) # counter
for num in A:
C[num - mn] += 1
k = 0
for i in range(mn, mx + 1):
for j in range(C[i - mn]):
A[k] = i
k += 1
return A
check_fun(sorted, bucket_sort, generate_shuffle_array, n=500, ntimes=10)
# ## 7. Count Inversions
# 
def count_inversions_naive(array):
"Naive implementation of inversions."
n = len(array)
cnt = 0
for i in range(n):
for j in range(i + 1, n):
if array[j] < array[i]:
cnt += 1
return cnt
def count_and_sort(array):
"Count and sort."
A = list(array)
def count_and_sort_helper(A):
n = len(A)
if n == 1:
return (0, A)
else:
m = n // 2
cl, L = count_and_sort_helper(A[:m])
cr, R = count_and_sort_helper(A[m:])
c_cross = count_cross(L, R)
c = cl + cr + c_cross
B = merge(L, R)
return (c, B)
return count_and_sort_helper(A)
import heapq
def merge(L, R):
"Return merged array of sorted L and R."
return list(heapq.merge(L, R))
# 
def count_cross(L, R):
"count inversions between L and R."
l, r, c = 0, 0, 0
nL, nR = len(L), len(R)
while l < nL and r < nR:
if L[l] <= R[r]:
l += 1
else:
c += nL - l
r = r + 1
return c
def count_inversions(array):
"implementation of counting inversions."
c, _ = count_and_sort(array)
return c
check_fun(count_inversions_naive, count_inversions, generate_shuffle_array, n=500, ntimes=10)
| divide-and-conquer/sort.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import matplotlib.pyplot as plt
import pandas as pd
import scipy.stats as st
import numpy as np
health_info = r"C:\Users\david\Desktop\Davids Branch\Row-2-Group-Project\Health Insurance Coverage by State CSV.csv"
health_info = pd.read_csv(health_info)
health_info
obesity_info = r"C:\Users\david\Desktop\Davids Branch\Row-2-Group-Project\Obesity Rates by State.csv"
obesity_info = pd.read_csv(obesity_info)
obesity_info
uninsured_rates = health_info["Uninsured Percentage (2016)"]
uninsured_rates
obesity_rates = obesity_info["Obesity Prevalence"]
obesity_rates
# +
# data1 = obesity_rates
# data2 = uninsured_rates
# fig, ax1 = plt.subplots()
# color = 'tab:red'
# ax1.set_xlabel('States')
# ax1.set_ylabel('Obesity Rates', color=color)
# ax1.scatter(obesity_info['State'], data1, color=color)
# ax1.tick_params(axis='y', labelcolor=color)
# ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
# color = 'tab:blue'
# ax2.set_ylabel('Unisured Rates', color=color) # we already handled the x-label with ax1
# ax2.scatter(obesity_info['State'], data2, color=color)
# ax2.tick_params(axis='y', labelcolor=color)
# fig.tight_layout() # otherwise the right y-label is slightly clipped
# plt.xticks(rotation=45)
# plt.show()
plt.scatter(uninsured_rates, obesity_rates , color = "blue")
plt.xlabel("Uninsured Rate")
plt.ylabel("Obesity Rate")
plt.show
# -
| Health Insurance Coverage by State.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
# ---
# ## Explore the titanic training set
# +
import pandas as pd
import numpy as np
# visualization
import seaborn as sns
import matplotlib.pyplot as plt
# %matplotlib inline
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
# -
train = pd.read_csv('./data/train.csv')
print('Training set ( Rows , Columns ) : ', train.shape)
train.head(2)
train.info()
# ### Missing values
#
# * Age
# * Cabin
# * Embarked
train['Age'].fillna(train['Age'].mean(), inplace = True)
most_freq_port = train['Embarked'].mode()[0]
train['Embarked'].fillna(most_freq_port, inplace = True)
# ### Describe numeric
train_describe_numeric = train.describe()
train_describe_numeric
print('So survival rate is ')
print(train_describe_numeric.loc['mean', 'Survived'])
train_describe_categorical = train.describe(include=['O'])
train_describe_categorical
print('Most of the people on the ship were : ')
print('Sex : ', train_describe_categorical.loc['top', 'Sex'])
print('count : ', train_describe_categorical.loc['freq', 'Sex'])
# ---
# ### Drop unnecessary features
# +
columns_to_drop = ['PassengerId', 'Ticket', 'Fare', 'Cabin', 'Embarked']
train.drop(
columns_to_drop,
axis = 1,
inplace = True)
train.info()
# -
# ### Create new features
# ### Create *Family_Size* feature
train["Family_Size"] = train['SibSp'] + train['Parch'] + 1
train["Family_Size"].head()
# ### Create *Family_Type* feature
no_of_bins = 5
train['Family_Type'] = pd.cut(train['Family_Size'], no_of_bins, labels = np.arange(no_of_bins))
train['Family_Type'].head()
sns.countplot(x = "Family_Type", hue = "Survived", data = train)
# ### Create *Age_Group* category
no_of_bins = 5
train['Age_Group'] = pd.cut(train['Age'], no_of_bins, labels = np.arange(no_of_bins))
train[ 'Age_Group' ].head()
# ### Encode *gender* feature
train[ 'Sex' ] = labelencoder.fit_transform(train[ 'Sex' ])
train[ 'Sex' ].head()
# ----
# ### Visualize training set
# ### Survival rate by Age_Group
survival_rate_by_age_group = train[['Age_Group', 'Survived']].groupby(['Age_Group'], as_index = False).mean()
survival_rate_by_age_group = survival_rate_by_age_group.sort_values(by = 'Survived', ascending = False)
survival_rate_by_age_group
sns.countplot(x = "Age_Group", hue = "Survived", data = train)
# ### Survival rate by class
survival_rate_by_class = train[['Pclass', 'Survived']].groupby(['Pclass'], as_index = False).mean()
survival_rate_by_class = survival_rate_by_class.sort_values(by = 'Survived', ascending = False)
survival_rate_by_class
sns.countplot(x = "Pclass", hue = "Survived", data = train)
# ### Survival rate by gender
survival_rate_by_gender = train[["Sex", "Survived"]].groupby(['Sex'], as_index = False).mean()
survival_rate_by_gender = survival_rate_by_gender.sort_values(by = 'Survived', ascending = False)
survival_rate_by_gender
# Women were much more likely to survive
# ### Survival rate by family size
survival_rate_by_family_size = train[["Family_Size", "Survived"]].groupby(['Family_Size'], as_index = False).mean()
survival_rate_by_family_size = survival_rate_by_family_size.sort_values(by = 'Survived', ascending = False)
survival_rate_by_family_size
sns.countplot(x = "Family_Size", hue = "Survived", data = train)
| exploration.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 Data
# +
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
package_dir = os.path.join(os.environ['HOME'], 'DataScience', 'quickdraw-gan')
data_dir = os.path.join(package_dir, 'data', 'raw')
# load numpy file
input_file = os.path.join(data_dir, 'cat.npy')
# -
data = np.load(input_file)
data = np.reshape(data, newshape=(data.shape[0], 28, 28))
print('The dataset has %i drawings.' % data.shape[0])
# +
n_rows = 3
n_cols = 10
entry = np.random.randint(0, data.shape[0], n_rows*n_cols)
fig, axes = plt.subplots(n_rows, n_cols, figsize=(22,5))
axes = axes.ravel()
for i, ax in enumerate(axes):
ax.axis('off')
ax.imshow(data[entry[i],:,:], cmap='gray_r')
# -
import tensorflow as tf
from tensorflow.keras import layers
# +
DIM = 32
model = tf.keras.Sequential()
model.add(layers.Conv2D(filters=DIM, kernel_size=(4, 4), strides=(2, 2), input_shape=(28, 28, 1), use_bias=False, padding='same'))
model.add(layers.LeakyReLU(alpha=0.2))
model.add(layers.Conv2D(filters=2*DIM, kernel_size=(4, 4), strides=(2, 2), use_bias=False, padding='same'))
model.add(layers.LeakyReLU(alpha=0.2))
model.add(layers.Conv2D(filters=4*DIM, kernel_size=(4, 4), strides=(2, 2), use_bias=False, padding='same'))
model.add(layers.LeakyReLU(alpha=0.2))
# 2048
model.add(layers.Flatten())
model.add(layers.Dense(units=1, use_bias=False))
# -
model.output
AUX
| notebooks/Load 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
# ---
import numpy as np
import pandas as pd
# Calculate sigmoid
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# # Import data and preprocessing
# +
admissions = pd.read_csv('binary.csv')
# Make dummy variables for rank
data = pd.concat([admissions, pd.get_dummies(admissions['rank'], prefix='rank')], axis=1)
data = data.drop('rank', axis=1)
# Standarize features
for field in ['gre', 'gpa']:
mean, std = data[field].mean(), data[field].std()
data.loc[:,field] = (data[field]-mean)/std
# Split off random 10% of the data for testing
np.random.seed(21)
sample = np.random.choice(data.index, size=int(len(data)*0.9), replace=False)
data, test_data = data.loc[sample], data.drop(sample)
# Split into features and targets
features, targets = data.drop('admit', axis=1), data['admit']
features_test, targets_test = test_data.drop('admit', axis=1), test_data['admit']
# -
# # Backpropagation
# +
np.random.seed(21)
# Hyperparameters
n_hidden = 2 # number of hidden units
epochs = 900
learnrate = 0.005
n_records, n_features = features.shape
last_loss = None
# Initialize weights
weights_input_hidden = np.random.normal(scale=1 / n_features ** .5,
size=(n_features, n_hidden))
weights_hidden_output = np.random.normal(scale=1 / n_features ** .5,
size=n_hidden)
for e in range(epochs):
del_w_input_hidden = np.zeros(weights_input_hidden.shape)
del_w_hidden_output = np.zeros(weights_hidden_output.shape)
for x, y in zip(features.values, targets):
## Forward pass ##
# TODO: Calculate the output
hidden_input = np.dot(x, weights_input_hidden)
hidden_activations = sigmoid(hidden_input)
output = sigmoid(np.dot(hidden_activations,
weights_hidden_output))
## Backward pass ##
# TODO: Calculate the error
error = y - output
# TODO: Calculate error gradient in output unit
output_error = error * output * (1 - output)
# TODO: propagate errors to hidden layer
hidden_error = np.dot(output_error, weights_hidden_output) * \
hidden_activations * (1 - hidden_activations)
# TODO: Update the change in weights
del_w_hidden_output += output_error * hidden_activations
del_w_input_hidden += hidden_error * x[:, None]
# TODO: Update weights
weights_input_hidden += learnrate * del_w_input_hidden / n_records
weights_hidden_output += learnrate * del_w_hidden_output / n_records
# Printing out the mean square error on the training set
if e % (epochs / 10) == 0:
hidden_activations = sigmoid(np.dot(x, weights_input_hidden))
out = sigmoid(np.dot(hidden_activations,
weights_hidden_output))
loss = np.mean((out - targets) ** 2)
if last_loss and last_loss < loss:
print("Train loss: ", loss, " WARNING - Loss Increasing")
else:
print("Train loss: ", loss)
last_loss = loss
# Calculate accuracy on test data
hidden = sigmoid(np.dot(features_test, weights_input_hidden))
out = sigmoid(np.dot(hidden, weights_hidden_output))
predictions = out > 0.5
accuracy = np.mean(predictions == targets_test)
print("Prediction accuracy: {:.3f}".format(accuracy))
| DeepLearning - Udacity/code/Backpropagation/.ipynb_checkpoints/BP For NN-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
def test_exercise_27_2(x) -> bool:
list_1 = [1,2,3]
return x == np.array(list_1)
# -
def test_exercise_27_2(x) -> bool:
list_1 = [1,2,3]
return x == list_1 + list_1
def test_exercise_27_3(x) -> bool:
list_1 = [1,2,3]
array_1 = np.array(list_1)
return x == array_1 + array_1
def test_exercise_27_4(x) -> bool:
data = np.genfromtxt('../numbers.csv', delimiter=',', names=True)
data = data.astype('float64')
return x == data + data
| Chapter03/unit_tests/.ipynb_checkpoints/Exercise 27-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
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/skywalker0803r/c620/blob/main/C620.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + id="UlSIoDuFhzeA"
import pandas as pd
import numpy as np
import joblib
# #!pip install autorch
# + colab={"base_uri": "https://localhost:8080/"} id="33VeJjbyjuv2" outputId="a31e6584-c7f1-4329-b718-6f9fcec17ea3"
c = joblib.load('/content/drive/MyDrive/台塑輕油案子/data/c620/col_names/c620_col_names.pkl')
c.keys()
# + colab={"base_uri": "https://localhost:8080/", "height": 525} id="I1LZZ_tLl0HX" outputId="9822a71f-e1f4-4456-c9bf-885b37836105"
c620_df = pd.read_csv('/content/drive/MyDrive/台塑輕油案子/data/c620/cleaned/c620_train.csv',index_col=0).dropna(axis=0)
print(c620_df.shape)
c620_df.head()
# + colab={"base_uri": "https://localhost:8080/"} id="OjVFbrFdkhcU" outputId="2344b0be-ac1b-4ed2-d2e2-0178011d5b4e"
for k,v in c.items():
print(k,len(v))
# + id="wX76mjFFnPMW"
x_col = c['case']+c['x41']
op_col = c['yRefluxRate']+c['yControl']+c['yHeatDuty']+c['density']
sp_col = c['vent_gas_sf'] +c['distillate_sf'] +c['sidedraw_sf'] +c['bottoms_sf']
wt_col = c['vent_gas_x'] +c['distillate_x'] +c['sidedraw_x'] +c['bottoms_x']
y_col = sp_col + op_col
n_idx = [ [i,i+41,i+41*2,i+41*3]for i in range(41)]
for idx in n_idx:
assert np.allclose(c620_df[y_col].iloc[:,idx].sum(axis=1),1.0) # check
# + colab={"base_uri": "https://localhost:8080/", "height": 783} id="3z_h7BbOpxJ-" outputId="1acfd67a-1cfd-4f98-e3fb-4384671e2cd9"
from autorch.utils import PartBulider
c620 = PartBulider(c620_df,x_col,y_col,normalize_idx_list=n_idx)
c620.train()
c620.test()
# + id="AelwkA--qoVt"
c620.shrink()
# + colab={"base_uri": "https://localhost:8080/"} id="UvPNVFVgtveh" outputId="ffc8531e-5dbc-4e15-b981-7d7b7b685012"
joblib.dump(c620,'/content/drive/MyDrive/台塑輕油案子/data/c620/model/c620.pkl')
# + id="SHUTpMqTuBM8"
| C620.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
# ---
envname = 'variables/loop_stim10e-16.0et6.0phvaryp1.0t0.1plNonebp0.5.pkl'
# import stuff
from placerg.funcs import *
from placerg.objects import*
from placerg.funcsrg import *
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib
# set up notebook displayt
np.set_printoptions(threshold=5)
alpha=0.4
color='black'
cmap='Greys'
colorline='black'
linethick=3.
colorfit='grey'
plt.style.use('seaborn-paper')
fontsize=20
ticksize=20
fontsizesmall=25
ticksizesmall=20
legendsize=20
alpha=.3
colorfit='gray'
linecolor='black'
palit=['black','firebrick', 'crimson', 'orangered', 'darkorange', 'goldenrod', 'gold', 'khaki']
mycmap = cm.gnuplot
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
# load in objects
allo=load_object(envname)
orderplot(allo)
if allo.labeltype[0]=='cell type':
maxx=np.max(np.array(allo.phi).flatten())
minn=np.min(np.array(allo.phi).flatten())
cc=allo.phi
if allo.labeltype[0]=='phi':
maxx=np.max(np.array(allo.phi).flatten())
minn=np.min(np.array(allo.phi).flatten())
cc=allo.phi
if allo.labeltype[0]=='eta':
maxx=np.max(np.array(allo.eta).flatten())
minn=np.min(np.array(allo.eta).flatten())
cc=allo.eta
if allo.labeltype[0]=='epsilon':
maxx=np.max(np.array(allo.epsilon).flatten())
minn=np.min(np.array(allo.epsilon).flatten())
cc=allo.epsilon
if allo.labeltype[0]=='time constant':
maxx=np.max(np.array(allo.timeconst).flatten())
minn=np.min(np.array(allo.timeconst).flatten())
cc=np.array(allo.timeconst)[:,0]
if allo.labeltype[0]=='# of stimuli':
maxx=np.max(np.array(allo.stim).flatten())
minn=np.min(np.array(allo.stim).flatten())
cc=allo.stim
if allo.labeltype[0]=='p':
maxx=np.max(np.array(allo.percell).flatten())
minn=np.min(np.array(allo.percell).flatten())
cc=allo.percell
mrange=maxx-minn
allo.label
# # variance of activity at each RG step over clusters
"""
Here plot the eigenvalues from each sucessive RG step, averaged over all clusters and
normalized by cluster size.
"""
fig, ax = plt.subplots(2,2, sharex=True, sharey=True, figsize=(10,10))
ylabel= 'eigenvalue'
ax[0,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_xlabel('rank$/K$', fontsize=fontsize)
ax[1,1].set_xlabel('rank$/K$', fontsize=fontsize)
c=0
for h in np.array([0,2,4, 7]):
n=int(c/2)
l=c-2*n
errplot=allo.eigspecerr[h]
xplot,plot=(allo.eigspecx[h], allo.eigspec[h])
for m in range(len(xplot)):
ax[n,l].errorbar(xplot[m], plot[m], yerr=errplot[m], \
label= r'$K=$'+str(2**(m+4)),\
color=palit[m+2], marker='o', \
markersize=5, linestyle='None', linewidth=2)
ax[n,l].set_xlabel('rank$/K$', fontsize=fontsize)
popt=allo.mu[h]
ax[n,l].plot(xplot[m],linfunc(xplot[m], \
popt[0], popt[1]), '--', color=colorfit, linewidth=2)
ax[n,l].tick_params(labelsize=ticksize)
ax[n,l].text(.01, .0055, r'$\mu$='+ str(np.round(popt[1],3))+r'$\pm$'\
+str(np.round(allo.muerr[h]\
[0], 3)), fontsize=ticksize)
ax[n,l].text(.01, .0015, r'$\phi=$'+str(np.round(allo.label[h],2)), \
fontsize=ticksize)
ax[n,l].set_yscale('log')
ax[n,l].set_xscale('log')
#ax[c].set_ylim(top=1)
c+=1
for n in range(2):
for l in range(2):
ax[n,l].set_yticks([.1, .01,.001,.0001])
ax[n,l].tick_params(length=6, width=1, which='major')
ax[n,l].tick_params(length=3, width=1, which='minor')
#a.grid(True, linewidth=1)
ax[0,0].text(.0015,1.0,r'(A)', fontsize=ticksize, weight='bold')
ax[0,1].text(.0015,1.0,r'(B)', fontsize=ticksize, weight='bold')
ax[1,0].text(.0015,1.0,r'(C)', fontsize=ticksize, weight='bold')
ax[1,1].text(.0015,1.0,r'(D)', fontsize=ticksize, weight='bold')
lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes[:1]]
lines, labels = [sum(z, []) for z in zip(*lines_labels)]
fig.legend(lines, labels, fontsize=ticksize-5, loc=(.15,.57))
plt.tight_layout()
name=str(envname)+'eigs.pdf'
plt.savefig(name)
# +
"""
plot coarse grained variance vs. cluster size
"""
fig, ax = plt.subplots(2,2, sharex=True, sharey=True, figsize=(10,10))
ylabel= 'activity variance'
ax[0,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_xlabel(r'cluster size $K$', fontsize=fontsize)
ax[1,1].set_xlabel(r'cluster size $K$', fontsize=fontsize)
c=0
for h in np.array([0,2,4, 7]):
n=int(c/2)
l=c-2*n
ax[n,l].errorbar(allo.varx[h],allo.var[h], allo.varerr[h], \
color='black', marker='o', markersize=5, linewidth=2, linestyle='None')
popt = allo.alpha[h]
ax[n,l].plot(allo.varx[h],linfunc(allo.varx[h], \
popt[0], popt[1]), '--', color=colorfit, linewidth=2)
ax[n,l].set_xlabel(r'cluster size $K$', fontsize=fontsize)
ax[n,l].plot(allo.varx[h], linfunc(allo.varx[h], popt[0], 1.), \
color=colorfit, linewidth=2, alpha=alpha)
ax[n,l].text(2, 10, r'$\phi=$'+str(np.round(allo.label[h],2)), fontsize=ticksize)
ax[n,l].tick_params(labelsize=ticksize)
ax[n,l].text(2, 20, r'${\alpha}$='+ str(np.round(popt[1],3))+r'$\pm$'+\
str(np.round(allo.alphaerr[h][0], 3)), fontsize=fontsize)
ax[n,l].set_yscale('log')
ax[n,l].set_xscale('log')
ax[n,l].set_ylim(top=260)
c+=1
for n in range(2):
for l in range(2):
#ax[n,l].set_yticks([.1, .01,.001,.0001])
ax[n,l].tick_params(length=6, width=1, which='major')
ax[n,l].tick_params(length=3, width=1, which='minor')
#a.grid(True, linewidth=1)
ax[0,0].text(.35,160,r'(A)', fontsize=ticksize, weight='bold')
ax[0,1].text(.35,160,r'(B)', fontsize=ticksize, weight='bold')
ax[1,0].text(.35, 160,r'(C)', fontsize=ticksize, weight='bold')
ax[1,1].text(.35,160,r'(D)', fontsize=ticksize, weight='bold')
plt.tight_layout()
name=str(envname)+'var.pdf'
plt.savefig(name)
# -
"""
Plot log probability of complete cluster silence vs cluster size
"""
fig, ax = plt.subplots(2,2, sharex=True, sharey=True, figsize=(10,10))
ylabel= r'$F$'
ax[0,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_xlabel(r'cluster size $K$', fontsize=fontsize)
ax[1,1].set_xlabel(r'cluster size $K$', fontsize=fontsize)
c=0
for h in np.array([0,2,4,7]):
n=int(c/2)
l=c-2*n
x=allo.psilx[h]
y=allo.psil[h]
popt= allo.beta[h]
ax[n,l].errorbar(allo.psilx[h], allo.psil[h],allo.psilerr[h], \
color='black', marker='o', linestyle='None', markersize=5)
ax[n,l].plot(np.arange(np.min(allo.psilx[h]),np.max(allo.psilx[h]), .01),\
(probfunc(np.arange(np.min(allo.psilx[h]),np.max(allo.psilx[h]), .01), \
popt[0], popt[1])), '--', color=colorfit, linewidth=2)
ax[n,l].text(1, -1.0, r'$\phi=$'+str(np.round(allo.label[h],2)),\
fontsize=ticksize)
ax[n,l].text(1, -.75, r'$\tilde{\beta}=$'+str(np.round(popt[1], 3))+r'$\pm$'+\
str(np.round(allo.alphaerr[h][0], 3)),fontsize=ticksize)
ax[n,l].tick_params(labelsize=ticksize)
ax[n,l].set_xlabel(r'cluster size $K$', fontsize=fontsize)
ax[n,l].set_xscale('log')
ax[n,l].set_ylim(top=0.5, bottom=-4)
c+=1
for n in range(2):
for l in range(2):
#ax[n,l].set_yticks([.1, .01,.001,.0001])
ax[n,l].tick_params(length=6, width=1, which='major')
ax[n,l].tick_params(length=3, width=1, which='minor')
#a.grid(True, linewidth=1)
ax[0,0].text(.4,.25,r'(A)', fontsize=ticksize, weight='bold')
ax[0,1].text(.4,.25,r'(B)', fontsize=ticksize, weight='bold')
ax[1,0].text(.4, .25,r'(C)', fontsize=ticksize, weight='bold')
ax[1,1].text(.4,.25,r'(D)', fontsize=ticksize, weight='bold')
plt.tight_layout()
name=str(envname)+'freeenergy.pdf'
plt.savefig(name)
minnm=16
maxxm=128
mrangem=np.abs(minnm-maxxm)
x=allo.actmomx
plott=allo.actmom
plterr=allo.actmomerr
fig, ax = plt.subplots(2,2, sharex=True, sharey=True, figsize=(10,10))
ylabel= r'density'
ax[0,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_xlabel('normalized activity', fontsize=fontsize)
ax[1,1].set_xlabel('normalized activity', fontsize=fontsize)
c=0
for h in np.array([0,2,4,7]):
n=int(c/2)
l=c-2*n
for i in (np.arange(len(allo.actmomx[0]))):
if i==3:
ax[n,l].errorbar(x[h][i],plott[h][i], plterr[h][i], \
label='N/'+str(2**(i+4)), \
color=palit[i+2], linewidth=2, errorevery=3, alpha=.7)
popt, pcov = curve_fit(gaussian,x[h][i], plott[h][i])
ax[n,l].plot(np.arange(-4, 4,.1), \
gaussian(np.arange(-4, 4, .1),\
popt[0], popt[1]), '--', color=colorfit, linewidth=2)
else:
ax[n,l].plot(x[h][i],plott[h][i], \
label='N/'+str(2**(i+4)), \
color=palit[i+2], linewidth=2)
ax[n,l].text(-8, 4, r'$\phi=$'+str(np.round(allo.label[h],2)), \
fontsize=ticksize)
ax[n,l].tick_params(labelsize=ticksize)
ax[n,l].set_xlabel('normalized activity', fontsize=fontsize)
ax[n,l].set_yscale('log')
ax[n,l].set_ylim(bottom=10**-6, top=9)
c+=1
for n in range(2):
for l in range(2):
#ax[n,l].set_yticks([.1, .01,.001,.0001])
ax[n,l].tick_params(length=6, width=1, which='major')
ax[n,l].tick_params(length=3, width=1, which='minor')
#a.grid(True, linewidth=1)
ax[0,0].legend(fontsize=fontsize)
ax[0,0].text(-14,5,r'(A)', fontsize=ticksize, weight='bold')
ax[0,1].text(-14,5,r'(B)', fontsize=ticksize, weight='bold')
ax[1,0].text(-14,5,r'(C)', fontsize=ticksize, weight='bold')
ax[1,1].text(-14,5,r'(D)', fontsize=ticksize, weight='bold')
plt.tight_layout()
plt.tight_layout()
name=str(envname)+'momdist.pdf'
plt.savefig(name)
minnm=2
maxxm=256
mrangem=np.abs(minnm-maxxm)
x=allo.autocorrx
plterr=allo.autocorrerr
result=allo.autocorr
fig, ax = plt.subplots(2,2, sharex=True, sharey=True, figsize=(10,10))
ylabel= r'$C(t)$'
ax[0,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_xlabel(r'time $t$', fontsize=fontsize)
ax[1,1].set_xlabel(r'time $t$', fontsize=fontsize)
c=0
for h in np.array([0,2,4,7]):
n=int(c/2)
l=c-2*n
for i in range(result[h].shape[0]):
#print(result[l][i, int(result[l].shape[1]/2)-50:int(result[l].shape[1]/2)+50])
ax[n,l].errorbar((x[h][int(result[h].shape[1]/2)-\
20:int(result[h].shape[1]/2)+20]), \
(result[h][i, int(result[h].shape[1]/2)-20:int(result[h].\
shape[1]/2)+20]),\
(plterr[h][i][int(result[h].shape[1]/2)-20:int(result[h]\
.shape[1]/2)+20]), \
label=r'$K$ ='+str(2**(i+2)),color=palit[i],\
linewidth=2)
ax[n,l].set_xlabel(r'time $t$', fontsize=fontsize)
ax[n,l].text(-10, 1.0, r'$\phi=$'+str(np.round(allo.label[h],2)), \
fontsize=fontsize)
ax[n,l].tick_params(labelsize=ticksize)
ax[n,l].set_ylim(top=1.15)
ax[n,l].set_xlim(-15,15)
c+=1
for n in range(2):
for l in range(2):
#ax[n,l].set_yticks([.1, .01,.001,.0001])
ax[n,l].tick_params(length=6, width=1, which='major')
ax[n,l].tick_params(length=3, width=1, which='minor')
#a.grid(True, linewidth=1)
ax[0,0].legend(fontsize=fontsize-5)
ax[0,0].text(-19,1.1,r'(A)', fontsize=ticksize, weight='bold')
ax[0,1].text(-19,1.1,r'(B)', fontsize=ticksize, weight='bold')
ax[1,0].text(-19,1.1,r'(C)', fontsize=ticksize, weight='bold')
ax[1,1].text(-19,1.1,r'(D)', fontsize=ticksize, weight='bold')
plt.tight_layout()
name=str(envname)+'dynamic.pdf'
plt.savefig(name)
"""
plot exponents
"""
fig, ax = plt.subplots(2,2, sharex=True, sharey=True, figsize=(10,10))
ylabel= r'$\tau_c$'
ax[0,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_xlabel(r'cluster size $K$', fontsize=fontsize)
ax[1,1].set_xlabel(r'cluster size $K$', fontsize=fontsize)
c=0
for h in np.array([0,2,4,7]):
n=int(c/2)
l=c-2*n
ax[n,l].errorbar(2**np.arange(1,8),allo.tau[h],allo.tauerr[h], color=colorline, \
label='taus', marker='o', markersize=5, linestyle='None')
popt= allo.z[h]
ax[n,l].plot(2**np.arange(1,8), linfunc(2**np.arange(1,8), \
popt[0], popt[1]), '--', label='fit', \
color=colorfit, linewidth=2)
ax[n,l].set_xlabel(r'cluster size $K$', fontsize=fontsize)
ax[n,l].text(2, 3, r'$\tilde{z}=$'+str(np.format_float_positional(popt[1],unique=False, precision=3))+r'$\pm$'+\
str(np.format_float_positional(allo.zerr[h][0], unique=False, precision=3)), fontsize=ticksize)
ax[n,l].set_yscale('log')
ax[n,l].set_xscale('log')
ax[n,l].text(2, 2.5, r'$\phi=$'+str(np.round(allo.label[h],2)), \
fontsize=fontsize)
ax[n,l].set_ylim(top=3.8)
c+=1
for n in range(2):
for l in range(2):
ax[n,l].set_yticks([1,2,3])
ax[n,l].tick_params(length=6, width=1, which='major', labelsize=ticksize)
ax[n,l].tick_params(length=3, width=1, which='minor')
#a.grid(True, linewidth=1)
ax[0,0].text(1,3.5,r'(A)', fontsize=ticksize, weight='bold')
ax[0,1].text(1,3.5,r'(B)', fontsize=ticksize, weight='bold')
ax[1,0].text(1,3.5,r'(C)', fontsize=ticksize, weight='bold')
ax[1,1].text(1,3.5,r'(D)', fontsize=ticksize, weight='bold')
plt.tight_layout()
name=str(envname)+'dynamicexps.pdf'
plt.savefig(name)
minnm=2
maxxm=256
mrangem=np.abs(minnm-maxxm)
x=allo.autocorrx
plterr=allo.autocorrerr
result=allo.autocorr
ylabel= r'$C(t)$'
fig, ax = plt.subplots(2,2, sharex=True, sharey=True, figsize=(10,10))
ax[0,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_ylabel(ylabel, fontsize=fontsize)
ax[1,0].set_xlabel(r'time $t/\tau_c$', fontsize=fontsize)
ax[1,1].set_xlabel(r'time $t/\tau_c$', fontsize=fontsize)
c=0
for h in np.array([0,2,4,7]):
n=int(c/2)
l=c-2*n
for i in range(result[h].shape[0]):
#print(result[l][i, int(result[l].shape[1]/2)-50:int(result[l].shape[1]/2)+50])
ax[n,l].errorbar((x[h][int(result[h].shape[1]/2)-\
20:int(result[h].shape[1]/2)+20])/allo.tau[h][i], \
(result[h][i, int(result[h].shape[1]/2)-20:int(result[h].\
shape[1]/2)+20]),\
(plterr[h][i][int(result[h].shape[1]/2)-20:int(result[h]\
.shape[1]/2)+20]), \
label=r'$K$ ='+str(2**(i+2)), color=palit[i],\
linewidth=2)
ax[n,l].set_xlabel(r'time $t/\tau_c$', fontsize=fontsize)
ax[n,l].text(-10, 1.0, r'$\phi=$'+str(np.round(allo.label[h],2)), \
fontsize=fontsize)
ax[n,l].tick_params(labelsize=ticksize)
ax[n,l].set_ylim(top=1.15)
ax[n,l].set_xlim(-15,15)
c+=1
for n in range(2):
for l in range(2):
ax[n,l].tick_params(length=6, width=1, which='major', labelsize=ticksize)
ax[n,l].tick_params(length=3, width=1, which='minor')
#a.grid(True, linewidth=1)
ax[0,0].legend(fontsize=fontsize-5)
ax[0,0].text(-19,1.1,r'(A)', fontsize=ticksize, weight='bold')
ax[0,1].text(-19,1.1,r'(B)', fontsize=ticksize, weight='bold')
ax[1,0].text(-19,1.1,r'(C)', fontsize=ticksize, weight='bold')
ax[1,1].text(-19,1.1,r'(D)', fontsize=ticksize, weight='bold')
plt.tight_layout()
name=str(envname)+'dynamicrescale.pdf'
plt.savefig(name)
inds=[2,3,4,5,6,7]
plotexps(allo,'phi', inds, fontsize, ticksize, 1.89, 1.3, 0.93, 0.74, 0.49, 0.13, -0.55, -0.91, 0.6, 1.87,\
0.6, 0.92,\
0.6,0.47, 0.6,-0.57)
name=str(envname)+'varvsphi.pdf'
plt.savefig(name)
| jupyter_notebooks/plotallnotebook_phi-Copy1.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
import pandas as pd
from sqlalchemy import Column, Integer, String, Float
Base = automap_base()
engine = create_engine('postgresql://postgres:postgres@localhost:5432/trade_data')
#Base.metadata.create_all(engine)
session = Session(bind=engine)
Base.prepare(engine, reflect=True)
Base.classes.keys()
total_exports = Base.classes.total_exports
session = Session(engine)
first_row = session.query(total_exports).first()
first_row.__dict__
for row in session.query(trade_balance.indicator_type, trade_balance.country, trade_balance.y_2017, trade_balance.y_2018):
print(row)
trade_balance_query = session.query(trade_balance.indicator_type, trade_balance.country, trade_balance.y_2017, trade_balance.y_2018)
trade_balance_query
all_results = []
for trade_balance.indicator_type, trade_balance.country, trade_balance.y_2017, trade_balance.y_2018 in trade_balance_query:
results_dict = {}
results_dict["indicator"] = trade_balance.indicator_type
results_dict["country"] = trade_balance.country
results_dict["2017"] = trade_balance.y_2017
results_dict["2018"] = trade_balance.y_2018
all_results.append(results_dict)
print(all_results)
total_gdp_test = Base.classes.total_gdp_test
session = Session(engine)
first_row = session.query(total_gdp_test).first()
first_row.__dict__
for row in session.query(total_gdp_test._indicator_type, total_gdp_test._year, total_gdp_test._canada, total_gdp_test._china, total_gdp_test._france, total_gdp_test._germany, total_gdp_test._italy, total_gdp_test._japan, total_gdp_test._united_kingdom, total_gdp_test._united_states):
print(row)
total_gdp_test_query = session.query(total_gdp_test._indicator_type, total_gdp_test._year, total_gdp_test._canada, total_gdp_test._china, total_gdp_test._france, total_gdp_test._germany, total_gdp_test._italy, total_gdp_test._japan, total_gdp_test._united_kingdom, total_gdp_test._united_states)
total_gdp_test_query
all_results = []
for total_gdp_test._indicator_type, total_gdp_test._year, total_gdp_test._canada, total_gdp_test._china, total_gdp_test._france, total_gdp_test._germany, total_gdp_test._italy, total_gdp_test._japan, total_gdp_test._united_kingdom, total_gdp_test._united_states in total_gdp_test_query:
results_dict = {}
results_dict["indicator"] = total_gdp_test._indicator_type
results_dict["year"] = total_gdp_test._year
results_dict["canada"] = total_gdp_test._canada
results_dict["china"] = total_gdp_test._china
results_dict["france"] = total_gdp_test._france
results_dict["germany"] = total_gdp_test._germany
results_dict["italy"] = total_gdp_test._italy
results_dict["japan"] = total_gdp_test._japan
results_dict["united_kingdom"] = total_gdp_test._united_kingdom
results_dict["united_states"] = total_gdp_test._united_states
all_results.append(results_dict)
print(all_results)
engine = create_engine('postgresql://postgres:postgres@localhost:5432/trade_data')
#Base.metadata.create_all(engine)
session = Session(bind=engine)
Base.prepare(engine, reflect=True)
Base.classes.keys()
total_imports_test = Base.classes.total_imports_test
session = Session(engine)
first_row = session.query(total_imports_test).first()
first_row.__dict__
for row in session.query(total_imports_test.indicator_type, total_imports_test.year, total_imports_test.canada, total_imports_test.china, total_imports_test.france, total_imports_test.germany, total_imports_test.italy, total_imports_test.japan, total_imports_test.united_kingdom, total_imports_test.united_states):
print(row)
total_imports_test_query = session.query(total_imports_test.indicator_type, total_imports_test.year, total_imports_test.canada, total_imports_test.china, total_imports_test.france, total_imports_test.germany, total_imports_test.italy, total_imports_test.japan, total_imports_test.united_kingdom, total_imports_test.united_states)
total_imports_test_query
all_results = []
for total_imports_test.indicator_type, total_imports_test.year, total_imports_test.canada, total_imports_test.china, total_imports_test.france, total_imports_test.germany, total_imports_test.italy, total_imports_test.japan, total_imports_test.united_kingdom, total_imports_test.united_states in total_imports_test_query:
results_dict = {}
results_dict["indicator"] = total_imports_test.indicator_type
results_dict["year"] = total_imports_test.year
results_dict["canada"] = total_imports_test.canada
results_dict["china"] = total_imports_test.china
results_dict["france"] = total_imports_test.france
results_dict["germany"] = total_imports_test.germany
results_dict["italy"] = total_imports_test.italy
results_dict["japan"] = total_imports_test.japan
results_dict["united_kingdom"] = total_imports_test.united_kingdom
results_dict["united_states"] = total_imports_test.united_states
all_results.append(results_dict)
print(all_results)
engine = create_engine('postgresql://postgres:postgres@localhost:5432/trade_data')
#Base.metadata.create_all(engine)
session = Session(bind=engine)
Base.prepare(engine, reflect=True)
Base.classes.keys()
total_exports_test = Base.classes.country_exports
session = Session(engine)
first_row = session.query(total_exports_test).first()
first_row.__dict__
for row in session.query(total_exports_test.indicator_type, total_exports_test.year, total_exports_test.canada, total_exports_test.china, total_exports_test.france, total_exports_test.germany, total_exports_test.italy, total_exports_test.japan, total_exports_test.united_kingdom, total_exports_test.united_states):
print(row)
total_exports_test_query = session.query(total_exports_test.indicator_type, total_exports_test.year, total_exports_test.canada, total_exports_test.china, total_exports_test.france, total_exports_test.germany, total_exports_test.italy, total_exports_test.japan, total_exports_test.united_kingdom, total_exports_test.united_states)
total_exports_test_query
all_results = []
for total_exports_test.indicator_type, total_exports_test.year, total_exports_test.canada, total_exports_test.china, total_exports_test.france, total_exports_test.germany, total_exports_test.italy, total_exports_test.japan, total_exports_test.united_kingdom, total_exports_test.united_states in total_exports_test_query:
results_dict = {}
results_dict["indicator"] = total_exports_test.indicator_type
results_dict["year"] = total_exports_test.year
results_dict["canada"] = total_exports_test.canada
results_dict["china"] = total_exports_test.china
results_dict["france"] = total_exports_test.france
results_dict["germany"] = total_exports_test.germany
results_dict["italy"] = total_exports_test.italy
results_dict["japan"] = total_exports_test.japan
results_dict["united_kingdom"] = total_exports_test.united_kingdom
results_dict["united_states"] = total_exports_test.united_states
all_results.append(results_dict)
print(all_results)
engine = create_engine('postgresql://postgres:postgres@localhost:5432/trade_data')
#Base.metadata.create_all(engine)
session = Session(bind=engine)
Base.prepare(engine, reflect=True)
Base.classes.keys()
country_growth = Base.classes.total_country_growth
session = Session(engine)
first_row = session.query(country_growth).first()
first_row.__dict__
for row in session.query(country_growth.indicator_type, country_growth.year, country_growth.canada, country_growth.china, country_growth.france, country_growth.germany, country_growth.italy, country_growth.japan, country_growth.united_kingdom, country_growth.united_states):
print(row)
country_growth_query = session.query(country_growth.indicator_type, country_growth.year, country_growth.canada, country_growth.china, country_growth.france, country_growth.germany, country_growth.italy, country_growth.japan, country_growth.united_kingdom, country_growth.united_states)
country_growth_query
growth_results = []
for country_growth.indicator_type, country_growth.year, country_growth.canada, country_growth.china, country_growth.france, country_growth.germany, country_growth.italy, country_growth.japan, country_growth.united_kingdom, country_growth.united_states in country_growth_query:
results_dict = {}
results_dict["indicator"] = country_growth.indicator_type
results_dict["year"] = country_growth.year
results_dict["canada"] = country_growth.canada
results_dict["china"] = country_growth.china
results_dict["france"] = country_growth.france
results_dict["germany"] = country_growth.germany
results_dict["italy"] = country_growth.italy
results_dict["japan"] = country_growth.japan
results_dict["united_kingdom"] = country_growth.united_kingdom
results_dict["united_states"] = country_growth.united_states
growth_results.append(results_dict)
print(growth_results)
engine = create_engine('postgresql://postgres:postgres@localhost:5432/trade_data')
#Base.metadata.create_all(engine)
session = Session(bind=engine)
Base.prepare(engine, reflect=True)
Base.classes.keys()
trade_balance_total = Base.classes.trade_balance_total
session = Session(engine)
first_row_total = session.query(trade_balance).first()
first_row.__dict__
for row in session.query(trade_balance_total.indicator_type, trade_balance_total.year, trade_balance_total.canada, trade_balance_total.china, trade_balance_total.france, trade_balance_total.germany, trade_balance_total.italy, trade_balance_total.japan, trade_balance_total.united_kingdom, trade_balance_total.united_states):
print(row)
trade_balance_query = session.query(trade_balance_total.indicator_type, trade_balance_total.year, trade_balance_total.canada, trade_balance_total.china, trade_balance_total.france, trade_balance_total.germany, trade_balance_total.italy, trade_balance_total.japan, trade_balance_total.united_kingdom, trade_balance_total.united_states)
trade_balance_query
trade_balance_results = []
for trade_balance_total.indicator_type, trade_balance_total.year, trade_balance_total.canada, trade_balance_total.china, trade_balance_total.france, trade_balance_total.germany, trade_balance_total.italy, trade_balance_total.japan, trade_balance_total.united_kingdom, trade_balance_total.united_states in trade_balance_query:
results_dict = {}
results_dict["indicator"] = trade_balance_total.indicator_type
results_dict["year"] = trade_balance_total.year
results_dict["canada"] = trade_balance_total.canada
results_dict["china"] = trade_balance_total.china
results_dict["france"] = trade_balance_total.france
results_dict["germany"] = trade_balance_total.germany
results_dict["italy"] = trade_balance_total.italy
results_dict["japan"] = trade_balance_total.japan
results_dict["united_kingdom"] = trade_balance_total.united_kingdom
results_dict["united_states"] = trade_balance_total.united_states
trade_balance_results.append(results_dict)
print(trade_balance_results)
| resources/line/flask-sqlalchemy.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
# ---
# + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _kg_hide-input=false _kg_hide-output=false _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5"
#Imports
# #!pip install scikit-learn==0.21.2
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_score, StratifiedKFold
pd.set_option('max_columns', None, "max_rows", None)
from numpy.random import seed
seed(1002)
tf.random.set_seed(1002)
# + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a"
#Declare Global variables
train_path = "../input/titanic/train.csv"
test_path = "../input/titanic/test.csv"
mapping = {'Col': 'Other',
'Major': 'Other',
'Ms': 'Miss',
'Mlle': 'Miss',
'Sir': 'Royal',
'Jonkheer': 'Royal',
'Countess': 'Royal',
'Lady': 'Royal',
'Capt': 'Other',
'Dona': 'Royal',
'Mme': 'Mrs',
'Don': 'Royal',
'Dr': 'Other',
'Rev' : 'Other'}
continuous = ['Age', 'Fare', 'Parch', 'SibSp', 'Family_Size', "Family_Survival"]
# -
def prepare_data(train_path,test_path):
train = pd.read_csv(train_path)
test = pd.read_csv(test_path)
df = pd.concat([train, test], axis = 0, sort = False)
df["Title"] = df["Name"].str.extract(r"([a-zA-Z]+)\.", expand = True)
df.replace({"Title": mapping}, inplace = True)
title_ages = dict(df.groupby('Title')['Age'].median())
df["age_med"] = df["Title"].apply(lambda a : title_ages[a])
df["Age"].fillna(df["age_med"], inplace = True)
#df["Pclass_rel"] = df["Pclass"]
submit = df[pd.isnull(df["Survived"])][["PassengerId","Survived"]]
df["Fare"].fillna(df["Fare"][df["Pclass"] == 3].median(), inplace = True)
df['Family_Size'] = df['Parch'] + df['SibSp'] + 1
df.loc[:,'FsizeD'] = 'Alone'
df.loc[(df['Family_Size'] > 1),'FsizeD'] = 'Small'
df.loc[(df['Family_Size'] > 4),'FsizeD'] = 'Big'
# Family Survival (https://www.kaggle.com/konstantinmasich/titanic-0-82-0-83)
df['Last_Name'] = df['Name'].apply(lambda x: str.split(x, ",")[0])
DEFAULT_SURVIVAL_VALUE = 0.5
df['Family_Survival'] = DEFAULT_SURVIVAL_VALUE
for grp, grp_df in df[['Survived','Name', 'Last_Name', 'Fare', 'Ticket', 'PassengerId',
'SibSp', 'Parch', 'Age', 'Cabin']].groupby(['Last_Name', 'Fare']):
if (len(grp_df) != 1):
# A Family group is found.
for ind, row in grp_df.iterrows():
smax = grp_df.drop(ind)['Survived'].max()
smin = grp_df.drop(ind)['Survived'].min()
passID = row['PassengerId']
if (smax == 1.0):
df.loc[df['PassengerId'] == passID, 'Family_Survival'] = 1
elif (smin == 0.0):
df.loc[df['PassengerId'] == passID, 'Family_Survival'] = 0
for _, grp_df in df.groupby('Ticket'):
if (len(grp_df) != 1):
for ind, row in grp_df.iterrows():
if (row['Family_Survival'] == 0) | (row['Family_Survival']== 0.5):
smax = grp_df.drop(ind)['Survived'].max()
smin = grp_df.drop(ind)['Survived'].min()
passID = row['PassengerId']
if (smax == 1.0):
df.loc[df['PassengerId'] == passID, 'Family_Survival'] = 1
elif (smin == 0.0):
df.loc[df['PassengerId'] == passID, 'Family_Survival'] = 0
df['Embarked'].fillna(method='backfill', inplace=True)
df['Sex'] = df['Sex'].astype('category').cat.codes
df.drop(['Cabin', 'Name', 'Ticket', 'PassengerId', 'age_med', 'Last_Name'], axis=1, inplace=True)
df = pd.get_dummies(df, columns = ["Embarked", "Pclass", "Title", "FsizeD"])
scaler = StandardScaler()
for var in continuous:
df[var] = scaler.fit_transform(df[var].astype('float64').values.reshape(-1, 1))
x_train = df[pd.notnull(df["Survived"])].drop("Survived",axis = 1)
y_train = df[pd.notnull(df["Survived"])]["Survived"].astype(int)
x_test = df[pd.isnull(df["Survived"])].drop("Survived",axis = 1)
return x_train, y_train, x_test, submit
x_train, y_train, x_test, submit = prepare_data(train_path, test_path)
layers = [[8],[16],[8,4],[16,8],[24,16,8],[24,8]]
activation = ["relu","linear","tanh"]
optimizer = ["SGD","RMSprop","Adam"]
dropout = [0.0,0.2]
batch_size = [32,64,128]
epochs = [50,75]
param_grid = dict(batch_size = batch_size,
epochs = epochs,
lyr = layers,
act = activation,
opt = optimizer,
dr = dropout)
def create_model(lyr = [13,8], act = "relu", opt = "adam", dr = 0.2):
model = Sequential()
model.add(Dense(lyr[0], input_dim = 22, activation = act))
model.add(Dropout(dr))
for i in lyr[1:]:
model.add(Dense(i, activation = act))
model.add(Dense(1, activation = "sigmoid"))
model.compile(loss = "binary_crossentropy", optimizer = opt, metrics = ["accuracy"])
return model
def search():
model = KerasClassifier(build_fn = create_model, verbose = 1)
grid = GridSearchCV(estimator = model, param_grid = param_grid, n_jobs = -1, cv = 2, verbose=2)
grid_result = grid.fit(x_train, y_train)
return grid_result
# **Now that we have done all this,**
# <br>
# <br>all we have to now do is just:
# <br>call the search method and store the result.
# <br>use the result to see the best parameter
# <br>
# <br>**BUT**
# <br>
# <br>The current kernal in kaggle uses the scikit-learn version 0.23.0
# <br>This version of Scikit-learn has got a bug in the GridSearchCV
# <br>and the only way to fix this is to roll back on a more stable release where
# <br>GridSearchCV is working ( I choose v0.21.2)
# <br>
# <br>**BUT**
# <br>
# <br>To roll to this version, i need to use conda inside of kaggle and that thing is also bugged out rn
# <br>
# <br>So it has become a rabbit hole of tryint to fix GridSearchCV -> Scikit-learn -> Conda installs
# <br>where I have already spent so many hours into
# <br>
# <br>**THEREFORE**
# <br>
# <br>I ran the GridSearchCV locally and stored its results in a dataframe
# <br>
# <br>Below are the output of codes that I ran locally:
# <br>
# > ```#codes to be run if GridSearchCV() is running properly
# > search_result = search()
# > view = pd.DataFrame(search_result.cv_results_)
# > view.to_csv('gridsearch_cv_results.csv', index=False)
# > search_result.best_params_```
# >
# ---
# > search_result = search()
# <br>
# ```Fitting 2 folds for each of 648 candidates, totalling 1296 fits
# [Parallel(n_jobs=-1)]: Using backend LokyBackend with 2 concurrent workers.
# [Parallel(n_jobs=-1)]: Done 37 tasks | elapsed: 41.0s
# [Parallel(n_jobs=-1)]: Done 158 tasks | elapsed: 3.0min
# [Parallel(n_jobs=-1)]: Done 361 tasks | elapsed: 5.8min
# [Parallel(n_jobs=-1)]: Done 644 tasks | elapsed: 10.5min
# [Parallel(n_jobs=-1)]: Done 1009 tasks | elapsed: 16.3min
# [Parallel(n_jobs=-1)]: Done 1296 out of 1296 | elapsed: 20.1min finished```
#
# > search_result
# <br>
# ```GridSearchCV(cv=2, error_score='raise-deprecating',
# estimator=<keras.wrappers.scikit_learn.KerasClassifier object at 0x7f79f41f2550>,
# iid='warn', n_jobs=-1,
# param_grid={'act': ['relu', 'linear', 'tanh'],
# 'batch_size': [32, 64, 128], 'dr': [0.0, 0.2],
# 'epochs': [50, 75],
# 'lyr': [[8], [16], [8, 4], [16, 8], [24, 16, 8],
# [24, 8]],
# 'opt': ['SGD', 'RMSprop', 'Adam']},
# pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
# scoring=None, verbose=2)```
#
# > search_result.best_params_
# <br>
# ```{'act': 'tanh',
# 'batch_size': 32,
# 'dr': 0.0,
# 'epochs': 75,
# 'lyr': [16, 8],
# 'opt': 'RMSprop'}```
#
# ---
#
# **Some different samples of batch size and their co-responding acc**
# <br>batch 32 : 85.07%
# <br>batch 16 : 85.41%
# <br>batch 1 : 85.63%
# <br>other
# <br>#Results: 84.06% (1.45%) <13,8,1>
# <br>#Results: 84.29% (1.87%) <13,8,1> with dr 0.2
# <br>#Results: 84.40% (1.72%) <13,8,1> with dr 0.2 epochs = 100 (choosen)
# <br>#Results: 84.17% (0.90%) <9,9,5> with dr 0.2 epochs = 100
#
# ---
estimator = KerasClassifier(build_fn = create_model, epochs = 100, batch_size = 10, verbose = 0)
kfold = StratifiedKFold(n_splits = 5, random_state = 42, shuffle = False)
results = cross_val_score(estimator, x_train, y_train, cv = kfold)
print("Results: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
estimator.fit(x_train, y_train, epochs = 100, batch_size = 10)
# The Ultimate oneliner
#
# ---
# ```submit["Survived"] = [int(np.round(best_nn.predict(x_test.loc[x].to_numpy().reshape(1,18)),0)) for x in range(0,submit["Survived"].size)]```
#
# ---
submit["Survived"] = estimator.predict(x_test)
submit["Survived"] = [int(np.round(x,0)) for x in submit["Survived"]]
submit.to_csv('predictions.csv', index=False)
submit.head()
| Titanic/titanic-survival-prediction.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # Conical Spirals - Arc Length
#
# In the previous notebook,<a href="./0 - conical spirals.ipynb">`0 - conical spirals.ipynb`</a>, we developed the model to trace the Archimedean spiral around the cone. In this notebook, we explore the derivation of the equations to calculate the arc length of the spiral (Archimedean spiral). In practical terms, if we use LED strips to create a sprial around the cone, we can determine the required LED strip length to get the job done.
# # Notebook Preamble
# + language="javascript"
# //Disable autoscroll in the output cells - needs to be in a separate cell with nothing else
# IPython.OutputArea.prototype._should_scroll = function(lines) {
# return false;
# }
# +
# decide whether charts will be displayed interactively or in a format that exports to pdf
# Interactive -----------------
# For interactive notebook uncomment:
# %matplotlib notebook
# PDF -----------------
# For pdf plotting uncomment:
# # %matplotlib inline
# import warnings
# warnings.filterwarnings('ignore')
# %config InlineBackend.figure_formats = ['png', 'pdf'] #['svg']
#------------
# Setup matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # handle 3D plots
import matplotlib as mpl
mpl.rc('font',family='monospace') # all font on the plot will be monospace
# +
import numpy as np
from plots import (
create_standard_figure,
axis_legend_remove_duplicates,
)
from common import (
plot_cone,
plot_spiral,
plot_center_pole,
spiral_arc_length_range,
plot_cone_and_sprial,
)
# -
# ## Arc Length of a Curve in Polar Coordinates
#
# Now that we can plot the spiral, how long is it? Essentially, we want to determine the length of the vector function:
#
# $$
# \begin{equation} \tag{1}
# \large \vec r \left(t \right) = \left \langle f(t), g(t), h(t) \right \rangle
# \end{equation}
# $$
# Writing the vector function in parametric form:
#
# $$
# \begin{matrix}
# \large x = f(t) \\
# \large y = g(t) \\
# \large z = h(t)
# \end{matrix}
# $$
# In 3 Dimensions, the length of the curve, $ \vec r \left(t \right)$ on the interval $m_1 \le t \le m_2$ is:
#
# $$
# \large
# \begin{equation} \tag{2}
# L = \int_{m_1}^{m_1} \sqrt{\left[f'(t)\right]^2 + \left[h'(t)\right]^2 + \left[g'(t) \right]^2} \; \frac{\mathrm{d} }{\mathrm{d} t}
# \end{equation}
# $$
# <div class="alert alert-block alert-info"> <b>NOTE:</b> In the notebook, <a href="./0 - conical spirals.ipynb">`0 - conical spirals.ipynb`</a>, we represented the angle as $\theta$. For this derivation, consider $t = \theta$. We will continue to use $t$ to represent the polar angle. </div>
# The parametric equations for the spiral are:
#
# $$
# \large
# \begin{equation} \tag{3}
# \begin{matrix}
# x(t) = bt \cos t \\
# y(t) = bt \sin t \\
# z(t) = kt + z_0
# \end{matrix}
# \end{equation}
# $$
#
# Where $b$ and $k$ are constants that control the shape and height of the spiral and $t$ is the angle in radians controlling the number of `loops`.
# <div class="alert alert-block alert-info"> <b>NOTE:</b> In the notebook, <a href="./0 - conical spirals.ipynb">`0 - conical spirals.ipynb`</a>, we represented the shape of the cone with $m$. For this document, consider $k = m$, from this point forward. </div>
# Take the derivative of each equation:
#
# $$
# \large
# \begin{equation} \tag{4}
# \begin{matrix}
# x'(t) = b \left( \cos(t) - t \sin(t) \right) \\
# y'(t) = b \left(\sin(t) + t \cos(t) \right) \\
# z'(t) = k
# \end{matrix}
# \end{equation}
# $$
# Let's rearrange things to make dealing with the polynomial and the radical easier:
#
# $$ \left[ f'(x) \right]^2 = \left[ b \cdot \left(\cos(t) - t \sin(t) \right) \right]^2$$
#
# $$\left[ f'(x) \right]^2 = b^2 \cos^2 t - b^2 t \sin(2 t) + b^2 t^2 \sin^2 t$$
# Where:
#
# $$\sin(2 t) = 2 \sin(t) \cos(t)$$
#
# $$\sin(t) \cos(t) = \frac{1}{2} \cdot \sin(2 t)$$
#
# $$\sin^2 t + \cos^2 t = 1$$
# $$ [h'(t)]^2 = \left( b \cdot \left(\sin(t) + t \cdot \cos(t) \right) \right)^2$$
#
# $$ [h'(t)]^2 = b^2 \sin^2 t + b^2 t \sin (2 t) + b^2 t^2 \cos^2 t$$
#
# $$ [g'(t)]^2 = k^2$$
#
# $$ [f'(t)]^2 + h'(t)^2 + g'(t)^2 = b^2 + b^2 t^2 + k^2$$
# $$
# \large
# \begin{equation} \tag{5}
# L = \int_{m_1}^{m_1} \sqrt{\left[f'(t)\right]^2 + \left[h'(t)\right]^2 + \left[g'(t) \right]^2} \; \frac{\mathrm{d} }{\mathrm{d} t}
# \end{equation}
# $$
# <div class="alert alert-block alert-info"> <b>NOTE:</b> Solving the integral we made use of :http://www.integral-calculator.com/ </div>
# Solve the integral. Substitute:
#
# $$t=\frac{\sqrt{k^2+b^2}\tan\left(u\right)}{b} \rightarrow u=\arctan\left(\frac{bt}{\sqrt{k^2+b^2}}\right)$$
#
# $$ \frac{\mathrm{d}t}{\mathrm{d}u}=\frac{\sqrt{k^2+b^2}\sec^2\left(u\right)}{b} $$
#
# $$ ={\int}\frac{\sqrt{k^2+b^2}\sec^2\left(u\right)\sqrt{\left(k^2+b^2\right)\tan^2\left(u\right)+k^2+b^2}}{b}\,\mathrm{d}u$$
# Simplify using:
#
# $$\left(k^2+b^2\right)\tan^2\left(u\right)+k^2+b^2=\left(k^2+b^2\right)\sec^2\left(u\right)$$
# Becomes:
#
# $$=\class{steps-node}{\cssId{steps-node-1}{\frac{k^2+b^2}{b}}}{\int}\sec^3\left(u\right)\,\mathrm{d}u$$
# Now Solving:
#
# $${\int}\sec^3\left(u\right)\,\mathrm{d}u$$
# Apply reduction formula with $n=3$:
#
# $$\small{{\int}\sec^{\mathtt{n}}\left(u\right)\,\mathrm{d}u=\class{steps-node}{\cssId{steps-node-2}{\frac{\mathtt{n}-2}{\mathtt{n}-1}}}{\int}\sec^{\mathtt{n}-2}\left(u\right)\,\mathrm{d}u+\frac{\sec^{\mathtt{n}-2}\left(u\right)\tan\left(u\right)}{\mathtt{n}-1}}$$
#
# $$=\class{steps-node}{\cssId{steps-node-3}{\frac{1}{2}}}{\int}\sec\left(u\right)\,\mathrm{d}u+\frac{\sec\left(u\right)\tan\left(u\right)}{2}$$
# Now Solving:
#
# $${\int}\sec\left(u\right)\,\mathrm{d}u =\ln\left(\tan\left(u\right)+\sec\left(u\right)\right)$$
#
# The solution is a standard integral...
# Plugin solved integrals:
#
# $$\class{steps-node}{\cssId{steps-node-4}{\frac{1}{2}}}{\int}\sec\left(u\right)\,\mathrm{d}u+\frac{\sec\left(u\right)\tan\left(u\right)}{2} =\frac{\ln\left(\tan\left(u\right)+\sec\left(u\right)\right)}{2}+\frac{\sec\left(u\right)\tan\left(u\right)}{2}$$
#
# $$\class{steps-node}{\cssId{steps-node-5}{\frac{k^2+b^2}{b}}}{\int}\sec^3\left(u\right)\,\mathrm{d}u =\frac{\left(k^2+b^2\right)\ln\left(\tan\left(u\right)+\sec\left(u\right)\right)}{2b}+\frac{\left(k^2+b^2\right)\sec\left(u\right)\tan\left(u\right)}{2b}$$
# Undo substitution:
#
# $$u=\arctan\left(\frac{bt}{\sqrt{k^2+b^2}}\right)$$
# Use:
#
# $$\tan\left(\class{steps-node}{\cssId{steps-node-6}{\arctan\left(\frac{bt}{\sqrt{k^2+b^2}}\right)}}\right)=\frac{bt}{\sqrt{k^2+b^2}}$$
#
# $$\sec\left(\class{steps-node}{\cssId{steps-node-7}{\arctan\left(\frac{bt}{\sqrt{k^2+b^2}}\right)}}\right)=\sqrt{\frac{b^2t^2}{k^2+b^2}+1}$$
#
# $$=\frac{\left(k^2+b^2\right)\ln\left(\sqrt{\frac{b^2t^2}{k^2+b^2}+1}+\frac{bt}{\sqrt{k^2+b^2}}\right)}{2b}+\frac{\sqrt{k^2+b^2}t\sqrt{\frac{b^2t^2}{k^2+b^2}+1}}{2}$$
# Solution:
# $$
# \large
# \begin{equation} \tag{6}
# \begin{split}
# \int \sqrt{b^2t^2+k^2+b^2}\,\mathrm{d}t & = \\
# & = \frac{\left(k^2+b^2\right)\ln\left(\left|\sqrt{\frac{b^2t^2}{k^2+b^2}+1}+\frac{bt}{\sqrt{k^2+b^2}}\right|\right)}{2b}+\frac{\sqrt{k^2+b^2}t\sqrt{\frac{b^2t^2}{k^2+b^2}+1}}{2}+C & \\
# & =\frac{\left(k^2+b^2\right)\ln\left(\left|\sqrt{b^2\left(t^2+1\right)+k^2}+bt\right|\right)+bt\sqrt{b^2\left(t^2+1\right)+k^2}}{2b}+C
# \end{split}
# \end{equation}
# $$
# <div class="alert alert-block alert-info"> <b>NOTE:</b> Applying the limits will eliminate the constant...</div>
# +
# Cone
r = 0.5 # m
h = 2.5 # m
d = 0.25 # spacing between loops
al = spiral_arc_length_range(r, h, d)
print('Sprial Length = {:.3f}'.format(al))
# +
fig, ax = create_standard_figure(
'Archimedean Spiral',
'x',
'y',
'z',
projection='3d',
figsize=(8, 8),
axes_rect=(0.1, 0.1, 0.85, 0.85), # rect [left, bottom, width, height]
)
# NOTE: Units are in what every system you want as long as all length units are the same (ft, m, inches, mm)
# Cone
r = 2 # m
h = 5 # m
d = 0.25 # spacing between loops
plot_cone_and_sprial(ax, r, h, d)
fig.show()
# -
| notebooks/1 - spiral arc length.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/mabelc/forcasting/blob/master/notebooks/Time_Series_EDA.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="7wq1weU5n3WS"
# # Exploratory analysis
#
# This is the very first step when analyzing time series data. We will use a time series data (http://otexts.com/fpp2/extrafiles/tute1.csv) as an example. Sales contains the quarterly sales for a small company over the period 1981-2005. AdBudget is the advertising budget and GDP is the gross domestic product.
#
# + id="9ssBVRO6w4Mk" colab={"base_uri": "https://localhost:8080/", "height": 71} outputId="1964f4c6-ca99-4b44-8b93-5899dba929dc"
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
from statsmodels.graphics.tsaplots import plot_acf
# + id="_reTqFLgndYO" colab={"base_uri": "https://localhost:8080/", "height": 419} outputId="41b2132b-cfc4-4ff9-a50e-9ea15156e9eb"
tute_df = pd.read_csv('http://otexts.com/fpp2/extrafiles/tute1.csv')
tute_df
# + [markdown] id="Stfcd-9-JnJO"
# To use the dates efectively, we need to covert this column to datetime type and assign it as the index.
# + id="POAgFS20qG6c" colab={"base_uri": "https://localhost:8080/", "height": 450} outputId="c4161df2-e096-487e-b476-ece4965ee20f"
tute_df['datetime'] = pd.to_datetime(tute_df.iloc[:,0], format='%b-%y')
tute_df.set_index('datetime', inplace=True)
tute_df.drop('Unnamed: 0', axis=1, inplace=True)
tute_df
# + [markdown] id="R7PnMMt6KqUw"
# ## Plot the time series
#
# The first thing to do in any data analysis task is to plot the data.
# + id="zCopLHEyKucG" colab={"base_uri": "https://localhost:8080/", "height": 404} outputId="8e371d23-771e-44fe-97d1-3b3238ae965a"
tute_df.plot(figsize=(15,6), title='Sales')
plt.show()
# + [markdown] id="9DWLGLpCP6A0"
# There is no apparent trend in the data over this period. The monthly sales and AdBudget show strong seasonality within each year.
#
# ## Seasonal plot
#
# A seasonal plot allows the underlying seasonal pattern to be seen more clearly, and is especially useful in identifying years in which the pattern changes.
# + id="7b5t623tM1VG" colab={"base_uri": "https://localhost:8080/", "height": 693} outputId="a2092e4d-e735-4c7c-9d16-e4b10ee96227"
# Prepare data
tute_df['year'] = tute_df.index.year
tute_df['month'] = tute_df.index.month
years = tute_df['year'].unique()
# Prep Colors
np.random.seed(100)
mycolors = np.random.choice(list(mpl.colors.XKCD_COLORS.keys()), len(years), replace=False)
# Draw Plot
plt.figure(figsize=(12,10), dpi= 80)
for i, y in enumerate(years):
if i > 0:
plt.plot('month', 'Sales', data=tute_df.loc[tute_df.year==y, :], color=mycolors[i], label=y)
plt.text(12, tute_df.loc[tute_df.year==y, 'Sales'][-1:].values[0], y, fontsize=12, color=mycolors[i])
# Decoration
plt.gca().set(ylabel='$Sales$', xlabel='$Month$')
plt.xticks([3,6,9,12], ['March','June','September', 'December'])
plt.yticks(fontsize=12, alpha=.7)
plt.title("Seasonal Plot of Quartely Sales", fontsize=20)
plt.show()
# + [markdown] id="fIvD2yjM_ItD"
# The sales increase at the end of the year and decreased between March and September.
#
#
# + [markdown] id="svHfSkNykUee"
# ## Scatterplots
#
# We can study the relationship between Sales and AdBudget by plotting one series against the other, using a scatterplot.
# + id="mdJGDAyI0D2t" colab={"base_uri": "https://localhost:8080/", "height": 513} outputId="624ae673-b694-4884-a6de-9b840a09bdda"
plt.figure(figsize=(8,8))
plt.scatter(tute_df.Sales, tute_df.AdBudget)
plt.title('Scatter plot')
plt.xlabel('Sales')
plt.ylabel('AdBudget')
plt.show()
# + [markdown] id="Pl13ar1l3beu"
# We can see a positive correlation between both variables. If we are interested in exploring the relation between all variables, we can use a scatterplot matrix.
# + id="7wrl7fmY9I0I" colab={"base_uri": "https://localhost:8080/", "height": 567} outputId="2b672cdb-f405-43c3-b756-4bbb9f38700f"
sns.set(style="ticks")
sns.pairplot(tute_df.loc[:, ['Sales','AdBudget','GDP']])
plt.show()
# + [markdown] id="fRqeAtjuBzrD"
# Here, we can see a negative correlation between Sales and AdBudget against GDP. The main diagonal shows the distribution of the variables.
#
# ## Autocorrelation
#
# Just as correlation measures the extent of a linear relationship between two variables, autocorrelation measures the linear relationship between lagged values of a time series. For example, we can measure the relationship between the sales at quarter _t_ and _t-1_, _t_ and _t-2_, and so on.
# + id="HfHkdtfk_61I" colab={"base_uri": "https://localhost:8080/", "height": 393} outputId="5ec098d3-4153-4877-c1b1-31b010411714"
with mpl.rc_context():
mpl.rc("figure", figsize=(10,6))
plot_acf(tute_df.Sales, zero=False)
plt.xticks(range(4,20,4))
plt.show()
# + [markdown] id="eZ3w38zgNiub"
# Attending to the seasonality we observed in the data, we can see a strong positive autocorrelation between the quarters (_t_ and _t-4_, t and _t-8_, etc). On the other hand, we observe a negative autocorrelation because troughs tend to be two quarters behind peaks.
| notebooks/Time_Series_EDA.ipynb |
# +
# Copyright 2010-2018 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This model implements a sudoku solver."""
from __future__ import print_function
from ortools.sat.python import cp_model
def solve_sudoku():
"""Solves the sudoku problem with the CP-SAT solver."""
# Create the model.
model = cp_model.CpModel()
cell_size = 3
line_size = cell_size**2
line = list(range(0, line_size))
cell = list(range(0, cell_size))
initial_grid = [[0, 6, 0, 0, 5, 0, 0, 2, 0], [0, 0, 0, 3, 0, 0, 0, 9, 0],
[7, 0, 0, 6, 0, 0, 0, 1, 0], [0, 0, 6, 0, 3, 0, 4, 0, 0], [
0, 0, 4, 0, 7, 0, 1, 0, 0
], [0, 0, 5, 0, 9, 0, 8, 0, 0], [0, 4, 0, 0, 0, 1, 0, 0, 6],
[0, 3, 0, 0, 0, 8, 0, 0, 0], [0, 2, 0, 0, 4, 0, 0, 5, 0]]
grid = {}
for i in line:
for j in line:
grid[(i, j)] = model.NewIntVar(1, line_size, 'grid %i %i' % (i, j))
# AllDifferent on rows.
for i in line:
model.AddAllDifferent([grid[(i, j)] for j in line])
# AllDifferent on columns.
for j in line:
model.AddAllDifferent([grid[(i, j)] for i in line])
# AllDifferent on cells.
for i in cell:
for j in cell:
one_cell = []
for di in cell:
for dj in cell:
one_cell.append(grid[(i * cell_size + di,
j * cell_size + dj)])
model.AddAllDifferent(one_cell)
# Initial values.
for i in line:
for j in line:
if initial_grid[i][j]:
model.Add(grid[(i, j)] == initial_grid[i][j])
# Solve and print out the solution.
solver = cp_model.CpSolver()
status = solver.Solve(model)
if status == cp_model.FEASIBLE:
for i in line:
print([int(solver.Value(grid[(i, j)])) for j in line])
solve_sudoku()
| examples/notebook/examples/sudoku_sat.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# <font size="+5">#03 | Transforming Basic Objects into the Powerful DataFrame</font>
# - <ins>Python</ins> + <ins>Data Science</ins> Tutorials in [YouTube ↗︎](https://www.youtube.com/c/PythonResolver)
# ## All that glitters is not gold
#
# > - Not all objects can call the same functions
# > - Even though they may store the same information
# ### `list`
# > - Create a list with your math `grades`
# > - Compute the mean
# > - You cannot do the mean
# > - But you could `sum()` and `len()`
# > - And divide the sum by the number of exams you did
# > - [ ] Isn't it an `object` that could calculate the `mean()`?
# ### `Series`
# > - Use the `.` + `[tab]` key to see the `functions/methods` of the object
# ## Store the information in Python `objects` for the Best Tennis Players
# > - income
# > - titles
# > - grand slams
# > - turned professional
# > - wins
# > - losses
# ### Create a `dictionary` for <NAME>
# + [markdown] tags=[]
# ### Create a `dictionary` for <NAME>
# -
# ### Create a `dictionary` for <NAME>
# ### How much wealth did all of them earned?
# > - You may put all of them into a `list`
# > - And `sum()` the `income`
# > - The `sum()` is not an action
# > - that a simple object `list` can perform
# > - [ ] Could we convert the list into a
# > - more powerful object
# > - that could compute the `sum()`?
# > - Access the `income` column
# > - and compute the `sum()`
# > - [ ] Which type of `object` is the table?
# > - [ ] What else can we do with this `object`?
# ## Can we select specific parts of the `DataFrame`?
# > - Remember that an `object` is a **structure of data**
# > - In other words, it may contain **more objects**
# ### Names of rows `index`
# ### Names of `columns`
# > Number of rows & columns `shape`
# ## Read data from a file
| 03_Transforming Basic Objects into the Powerful DataFrame/03session_transforming-to-powerful-dataframe.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + id="DomJn9DynNif" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="72db6833-6b72-480e-8dd1-44b56b66249d"
# installing required module
# !pip install fuzzy-c-means
# + id="CzfW0KyYJqdi" colab_type="code" colab={}
import cv2
import numpy as np
import math
import bisect
from google.colab.patches import cv2_imshow
from skimage import morphology
from sklearn.cluster import KMeans
from fcmeans import FCM
def imadjust(src, tol=1, vin=[0,255], vout=(0,255)):
# src : input one-layer image (numpy array)
# tol : tolerance, from 0 to 100.
# vin : src image bounds
# vout : dst image bounds
# return : output img
dst = src.copy()
tol = max(0, min(100, tol))
if tol > 0:
# Compute in and out limits
# Histogram
hist = np.zeros(256, dtype=np.int)
for r in range(src.shape[0]):
for c in range(src.shape[1]):
hist[src[r,c]] += 1
# Cumulative histogram
cum = hist.copy()
for i in range(1, len(hist)):
cum[i] = cum[i - 1] + hist[i]
# Compute bounds
total = src.shape[0] * src.shape[1]
low_bound = total * tol / 100
upp_bound = total * (100 - tol) / 100
vin[0] = bisect.bisect_left(cum, low_bound)
vin[1] = bisect.bisect_left(cum, upp_bound)
# Stretching
scale = (vout[1] - vout[0]) / (vin[1] - vin[0])
for r in range(dst.shape[0]):
for c in range(dst.shape[1]):
vs = max(src[r,c] - vin[0], 0)
vd = min(int(vs * scale + 0.5) + vout[0], vout[1])
dst[r,c] = vd
return dst
def matlab_fspecial(typex = "motion", len = 9, theta = 0):
# h = fspecial('motion',len,theta)
if typex == 'motion':
# Create the vertical kernel.
kernel_v = np.zeros((len, theta))
# Fill the middle row with ones.
kernel_v[:, int((kernel_size - 1)/2)] = np.ones(kernel_size)
# Normalize.
kernel_v /= kernel_size
# Apply the vertical kernel.
motion_blur = cv2.filter2D(img, -1, kernel_v)
return motion_blur
# equal to mat2gray on matlab
# https://stackoverflow.com/questions/39808545/implement-mat2gray-in-opencv-with-python
def matlab_mat2gray(A, alpha = False, beta = False):
if not alpha:
alpha = min(A.flatten())
else:
alpha = 0
if not beta:
beta = max(A.flatten())
else:
beta = 255
I = A
cv2.normalize(A, I, alpha , beta ,cv2.NORM_MINMAX)
I = np.uint8(I)
return I
def matlab_strel_disk(r1):
from skimage.morphology import disk
mask = disk(r1)
return mask
def matlab_strel_ball(r1,r2):
from skimage.morphology import (octagon)
mask = octagon(r1,r2)
return mask
# + id="BsXzROxcL1Fz" colab_type="code" colab={}
# function to resize image
def resize_img(file, size = 200):
nrows = (np.shape(file)[0]) # image height
ncols = (np.shape(file)[1])
ratio = nrows/ncols
t_width = size
t_height = math.ceil(t_width * ratio)
return cv2.resize(file, (t_width, t_height))
# get filename from path
def getfilename(path, ext = False):
import ntpath
import os
if ext:
return ntpath.basename(path)
else:
return os.path.splitext(ntpath.basename(path))[0]
# + id="fSBpWcIlZ5VG" colab_type="code" colab={}
# modified vogado's segmentaion
# segmentation: fcm
def wbc_vogado_modified(f, debug_mode = False):
image_lab = int(0)
image_rgb = f # send into figure (a)
# time measurement
import time
start_time = time.time()
# pre-processing step, convert rgb into CIELAB (L*a*b)
image_lab = cv2.cvtColor(image_rgb, cv2.COLOR_BGR2Lab);
L = image_lab[:,:,0]
A = image_lab[:,:,1]
B = image_lab[:,:,2] # the bcomponent
lab_y = B # send into figure (c)
AD = cv2.add(L,B)
# f (bgr)
r = f[:,:,2] # red channel (rgb)
r = imadjust(r)
g = f[:,:,1]
g = imadjust(g)
b = f[:,:,0]
b = imadjust(b)
c = np.subtract(255,r)
c = imadjust(c)
m = np.subtract(255,g)
cmyk_m = m # send into figure (b)
# add median filter into M component of CMYK
m = cv2.blur(m,(10,10)) # updated in 13/04/2016 - 6:15
cmyk_m_con_med = m # send into figure (d)
m = imadjust(m)
y = np.subtract(255,b)
y = imadjust(y)
AD = matlab_mat2gray(B)
AD = cv2.medianBlur(AD,7)
lab_y_con_med = AD # send into figure (e)
# subtract the M and b
sub = cv2.subtract(m,AD)
img_subt = sub # send into figure (f)
CMY = np.stack((c,m,y), axis=2)
F = np.stack((r, g, b), axis=2)
ab = CMY # generate CMY color model
nrows = (np.shape(f)[0]) # image height
ncols = (np.shape(f)[1])
# reshape into one single array
ab = ab.flatten()
x = nrows
y = ncols
data = sub.flatten() # sub = result of subtraction M and b, put them into one long array
## step 2 - clustering
nColors = 3 # Number of clusters (k)
# fit the fuzzy-c-means
fcm = FCM(n_clusters=nColors)
fcm.fit(data.reshape(-1, 1))
# outputs
cluster_idx = fcm.u.argmax(axis=1)
cluster_center = fcm.centers
kmeans = fcm
pixel_labels = np.reshape(cluster_idx, (nrows, ncols));
pixel_labels = np.uint8(pixel_labels)
# the problem is here,
tmp = np.sort(cluster_center.flatten())
idx = np.zeros((len(tmp), 1))
for i in range(len(tmp)):
idx[i] = cluster_center.tolist().index(tmp[i])
nuclei_cluster = idx[2] # sort asc, nuclei cluster is always who has higher value
A = np.zeros((nrows, ncols), dtype=np.uint8)
# print(np.shape(A))
for row in range(nrows):
for col in range(ncols):
# print(" pixel_labels[row,col] = ", row, col)
if pixel_labels[row,col] == nuclei_cluster:
A[row,col] = 255
else:
A[row,col] = 0
## step 3 - post-processing
img_clustering = A # send into figure (x)
img_clustering = imadjust(img_clustering)
# dilation (thing goes weird here)
sed = matlab_strel_disk(7) # disk
see = matlab_strel_ball(3,3) #circle
A = cv2.dilate(A,sed)
# erosion
A = cv2.erode(A, see)
# remove area < 800px
A = morphology.area_opening(A, area_threshold=800*3, connectivity=1) # vogado mention he use 800px
img_morpho = A # send into figure (g)
# debug mode
if(debug_mode):
# resize image into width 200px
ratio = ncols/nrows
t_width = 200
t_height = math.ceil(t_width * ratio)
print("(a) Original")
cv2_imshow(resize_img(image_rgb, t_width))
print("(b) M from CMYK")
cv2_imshow(resize_img(cmyk_m, t_width))
print("(c) *b from CIELAB")
cv2_imshow(resize_img(lab_y, t_width))
print("(d) M con adj + med(7x7)")
cv2_imshow(resize_img(cmyk_m_con_med, t_width))
print("(e) *b con adj + med(7x7)")
cv2_imshow(resize_img(lab_y_con_med, t_width))
print("(f) *b - M")
cv2_imshow(resize_img(img_subt, t_width))
print("(x) clustering")
cv2_imshow(resize_img(img_clustering, t_width))
print("(g) Morphological Ops.")
cv2_imshow(resize_img(img_morpho, t_width))
print("--- %s seconds ---" % (time.time() - start_time))
return img_morpho
# + id="X9NzVN7Tj835" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="3b7ba4ee-b0d5-4653-ebeb-b1558ca00b7a"
# SET THIS
path = "drive/My Drive/ALL_IDB2/Im007_1.jpg"
original_image = cv2.imread(path)
result = wbc_vogado_modified(original_image, True)
| proposed_method.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
# ---
# # Ludwig Time Series Forecasting
#
# https://github.com/uber/ludwig
# %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from time import time
matplotlib.rcParams['figure.figsize'] = (16, 9)
pd.options.display.max_columns = 999
# ## Load Dataset
df = pd.read_csv('../_datasets/hourly-weather-wind_speed.csv', parse_dates=[0], index_col='DateTime')
print(df.shape)
df.head()
# ## Define Parameters
#
# Make predictions for 24-hour period using a training period of four weeks.
dataset_name = 'Hourly Weather Wind Speed'
dataset_abbr = 'HWS'
model_name = 'Ludwig'
context_length = 24*2 # Two days
prediction_length = 3
# ## Define Error Metric
#
# The seasonal variant of the mean absolute scaled error (MASE) will be used to evaluate the forecasts.
def calc_sMASE(training_series, testing_series, prediction_series, seasonality=prediction_length):
a = training_series.iloc[seasonality:].values
b = training_series.iloc[:-seasonality].values
d = np.sum(np.abs(a-b)) / len(a)
errors = np.abs(testing_series - prediction_series)
return np.mean(errors) / d
# ## Evaluating Ludwig
#
# To evaluate Ludwig, forecasts will be generated for each time series. sMASE will be calculated for each individual time series, and the mean of all these scores will be used as the overall accuracy metric for Ludwig on this dataset.
# ### Prepare model definition file
# !touch ludwig.yaml
# +
config_str = """input_features:
-
name: {}
type: timeseries
output_features:
""".format(dataset_abbr)
for i in range(prediction_length):
config_str += """ -
name: y{}
type: numerical
""".format(i+1)
# -
with open("ludwig.yaml", "w+") as f:
f.write(config_str)
# ### Prepare data
df1 = df.iloc[-(context_length+prediction_length):]
df1_train = df1.iloc[:-prediction_length]
df1_test = df1.iloc[-prediction_length:]
# +
df2 = pd.DataFrame()
for i, col in enumerate(df1.columns[:1]):
y_cols = ['y%s' % str(j+1) for j in range(prediction_length)]
cols = [dataset_abbr] + y_cols
train = df1_train[col].values
test = df1_test[col].values
train_str = ""
for val in train:
train_str += str(val) + " "
train_str = train_str[:-1]
vals = [train_str] + list(test)
df_t = pd.DataFrame([vals], columns=cols, index=[i])
df2 = df2.append(df_t)
# -
df2.to_csv('full.csv', index=False)
df2
# ### Run Model
#
# For this dataset and these parameters, the Ludwig model fails to complete training within an acceptable period of time
# !ludwig experiment --data_csv full.csv --model_definition_file ludwig.yaml
| Ludwig/hourly-weather-wind_speed-reduced.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Apache Toree - PySpark
# language: python
# name: apache_toree_pyspark
# ---
# # Hands-on!
#
# Nessa prática, sugerimos alguns pequenos exemplos para você implementar sobre o Spark.
# ## Apriorando o Word Count Memória Postumas de Brás Cubas
#
# Memórias Póstumas de Brás Cubas é um romance escrito por Machado de Assis, desenvolvido em princípio como folhetim, de março a dezembro de 1880, na Revista Brasileira, para, no ano seguinte, ser publicado como livro, pela então Tipografia Nacional.
#
# A obra retrata a escravidão, as classes sociais, o cientificismo e o positivismo da época. Dada essas informações, será que conseguimos idenficar essas características pelas palavras mais utilizadas em sua obra?
#
# Utilizando o dataset `Machado-de-Assis-Memorias-Postumas.txt`, elabore um `pipeline` utilizando `Estimators` e `Transformers` necessário do Spark para responder as perguntas abaixo. Não esqueça de utilizar `stopwords.pt` para remover as `stop words`!
#
# - Quais as 10 palavras mais frequentes?
# - Quais as 2-grams e 3-grams mais frequentes?
#
# ## TF-IDF com CountVectorizer
#
# No exemplo `TFIDF`, atualize a cell 15 para utilizar o Transformer `CountVectorizer`.
| 2019/12-spark/13-spark-mllib/Hands-on.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .r
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: R
# name: ir
# ---
# + colab={"base_uri": "https://localhost:8080/"} id="up3a84fcx1QX" outputId="29b5ce1e-4efa-41fe-ce90-bc4ce168ceaa"
library(dplyr)
library(tidyr)
library(ggplot2)
library(magrittr) # for %>% operator
# + [markdown] id="pViAlsx38Ufz"
# ### Bar plot for car frequency by number of cylinders
# + colab={"base_uri": "https://localhost:8080/", "height": 437} id="RmIcK8U9zFz6" outputId="27a99fcd-5428-4f21-f68d-ab9955dab7c0"
data <- datasets::mtcars
barplot(table(data$cyl),main="Car Frequency by Number of Cylinders",xlab="Number of Cylinders")
# + [markdown] id="tcGOFopzFhmO"
# ## bar plot of average miles per gallon by the number of cylinders
# + colab={"base_uri": "https://localhost:8080/", "height": 437} id="TyJOB6wuBliD" outputId="0d792bbc-2914-4648-dada-5107ff1e73d1"
# Calculate avg mpg by number of cylinders
mpg_avg <- aggregate(x=data$mpg, by=list(data$cyl), FUN=mean)
# Plot average mpg by number of cylinders
barplot(height = mpg_avg[,2], names.arg = mpg_avg[,1])
# + colab={"base_uri": "https://localhost:8080/", "height": 455} id="WSGiirvlFIFz" outputId="c807e681-e1d0-4d32-acb6-1155694b4e2a"
mpg.avg.barplot <- barplot(height = mpg_avg[,2],
names.arg = mpg_avg[,1],
main="Average MPG by Number of Cylinders",
xlab="Number of Cylinders",
ylab="Average MPG",
ylim = c(0,30))
mpg.avg.barplot <- text(x=mpg.avg.barplot,
y=mpg_avg[,2]+2,
labels=as.character(round(mpg_avg[,2],2)))
mpg.avg.barplot
| R/Day10/day10ofmathandstats_R.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize
import warnings
def ratFunc(x, a, b, c, d): # rational function
return a/(x+b)**c + d
# +
warnings.filterwarnings('ignore')
#list with values calculated in pk_intra_mmk
VmaxList = [75, 100, 250, 500, 750, 1000, 2000, 10000]
RSSList = [4.84, 4.69, 4.44, 4.36, 4.32, 4.32, 4.32, 4.31]
aVmax = np.asarray(VmaxList)/10000;
aRSS = np.asarray(RSSList)
#plot result
plt.plot(VmaxList,RSSList,'co-',label = 'minimizer')
plt.xlabel('Vmax values ')
plt.ylabel('RSS')
#perform the fit
p0 = (1, 1, 1, 1) # start with values near those we expect
params, cv = scipy.optimize.curve_fit(ratFunc, aVmax, aRSS, p0)
a, b, c, d = params
sampleRate = 20_000
tauSec = 1 / sampleRate
plt.plot(aVmax*10000, ratFunc(aVmax, a, b, c, d), 'b--', label="fitted")
plt.legend(loc='best')
comment = 'RSS vs. Vmax MMK model'
plt.title(comment)
plt.show()
| Code/1_PK/2_intracellular/estimate_vmax.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
from pandas import Series,DataFrame
from numpy.random import randn
ser1 = Series([1,2,3,4],index=['a','b','c','d'])
ser1
dframe = DataFrame(randn(25).reshape(5,5),index = ['r1','r2','r3','r4','r5'],columns=['c1','c2','c3','c4','c5'])
dframe
dframe.drop('r2')
dframe['c1']
dframe[0:3]
dframe[['c1','c2']]
dframe[dframe> 1]
dframe.describe()
dframe.head()
dframe.corr
# %matplotlib inline
dframe.plot()
import seaborn as sns
import matplotlib as plt
| dataframe (1).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
# ---
# # Calculate Shapley values (Solution)
# Shapley values as used in coalition game theory were introduced by <NAME> in 1953.
# [<NAME>](http://scottlundberg.com/) applied Shapley values for calculating feature importance in [2017](http://papers.nips.cc/paper/7062-a-unified-approach-to-interpreting-model-predictions.pdf).
#
# If you want to read the paper, I recommend reading:
# Abstract, 1 Introduction, 2 Additive Feature Attribution Methods, (skip 2.1, 2.2, 2.3), and 2.4 Classic Shapley Value Estimation.
#
# Lundberg calls this feature importance method "SHAP", which stands for SHapley Additive exPlanations.
#
# Here’s the formula for calculating Shapley values:
#
# $ \phi_{i} = \sum_{S \subseteq M \setminus i} \frac{|S|! (|M| - |S| -1 )!}{|M|!} [f(S \cup i) - f(S)]$
#
# A key part of this is the difference between the model’s prediction with the feature $i$, and the model’s prediction without feature $i$.
# $S$ refers to a subset of features that doesn’t include the feature for which we're calculating $\phi_i$.
# $S \cup i$ is the subset that includes features in $S$ plus feature $i$.
# $S \subseteq M \setminus i$ in the $\Sigma$ symbol is saying, all sets $S$ that are subsets of the full set of features $M$, excluding feature $i$.
#
# ##### Options for your learning journey
# * If you’re okay with just using this formula, you can skip ahead to the coding section below.
# * If you would like an explanation for what this formula is doing, please continue reading here.
# ## Optional (explanation of this formula)
#
# The part of the formula with the factorials calculates the number of ways to generate the collection of features, where order matters.
#
# $\frac{|S|! (|M| - |S| -1 )!}{|M|!}$
# #### Adding features to a Coalition
#
# The following concepts come from coalition game theory, so when we say "coalition", think of it as a team, where members of the team are added, one after another, in a particular order.
#
# Let’s imagine that we’re creating a coalition of features, by adding one feature at a time to the coalition, and including all $|M|$ features. Let’s say we have 3 features total. Here are all the possible ways that we can create this “coalition” of features.
#
# <ol>
# <li>$x_0,x_1,x_2$</li>
# <li>$x_0,x_2,x_1$</li>
# <li>$x_1,x_0,x_2$</li>
# <li>$x_1,x_2,x_0$</li>
# <li>$x_2,x_0,x_1$</li>
# <li>$x_2,x_1,x_0$</li>
# </ol>
#
# Notice that for $|M| = 3$ features, there are $3! = 3 \times 2 \times 1 = 6$ possible ways to create the coalition.
# #### marginal contribution of a feature
#
# For each of the 6 ways to create a coalition, let's see how to calculate the marginal contribution of feature $x_2$.
#
# <ol>
# <li>Model’s prediction when it includes features 0,1,2, minus the model’s prediction when it includes only features 0 and 1.
#
# $x_0,x_1,x_2$: $f(x_0,x_1,x_2) - f(x_0,x_1)$
#
#
# <li>Model’s prediction when it includes features 0 and 2, minus the prediction when using only feature 0. Notice that feature 1 is added after feature 2, so it’s not included in the model.
#
# $x_0,x_2,x_1$: $f(x_0,x_2) - f(x_0)$</li>
#
#
# <li>Model's prediction including all three features, minus when the model is only given features 1 and 0.
#
# $x_1,x_0,x_2$: $f(x_1,x_0,x_2) - f(x_1,x_0)$</li>
#
#
# <li>Model's prediction when given features 1 and 2, minus when the model is only given feature 1.
#
# $x_1,x_2,x_0$: $f(x_1,x_2) - f(x_1)$</li>
#
#
# <li>Model’s prediction if it only uses feature 2, minus the model’s prediction if it has no features. When there are no features, the model’s prediction would be the average of the labels in the training data.
#
# $x_2,x_0,x_1$: $f(x_2) - f( )$
# </li>
#
#
# <li>Model's prediction (same as the previous one)
#
# $x_2,x_1,x_0$: $f(x_2) - f( )$
# </li>
#
# Notice that some of these marginal contribution calculations look the same. For example the first and third sequences, $f(x_0,x_1,x_2) - f(x_0,x_1)$ would get the same result as $f(x_1,x_0,x_2) - f(x_1,x_0)$. Same with the fifth and sixth. So we can use factorials to help us calculate the number of permutations that result in the same marginal contribution.
#
# #### break into 2 parts
#
# To get to the formula that we saw above, we can break up the sequence into two sections: the sequence of features before adding feature $i$; and the sequence of features that are added after feature $i$.
#
# For the set of features that are added before feature $i$, we’ll call this set $S$. For the set of features that are added after feature $i$ is added, we’ll call this $Q$.
#
# So, given the six sequences, and that feature $i$ is $x_2$ in this example, here’s what set $S$ and $Q$ are for each sequence:
#
# <ol>
# <li>$x_0,x_1,x_2$: $S$ = {0,1}, $Q$ = {}</li>
# <li>$x_0,x_2,x_1$: $S$ = {0}, $Q$ = {1} </li>
# <li>$x_1,x_0,x_2$: $S$ = {1,0}, $Q$ = {} </li>
# <li>$x_1,x_2,x_0$: $S$ = {1}, $Q$ = {0} </li>
# <li>$x_2,x_0,x_1$: $S$ = {}, $Q$ = {0,1} </li>
# <li>$x_2,x_1,x_0$: $S$ = {}, $Q$ = {1,0} </li>
# </ol>
# So for the first and third sequences, these have the same set S = {0,1} and same set $Q$ = {}.
# Another way to calculate that there are two of these sequences is to take $|S|! \times |Q|! = 2! \times 0! = 2$.
#
# Similarly, the fifth and sixth sequences have the same set S = {} and Q = {0,1}.
# Another way to calculate that there are two of these sequences is to take $|S|! \times |Q|! = 0! \times 2! = 2$.
#
# #### And now, the original formula
#
# To use the notation of the original formula, note that $|Q| = |M| - |S| - 1$.
#
# Recall that to calculate that there are 6 total sequences, we can use $|M|! = 3! = 3 \times 2 \times 1 = 6$.
# We’ll divide $|S|! \times (|M| - |S| - 1)!$ by $|M|!$ to get the proportion assigned to each marginal contribution.
# This is the weight that will be applied to each marginal contribution, and the weights sum to 1.
#
# So that’s how we get the formula:
#
# $\frac{|S|! (|M| - |S| -1 )!}{|M|!} [f(S \cup i) - f(S)]$
#
# for each set $S \subseteq M \setminus i$
#
# We can sum up the weighted marginal contributions for all sets $S$, and this represents the importance of feature $i$.
#
# You’ll get to practice this in code!
import sys
# !{sys.executable} -m pip install numpy==1.14.5
# !{sys.executable} -m pip install scikit-learn==0.19.1
# !{sys.executable} -m pip install graphviz==0.9
# !{sys.executable} -m pip install shap==0.25.2
import sklearn
import shap
import numpy as np
import graphviz
from math import factorial
# ## Generate input data and fit a tree model
# We'll create data where features 0 and 1 form the "AND" operator, and feature 2 does not contribute to the prediction (because it's always zero).
# +
# AND case (features 0 and 1)
N = 100
M = 3
X = np.zeros((N,M))
X.shape
y = np.zeros(N)
X[:1 * N//4, 1] = 1
X[:N//2, 0] = 1
X[N//2:3 * N//4, 1] = 1
y[:1 * N//4] = 1
# fit model
model = sklearn.tree.DecisionTreeRegressor(random_state=0)
model.fit(X, y)
# draw model
dot_data = sklearn.tree.export_graphviz(model, out_file=None, filled=True, rounded=True, special_characters=True)
graph = graphviz.Source(dot_data)
graph
# -
# ### Calculate Shap values
#
# We'll try to calculate the local feature importance of feature 0.
#
# We have 3 features, $x_0, x_1, x_2$. For feature $x_0$, determine what the model predicts with or without $x_0$.
#
# Subsets S that exclude feature $x_0$ are:
# {}
# {$x_1$}
# {$x_2$}
# {$x_1,x_2$}
#
# We want to see what the model predicts with feature $x_0$ compared to the model without feature $x_0$:
# $f(x_0) - f( )$
# $f(x_0,x_1) - f(x_1)$
# $f(x_0,x_2) - f(x_2)$
# $f(x_0,x_1,x_2) - f(x_1,x_2)$
#
# ## Sample data point
# We'll calculate the local feature importance of a sample data point, where
# feature $x_0 = 1$
# feature $x_1 = 1$
# feature $x_2 = 1$
sample_values = np.array([1,1,1])
print(f"sample values to calculate local feature importance on: {sample_values}")
# ## helper function
#
# To make things easier, we'll use a helper function that takes the entire feature set M, and also a list of the features (columns) that we want, and puts them together into a 2D array.
def get_subset(X, feature_l):
"""
Given a 2D array containing all feature columns,
and a list of integers representing which columns we want,
Return a 2D array with just the subset of features desired
"""
cols_l = []
for f in feature_l:
cols_l.append(X[:,f].reshape(-1,1))
return np.concatenate(cols_l, axis=1)
# try it out
tmp = get_subset(X,[0,2])
tmp[0:10]
# ## helper function to calculate permutation weight
#
# This helper function calculates
#
# $\frac{|S|! (|M| - |S| - 1)!}{|M|!}$
from math import factorial
def calc_weight(size_S, num_features):
return factorial(size_S) * factorial(num_features - size_S - 1) / factorial(num_features)
# Try it out when size of S is 2 and there are 3 features total.
# The answer should be equal to $\frac{2! \times (3-2-1)!}{3!} = \frac{2 \times 1}{6} = \frac{1}{3}$
#
calc_weight(size_S=2,num_features=3)
# ## case A
#
# Calculate the prediction of a model that uses features 0 and 1
# Calculate the prediction of a model that uses feature 1
# Calculate the difference (the marginal contribution of feature 0)
#
# $f(x_0,x_1) - f(x_1)$
# #### Calculate $f(x_0,x_1)$
# +
# S_union_i
S_union_i = get_subset(X,[0,1])
# fit model
f_S_union_i = sklearn.tree.DecisionTreeRegressor()
f_S_union_i.fit(S_union_i, y)
# -
# Remember, for the sample input for which we'll calculate feature importance, we chose values of 1 for all features.
# +
# This will throw an error
try:
f_S_union_i.predict(np.array([1,1]))
except Exception as e:
print(e)
# -
# The error message says:
#
# >Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
#
# So we'll reshape the data so that it represents a sample (a row), which means it has 1 row and 1 or more columns.
# feature 0 and feature 1 are both 1 in the sample input
sample_input = np.array([1,1]).reshape(1,-1)
sample_input
# The prediction of the model when it has features 0 and 1 is:
pred_S_union_i = f_S_union_i.predict(sample_input)
pred_S_union_i
# When feature 0 and feature 1 are both 1, the prediction of the model is 1
# #### Calculate $f(x_1)$
# S
S = get_subset(X,[1])
f_S = sklearn.tree.DecisionTreeRegressor()
f_S.fit(S, y)
# The sample input for feature 1 is 1.
sample_input = np.array([1]).reshape(1,-1)
# The model's prediction when it is only training on feature 1 is:
pred_S = f_S.predict(sample_input)
pred_S
# When feature 1 is 1, then the prediction of this model is 0.5. If you look at the data in X, this makes sense, because when feature 1 is 1, half of the time, the label in y is 0, and half the time, the label in y is 1. So on average, the prediction is 0.5
# #### Calculate difference
diff_A = pred_S_union_i - pred_S
diff_A
# #### Calculate the weight
# Calculate the weight assigned to the marginal contribution. In this case, if this marginal contribution occurs 1 out of the 6 possible permutations of the 3 features, then its weight is 1/6
size_S = S.shape[1] # should be 1
weight_A = calc_weight(size_S, M)
weight_A # should be 1/6
# ## Quiz: Case B
#
# Calculate the prediction of a model that uses features 0 and 2
# Calculate the prediction of a model that uses feature 2
# Calculate the difference
#
# $f(x_0,x_2) - f(x_2)$
# #### Calculate $f(x_0,x_2)$
# +
# TODO
S_union_i = get_subset(X,[0,2])
f_S_union_i = sklearn.tree.DecisionTreeRegressor()
f_S_union_i.fit(S_union_i, y)
sample_input = np.array([1,1]).reshape(1,-1)
pred_S_union_i = f_S_union_i.predict(sample_input)
pred_S_union_i
# -
# Since we're using features 0 and 2, and feature 2 doesn't help with predicting the output, then the model really just depends on feature 0. When feature 0 is 1, half of the labels are 0, and half of the labels are 1. So the average prediction is 0.5
# #### Calculate $f(x_2)$
# +
# TODO
S = get_subset(X,[2])
f_S = sklearn.tree.DecisionTreeRegressor()
f_S.fit(S, y)
sample_input = np.array([1]).reshape(1,-1)
pred_S = f_S.predict(sample_input)
pred_S
# -
# Since feature 2 doesn't help with predicting the labels in y, and feature 2 is 0 for all 100 training observations, then the prediction of the model is the average of all 100 training labels. 1/4 of the labels are 1, and the rest are 0. So that prediction is 0.25
# #### Calculate the difference in predictions
# TODO
diff_B = pred_S_union_i - pred_S
diff_B
# #### Calculate the weight
# TODO
size_S = S.shape[1] # is 1
weight_B = calc_weight(size_S, M)
weight_B # should be 1/6
# # Quiz: Case C
#
# Calculate the prediction of a model that uses features 0,1 and 2
# Calculate the prediction of a model that uses feature 1 and 2
# Calculate the difference
#
# $f(x_0,x_1,x_2) - f(x_1,x_2)$
# #### Calculate $f(x_0,x_1,x_2) $
# +
# TODO
S_union_i = get_subset(X,[0,1,2])
f_S_union_i = sklearn.tree.DecisionTreeRegressor()
f_S_union_i.fit(S_union_i, y)
sample_input = np.array([1,1,1]).reshape(1,-1)
pred_S_union_i = f_S_union_i.predict(sample_input)
pred_S_union_i
# -
# When we use all three features, the model is able to predict that if feature 0 and feature 1 are both 1, then the label is 1.
# #### Calculate $f(x_1,x_2)$
# +
# TODO
S = get_subset(X,[1,2])
f_S = sklearn.tree.DecisionTreeRegressor()
f_S.fit(S, y)
sample_input = np.array([1,1]).reshape(1,-1)
pred_S = f_S.predict(sample_input)
pred_S
# -
# When the model is trained on features 1 and 2, then its training data tells it that half of the time, when feature 1 is 1, the label is 0; and half the time, the label is 1. So the average prediction of the model is 0.5
# #### Calculate difference in predictions
# TODO
diff_C = pred_S_union_i - pred_S
diff_C
# #### Calculate weights
# TODO
size_S = S.shape[1]
weight_C = calc_weight(size_S,M) # should be 2 / 6 = 1/3
weight_C
# ## Quiz: case D: remember to include the empty set!
#
# The empty set is also a set. We'll compare how the model does when it has no features, and see how that compares to when it gets feature 0 as input.
#
# Calculate the prediction of a model that uses features 0.
# Calculate the prediction of a model that uses no features.
# Calculate the difference
#
# $f(x_0) - f()$
# #### Calculate $f(x_0)$
# +
# TODO
S_union_i = get_subset(X,[0])
f_S_union_i = sklearn.tree.DecisionTreeRegressor()
f_S_union_i.fit(S_union_i, y)
sample_input = np.array([1]).reshape(1,-1)
pred_S_union_i = f_S_union_i.predict(sample_input)
pred_S_union_i
# -
# With just feature 0 as input, the model predicts 0.5
# #### Calculate $f()$
# **hint**: you don't have to fit a model, since there are no features to input into the model.
# TODO
# with no input features, the model will predict the average of the labels, which is 0.25
pred_S = np.mean(y)
pred_S
# With no input features, the model's best guess is the average of the labels, which is 0.25
# #### Calculate difference in predictions
# TODO
diff_D = pred_S_union_i - pred_S
diff_D
# #### Calculate weight
#
# We expect this to be: 0! * (3-0-1)! / 3! = 2/6 = 1/3
# TODO
size_S = 0
weight_D = calc_weight(size_S,M) # weight is 1/3
weight_D
# # Calculate Shapley value
# For a single sample observation, where feature 0 is 1, feature 1 is 1, and feature 2 is 1, calculate the shapley value of feature 0 as the weighted sum of the differences in predictions.
#
# $\phi_{i} = \sum_{S \subseteq N \setminus i} weight_S \times (f(S \cup i) - f(S))$
# TODO
shap_0 = weight_A * diff_A + weight_B * diff_B + weight_C * diff_C + weight_D * diff_D
shap_0
# ## Verify with the shap library
#
# The [shap](https://github.com/slundberg/shap) library is written by <NAME>, the creator of Shapley Additive Explanations.
# +
sample_values = np.array([1,1,1])
shap_values = shap.TreeExplainer(model).shap_values(sample_values)
print(f"Shapley value for feature 0 that we calculated: {shap_0}")
print(f"Shapley value for feature 0 is {shap_values[0]}")
print(f"Shapley value for feature 1 is {shap_values[1]}")
print(f"Shapley value for feature 2 is {shap_values[2]}")
# -
# ## Quiz: Does this make sense?
#
# The shap libary outputs the shap values for features 0, 1 and 2. We can see that the shapley value for feature 0 matches what we calculated. The Shapley value for feature 1 is also given the same importance as feature 0.
# * Given that the training data is simulating an AND operation, do you think these values make sense?
# * Do you think feature 0 and 1 are equally important, or is one more important than the other?
# * Does the importane of feature 2 make sense as well?
# * How does this compare to the feature importance that's built into sci-kit learn?
# ## Answer
#
# * The shapley values appear to make sense, since feature 0 and feature 1 are both required to be 1 for the label to also be 1. So it makes sense that their importance values are equal.
# * Features 0 and 1 are equally important, based on our intuition about the AND operator, and the shapley values calculated by the shap library.
# * Since feature 2 does not help in predicting the label, it also makes sense that the importance of feature 2 is 0.
# * Compared to the feature importance method built into sci-kit learn, the shapley additive explanations method is more consistent in assigning the importance of each feature.
# ## Note
# This method is general enough that it works for any model, not just trees. There is an optimized way to calculate this when the complex model being explained is a tree-based model. We'll look at that next.
# ## Solution
#
# [Solution notebook](calculate_shap_solution.ipynb)
| TradingAI/AI Algorithms in Trading/Lesson 19 - Feature Engineering/calculate_shap_solution.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (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
#
# +
import numpy as np
import matplotlib.pyplot as plt
#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'] = (12, 6)
# -
# # Exercise 6 - Linear FEM: soil column under gravity and top load
#
# ## Governing differential equation
#
# Consider the equilibrium conditions on an infinitesimal element of the soil column:
#
# $$
# \downarrow: \quad F_z + \frac{\partial F_z}{\partial z}\text{d}z - F_z + \varrho g A \text{d}z = 0
# $$
#
# The vertical force is determined by $F_z = \sigma_{zz}A = E_\text{s} A \epsilon_{zz} = -E_\text{s} A u_{z,z}$. Therefore, the equilibrium conditions read:
#
# $$
# 0 = \left[ \frac{\partial}{\partial z} \left(E_\text{s} A \frac{\partial u_z}{\partial z}\right) - \varrho g A \right]\text{d}z
# $$
#
# Considering, that the equation has to hold for an arbitrary infinitesimal non-zero $\text{d}z$, we find the ordinary differential equation
#
# $$
# 0 = \frac{\partial}{\partial z} \left(E_\text{s} A \frac{\partial u_z}{\partial z}\right) - \varrho g A
# $$
#
# Nota bene: compare this to the differential equation for a rod ('Zugstab'): $(EAu')' + n = 0$. While the cross section of a rod can vary along its length, the cross-sectional area of a soil column is considered a constant, simplifying the equation further:
#
# $$
# 0 = \frac{\partial}{\partial z} \left(E_\text{s} \frac{\partial u_z}{\partial z}\right) - \varrho g
# $$
#
# ## Weak form
#
# The displacements can have (the essential/Dirichlet) boundary conditions in the form:
#
# $$
# u = \bar{u}\ \forall z \in \partial \Omega_\mathrm{D}% \qquad \text{and} \qquad - E_\text{s}A \frac{\partial u_z}{\partial z} = \bar{F} \ \forall z \in \partial \Omega_\mathrm{N}
# $$
#
# We now introduce a test function $\delta u$ (virtual displacement) which vanishes where the displacement is given
#
# $$
# \delta u = 0\ \forall z \in \partial \Omega_\mathrm{D}
# $$
#
# and construct the weak form (using integration by parts):
#
# \begin{align}
# 0 &= \int \limits_0^H \left[\frac{\partial}{\partial z} \left(E_\text{s} \frac{\partial u_z}{\partial z}\right) - \varrho g\right] \delta u\, \text{d}z
# \\
# &= \int \limits_0^H \left[\frac{\partial}{\partial z} \left(E_\text{s} \frac{\partial u_z}{\partial z} \delta u \right) - \frac{\partial \delta u}{\partial z} E_\text{s} \frac{\partial u_z}{\partial z} - \varrho g \delta u \right] \, \text{d}z
# \end{align}
#
# Integrating the first term yields the natural/Neumann boundary conditions, so that
# $$
# \left[ \underbrace{E_\text{s} \frac{\partial u_z}{\partial z}}_{\displaystyle -\bar{\sigma}_z} \delta u \right]_0^H - \int \limits_0^H \varrho g \delta u \text{d}z = \int \limits_0^H \frac{\partial \delta u}{\partial z} E_\text{s} \frac{\partial u_z}{\partial z} \, \text{d}z
# $$
# which is recognised as the principal of virtual work: $\delta W_\text{ext} = \delta W_\text{int}$.
# ## Finite elements in 1D
#
# We have a soil column of $H=20$ m on top of the bed rock at $z=0$.
#
# We first create an element class. An element knows the number of nodes it has, their IDs in the global node vector, and the coordinates of its nodes. Linear elements have 2 nodes and 2 quadrature points, quadratic elements 3 nodes and 3 quadrature points. The natural coordinates of the element run from -1 to 1, and the quadrature points and weights are directly taken from Numpy.
#element class
class line_element():#local coordinates go from -1 to 1
#takes number of nodes, global nodal coordinates, global node ids
def __init__(self, nnodes=2, ncoords=[0.,1.], nids=[0,1]):
self.__nnodes = nnodes
if (len(ncoords) != self.__nnodes):
raise Exception("Number of coordinates does not match number \
of nodes of element (%i vs of %i)" %(self.__nnodes,len(ncoords)))
else:
self.__coords = np.array(ncoords)
self.__natural_coords = (self.__coords-self.__coords[0])/(self.__coords[-1]-self.__coords[0])*2. - 1.
if (len(nids) != self.__nnodes):
raise Exception("Number of node IDs does not match number \
of nodes of element (%i vs of %i)" %(self.__nnodes,len(nids)))
else:
self.__global_ids = np.array(nids)
self.__quad_degree = self.__nnodes
self.__quad_points, self.__quad_weights = np.polynomial.legendre.leggauss(self.__quad_degree)
# Next, we wish to generate a one-dimensional mesh by specifying the length of a line, the number of elements into which the mesh is to be split, and the number of nodes per element.
# +
def number_of_nodes(nelems,nodes_per_elem):
return nelems*nodes_per_elem - (nelems - 1)
def generate_mesh(domain_length,nelems,nodes_per_elem):
nn = number_of_nodes(nelems,nodes_per_elem)
#coordinate vector of global nodes
global_nodal_coordinates = np.linspace(0.,domain_length,nn)
global_solution = np.array([0.]*nn)
#generate elements
element_vector = []
for i in range(nelems):
node_start = (nodes_per_elem-1)*i
element_vector.append(
line_element(nodes_per_elem,
global_nodal_coordinates[node_start:node_start+nodes_per_elem],
list(range(node_start,node_start+nodes_per_elem))))
return global_nodal_coordinates, element_vector, global_solution
# -
# Let's put this to test.
# +
number_of_elements = 30
L = 10.
nodes_per_element = 3
nodes,elements,solution=generate_mesh(L,number_of_elements,nodes_per_element)
# -
plt.xlabel('$z$')
plt.ylabel('element ID')
plt.title('Finite element mesh')
for i,elem in enumerate(elements):
if (i==0):
plt.plot(elem._line_element__coords,[i]*elem._line_element__nnodes, 'bs-', label='elements')
else:
plt.plot(elem._line_element__coords,[i]*elem._line_element__nnodes, 'bs-')
plt.plot(nodes, [0]*len(nodes), 'ro ', label='nodes')
plt.legend();
# ## Shape functions in 1D
#
# Now we have a mesh consisting of a vector of elements, and a global node vector. The next ingredient required are the shape functions for the elements in order to interpolate variables and determine gradients.
#
# ### Linear elements
#
# Linear elements have two nodes with $\xi_1 = -1$ and $\xi_2 = 1$. The linear shape functions are
#
# $$
# N_1(\xi) = \frac{1-\xi}{2} \qquad \text{and} \qquad N_2(\xi) = \frac{1+\xi}{2}
# $$
#
# Their gradients in natural coordinates follow as
#
# $$
# \frac{\text{d} N_1}{\text{d}\xi} = - \frac{1}{2} \qquad \text{and} \qquad \frac{\text{d} N_2}{\text{d}\xi} = \frac{1}{2}
# $$
#
# ### Quadratic elements
#
# Quadratic elements have three nodes with $\xi_1 = -1$, $\xi_2 = 0$ and $\xi_3 = 1$. The quadratic shape functions are
#
# $$
# N_1(\xi) = \frac{\xi (\xi - 1)}{2}, \qquad N_2(\xi) = (1-\xi)(1+\xi) \qquad \text{and} \qquad N_3(\xi) = \frac{\xi(1+\xi)}{2}
# $$
#
# Their gradients in natural coordinates follow as
#
# $$
# \frac{\text{d} N_1}{\text{d}\xi} = \xi - \frac{1}{2}, \qquad \frac{\text{d} N_2}{\text{d}\xi} = -2\xi \qquad \text{and} \qquad \frac{\text{d} N_3}{\text{d}\xi} = \xi + \frac{1}{2}
# $$
#
# ### Jacobians and gradients
#
# An unknown is approximated as $u \approx N_i \hat{u}_i$ where $i$ runs over all nodes of a given element and $\hat{u}_i$ are the nodal degrees of freedom. To peform a gradient calculation (here in 1D)
#
# $$
# \text{grad} u = \frac{\text{d} u}{\text{d} z} = \frac{\text{d}N_i}{\text{d} z} \hat{u}_i = \frac{\text{d}N_i}{\text{d} \xi} \frac{\text{d}\xi}{\text{d} z} \hat{u}_i = \frac{\text{d}N_i}{\text{d} \xi} J^{-1} \hat{u}_i
# $$
#
# The element Jacobian follows from the isoparametric coordinate approximation $z \approx N_i \hat{z}_i$ where $\hat{z}_i$ are the nodal coordinates:
#
# $$
# J = \frac{\text{d} z}{\text{d}\xi} = \frac{\text{d} N_i}{\text{d}\xi} \hat{z}_i
# $$
#
# We use the following shorthand:
#
# $$
# \nabla N_i = \frac{\text{d}N_i}{\text{d} z} = \frac{\text{d}N_i}{\text{d} \xi} J^{-1}
# $$
# +
#N
def shape_function(element_order,xi):
if (element_order == 2): #-1,1
return np.array([(1.-xi)/2., (1.+xi)/2.])
elif (element_order == 3): #-1, 0, 1
return np.array([(xi - 1.)*xi/2., (1-xi)*(1+xi), (1+xi)*xi/2.])
#dN_dxi
def dshape_function_dxi(element_order,xi):
if (element_order == 2): #-1,1
return np.array([-0.5*xi/xi, 0.5*xi/xi]) #xi only later for plotting dimensions
elif (element_order == 3):#-1,0,1
return np.array([xi - 0.5,-2.*xi,xi + 0.5])
#dz_dxi
def element_jacobian(element,xi):
element_order = element._line_element__nnodes
Jacobian = 0.
Jacobian += dshape_function_dxi(element_order,xi).dot(element._line_element__coords)
return Jacobian
#dN_dz
def grad_shape_function(element,xi):
element_order = element._line_element__nnodes
Jac = element_jacobian(element,xi)
return dshape_function_dxi(element_order,xi)/Jac
# -
# Now let's plot the shape functions to see if they were implemented correctly.
def plot_shape_functions(order):
xi = np.linspace(-1.,1.,100)
fig, ax = plt.subplots(ncols=2)
ax[0].set_xlabel('$\\xi$')
ax[0].set_ylabel('$N(\\xi)$')
for i in range(order):
ax[0].plot(xi,shape_function(order,xi)[i],label='$N_{%i}$' %i)
ax[0].legend()
ax[1].set_xlabel('$\\xi$')
ax[1].set_ylabel('$\\mathrm{d}N(\\xi)/\\mathrm{d}\\xi$')
for i in range(order):
ax[1].plot(xi,dshape_function_dxi(order,xi)[i],label='$\\mathrm{d}N_{%i}/\\mathrm{d}\\xi$' %i)
ax[1].legend()
fig.tight_layout()
plot_shape_functions(2)
plot_shape_functions(3)
# ## Discretization of virtual work (weak form)
#
# Now let's write the discretized version of the principal of virtual work in the following form:
# $$
# \left[ \bar{\sigma}_z \delta u \right]_0^H - \int \limits_0^H \varrho g \delta u \text{d}z = \int \limits_0^H \frac{\partial \delta u}{\partial z} E_\text{s} \frac{\partial u_z}{\partial z} \, \text{d}z
# $$
#
# using
#
# $$
# u \approx N_i \hat{u}_i, \quad \delta u \approx N_i \delta \hat{u}_i, \quad \frac{\partial u_z}{\partial z} \approx \nabla N_i \hat{u}_i, \quad \frac{\partial \delta u_z}{\partial z} \approx \nabla N_i \delta \hat{u}_i
# $$
#
# This yields
#
# $$
# \begin{aligned}
# \int \limits_0^H \varrho g \delta u\, \text{d}z &= \int \limits_0^H \varrho g \delta u\, \text{d}z = \int \limits_0^H \varrho g N_i\, \text{d}z\ \delta \hat{u}_i= \bigcup \limits_{e=1}^{n_\text{el}} \int \limits_{z_e} \varrho g N_i \det J \, \text{d}\xi\ \delta \hat{u}_i
# \\
# \int \limits_0^H \frac{\partial \delta u}{\partial z} E_\text{s} \frac{\partial u_z}{\partial z} \, \text{d}z &= \int \limits_0^H \nabla N_i E_\text{s} \nabla N_k \, \text{d}z \ \hat{u}_k \delta \hat{u}_i = \bigcup \limits_{e=1}^{n_\text{el}} \int \limits_{z_e} \nabla N_i E_\text{s} \nabla N_k \det J \, \text{d}\xi \ \hat{u}_k \delta \hat{u}_i
# \\
# \left[ \bar{\sigma}_z \delta u \right]_0^H &= \bar{\sigma}_z(z=H) N_{n_\text{n}}(\xi_{n_\text{n}}) \delta \hat{u}_{n_\text{n}} - \bar{\sigma}_z(z=0) N_{0}(\xi_0) \delta \hat{u}_0 = \left[ \bar{\sigma}_z(z=H) N_{n_\text{n}}(\xi_{n_\text{n}}) \delta_{in_\text{n}} - \bar{\sigma}_z(z=0) N_{0}(\xi_0) \delta_{i0} \right] \delta \hat{u}_i
# \end{aligned}
# $$
#
# where in the last step we assumed that the node at $z=0$ has the node id $0$, while the node at $z=H$ has the node id $n_\text{n}$.
#
# The discretized system
#
# $$
# \left[ \bar{\sigma}_z(z=H) N_{n_\text{n}}(\xi_{n_\text{n}}) \delta_{in_\text{n}} - \bar{\sigma}_z(z=0) N_{0}(\xi_0) \delta_{i0} - \bigcup \limits_{e=1}^{n_\text{el}} \int \limits_{z_e} \varrho g N_i \det J \, \text{d}\xi \right] \delta \hat{u}_i = \bigcup \limits_{e=1}^{n_\text{el}} \int \limits_{z_e} \nabla N_i E_\text{s} \nabla N_k \det J \, \text{d}\xi \ \hat{u}_k \delta \hat{u}_i
# $$
#
# can be simplified by realizing that the nodal virtual displacements are arbitrary and thus
#
# $$
# \bar{\sigma}_z(z=H) N_{n_\text{n}}(\xi_{n_\text{n}}) \delta_{in_\text{n}} - \bar{\sigma}_z(z=0) N_{0}(\xi_0) \delta_{i0} - \bigcup \limits_{e=1}^{n_\text{el}} \int \limits_{z_e} \varrho g N_i \det J \, \text{d}\xi = \bigcup \limits_{e=1}^{n_\text{el}} \int \limits_{z_e} \nabla N_i E_\text{s} \nabla N_k \det J \, \text{d}\xi \ \hat{u}_k
# $$
#
# which leaves us with $n_\text{n}$ equations for the $n_\text{n}$ unknown nodal displacements $\hat{u}_k$. This is the discretized force balance with
#
# $$
# F_i^\text{surf} + F_i^\text{body} = K_{ik} \hat{u}_k
# $$
# What we require now is the local assembler to calculate the stiffness matrix and the local right-hand side. Local integration is performed by Gauss quadrature:
#
# $$
# \int \limits_{-1}^1 f(\xi)\,\text{d}\xi \approx \sum \limits_{i=1}^{n_\text{gp}} f(\xi_i) w_i
# $$
# ## Local assember
# +
def Stiffness(z):
E0 = 1.e8 #Pa
return E0
def Density(z):
rho0 = 2600.*(1.-0.38) #kg/m³
return rho0
def BodyForce(z):#N/m
g = 9.81
return g*Density(z)
# -
def local_assembler(elem):
element_order = elem._line_element__nnodes
K_loc = np.zeros((element_order,element_order))
b_loc = np.zeros(element_order)
z_nodes = elem._line_element__coords
for i in range(elem._line_element__quad_degree):
#local integration point coordinate
xi = elem._line_element__quad_points[i]
#shape function
N = shape_function(element_order,xi)
#gradient of shape function
dN_dX = grad_shape_function(elem,xi)
#determinant of Jacobian
detJ = np.abs(element_jacobian(elem,xi))
#integration weight
w = elem._line_element__quad_weights[i]
#global integration point coordinate (for spatially varying properties)
z_glob = np.dot(N,z_nodes)
#evaluation of local material/structural properties
E = Stiffness(z_glob)
#evaluation of local body force
rho_g = BodyForce(z_glob)
#assembly of local stiffness matrix
K_loc += np.outer(dN_dX,dN_dX) * E * w * detJ
#assembly of local RHS
b_loc += N * rho_g * w * detJ
return K_loc,b_loc
local_assembler(elements[3])
# ## Global assembly
#
# Now we can construct the global matrix system $\mathbf{K}\mathbf{u} = \mathbf{f}$ or $\mathbf{A}\mathbf{x}=\mathbf{b}$ (see lecture script).
def global_assembler(nodes,elements,solution):
K_glob = np.zeros((len(nodes),len(nodes)))
b_glob = np.zeros(len(nodes))
for i,elem in enumerate(elements):
K_i, b_i = local_assembler(elem)
start_id = elem._line_element__global_ids[0]
end_id = elem._line_element__global_ids[-1]
K_glob[start_id:end_id+1,start_id:end_id+1] += K_i
b_glob[start_id:end_id+1] += b_i
return K_glob, b_glob
# ## Application of boundary conditions
#
# Now we apply the natural (Neumann, nodal force) and the essential (Dirichlet, nodal displacement) boundary conditions.
#
# A nodal force $F_\text{bc}$ at node $m$ is simply added by
# $$
# F^\text{ext}_i = \left(
# \begin{array}{c}
# F_0\\ F_1\\ \vdots\\ F_m \\ \vdots \\ F_{n_\text{n}}
# \end{array}
# \right)
# = F_i^\text{body} + F_\text{bc} \delta_{im} = F_i^\text{body} + F_\text{bc}
# \left(
# \begin{array}{c}
# 0\\ 0\\ \vdots \\ 1 \\ \vdots \\ 0
# \end{array}
# \right)
# $$
def apply_Neumann_bc(b_glob,node_id,value):
b_glob[node_id] += value
return b_glob
# A Dirichlet boundary condition $\bar{u}$ at node $m$ is introduced into the system $K_{ik} u_k = f_i$ via
#
# $$
# \left(
# \begin{array}{c}
# K_{11} & K_{12} & \dots & K_{1m} & \dots & K_{1n_\text{n}}
# \\
# K_{21} & K_{22} & \dots & K_{2m} & \dots & K_{2n_\text{n}}
# \\
# \vdots & \vdots & \vdots & \vdots & \vdots & \vdots
# \\
# K_{m1}:=0 & K_{m2}:=0 & \dots & K_{mm}:=1 & \dots & K_{mn_\text{n}}:=0
# \\
# \vdots & \vdots & \vdots & \vdots & \vdots & \vdots
# \\
# K_{n_\text{n}1} & K_{n_\text{n}2} & \dots & K_{n_\text{n}m} & \dots & K_{n_\text{n}n_\text{n}}
# \end{array}
# \right)
# \left(
# \begin{array}{c}
# u_0\\ u_1\\ \vdots\\ u_m \\ \vdots \\ u_{n_\text{n}}
# \end{array}
# \right)
# =
# \left(
# \begin{array}{c}
# F_0\\ F_1\\ \vdots\\ F_m:=\bar{u} \\ \vdots \\ F_{n_\text{n}}
# \end{array}
# \right)
# $$
def apply_Dirichlet_bc(K_glob,b_glob,node_id,value):
K_glob[node_id,:] = 0.# = K_glob[:,node_id] = 0.
K_glob[node_id,node_id] = 1.
b_glob[node_id] = value
return K_glob, b_glob
# ## Problem solution
#
# We now perform the global assembly, apply a vanishing traction on the top and constrain the displacement at the bottom to zero.
# +
number_of_elements = 20
L = 10.
nodes_per_element = 3
nodes,elements,solution=generate_mesh(L,number_of_elements,nodes_per_element)
# -
K, f = global_assembler(nodes,elements,solution)
plt.spy(K,marker='.')
plt.title('sparsity pattern')
plt.tight_layout()
f = apply_Neumann_bc(f,len(nodes)-1,0)
K, f = apply_Dirichlet_bc(K, f, 0, 0.)
solution = np.linalg.solve(K,f)
plt.xlabel('$x$')
plt.ylabel('$u$ / mm')
plt.title('Finite element solution')
plt.plot(nodes, solution*1e3, 'ro-', label='$u$')
plt.legend();
# ### Convergence study
#
# Let's do a simple convergence study.
plt.xlabel('$x$')
plt.ylabel('$u$ / mm')
plt.title('Mesh convergence')
for i in [3,5,11]:
number_of_elements = i
nodes_per_element = 2
nodes,elements,solution=generate_mesh(L,number_of_elements,nodes_per_element)
K, f = global_assembler(nodes,elements,solution)
f = apply_Neumann_bc(f,len(nodes)-1,0)
K, f = apply_Dirichlet_bc(K, f, 0, 0.)
solution = np.linalg.solve(K,f)
plt.plot(nodes, solution*1e3, marker = 'o', label='%i elements' %i)
plt.legend();
# That's quite boring. Let's make the case a little bit more interesting, by giving the stiffness a variation with depth and by applying a compressive traction at the surface.
Stiffness = lambda x: 1.e8+0.8e8*np.sin(x) #Pa
sig_top = - 300e3#Pa
fig, ax = plt.subplots(ncols=2)
ax[0].set_xlabel('$x$')
ax[1].set_xlabel('$x$')
ax[0].set_ylabel('$u$ / mm')
ax[1].set_ylabel('$E$ / GPa')
nodes_per_element = 2
finest = 1000
for i in [finest,5,10,20]:
number_of_elements = i
nodes,elements,solution=generate_mesh(L,number_of_elements,nodes_per_element)
K, f = global_assembler(nodes,elements,solution)
f = apply_Neumann_bc(f,len(nodes)-1,sig_top)
K, f = apply_Dirichlet_bc(K, f, 0, 0.)
solution = np.linalg.solve(K,f)
if (i == finest):
ax[1].plot(nodes, Stiffness(nodes)/1e9, label='reference',color='black')
ax[0].plot(nodes, solution*1e3, label='reference',color='black')
else:
ax[1].plot(nodes, Stiffness(nodes)/1e9, marker = 'o', label='%i elements' %i)
ax[0].plot(nodes, solution*1e3, marker = 'o', label='%i elements' %i)
ax[0].legend();
ax[1].legend();
fig.tight_layout()
# Something similar can be done to demonstrate the effect of higher-order elements.
def run_sim(npe,ne):
nodes,elements,solution=generate_mesh(L,ne,npe)
K, f = global_assembler(nodes,elements,solution)
f = apply_Neumann_bc(f,len(nodes)-1,sig_top)
K, f = apply_Dirichlet_bc(K, f, 0, 0.)
solution = np.linalg.solve(K,f)
return nodes, solution, K
# +
fig, ax = plt.subplots(ncols=2)
ax[0].set_xlabel('$x$')
ax[1].set_xlabel('$x$')
ax[0].set_ylabel('$u$ / mm')
ax[1].set_ylabel('$E$ / GPa')
#reference
nodes, solution, matrix = run_sim(2,1000)
ax[0].plot(nodes, solution*1e3, label='reference',color='black')
ax[1].plot(nodes, Stiffness(nodes)/1e9, label='reference',color='black')
#10 linear elements
nodes, solution, matrix = run_sim(2,6)
ax[0].plot(nodes, solution*1e3, label='6 elements with 2 nodes',marker='o')
ax[1].plot(nodes, Stiffness(nodes)/1e9, label='6 elements with 2 nodes',marker='o')
#20 linear elements
nodes, solution, matrix = run_sim(2,12)
ax[0].plot(nodes, solution*1e3, label='12 elements with 2 nodes',marker='o')
ax[1].plot(nodes, Stiffness(nodes)/1e9, label='12 elements with 2 nodes',marker='o')
#10 quadratic elements
nodes, solution, matrix = run_sim(3,6)
ax[0].plot(nodes, solution*1e3, label='6 elements with 3 nodes',marker='o')
ax[1].plot(nodes, Stiffness(nodes)/1e9, label='6 elements with 3 nodes',marker='o')
ax[0].legend()
fig.tight_layout();
# -
# We see that with the same number of nodes, the higher-order approximation is better. *Note* that the lines connecting the nodal values are linear here, whereas the actual approximation between the nodes of one element is quadratic and thus smoother than shown here!
# ## Interactive playground
# +
from ipywidgets import widgets
from ipywidgets import interact
#Compute reference solution with 100 cells
nodes_ref, solution_ref, matrix_ref = run_sim(2,1000)
@interact(num_nodes=widgets.IntSlider(min=3, max=41, value=9, step=2, description='nodes'),
npes=widgets.RadioButtons(options=[2,3], value=2, description='element order',))
def plot(num_nodes=5,npes=2):
fig,ax = plt.subplots(ncols=2)
ax[0].set_xlabel('$x$')
ax[0].set_ylabel('$u$ / mm')
num_cells = int((num_nodes - 1)/(npes - 1))
x, u, matrix = run_sim(npes,num_cells)
ax[0].plot(nodes_ref, solution_ref*1e3, '--', color='k', label='reference solution');
ax[0].plot(x, u*1e3, 'o-', label=str(len(x)) + ' nodes');
ax[0].legend(loc='lower left')
ax[1].spy(matrix,marker='.')
plt.show()
# -
# And here's a convergence plot in terms of number of nodes for linear (blue) and quadratic (red) elements. We see that, despite the more complicated problem, the observed convergence order of the FEM scheme is much higher than with the FDM scheme for this type of problem.
#HIDDEN
fig, ax = plt.subplots()
disc_n = np.logspace(1,2,10)
z, analytical, K = run_sim(3,1000)
analytical_top = analytical[-1]
for nn in disc_n:
z, numerical, K = run_sim(2,int(nn))
numerical_top = numerical[-1]
relerr = np.abs((numerical_top - analytical_top)/analytical_top)
ax.plot(len(z),relerr,ls='',marker='d',color='blue')
z, numerical, K = run_sim(3,int(nn))
numerical_top = numerical[-1]
relerr = np.abs((numerical_top - analytical_top)/analytical_top)
ax.plot(len(z),relerr,ls='',marker='d',color='red')
ax.plot([5e1,1e2],[1e-3,1e-3/2],ls='-',color='black')
ax.text(1.1e2,1e-3/2,'1')
ax.plot([5e1,1e2],[1e-3,1e-3/4],ls='-',color='black')
ax.text(1.1e2,1e-3/4,'2')
ax.plot([5e1,1e2],[1e-3,1e-3/8],ls='-',color='black')
ax.text(1.1e2,1e-3/8,'3')
ax.plot([5e1,1e2],[1e-3,1e-3/16],ls='-',color='black')
ax.text(1.1e2,1e-3/16,'4')
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel('$n_\\mathrm{nodes}$')
ax.set_ylabel('$\\left| \\frac{u_z^\\mathrm{numerical} - u_z^\\mathrm{analytical}}{u_z^\\mathrm{analytical}} \\right|_{z=H}$',size=24)
fig.tight_layout();
| 06_soil_column_FEM.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: dev
# language: python
# name: dev
# ---
# # Module 10 Application
#
# ## Challenge: Crypto Investments
#
# In this Challenge, you’ll combine your financial Python programming skills with the new unsupervised learning skills that you acquired in this module.
#
# The CSV file provided for this challenge contains price change data of cryptocurrencies in different periods.
#
# The steps for this challenge are broken out into the following sections:
#
# * Import the Data (provided in the starter code)
# * Prepare the Data (provided in the starter code)
# * Cluster Cryptocurrencies with K-means
# * Find the Best Value for k
# * Optimize Clusters with Principal Component Analysis
# * Visualize the Results
# ### Import the Data
#
# This section imports the data into a new DataFrame. It follows these steps:
#
# 1. Read the “crypto_market_data.csv” file from the Resources folder into a DataFrame, and use `index_col="coin_id"` to set the cryptocurrency name as the index. Review the DataFrame.
#
# 2. Generate the summary statistics, and and use HvPlot to visualize your data to observe what your DataFrame contains.
#
#
# > **Rewind:** The [Pandas`describe()`function](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.describe.html) generates summary statistics for a DataFrame.
# Import required libraries and dependencies
import pandas as pd
import hvplot.pandas
from path import Path
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
# +
# Load the data into a Pandas DataFrame
df_market_data = pd.read_csv(
Path("../Resources/crypto_market_data.csv"),
index_col="coin_id")
# Display sample data
df_market_data.head(10)
# -
# Generate summary statistics
df_market_data.describe()
# +
# Plot your data to see what's in your DataFrame
df_market_data.hvplot.line(
width=1000,
height=700,
rot=90,
xlabel='Cryptocurrencies',
ylabel='Price Change Percentage',
line_width=2.5
)
# -
# ### Prepare the Data
#
# This section prepares the data before running the K-Means algorithm. It follows these steps:
#
# 1. Use the `StandardScaler` module from scikit-learn to normalize the CSV file data. This will require you to utilize the `fit_transform` function.
#
# 2. Create a DataFrame that contains the scaled data. Be sure to set the `coin_id` index from the original DataFrame as the index for the new DataFrame. Review the resulting DataFrame.
#
# Use the `StandardScaler()` module from scikit-learn to normalize the data from the CSV file
scaled_data = StandardScaler().fit_transform(df_market_data)
# +
# Create a DataFrame with the scaled data
df_market_data_scaled = pd.DataFrame(
scaled_data,
columns=df_market_data.columns
)
# Copy the crypto names from the original data
df_market_data_scaled["coin_id"] = df_market_data.index
# Set the coinid column as index
df_market_data_scaled = df_market_data_scaled.set_index("coin_id")
# Display sample data
df_market_data_scaled.head()
# -
# ---
# # Cluster Cryptocurrencies with K-means
#
# In this section, you will use the K-Means algorithm with a given value for `k` to cluster the cryptocurrencies according to the price changes of cryptocurrencies provided.
#
# 1. Initialize the K-Means model with four clusters (`n_clusters=4`).
#
# 2. Fit the K-Means model using the scaled data.
#
# 3. Predict the clusters to group the cryptocurrencies using the scaled data. View the resulting array of cluster values.
#
# 4. Add a new column to the DataFrame with the scaled data with the predicted clusters.
#
# 5. Create a scatter plot using hvPlot by setting `x="price_change_percentage_14d"` and `y="price_change_percentage_1y"`. Color the graph points with the labels found using K-Means and add the crypto name in the `hover_cols` parameter to identify the cryptocurrency represented by each data point.
# Initialize the K-Means model with four clusters
# YOUR CODE HERE!
kmodel = KMeans(n_clusters=4, random_state=1)
# Fit the K-Means model using the scaled data
# YOUR CODE HERE!
kmodel.fit(df_market_data_scaled)
# +
# Predict the clusters to group the cryptocurrencies using the scaled data
crypto_clusters_k4 = kmodel.predict(df_market_data_scaled)
# View the resulting array of cluster values.
print(crypto_clusters_k4)
# +
# Note: The code for this step is provided for you.
# Add a new column to the DataFrame with the predicted clusters with k=4
df_market_data_scaled["crypto_cluster_k4"] = crypto_clusters_k4
# Display sample data
df_market_data_scaled.head()
# +
# Create a scatter plot using hvPlot by setting
# `x="price_change_percentage_14d"` and `y="price_change_percentage_1y"`.
# Group the results by the clusters using `by="crypto_cluster_k4".
# Set the hover to the coin id using `hover_cols=["coin_id"]`.
df_market_data_scaled.hvplot.scatter(
x="price_change_percentage_14d",
y="price_change_percentage_1y",
by="crypto_cluster_k4",
hover_cols=["coin_id"],
marker=["hex", "square", "cross", "inverted_triangle", "triangle"],
)
# -
# ---
# # Find the Best Value for k
#
# In this section, you will use the elbow method to find the best value for k.
#
# 1. Code the elbow method algorithm to find the best value for k. Use a range from 1 to 11.
#
# 2. Plot a line chart with all the inertia values computed with the different values of k to visually identify the optimal value for k.
#
# 3. Answer the following question: What is the best value for k?
# Create a list with the number of k-values to try
# Use a range from 1 to 11
k = list(range(1, 11))
# Create an empy list to store the inertia values
inertia = []
# Create a for loop to compute the inertia with each possible value of k
# Inside the loop:
# 1. Create a KMeans model using the loop counter for the n_clusters
# 2. Fit the model to the data using `df_market_data_scaled`
# 3. Append the model.inertia_ to the inirtia list
# YOUR CODE HERE!
for i in k:
k_model = KMeans(n_clusters=i, random_state=0)
k_model.fit(df_market_data_scaled)
inertia.append(k_model.inertia_)
# +
# Create a dictionary with the data to plot the Elbow curve
elbow_data = {
"k": k,
"inertia": inertia
}
# Create a DataFrame with the data to plot the Elbow curve
df_elbow = pd.DataFrame(elbow_data)
# -
# Plot a line chart with all the inertia values computed with
# the different values of k to visually identify the optimal value for k.
# YOUR CODE HERE!
df_elbow.hvplot.line(
x="k",
y="inertia",
title="Elbow Curve",
xticks=k
)
# #### 3. Answer the following question: What is the best value for k?
# **Question:** What is the best value for `k`?
#
# **Answer:** The best values for k, that is the number is clusters is indeed five.
# The best value for k is five. K = 5.
# ---
# # Optimize Clusters with Principal Component Analysis
#
# In this section, you will perform a principal component analysis (PCA) and reduce the features to three principal components.
#
# 1. Create a PCA model instance and set `n_components=3`.
#
# 2. Use the PCA model to reduce to three principal components. View the first five rows of the DataFrame.
#
# 3. Retrieve the explained variance to determine how much information can be attributed to each principal component.
#
# 4. Answer the following question: What is the total explained variance of the three principal components?
#
# 5. Create a new DataFrame with the PCA data. Be sure to set the `coin_id` index from the original DataFrame as the index for the new DataFrame. Review the resulting DataFrame.
#
# 6. Initiate a new K-Means algorithm using the PCA DataFrame to group the cryptocurrencies. Set the `n_components` parameter equal to the best value for `k` found before. View the resulting array.
#
# 7. For further analysis, add the following columns to the DataFrame with the PCA data. Review the resulting DataFrame once the additional columns have been added. Make sure to do the following:
#
# - From the original DataFrame, add the `price_change_percentage_1y` and `price_change_percentage_14d` columns.
#
# - Add a column with the predicted cluster values identified using a k value of 4. (The predicted cluster values were calculated in the “Cluster Cryptocurrencies with K-means” section.)
#
# - Add a column with the predicted cluster values identified using the optimal value for k.
#
# Create a PCA model instance and set `n_components=3`.
# YOUR CODE HERE!
pca=PCA(n_components=3)
# +
# Use the PCA model with `fit_transform` to reduce to
# three principal components.
# YOUR CODE HERE!
market_pca_data = pca.fit_transform(df_market_data_scaled)
# View the first five rows of the DataFrame.
market_pca_data[:5]
# +
# Retrieve the explained variance to determine how much information
# can be attributed to each principal component.
# YOUR CODE HERE!
pca.explained_variance_ratio_
# -
# Answer the following question: What is the total explained variance of the three principal components?
#
# **Question** What is the total explained variance of the three principal components?
#
# **Answer** YOUR ANSWER HERE!
#
# The total explained variance of the three principal components is 0.8844285111826466S
# +
# total explained variance of the three principal components
pca.explained_variance_ratio_.sum()
# +
# Create a new DataFrame with the PCA data.
# Creating a DataFrame with the PCA data
df_market_data_pca = pd.DataFrame(
market_pca_data,
columns=["PC1", "PC2", "PC3"]
)
# Copy the crypto names from the original data
df_market_data_pca["coin_id"] = df_market_data.index
# Set the coinid column as index
df_market_data_pca = df_market_data_pca.set_index("coin_id")
# Display sample data
df_market_data_pca.head()
# +
# Initiate a new K-Means algorithm using the PCA DataFrame to group
# the cryptocurrencies. Set the `n_components` parameter equal to
# the best value for `k` found before. View the resulting array.
# Initialize the K-Means model
# YOUR CODE HERE!
nmodel = KMeans(n_clusters=4, random_state=1)
# Fit the model
# YOUR CODE HERE!
nmodel.fit(df_market_data_pca)
# Predict clusters
crypto_clusters_k5 = nmodel.predict(df_market_data_pca)
# YOUR CODE HERE!
# View the resulting array
crypto_clusters_k5
# +
# For further analysis, add the following columns to the DataFrame
# with the PCA data. Review the resulting DataFrame once the additional
# columns have been added. Make sure to do the following:
# - From the original DataFrame, add the `price_change_percentage_1y` and `price_change_percentage_14d` columns.
# - Add a column with the predicted cluster values identified using a k value of 4. (The predicted cluster values were calculated in the “Cluster Cryptocurrencies with K-means” section.)
# - Add a column with the predicted cluster values identified using the optimal value for k.
# Add the price_change_percentage_1y column from the original data
df_market_data_pca["price_change_percentage_1y"] = df_market_data["price_change_percentage_1y"]
# Add the price_change_percentage_14d column from the original data
df_market_data_pca["price_change_percentage_14d"] = df_market_data["price_change_percentage_14d"]
# Add a new column to the DataFrame with the predicted clusters using the best value of k
df_market_data_pca["crypto_cluster_k5"] = crypto_clusters_k5
# Add a new column to the DataFrame with the predicted clusters using k=4
df_market_data_pca["crypto_cluster_k4"] = crypto_clusters_k4
# Display sample data
df_market_data_pca.head()
# -
# ---
# # Step 6: Plot Results
#
# In this section, you will visually analyze the cluster analysis results after using the optimization techniques.
#
# 1. Use the PCA data to create two scatter plots using hvPlot by setting `x="price_change_percentage_14d"` and `y="price_change_percentage_1y"`. Make sure to do the following:
#
# - In the first plot, color the plot points by the cluster values identified using a k value of 4.
#
# - In the second plot, color the plot points by the cluster values identified using the optimal value for k.
#
# - In both plots, add the crypto name by sing the `hover_cols` parameter to identify the cryptocurrency represented by each data point.
#
# 2. Be sure to professionally style and format the plots so that the visualizations can be easily read.
#
# 3. Answer the following question: What value of k creates the most accurate clusters of cryptocurrencies, grouped by profitability?
#
# +
# Create a scatter plot for the Crypto Clusters using k=4 data.
# Use the PCA data to create a scatter plot with hvPlot by setting
# x="price_change_percentage_14d" and y="price_change_percentage_1y".
# Group by the clusters using `by="crypto_cluster_k4".
# Set the hover colors to the coin id with `hover_cols=["coin_id"]
# Create a descriptive title for the plot using the title parameter.
# YOUR CODE HERE!
scatter_plot_k4 = df_market_data_scaled.hvplot.scatter(
x="price_change_percentage_14d",
y="price_change_percentage_1y",
by="crypto_cluster_k4",
hover_cols=["coin_id"])
scatter_plot_k4
# -
# Create a scatter plot for the Crypto Clusters using k=5 data.
# Use the PCA data to create a scatter plot with hvPlot by setting
# x="price_change_percentage_14d" and y="price_change_percentage_1y".
# Group by the clusters using `by="crypto_cluster_k5".
# Set the hover colors to the coin id with `hover_cols=["coin_id"]
# Create a descriptive title for the plot using the title parameter.
# YOUR CODE HERE!
scatter_plot_k5 = df_market_data_pca.hvplot.scatter(
x="price_change_percentage_14d",
y="price_change_percentage_1y",
by="crypto_cluster_k5",
hover_cols=["coin_id"])
scatter_plot_k5
# Compare both scatter plots
display(scatter_plot_k4)
display(scatter_plot_k5)
# Answer the following question: What value of k creates the most accurate clusters of cryptocurrencies, grouped by profitability?
#
# **Question:** What value of `k` seems to create the most accurate clusters to group cryptocurrencies according to their profitability?
#
# **Answer:** YOUR ANSWER HERE!
# The value for k that seems to create the most accurate clusters grouping cryptocurrencies according to profitability is 4.
# K = 4
| Starter_Code/crypto_investment_final_draft.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
# ---
# # Линейная регрессия и стохастический градиентный спуск
# Задание основано на материалах лекций по линейной регрессии и градиентному спуску. Вы будете прогнозировать выручку компании в зависимости от уровня ее инвестиций в рекламу по TV, в газетах и по радио.
# ## Вы научитесь:
# - решать задачу восстановления линейной регрессии
# - реализовывать стохастический градиентный спуск для ее настройки
# - решать задачу линейной регрессии аналитически
# ## Введение
# Линейная регрессия - один из наиболее хорошо изученных методов машинного обучения, позволяющий прогнозировать значения количественного признака в виде линейной комбинации прочих признаков с параметрами - весами модели. Оптимальные (в смысле минимальности некоторого функционала ошибки) параметры линейной регрессии можно найти аналитически с помощью нормального уравнения или численно с помощью методов оптимизации.
# Линейная регрессия использует простой функционал качества - среднеквадратичную ошибку. Мы будем работать с выборкой, содержащей 3 признака. Для настройки параметров (весов) модели решается следующая задача:
# $$\Large \frac{1}{\ell}\sum_{i=1}^\ell{{((w_0 + w_1x_{i1} + w_2x_{i2} + w_3x_{i3}) - y_i)}^2} \rightarrow \min_{w_0, w_1, w_2, w_3},$$
# где $x_{i1}, x_{i2}, x_{i3}$ - значения признаков $i$-го объекта, $y_i$ - значение целевого признака $i$-го объекта, $\ell$ - число объектов в обучающей выборке.
# ## Градиентный спуск
# Параметры $w_0, w_1, w_2, w_3$, по которым минимизируется среднеквадратичная ошибка, можно находить численно с помощью градиентного спуска.
# Градиентный шаг для весов будет выглядеть следующим образом:
# $$\Large w_0 \leftarrow w_0 - \frac{2\eta}{\ell} \sum_{i=1}^\ell{{((w_0 + w_1x_{i1} + w_2x_{i2} + w_3x_{i3}) - y_i)}}$$
# $$\Large w_j \leftarrow w_j - \frac{2\eta}{\ell} \sum_{i=1}^\ell{{x_{ij}((w_0 + w_1x_{i1} + w_2x_{i2} + w_3x_{i3}) - y_i)}},\ j \in \{1,2,3\}$$
# Здесь $\eta$ - параметр, шаг градиентного спуска.
# ## Стохастический градиентный спуск
# Проблема градиентного спуска, описанного выше, в том, что на больших выборках считать на каждом шаге градиент по всем имеющимся данным может быть очень вычислительно сложно.
# В стохастическом варианте градиентного спуска поправки для весов вычисляются только с учетом одного случайно взятого объекта обучающей выборки:
# $$\Large w_0 \leftarrow w_0 - \frac{2\eta}{\ell} {((w_0 + w_1x_{k1} + w_2x_{k2} + w_3x_{k3}) - y_k)}$$
# $$\Large w_j \leftarrow w_j - \frac{2\eta}{\ell} {x_{kj}((w_0 + w_1x_{k1} + w_2x_{k2} + w_3x_{k3}) - y_k)},\ j \in \{1,2,3\},$$
# где $k$ - случайный индекс, $k \in \{1, \ldots, \ell\}$.
# ## Нормальное уравнение
# Нахождение вектора оптимальных весов $w$ может быть сделано и аналитически.
# Мы хотим найти такой вектор весов $w$, чтобы вектор $y$, приближающий целевой признак, получался умножением матрицы $X$ (состоящей из всех признаков объектов обучающей выборки, кроме целевого) на вектор весов $w$. То есть, чтобы выполнялось матричное уравнение:
# $$\Large y = Xw$$
# Домножением слева на $X^T$ получаем:
# $$\Large X^Ty = X^TXw$$
# Это хорошо, поскольку теперь матрица $X^TX$ - квадратная, и можно найти решение (вектор $w$) в виде:
# $$\Large w = {(X^TX)}^{-1}X^Ty$$
# Матрица ${(X^TX)}^{-1}X^T$ - [*псевдообратная*](https://ru.wikipedia.org/wiki/Псевдообратная_матрица) для матрицы $X$. В NumPy такую матрицу можно вычислить с помощью функции [numpy.linalg.pinv](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.linalg.pinv.html).
#
# Однако, нахождение псевдообратной матрицы - операция вычислительно сложная и нестабильная в случае малого определителя матрицы $X$ (проблема мультиколлинеарности).
# На практике лучше находить вектор весов $w$ решением матричного уравнения
# $$\Large X^TXw = X^Ty$$Это может быть сделано с помощью функции [numpy.linalg.solve](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.linalg.solve.html).
#
# Но все же на практике для больших матриц $X$ быстрее работает градиентный спуск, особенно его стохастическая версия.
# ## Инструкции по выполнению
# В начале напишем простую функцию для записи ответов в текстовый файл. Ответами будут числа, полученные в ходе решения этого задания, округленные до 3 знаков после запятой. Полученные файлы после выполнения задания надо отправить в форму на странице задания на Coursera.org.
def write_answer_to_file(answer, filename):
with open(filename, 'w') as f_out:
f_out.write(str(round(answer, 3)))
# **1. Загрузите данные из файла *advertising.csv* в объект pandas DataFrame. [Источник данных](http://www-bcf.usc.edu/~gareth/ISL/data.html).**
import pandas as pd
adver_data = pd.read_csv('advertising.csv')
# **Посмотрите на первые 5 записей и на статистику признаков в этом наборе данных.**
import numpy as np
print(adver_data.head(5))
# **Создайте массивы NumPy *X* из столбцов TV, Radio и Newspaper и *y* - из столбца Sales. Используйте атрибут *values* объекта pandas DataFrame.**
X = adver_data.drop("Sales", axis=1).values
y = adver_data.Sales.values
print(y[: 5])
print(X[: 5])
# **Отмасштабируйте столбцы матрицы *X*, вычтя из каждого значения среднее по соответствующему столбцу и поделив результат на стандартное отклонение. Для определенности, используйте методы mean и std векторов NumPy (реализация std в Pandas может отличаться). Обратите внимание, что в numpy вызов функции .mean() без параметров возвращает среднее по всем элементам массива, а не по столбцам, как в pandas. Чтобы произвести вычисление по столбцам, необходимо указать параметр axis.**
a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(a[0, 2])
s = np.std(X[:, 1])
print(s)
means, stds = np.mean(X,axis=0), np.std(X, axis=0)
print(f"means = {means}\nstds = {stds}")
# +
X = np.array([(X[:, 0] - means[0]) / stds[0],
(X[:, 1] - means[1]) / stds[1],
(X[:, 2] - means[2]) / stds[2]]).T
print("X:\n", X[:5])
# -
# **Добавьте к матрице *X* столбец из единиц, используя методы *hstack*, *ones* и *reshape* библиотеки NumPy. Вектор из единиц нужен для того, чтобы не обрабатывать отдельно коэффициент $w_0$ линейной регрессии.**
print()
print()
A =X
X = np.insert(X, 0, np.ones(X[:,0].size), axis=1)#np.append(X, np.reshape(np.ones(X[:,0].size), (200, 1)), axis=1)
print(X[:5])
# **2. Реализуйте функцию *mserror* - среднеквадратичную ошибку прогноза. Она принимает два аргумента - объекты Series *y* (значения целевого признака) и *y\_pred* (предсказанные значения). Не используйте в этой функции циклы - тогда она будет вычислительно неэффективной.**
a = np.array([1, 2, 3])
b = np.array([2, 2, 3])
print(mserror(a, b))
def mserror(y, y_pred):
return sum((y_pred - y)**2)/len(y)
# **Какова среднеквадратичная ошибка прогноза значений Sales, если всегда предсказывать медианное значение Sales по исходной выборке? Запишите ответ в файл '1.txt'.**
answer1 = mserror(y, np.ones(y.size)*np.median(y))
print(answer1)
write_answer_to_file(answer1, '1.txt')
# **3. Реализуйте функцию *normal_equation*, которая по заданным матрицам (массивам NumPy) *X* и *y* вычисляет вектор весов $w$ согласно нормальному уравнению линейной регрессии.**
X_T = X.T
print(X_T.shape)
Y = X_T.dot(y)
print(np.linalg.inv(X.T.dot(X)).dot(X.T.dot(y)))
print(np.linalg.pinv(X).dot(y))
w = np.linalg.solve(X.T.dot(X), X.T.dot(y))
print(w)
print(np.allclose(X.dot(w), y))
print(X.dot(w)[:5])
print(y[:5])
def normal_equation(big_x, y):
return np.linalg.inv(np.dot(big_x.T, big_x)).dot(np.dot(big_x.T, y)) # Ваш код здесь
norm_eq_weights = normal_equation(X, y)
print(norm_eq_weights)
# **Какие продажи предсказываются линейной моделью с весами, найденными с помощью нормального уравнения, в случае средних инвестиций в рекламу по ТВ, радио и в газетах? (то есть при нулевых значениях масштабированных признаков TV, Radio и Newspaper). Запишите ответ в файл '2.txt'.**
answer2 = np.dot(np.array([1, 0, 0, 0]), norm_eq_weights)
print(answer2)
write_answer_to_file(answer2, '2.txt')
# **4. Напишите функцию *linear_prediction*, которая принимает на вход матрицу *X* и вектор весов линейной модели *w*, а возвращает вектор прогнозов в виде линейной комбинации столбцов матрицы *X* с весами *w*.**
def linear_prediction(X, w):
return np.dot(X, w)
# **Какова среднеквадратичная ошибка прогноза значений Sales в виде линейной модели с весами, найденными с помощью нормального уравнения? Запишите ответ в файл '3.txt'.**
answer3 = mserror(y, linear_prediction(X, norm_eq_weights))
print(answer3)
write_answer_to_file(answer3, '3.txt')
# **5. Напишите функцию *stochastic_gradient_step*, реализующую шаг стохастического градиентного спуска для линейной регрессии. Функция должна принимать матрицу *X*, вектора *y* и *w*, число *train_ind* - индекс объекта обучающей выборки (строки матрицы *X*), по которому считается изменение весов, а также число *$\eta$* (eta) - шаг градиентного спуска (по умолчанию *eta*=0.01). Результатом будет вектор обновленных весов. Наша реализация функции будет явно написана для данных с 3 признаками, но несложно модифицировать для любого числа признаков, можете это сделать.**
print(X[:, 0].size)
print(1999%1000)
print(999%1000)
def stochastic_gradient_step(X, y, w, train_ind, eta=0.01):
grad0 = (2 / X[:, 0].size) * ((w[3] + w[0]*X[train_ind, 0] + w[1]*X[train_ind, 1] + w[2]*X[train_ind, 2]) - y[train_ind])# Ваш код здесь
grad1 = grad0 * X[train_ind, 1]# Ваш код здесь
grad2 = grad0 * X[train_ind, 2]# Ваш код здесь
grad3 = grad0 * X[train_ind, 3]# Ваш код здесь
return w - eta * np.array([grad0, grad1, grad2, grad3])
# **6. Напишите функцию *stochastic_gradient_descent*, реализующую стохастический градиентный спуск для линейной регрессии. Функция принимает на вход следующие аргументы:**
# - X - матрица, соответствующая обучающей выборке
# - y - вектор значений целевого признака
# - w_init - вектор начальных весов модели
# - eta - шаг градиентного спуска (по умолчанию 0.01)
# - max_iter - максимальное число итераций градиентного спуска (по умолчанию 10000)
# - max_weight_dist - максимальное евклидово расстояние между векторами весов на соседних итерациях градиентного спуска,
# при котором алгоритм прекращает работу (по умолчанию 1e-8)
# - seed - число, используемое для воспроизводимости сгенерированных псевдослучайных чисел (по умолчанию 42)
# - verbose - флаг печати информации (например, для отладки, по умолчанию False)
#
# **На каждой итерации в вектор (список) должно записываться текущее значение среднеквадратичной ошибки. Функция должна возвращать вектор весов $w$, а также вектор (список) ошибок.**
def stochastic_gradient_descent(X, y, w_init, eta=1e-2, max_iter=1e4,
min_weight_dist=1e-8, seed=42, verbose=False):
# Инициализируем расстояние между векторами весов на соседних
# итерациях большим числом.
weight_dist = np.inf
# Инициализируем вектор весов
w = w_init
# Сюда будем записывать ошибки на каждой итерации
errors = []
# Счетчик итераций
iter_num = 0
# Будем порождать псевдослучайные числа
# (номер объекта, который будет менять веса), а для воспроизводимости
# этой последовательности псевдослучайных чисел используем seed.
np.random.seed(seed)
# Основной цикл
while weight_dist > min_weight_dist and iter_num < max_iter:
# порождаем псевдослучайный
# индекс объекта обучающей выборки
random_ind = np.random.randint(X.shape[0])
w1 = stochastic_gradient_step(X, y, w, random_ind)# Ваш код здесь
errors.append(mserror(y, linear_prediction(X, w1)))
if errors[iter_num] <= errors[iter_num -1] and len(errors) != 0:
w = w1
if (iter_num % 10000 == 0) and verbose:
print(f"iter_num = {iter_num}\nw = {w}\nerror = {errors[iter_num]}\n")
iter_num += 1
return w, errors
# **Запустите $10^5$ итераций стохастического градиентного спуска. Укажите вектор начальных весов *w_init*, состоящий из нулей. Оставьте параметры *eta* и *seed* равными их значениям по умолчанию (*eta*=0.01, *seed*=42 - это важно для проверки ответов).**
# %%time
w_init = [0, 0, 0, 0]
stoch_grad_desc_weights, stoch_errors_by_iter = stochastic_gradient_descent(X, y, w_init, eta=1e-2, max_iter=1e6,
min_weight_dist=1e-8, seed=42, verbose=True)# Ваш код здесь
# **Посмотрим, чему равна ошибка на первых 50 итерациях стохастического градиентного спуска. Видим, что ошибка не обязательно уменьшается на каждой итерации.**
# %pylab inline
plot(range(50), stoch_errors_by_iter[:50])
xlabel('Iteration number')
ylabel('MSE')
# **Теперь посмотрим на зависимость ошибки от номера итерации для $10^5$ итераций стохастического градиентного спуска. Видим, что алгоритм сходится.**
# %pylab inline
plot(range(len(stoch_errors_by_iter)), stoch_errors_by_iter)
xlabel('Iteration number')
ylabel('MSE')
# **Посмотрим на вектор весов, к которому сошелся метод.**
stoch_grad_desc_weights
# **Посмотрим на среднеквадратичную ошибку на последней итерации.**
stoch_errors_by_iter[-1]
# **Какова среднеквадратичная ошибка прогноза значений Sales в виде линейной модели с весами, найденными с помощью градиентного спуска? Запишите ответ в файл '4.txt'.**
answer4 = mserror(y, linear_prediction(X, stoch_grad_desc_weights))# Ваш код здесь
print(answer4)
write_answer_to_file(answer4, '4.txt')
# **Ответами к заданию будут текстовые файлы, полученные в ходе этого решения. Обратите внимание, что отправленные файлы не должны содержать пустую строку в конце. Данный нюанс является ограничением платформы Coursera. Мы работаем над исправлением этого ограничения.**
| LearningOnMarkedData/week1/c02_w01_02.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
# ---
# # 7.4 Venturi Type Valves
# A 150 by 100 mm class 600 steel gate valve, conically tapered ports, length 550 mm, back of seat ring ~150 mm. The valve is connected to 146 mm schedule 80 pipe. The angle can be calculated to be 13 degrees. The valve is specified to be operating in turbulent conditions.
# +
from fluids.units import *
D1 = 100*u.mm
D2 = 146*u.mm
angle = 13.115*u.degrees
fd = friction_factor(Re=1E5, eD=.0018*u.inch/D1)
K2 = K_gate_valve_Crane(D1, D2, angle, fd)
L_D = L_equiv_from_K(K2, fd)
L = (L_D*D2).to(u.m)
print('Darcy friction factor = %s' %fd)
print('K2 = %s' %K2)
print('Equivalent length L_D = %s' %L_D)
print('Length for flow in complete turbulence = %s' %L)
# -
# The values calculated in the problem use a friction factor of 0.015; this is the source of the discrepancies. Their procedure for loss in valves and fittings is based around the roughness of commercial steel pipe with a roughness of 0.0018 inches, but in their examples they simply look their friction factors up in a table which does not consider the diameter of the pipe.
# Their calculated values are K2 = 1.22, L/D=81.3, and L = 11.9.
| docs/Examples/Crane TP 410 Solved Problems/7.4 Venturi Type Valves.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="JS6jP7tpCrLr" colab_type="text"
# ## Digit Recognizer
# Learn computer vision fundamentals with the famous MNIST dat
#
# https://www.kaggle.com/c/digit-recognizer
#
# ### Competition Description
# MNIST ("Modified National Institute of Standards and Technology") is the de facto “hello world” dataset of computer vision. Since its release in 1999, this classic dataset of handwritten images has served as the basis for benchmarking classification algorithms. As new machine learning techniques emerge, MNIST remains a reliable resource for researchers and learners alike.
#
# In this competition, your goal is to correctly identify digits from a dataset of tens of thousands of handwritten images. We’ve curated a set of tutorial-style kernels which cover everything from regression to neural networks. We encourage you to experiment with different algorithms to learn first-hand what works well and how techniques compare.
#
# ### Practice Skills
# Computer vision fundamentals including simple neural networks
#
# Classification methods such as SVM and K-nearest neighbors
#
# #### Acknowledgements
# More details about the dataset, including algorithms that have been tried on it and their levels of success, can be found at http://yann.lecun.com/exdb/mnist/index.html. The dataset is made available under a Creative Commons Attribution-Share Alike 3.0 license.
# -
# Select tensorflow 1.x (colab only)
# %tensorflow_version 1.x
# + id="LgcAAVmXgBPm" colab_type="code" colab={}
import pandas as pd
import math
import numpy as np
import matplotlib.pyplot as plt, matplotlib.image as mpimg
from sklearn.model_selection import train_test_split
import tensorflow as tf
# %matplotlib inline
# + id="EITzxKZRgBPy" colab_type="code" colab={}
from tensorflow import keras
from tensorflow.keras import models
from tensorflow.keras import losses,optimizers,metrics
from tensorflow.keras import layers
# + [markdown] id="4PihLjAggBP1" colab_type="text"
# ## Data Preparation
# + id="cra90fdEsmsI" colab_type="code" outputId="d873fca1-d2d0-40dc-9c09-9cb07b14a591" colab={"base_uri": "https://localhost:8080/", "height": 34}
from google.colab import drive
drive.mount('/content/gdrive')
# + id="K58DeQH2gBP2" colab_type="code" colab={}
labeled_images = pd.read_csv('gdrive/My Drive/dataML/train.csv')
#labeled_images = pd.read_csv('train.csv')
images = labeled_images.iloc[:,1:]
labels = labeled_images.iloc[:,:1]
train_images, test_images,train_labels, test_labels = train_test_split(images, labels, test_size=0.01)
# + id="At9soAW0qOs4" colab_type="code" outputId="f4fa52ce-be55-4e43-dccc-e72632b8fe93" colab={"base_uri": "https://localhost:8080/", "height": 85}
print(train_images.shape)
print(train_labels.shape)
print(test_images.shape)
print(test_labels.shape)
# + [markdown] id="f87cEn1_xfqI" colab_type="text"
# ## Keras
# + [markdown] id="UfkBgDM1gBP5" colab_type="text"
# #### convert the data to the right type
# + id="-X3Uu-o_gBP6" colab_type="code" colab={}
x_train = train_images.values.reshape(train_images.shape[0],28,28,1)
x_test = test_images.values.reshape(test_images.shape[0],28,28,1)
y_train = train_labels.values
y_test = test_labels.values
# + id="7vboLIlsgBP9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 282} outputId="b12b1420-306e-4486-a168-7e5da894cb45"
plt.imshow(x_train[12].squeeze())
# + [markdown] id="b6I1adl5gBQD" colab_type="text"
# #### convert the data to the right type
# + id="GAIvNCv6gBQE" colab_type="code" outputId="e6f42659-0766-4f2c-df33-fba496026756" colab={"base_uri": "https://localhost:8080/", "height": 68}
x_train = train_images
x_test = test_images
x_train /= 255
x_test /= 255
y_train = train_labels
y_test = test_labels
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# + [markdown] id="xeMZR7ntgBQI" colab_type="text"
# ### convert class vectors to binary class matrices - this is for use in the
# ### categorical_crossentropy loss below
# + id="8e2qjHPLgBQJ" colab_type="code" colab={}
y_train = keras.utils.to_categorical(y_train)
y_test = keras.utils.to_categorical(y_test)
# + [markdown] id="LT78eGccgBQN" colab_type="text"
# ### Creating the Model
#
# + id="AMOStnPCFWSI" colab_type="code" outputId="67e94478-d67d-40c4-e1c6-b1f9840d6c3e" colab={"base_uri": "https://localhost:8080/", "height": 513}
model = models.Sequential()
model.add(layers.Dense(units=200, activation='relu',input_shape=(784,)))
model.add(layers.Dropout(0.25))
model.add(layers.Dense(units=100, activation='relu'))
model.add(layers.Dropout(0.25))
model.add(layers.Dense(units=60, activation='relu'))
model.add(layers.Dropout(0.25))
model.add(layers.Dense(units=30, activation='relu'))
model.add(layers.Dropout(0.25))
model.add(layers.Dense(units=10, activation='softmax'))
model.summary()
# + id="BLdOV8vYgBQS" colab_type="code" colab={}
adam = keras.optimizers.Adam(lr = 0.0001)
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=adam,
metrics=['accuracy'])
# + id="pxI5Gi4xgBQV" colab_type="code" outputId="8f81e033-49ed-4cbb-bb7b-0bb92596fc75" colab={"base_uri": "https://localhost:8080/", "height": 10234}
H = model.fit(x_train, y_train,
batch_size=100,
epochs=300,
verbose=1,
validation_data=(x_test, y_test))
# + id="CHDGYz_Mki4G" colab_type="code" outputId="1b6c61da-3632-4606-e1e0-3c829e1c58a9" colab={"base_uri": "https://localhost:8080/", "height": 34}
H.history.keys()
# + id="G1s_nCBWk-91" colab_type="code" outputId="b4917a58-50f3-4500-8851-9ba90db6cf34" colab={"base_uri": "https://localhost:8080/", "height": 282}
plt.plot(H.history['acc'])
plt.plot(H.history['val_acc'],'r')
# + id="-AGE67k2lGxL" colab_type="code" outputId="e1ce36c6-50c0-4b3a-81ea-4fa7861d5e8b" colab={"base_uri": "https://localhost:8080/", "height": 282}
plt.plot(H.history['loss'])
plt.plot(H.history['val_loss'],'r')
# + [markdown] id="4RIGVSojmy-R" colab_type="text"
# ### Predict
# + id="tnigE74rm39a" colab_type="code" colab={}
unlabeled_images_test = pd.read_csv('gdrive/My Drive/dataML/test.csv')
#unlabeled_images_test = pd.read_csv('test.csv')
# + id="3Fotf1KrpXVE" colab_type="code" colab={}
X_unlabeled = unlabeled_images_test.values.reshape(unlabeled_images_test.shape[0],28,28,1)/255
# + id="jeRnCHzdutQ0" colab_type="code" colab={}
y_pred = model.predict(X_unlabeled)
# + id="3M_fePteu-3X" colab_type="code" colab={}
y_label = np.argmax(y_pred, axis=1)
# + [markdown] id="RX5PuSUmvRri" colab_type="text"
# ### Save csv
# + id="zU5Q1fSRvVbn" colab_type="code" colab={}
imageId = np.arange(1,y_label.shape[0]+1).tolist()
prediction_pd = pd.DataFrame({'ImageId':imageId, 'Label':y_label})
prediction_pd.to_csv('gdrive/My Drive/dataML/out_cnn05.csv',sep = ',', index = False)
# + [markdown] id="_qetEX7AgBQY" colab_type="text"
# # Tensorflow
# + [markdown] id="4keUL7d0gBQZ" colab_type="text"
# ### Helper functions for batch learning
# + id="czdbjPfcgBQd" colab_type="code" colab={}
def one_hot_encode(vec, vals=10):
'''
For use to one-hot encode the 10- possible labels
'''
n = len(vec)
out = np.zeros((n, vals))
out[range(n), vec] = 1
return out
# + id="Afc2XmK2gBQh" colab_type="code" colab={}
class CifarHelper():
def __init__(self):
self.i = 0
# Intialize some empty variables for later on
self.training_images = None
self.training_labels = None
self.test_images = None
self.test_labels = None
def set_up_images(self):
print("Setting Up Training Images and Labels")
# Vertically stacks the training images
self.training_images = train_images.as_matrix()
train_len = self.training_images.shape[0]
# Reshapes and normalizes training images
self.training_images = self.training_images.reshape(train_len,28,28,1)/255
# One hot Encodes the training labels (e.g. [0,0,0,1,0,0,0,0,0,0])
self.training_labels = one_hot_encode(train_labels.as_matrix().reshape(-1), 10)
print("Setting Up Test Images and Labels")
# Vertically stacks the test images
self.test_images = test_images.as_matrix()
test_len = self.test_images.shape[0]
# Reshapes and normalizes test images
self.test_images = self.test_images.reshape(test_len,28,28,1)/255
# One hot Encodes the test labels (e.g. [0,0,0,1,0,0,0,0,0,0])
self.test_labels = one_hot_encode(test_labels.as_matrix().reshape(-1), 10)
def next_batch(self, batch_size):
# Note that the 100 dimension in the reshape call is set by an assumed batch size of 100
x = self.training_images[self.i:self.i+batch_size]
y = self.training_labels[self.i:self.i+batch_size]
self.i = (self.i + batch_size) % len(self.training_images)
return x, y
# + id="1qAiPT1-gBQp" colab_type="code" outputId="77cb7989-501e-41d6-84a5-e65cef94fd1f" colab={"base_uri": "https://localhost:8080/", "height": 51}
# Before Your tf.Session run these two lines
ch = CifarHelper()
ch.set_up_images()
# During your session to grab the next batch use this line
# (Just like we did for mnist.train.next_batch)
# batch = ch.next_batch(100)
# + [markdown] id="QUkUv8sKgBQw" colab_type="text"
# ## Creating the Model
#
#
# + [markdown] id="l1XSMzIpgBQx" colab_type="text"
# ** Create 2 placeholders, x and y_true. Their shapes should be: **
#
# * X shape = [None,28,28,1]
# * Y_true shape = [None,10]
#
# ** Create three more placeholders
# * lr: learning rate
# * step:for learning rate decay
# * drop_rate
# + id="8Y_4DDQvgBQz" colab_type="code" colab={}
X = tf.placeholder(tf.float32, shape=[None,28,28,1])
Y_true = tf.placeholder(tf.float32, shape=[None,10])
lr = tf.placeholder(tf.float32)
step = tf.placeholder(tf.int32)
drop_rate = tf.placeholder(tf.float32)
# + [markdown] id="5egQVsS4NhxW" colab_type="text"
# ### Initialize Weights and bias
# Five layers with 200, 100, 60, 30 and 10 neurons
# + id="RQ_UDA08dBcN" colab_type="code" colab={}
L = 200
M = 100
N = 60
O = 30
# + id="xiVQdlDsN1W-" colab_type="code" colab={}
W1 = tf.Variable(tf.truncated_normal([784, L], stddev=0.1)) # 784 = 28 * 28
B1 = tf.Variable(tf.ones([L])/10)
W2 = tf.Variable(tf.truncated_normal([L, M], stddev=0.1))
B2 = tf.Variable(tf.ones([M])/10)
W3 = tf.Variable(tf.truncated_normal([M, N], stddev=0.1))
B3 = tf.Variable(tf.ones([N])/10)
W4 = tf.Variable(tf.truncated_normal([N, O], stddev=0.1))
B4 = tf.Variable(tf.ones([O])/10)
W5 = tf.Variable(tf.truncated_normal([O, 10], stddev=0.1))
B5 = tf.Variable(tf.zeros([10]))
# + [markdown] id="u4RDJq8pO_Og" colab_type="text"
# ### layers
# + id="x52yDbi6bCMb" colab_type="code" colab={}
XX = tf.reshape(X,[-1,784])
# + id="DM5_O098O4Di" colab_type="code" colab={}
Y1 = tf.nn.relu(tf.matmul(XX, W1) + B1)
Y1d = tf.nn.dropout(Y1,rate = drop_rate)
Y2 = tf.nn.relu(tf.matmul(Y1, W2) + B2)
Y2d = tf.nn.dropout(Y2,rate = drop_rate)
Y3 = tf.nn.relu(tf.matmul(Y2, W3) + B3)
Y3d = tf.nn.dropout(Y3,rate = drop_rate)
Y4 = tf.nn.relu(tf.matmul(Y3, W4) + B4)
Y4d = tf.nn.dropout(Y4,rate = drop_rate)
Ylogits = tf.matmul(Y4d, W5) + B5
Y = tf.nn.softmax(Ylogits)
# + [markdown] id="tT4TvNz-gBRI" colab_type="text"
# ### Loss Function
# + id="wkqQ5GurgBRJ" colab_type="code" colab={}
#cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=Y_true,logits=Ylogits))
cross_entropy = tf.losses.softmax_cross_entropy(onehot_labels = Y_true, logits = Ylogits)
#cross_entropy = -tf.reduce_mean(y_true * tf.log(Ylogits)) * 1000.0
# + [markdown] id="jmnEUVWxgBRM" colab_type="text"
# ### Optimizer
# + id="MoyIlzCagBRN" colab_type="code" colab={}
lr = 0.0001 + tf.train.exponential_decay(learning_rate = 0.003,
global_step = step,
decay_steps = 2000,
decay_rate = 1/math.e
)
#optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.005)
optimizer = tf.train.AdamOptimizer(learning_rate=lr)
train = optimizer.minimize(cross_entropy)
# + [markdown] id="47rAzeVNgBRP" colab_type="text"
# ### Intialize Variables
# + id="7WG1AszIgBRQ" colab_type="code" colab={}
init = tf.global_variables_initializer()
# + [markdown] id="rseSYLjggBRb" colab_type="text"
# ### Saving the Model
# + id="OwdUgOG4gBRc" colab_type="code" colab={}
saver = tf.train.Saver()
# + [markdown] id="xGdHTpE0gBRe" colab_type="text"
# ## Graph Session
#
# ** Perform the training and test print outs in a Tf session and run your model! **
# + id="pQHEYbyZgBRf" colab_type="code" outputId="12d77dbd-681f-47c3-cceb-db6c403aeca9" colab={"base_uri": "https://localhost:8080/", "height": 10237}
history = {'acc_train':list(),'acc_val':list(),
'loss_train':list(),'loss_val':list(),
'learning_rate':list()}
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(20000):
batch = ch.next_batch(100)
sess.run(train, feed_dict={X: batch[0], Y_true: batch[1], step: i, drop_rate: 0.25})
# PRINT OUT A MESSAGE EVERY 100 STEPS
if i%100 == 0:
# Test the Train Model
feed_dict_train = {X: batch[0], Y_true: batch[1], drop_rate: 0.25}
feed_dict_val = {X:ch.test_images, Y_true:ch.test_labels, drop_rate: 0}
matches = tf.equal(tf.argmax(Y,1),tf.argmax(Y_true,1))
acc = tf.reduce_mean(tf.cast(matches,tf.float32))
history['acc_train'].append(sess.run(acc, feed_dict = feed_dict_train))
history['acc_val'].append(sess.run(acc, feed_dict = feed_dict_val))
history['loss_train'].append(sess.run(cross_entropy, feed_dict = feed_dict_train))
history['loss_val'].append(sess.run(cross_entropy, feed_dict = feed_dict_val))
history['learning_rate'].append(sess.run(lr, feed_dict = {step: i}))
print("Iteration {}:\tlearning_rate={:.6f},\tloss_train={:.6f},\tloss_val={:.6f},\tacc_train={:.6f},\tacc_val={:.6f}"
.format(i,history['learning_rate'][-1],
history['loss_train'][-1],
history['loss_val'][-1],
history['acc_train'][-1],
history['acc_val'][-1]))
print('\n')
saver.save(sess,'models_saving/my_model.ckpt')
# + id="s5rC6lSIAR-P" colab_type="code" outputId="7e18fb26-18d7-4035-c327-c534664d0ecc" colab={"base_uri": "https://localhost:8080/", "height": 282}
plt.plot(history['acc_train'],'b')
plt.plot(history['acc_val'],'r')
# + id="tkToA3CjBxJe" colab_type="code" outputId="e75209fc-0db4-4637-d133-ce044a4e5efe" colab={"base_uri": "https://localhost:8080/", "height": 282}
plt.plot(history['loss_train'],'b')
plt.plot(history['loss_val'],'r')
# + id="NJPdR4IFb-uc" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 282} outputId="efeac19f-1b6b-4429-8884-4e9502a018ee"
plt.plot(history['learning_rate'])
# + [markdown] id="X9uiFJ-ogBRi" colab_type="text"
# ### Loading a Model
# + id="Doot7_0fY5tF" colab_type="code" colab={}
unlabeled_images_test = pd.read_csv('gdrive/My Drive/dataML/test.csv')
#unlabeled_images_test = pd.read_csv('test.csv')
X_unlabeled = unlabeled_images_test.values.reshape(unlabeled_images_test.shape[0],28,28,1)/255
# + id="dbtjpi8JgBRj" colab_type="code" outputId="ee65fc89-ef7e-4b99-b2bb-4d24d4e518c3" colab={"base_uri": "https://localhost:8080/", "height": 34}
with tf.Session() as sess:
# Restore the model
saver.restore(sess, 'models_saving/my_model.ckpt')
# Fetch Back Results
label = sess.run(Y, feed_dict={X:X_unlabeled,drop_rate:0})
# + id="MZ1xS7oJZYkV" colab_type="code" outputId="<PASSWORD>" colab={"base_uri": "https://localhost:8080/", "height": 34}
label
# + [markdown] id="ojRKNc76gBRx" colab_type="text"
# ## Predict the unlabeled test sets using the model
# + id="yQrGiou8gBRy" colab_type="code" colab={}
imageId = np.arange(1,label.shape[0]+1).tolist()
# + id="9Oj02pY3gBR1" colab_type="code" colab={}
prediction_pd = pd.DataFrame({'ImageId':imageId, 'Label':label})
# + id="VLjMgeXEgBR4" colab_type="code" colab={}
prediction_pd.to_csv('gdrive/My Drive/dataML/out_cnn4.csv',sep = ',', index = False)
# + id="ivz_HMLnZ684" colab_type="code" colab={}
| 4_Clasification_DigitRecognizer/2_DL_Multi_Layer_NN_for_DigitRecognizer.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
# ---
# # Apply transformer to Coarse Discourse Dataset
# +
# import required modules and set up environment
import os
# replace file path below with your own local convokit
os.chdir('/Users/marianneaubin/Documents/Classes/CS6742/Cornell-Conversational-Analysis-Toolkit')
import convokit
from convokit import Corpus, Parser, LengthTracker, Transformer, ComplexityTransformer, SelfTracker
import nltk
# -
# open corpus
cd = convokit.Corpus(filename='datasets/reddit_coarse_discourse-corpus/corpus')
# print basic info about the corpus
cd.print_summary_stats()
nltk.download('cmudict')
lt = LengthTracker()
cd1 = lt.transform(cd)
st = SelfTracker()
cd2 = st.transform(cd1)
ct = ComplexityTransformer()
cd3 = ct.transform(cd2)
| datasets/reddit_coarse_discourse-corpus/apply_complexity_transformer.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="AF24jDF8d_Po"
# # **Data Visualization**
#
# ### **Agenda**
#
# 1. What is Data Visualization?
# 2. Why Data Visualization?
# 3. What is Matplotlib?
# 4. Types of Plots
# 5. Getting Started with Matplotlib
# 6. Adding Styles to Our Graph
# 6. Introduction to Seaborn
# 7. Seaborn vs Matplotlib
# 8. Installing Seaborn
# 9. Installing Dependencies
# 10. Plotting Functions
# 11. Multi-Plot Grids
# 12. Plot-Aesthetics
#
#
# + [markdown] id="NHOQ0eb7g0CJ"
# ## **1. What is Data Visualization?**
#
# Data visualization is the presentation of data in a pictorial or graphical format.
#
#
# <img src="https://www.edsys.in/wp-content/uploads/tech-skills-in-demand-1-1024x614.jpg">
# + [markdown] id="MB0MeuyQe-Rf"
# ## **2. Why Data Visualization?**
#
# Human brain can process information easily when it is graphical or pictorial form.
#
# Data visualization allows us to quickly interpret the data and adjust different variables to see their effect.
#
# <img src="https://www.finereport.com/en/wp-content/themes/blogs/images/2019071010A.png">
# + [markdown] id="wboK49IuivYE"
# ## **3. What is Matplotlib?**
#
# Matplotlib is a Python package used for 2D graphics. It's a comprehensive library for creating static, animated, and interactive, visualizations in python. It is easily customizable through accessing the class.
#
# See [Matplotlib documentations](https://matplotlib.org/py-modindex.html)
#
# <img src="https://miro.medium.com/max/2700/1*ALunX6D3tSlatdprOzKS8g.png">
# + [markdown] id="XQXosE2QivU6"
# ## **4. Types of Plots**
#
# There are many types of plotting, few of them which are commonly used are visualized below.
#
# <img src = "https://www.machinelearningplus.com/wp-content/uploads/2019/01/20_Histogram_Boxplot_TimeSeries_Matplotlib-min.png">
# + [markdown] id="fUd23Wh-lrF2"
# ## **5. Getting Started with Matplotlib**
# + id="FBI9F6j0KG4n" outputId="d7d4d499-7bbb-4cda-d0ed-047b5d524ca7" colab={"base_uri": "https://localhost:8080/", "height": 136}
#Make sure Matplotlib is installed in your pip environment.
#Installing Matplotlib
# !pip install Matplotlib
# + id="C1iCx62lmN0-"
#Importing pylot function as alias "plt" from Matplotlib library
from matplotlib import pyplot as plt
# + id="caAkRCUSmha9" outputId="98c5332c-9c78-4612-cfb2-178c59e1fa78" colab={"base_uri": "https://localhost:8080/", "height": 265}
#Plotting to our canvas
plt.plot([1,2,3],[4,5,9])
#Showing what we plotted
plt.show()
# + id="rLOKrpRbnQ-7" outputId="689d132f-d05f-4e4a-c497-b8c1c6561f32" colab={"base_uri": "https://localhost:8080/", "height": 295}
#Lets add title and labels to our graph
x= [10,16,20]
y=[24,32,12]
plt.plot(x,y)
plt.title("Just Playing Around")
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
# + [markdown] id="60enCWo3nJJT"
# ## **6. Adding Styles to Our Graph**
# + id="MrThMkZ-nRuf" outputId="c9607d30-3ea6-425c-bc6a-c15b68d03700" colab={"base_uri": "https://localhost:8080/", "height": 299}
#Importing style function from MatplotLib
from matplotlib import style
style.use("ggplot")
x= [10,16,20]
y= [24,32,12]
x2= [12,19,24]
y2= [20,28,18]
plt.plot(x,y,'g', label ='Line 1', linewidth = 4)
plt.plot(x2,y2,'c', label = "Line 2", linewidth=4)
plt.title('Added Style')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.legend()
plt.grid(True, color = 'k') # Red = "r", Blue = "b", Green = "g", Black = "k"
plt.show()
# + [markdown] id="PYRJ8WuKrJ_T"
# ## **7. Bar Graph**
#
# Bar graphs can be used to show how something changes over time or to compare items. They have an x-axis (horizontal) and a y-axis (vertical).
#
# ***Bar Graph uses Categorical Data***
# + id="wiNxAvKXnRxl" outputId="f3504e24-f45c-4652-d0d1-409f120803e6" colab={"base_uri": "https://localhost:8080/", "height": 299}
plt.bar([2,4,6,8,10],[10,4,14,16,6]) #Where x = [2,4,6,8,10] & y = [10,4,14,16,6]
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title("Bar Graph")
plt.show()
# + [markdown] id="73OnB8QNsP7A"
# ## **8. Histogram**
#
# A histogram is a graphical display of data using bars of different heights. In a histogram, each bar groups numbers into ranges. Taller bars show that more data falls in that range. A histogram displays the shape and spread of continuous sample data.
#
# ***Histogram uses Quantative Data***
# + id="00ndHitesPap" outputId="a2945616-8728-474b-c30c-dff65044c9c3" colab={"base_uri": "https://localhost:8080/", "height": 299}
x = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100]
num_bins = 10
plt.hist(x, num_bins)
plt.xlabel("Weekly Earnings ($)")
plt.ylabel("No. of Students")
plt.title("Histogram")
#plt.legend()
plt.show()
# + [markdown] id="rIyZYPZu0-FH"
# ## **9. Scatter Plot**
#
# A scatter plot uses dots to represent values for two different numeric variables. The position of each dot on the horizontal and vertical axis indicates values for an individual data point. Scatter plots are used to observe relationships between variables.
# + id="vUOnFZha09Yf" outputId="0d3dcc91-40e5-4380-e993-1a621d589440" colab={"base_uri": "https://localhost:8080/", "height": 299}
x= [2,4,6,8,10,12]
y= [4,8,12,16,20,24]
plt.scatter(x,y, color = 'r')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Scatter Plot')
plt.show()
# + [markdown] id="4NKKS_B6OPQN"
# ## **10. Stack Plot**
#
# A stack plot is a plot that shows the whole data set with easy visualization of how each part makes up the whole. Each constituent of the stack plot is stacked on top of each other. It shows the part makeup of the unit, as well as the whole unit.
# + id="vvaELJygOPgW" outputId="35e02b6b-9059-462f-a41b-1f7783a6f41e" colab={"base_uri": "https://localhost:8080/", "height": 299}
years = [2000, 2005, 2010, 2015, 2020]
revenue = [140, 250, 300, 400, 500]
profit = [40, 50, 60, 70, 130]
plt.stackplot(years, profit, revenue, colors = ['r','k','b'])
plt.xlabel('Years')
plt.ylabel('Billions ($)')
plt.title('Stack or Area Plot')
plt.show()
# + [markdown] id="h_EBj1SjQ348"
# ## **11. Pie Chart**
#
# **#EveryoneKnowsIt**
#
# A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportion. In a pie chart, the arc length of each slice, is proportional to the quantity it represents.
# + id="1kq6JW2ARU4k" outputId="bf59721c-aca1-4162-ec4b-29fa0ef022d3" colab={"base_uri": "https://localhost:8080/", "height": 265}
students = [1000, 1450, 6094, 4150, 2150]
interests = ['XR Development','Game Development','Web Development','Mobile Apps','Artificial Intelligence & Data SCience']
col= ['r','b','g','y','m']
plt.pie(students,labels=interests, colors= col)
plt.title('Pie Plot')
plt.show()
# + [markdown] id="ER2bw6YgT_M8"
# ## **12. Introduction to Seaborn**
#
# Seaborn is a library for making statistical graphics in Python. It builds on top of matplotlib and integrates closely with pandas data structures.
#
# Seaborn helps you explore and understand your data. Its plotting functions operate on dataframes and arrays containing whole datasets and internally perform the necessary semantic mapping and statistical aggregation to produce informative plots. Its dataset-oriented, declarative API lets you focus on what the different elements of your plots mean, rather than on the details of how to draw them.
#
# **Matplotlib:** Matplotlib is mainly deployed for basic plotting. Visualization using Matplotlib generally consists of bars, pies, lines, scatter plots and so on.
#
# **Seaborn:** Seaborn, on the other hand, provides a variety of visualization patterns. It uses fewer syntax and has easily interesting default themes.
#
# See [Seaborn Documentations](https://seaborn.pydata.org/introduction.html)
#
# <img src="https://seaborn.pydata.org/_images/introduction_29_0.png">
# + [markdown] id="7hfQ0cem4GjM"
# ## **13. Getting Started with Seaborn**
#
# Seaborn has 4 dependencies. before installing Seaborn, make sure you have already installed NumPy, Pandas, Matplotlib and SciPy
# + id="MCpYDo_Uw2eb" outputId="d8fee6f0-4676-45b1-bd26-e8ed94ac6b13" colab={"base_uri": "https://localhost:8080/", "height": 459}
#Installing dependencies (if haven't)
# !pip install pandas
# !pip install numpy
# !pip install matplotlib
# !pip install scipy
#Installing Seaborn
# !pip install seaborn
# + id="09RTdGnn5Q7Q"
#Importing all dependencies and Seaborn itself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy
import seaborn as sns
# + id="nyp43qzE5i7K" outputId="6e5cd134-e28b-4dee-9acc-4c5863300215" colab={"base_uri": "https://localhost:8080/", "height": 403}
#Relationship Plot
a = sns.load_dataset("flights")
sns.relplot(x="passengers", y="month", data=a) #Add hue=y and try with different combinations
# + id="jSWMeWrV7CI2" outputId="f9b12e1b-0a70-4119-e6d1-2fccd0ce27ad" colab={"base_uri": "https://localhost:8080/", "height": 403}
b = sns.load_dataset("tips")
sns.relplot(x="time", y="tip", data=b, kind ="line")
# + id="7Gcm79XH7iG0" outputId="5f896621-d7e9-463a-c227-0d01604b16da" colab={"base_uri": "https://localhost:8080/", "height": 403}
#Categorical Plot
sns.catplot(x="day", y="total_bill", data=b)
# + [markdown] id="EOQTJoE--J-5"
# ### **For Skewed Data**
#
# <img src= "https://d20khd7ddkh5ls.cloudfront.net/befunky-collage.jpg">
# + [markdown] id="5wS1nUhFUPze"
# **Violin Plot**
# + id="3nj-EuqG8DYG" outputId="ada78971-5dea-493d-9997-dbef36e2cd73" colab={"base_uri": "https://localhost:8080/", "height": 403}
sns.catplot(x="day", y="total_bill", kind= "violin", data=b)
# + [markdown] id="TPmyagzLUMhQ"
# **Box Plot**
# + id="Y0nLykZs8Dod" outputId="4303c9fe-8c59-4272-f082-989b4f70a154" colab={"base_uri": "https://localhost:8080/", "height": 403}
sns.catplot(x="day", y="total_bill",kind="boxen", data=b)
# + [markdown] id="71kQw6Tw8VQa"
# ## **14. Multi-Plot Grids**
#
# Graphs are plotted side-by-side using the same scale and axes to aid comparison
#
# It is pretty useful to help developer or researchers to understand the large amount of data in a blink.
#
#
# + id="j8VzYf8T8Rs4" outputId="ebcc8add-7867-42d4-f2a6-ab0df113d24a" colab={"base_uri": "https://localhost:8080/", "height": 242}
a = sns.load_dataset("iris")
b = sns.FacetGrid(a, col = "species")
b.map(plt.hist, "sepal_length")
| 03_Data_Visualization/03_DataVisualization.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/chandrusuresh/ReinforcementLearning/blob/master/Ch10-OnPolicyControlwithApproximation/MountainCar.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + id="BW7e_fu1haZ2" colab_type="code" colab={}
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from tqdm.auto import trange
# %matplotlib inline
# + [markdown] id="Hueno8VNhfL3" colab_type="text"
# ## Tile Coding
# + id="Hg4M45jEha1_" colab_type="code" colab={}
"""
Tile Coding Software version 3.0beta
by <NAME>
based on a program created by <NAME> and others
External documentation and recommendations on the use of this code is available in the
reinforcement learning textbook by Sutton and Barto, and on the web.
These need to be understood before this code is.
This software is for Python 3 or more.
This is an implementation of grid-style tile codings, based originally on
the UNH CMAC code (see http://www.ece.unh.edu/robots/cmac.htm), but by now highly changed.
Here we provide a function, "tiles", that maps floating and integer
variables to a list of tiles, and a second function "tiles-wrap" that does the same while
wrapping some floats to provided widths (the lower wrap value is always 0).
The float variables will be gridded at unit intervals, so generalization
will be by approximately 1 in each direction, and any scaling will have
to be done externally before calling tiles.
Num-tilings should be a power of 2, e.g., 16. To make the offsetting work properly, it should
also be greater than or equal to four times the number of floats.
The first argument is either an index hash table of a given size (created by (make-iht size)),
an integer "size" (range of the indices from 0), or nil (for testing, indicating that the tile
coordinates are to be returned without being converted to indices).
"""
basehash = hash
class IHT:
"Structure to handle collisions"
def __init__(self, sizeval):
self.size = sizeval
self.overfullCount = 0
self.dictionary = {}
def __str__(self):
"Prepares a string for printing whenever this object is printed"
return "Collision table:" + \
" size:" + str(self.size) + \
" overfullCount:" + str(self.overfullCount) + \
" dictionary:" + str(len(self.dictionary)) + " items"
def count (self):
return len(self.dictionary)
def fullp (self):
return len(self.dictionary) >= self.size
def getindex (self, obj, readonly=False):
d = self.dictionary
if obj in d: return d[obj]
elif readonly: return None
size = self.size
count = self.count()
if count >= size:
if self.overfullCount==0: print('IHT full, starting to allow collisions')
self.overfullCount += 1
return basehash(obj) % self.size
else:
d[obj] = count
return count
def hashcoords(coordinates, m, readonly=False):
if type(m)==IHT: return m.getindex(tuple(coordinates), readonly)
if type(m)==int: return basehash(tuple(coordinates)) % m
if m==None: return coordinates
from math import floor, log
from itertools import zip_longest
def tiles (ihtORsize, numtilings, floats, ints=[], readonly=False):
"""returns num-tilings tile indices corresponding to the floats and ints"""
qfloats = [floor(f*numtilings) for f in floats]
Tiles = []
for tiling in range(numtilings):
tilingX2 = tiling*2
coords = [tiling]
b = tiling
for q in qfloats:
coords.append( (q + b) // numtilings )
b += tilingX2
coords.extend(ints)
Tiles.append(hashcoords(coords, ihtORsize, readonly))
return Tiles
# + [markdown] id="KoesDKjChzJ5" colab_type="text"
# ## Mountain Car
# 
# + [markdown] id="a2cW3hU1A2tC" colab_type="text"
# This is the solution to Example 10.1 in Page-244 of the [Reinforcement Learning book by Sutton & Barto](http://www.incompleteideas.net/book/the-book.html).
#
# Consider the task of driving an underpowered car up a steep mountain road as shown above. The state of the car at time $t$ is defined by its position $(x_t)$ and velocity $(\dot{x}_t)$ & dynamics of the car is given by:
# $$ \begin{align} x_{t+1} &= \text{bound}[x_t + \dot{x}_{t+1}] \\
# \dot{x}_{t+1} &= \text{bound}[\dot{x}_t + 0.001 A_t - 0.0025 \cos(3 x_t)] \end{align}$$
#
# The bound operation enforces the following constrains on the position & velocity:
# $$ \begin{align} -1.2 \le & x_t \le 0.5 \\
# -0.07 \le & \dot{x}_t \le 0.07 \end{align}$$
#
# Each episode starts from a random position $x_t \in [-0.6,0.4) $ and $\dot{x}_t = 0$.
# $A_t = [-1,0,1]$ is the action which needs to be learnt to reach the goal.
# + id="6TuRd9OCh0fZ" colab_type="code" colab={}
maxSize = 4096
iht = IHT(maxSize)
numTilings = 8
# weights = np.random.uniform(0,1,(maxSize,))#[0]*maxSize
numTilings = 8
stepSize = 0.3/float(numTilings)
xLim = [-1.2,0.5]
yLim = [-0.07,0.07]
actions = [-1,0,1]
nA = len(actions)
# + id="1Yevsh7HijYq" colab_type="code" colab={}
def mytiles(s,a):
x = s[0]
y = s[1]
scaleFactor_x = float(numTilings)/(xLim[1]-xLim[0])
scaleFactor_y = float(numTilings)/(yLim[1]-yLim[0])
return tiles(iht, numTilings, [x*scaleFactor_x,y*scaleFactor_y],[a])
def move(pos,action):
new_pos = list(pos)
new_pos[1] += 0.001*action - 0.0025*np.cos(3*pos[0])
new_pos[1] = max(yLim[0],min(yLim[1],new_pos[1]))
new_pos[0] += new_pos[1]
new_pos[0] = max(xLim[0],min(xLim[1],new_pos[0]))
if new_pos[0] == xLim[0]:
new_pos[1] = 0
return new_pos
def getActionValue(s,a,wt):
tile_idx = mytiles(s,a)
return np.sum(wt[tile_idx])
def target_policy(s,wt,epsilon):
Q = np.zeros((nA,))
for i,a in enumerate(actions):
Q[i] = getActionValue(s,a,wt)
action_prob = epsilon/float(nA)*np.ones((nA,))
maxQ = np.max(Q)
idx = np.where(Q == maxQ)[0]
action_prob[idx] += (1-epsilon)/float(len(idx))
# print('Q = ',Q)
# print('Max Q = ',maxQ)
# print('Max Q idx = ',idx)
# print('Action_prob = ',action_prob)
return np.random.choice(range(nA),p=action_prob)
def episodic_semigradient_nStep_sarsa(numRuns,num_episodes,numSteps,alpha,gamma,epsilon,saveWeights=False):
step_stats = np.zeros((num_episodes,1))
count = 0
stats = []
for run in trange(numRuns, desc='Runs'):
weights = np.zeros((maxSize,))
for episode in trange(num_episodes,desc="Episodes",disable=numRuns>1):
pos = [0,0]
pos[0] = np.random.uniform(-0.6,-0.4)
T = np.inf
traj = []
t = 0
R = []
while True:
count += 1
if t < T:
act_idx = target_policy(pos,weights,epsilon)
traj += [pos + [act_idx]]
next_pos = move(pos,actions[act_idx])
if next_pos[0] >= xLim[1]:
R += [0]
T = t+1
else:
R += [-1]
pos = next_pos.copy()
tau = t-numSteps
if tau >= 0:
G = np.sum([gamma**(i-tau-1)*R[i] for i in range(tau+1,min(tau+numSteps+1,T))])
if tau+numSteps < T:
# print('Traj:',len(traj),tau+numSteps)
pos_n = traj[tau+numSteps][:2]
actidx_n = traj[tau+numSteps][2]
pos_curr = traj[tau][:2]
actidx_curr = traj[tau][2]
Qn = getActionValue(pos_n,actions[actidx_n],weights)
Qcurr = getActionValue(pos_curr,actions[actidx_curr],weights)
tile_idx = mytiles(pos_curr,actions[actidx_curr])
# print("tile_idx:",tile_idx)
if tau+numSteps < T:
G += (gamma**numSteps)*Qn
# print("Update = ",alpha*(G-Qcurr))
weights[tile_idx] += alpha*(G-Qcurr)
if count == 427 and saveWeights:
stats += [np.copy(weights)]
if tau == T-1:
break
t += 1
step_stats[episode,0] += float(len(traj))/float(numRuns)
if episode in [11,103,999] and saveWeights:
stats += [np.copy(weights)]
if saveWeights:
stats += [np.copy(weights)]
return stats,step_stats
# + [markdown] id="OWyLyZVr6B_w" colab_type="text"
# ### Episodic Semi-Gradient 1-step SARSA
# + id="pRbaJ3_akqvQ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 116, "referenced_widgets": ["76306f5bc1c64fa6b0b4f87e5427e0c5", "9496abf168c74843aaee1bb1fd6324a0", "3ec869e40a6344bc9a51a9b38dd5ebbf", "6e3eafc1685f4220b561d6bda3d9b852", "0b305cdab3af47588310f13e4fcdabad", "0501a678e3a14b3db763a53f04436dd2", "<KEY>", "5d65d127d5044861b60e907b4b806dc8", "<KEY>", "4206e66a503741479175ec3557000ae4", "5499402afde448c7a25ab991eaee6a68", "<KEY>", "b17545eddf28458e86e0422f82ee5872", "4ab36ad4551843a4a783b2d1b9224ec9", "<KEY>", "ff35af6d9f0c435bbaf3ee53c987c25b"]} outputId="fab22878-9bcb-4f6b-e8f4-bef500db892e"
gamma = 1.0
epsilon = 0.0
num_episodes = 9000
numRuns = 1
numSteps = 1
np.random.seed(42)
stats,step_stats = episodic_semigradient_nStep_sarsa(numRuns,num_episodes,numSteps,stepSize,gamma,epsilon,True)
# + id="mj7sMipVsfpT" colab_type="code" colab={}
pos = np.linspace(xLim[0],xLim[1],50)
vel = np.linspace(yLim[0],yLim[1],50)
costToGo = []
for wt in stats:
neg_maxQ = np.zeros((len(pos),len(vel)))
for i,p in enumerate(pos):
for j,v in enumerate(vel):
s = [p,v]
Q = np.zeros((nA,))
for k,a in enumerate(actions):
Q[k] = getActionValue(s,a,wt)
neg_maxQ[i,j] = -np.max(Q)
costToGo += [neg_maxQ]
# + id="Hm-jPPmdt9Xs" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 396} outputId="8759430b-533f-42df-b4b1-b572311b6520"
X,Y = np.meshgrid(pos,vel)
fig = plt.figure(figsize=(24,14))
title = ['Step-428','Episode-12','Episode-104','Episode-1000','Episode-9000']
for i,neg_maxQ in enumerate(costToGo):
ax = fig.add_subplot(2, 3, i+1, projection='3d')
ax.set_title('Value function after ' + title[i])
ax.plot_wireframe(X, Y, neg_maxQ)#, rstride=10, cstride=10)
ax.view_init(elev=30., azim=-60)
ax.set_xlim([xLim[0],xLim[1]])
ax.set_ylim([yLim[0],yLim[1]])
ax.set_xlabel('Position')
ax.set_ylabel('Velocity')
ax = fig.add_subplot(2,3,6)
ax.plot(range(1,num_episodes),step_stats[1:]);
ax.set_title('Steps per episode with step-size = 0.3/8')
ax.set_ylabel('Steps per episode (log scale)')
ax.set_xlabel('Episodes')
ax.set_yscale('log')
ax.set_yticklabels([100,200,400,1000])
ax.set_ylim([80,1000]);
ax.set_xlim([1,500]);
# + [markdown] id="JoCTBT6e6UaY" colab_type="text"
# ### Comparing Step-sizes for 1-step SARSA
# + id="sg5TYBtr0iOS" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 215, "referenced_widgets": ["1c5a9e840fb944af8013a19bf16a36e2", "f4812e06fca04f17b8866d3396262712", "fe7178664e2c43b1a0c7f49904f38875", "8c7ef7eb64f2466fbf6746681fb10210", "e8973598f1044ea49785ff16b4a984d1", "ea0280367dea4c0cb827e1102176047f", "5732adcfec514734aa04b9a4e97cddc6", "<KEY>", "20a68bbaf0004460bb909b9413218211", "e348959dde2b4565b93b84942d93a9df", "b1fd7c7edcfc4ba1900a365b73381a21", "26e74faf16dc4a7e87b5f3010bc31b64", "d4e9538ed33d4670864994e209baab67", "<KEY>", "4fdb93befe4f4c7abb057629ab9c8852", "<KEY>", "<KEY>", "<KEY>", "ef62bf800e174461a48df67210dda233", "466787e22fae49899fcad9d336fca7a8", "<KEY>", "57b07e08020d415abb7d156fe41c6163", "<KEY>", "39c8a6cf4f8c40db97f03d5e1d5cea43", "9b811be2e1014c43a6da9f01367f9392", "9ce15ef06f3f456c88d6b0cee4ca55b4", "73fe5e5349a74f7e951401938c8650d1", "<KEY>", "<KEY>", "ca6c43ca0db6415abc0167e4093ace6c", "eed41ec91aa4406b9c4f1ebf57ef3542", "dc5abfee5570441a8bef5770e78fc3a6"]} outputId="7dac240b-ff00-4fb2-b260-0977f685db5f"
gamma = 1.0
epsilon = 0.0
num_episodes = 500
numRuns = 50
step_size = [0.1/8,0.2/8,0.5/8]
step_stats = np.zeros((num_episodes,len(step_size)))
for i in trange(len(step_size),desc='Step Size'):
alpha = step_size[i]
np.random.seed(42)
_,steps = episodic_semigradient_nStep_sarsa(numRuns,num_episodes,numSteps,alpha,gamma,epsilon)
step_stats[:,i] = steps.reshape((step_stats[:,i].shape))
# + id="EMp1r6U9Toza" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 457} outputId="1814b4c8-843b-43de-b311-c23d4191c516"
fig,ax = plt.subplots(1,1,figsize=(10,7))
legend = ['0.1/8','0.2/8','0.5/8']
color = ['b','g','r']
for i,s in enumerate(step_size):
ax.plot(range(num_episodes),step_stats[:,i],color[i])
ax.set_title('Comparing steps per episode with step-size')
ax.set_ylabel('Steps per episode (log scale) averaged over ' + str(numRuns) + ' runs')
ax.set_xlabel('Episodes')
ax.set_yscale('log')
ax.set_yticks([100,200,400,1000])
ax.legend(legend);
# + [markdown] id="RN2dgS0X6fla" colab_type="text"
# ### Episodic Semi-Gradient n-step SARSA
# + id="8CjcNtQj6kKq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 66, "referenced_widgets": ["264c9252d3134df7abdf3a02aec1213c", "<KEY>b", "ebc09b080c404f43a806ee30f64a82bd", "f357d7e754e34215a543ab84d58617bb", "5c1924e90173477db21079131afc8ff0", "caeffc94acdd4f1faf1e5f09319eae38", "7e078fce8ede47a3ac5855491a02b31e", "3d442708be254108b074db105e7afb2b"]} outputId="66430eeb-f83a-4756-d112-709ed7bd16f9"
alpha = 0.3/8
numSteps = 8
nstep_stats = np.zeros((num_episodes,1))
np.random.seed(42)
_,steps = episodic_semigradient_nStep_sarsa(numRuns,num_episodes,numSteps,alpha,gamma,epsilon)
nstep_stats[:,0] = steps.reshape((step_stats[:,0].shape))
# + id="ZooHKHK47CeV" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 457} outputId="0499e902-3034-4ee8-d270-c2e5de4b8823"
fig,ax = plt.subplots(1,1,figsize=(10,7))
legend = ['n=1 with alpha = 0.5/8','n=8 with alpha = 0.3/8']
color = ['r','purple']
ax.plot(range(num_episodes),step_stats[:,2],color[0])
ax.plot(range(num_episodes),nstep_stats,color[1])
ax.set_title('Comparing steps per episode for 1-step vs n-step SARSA')
ax.set_ylabel('Steps per episode (log scale) averaged over ' + str(numRuns) + ' runs')
ax.set_xlabel('Episodes')
ax.set_yscale('log')
ax.set_yticks([100,200,400,1000])
ax.legend(legend);
| Ch10-OnPolicyControlwithApproximation/MountainCar.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('../Dataset/Domains/Clean/domains.csv')
# +
# Defining Class and Sublcass
def get_class(s):
# Benign = 0
# Malware = 1
if s == 'benign':
return 0
return 1
def get_sub_class(s):
# Benign = 0
# Spam = 1
# Phishing = 2
# Malware = 3
sub_classes = ['benign', 'spam', 'phishing', 'malware']
return sub_classes.index(s)
df['sub_class'] = df['class'].apply(get_sub_class)
df['class'] = df['class'].apply(get_class)
# +
from IPy import IP
def ip_check(s):
try:
IP(s)
return 1
except:
return 0
df['ip_format'] = df['domain'].apply(ip_check)
# +
# Parsing Attributes
from tld import parse_tld
def parse_domain(s):
if ip_check(s):
return ('', '', '')
parse = parse_tld(s, fix_protocol=True)
if parse == (None, None, None):
return ('', s, '')
return parse
df['parse'] = df['domain'].apply(parse_domain)
# +
# Setting Attributes
def get_ssd(t):
if t[1] == '':
return t[2]
elif t[2] == '':
return t[1]
else:
return t[2]+'.'+t[1]
df['SSD'] = df['parse'].apply(get_ssd)
def get_sub(t):
return t[2]
df['SUB'] = df['parse'].apply(get_sub)
def get_sld(t):
return t[1]
df['SLD'] = df['parse'].apply(get_sld)
def get_tld(t):
return t[0]
df['TLD'] = df['parse'].apply(get_tld)
# +
# Dropping Unwanted Columns
df = df.drop(columns=['parse'])
# +
# Saving the dataset
df.to_csv('Dataset/Generated/attributes.csv', index=False)
# -
| jupyter-notebooks/.ipynb_checkpoints/[01] [02] Gerador de Atributos-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
# ---
# + id="kXQR7ZpCsYBP" outputId="02f33c4e-76d4-4d28-9821-1982c17f26a2"
# !pip install plotly
# -
import pandas as pd
import matplotlib.pyplot as plt
import plotly.offline as py
py.init_notebook_mode(connected = True)
import plotly.graph_objs as go
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.io as pio
# + id="2mD0OCHksYBY"
covid_data = pd.read_csv(r'C:\Users\Admin\Desktop\covid.csv')
# + id="gygDJvVfsYBd" outputId="d426bf76-a5fe-4038-8e34-8b5479280ce7"
covid_data.head()
# + id="eRF_RT3UsYBh"
covid_data = covid_data.drop(['NewCases','NewDeaths','NewRecovered'],axis=1)
# + id="6HAqD5gDsYBl" outputId="18e5bd47-a764-406c-8b8f-7fdcd8dd74d0"
covid_data.head()
# + id="FIKd213_sYBp"
def trunc(x):
r = round(x,2)
return r
def trunc1(x):
r = round(x,0)
return r
# + id="DTqVNLk5sYBs"
covid_data['Percentage_affected'] = ((covid_data['TotalCases']/covid_data['Population'])*100).apply(trunc)
# + id="BAXQ_TuYsYBw"
covid_data['Recovery_percentage'] = ((covid_data['TotalRecovered']/covid_data['TotalCases'])*100).apply(trunc)
# + id="f-QWnQYjsYBz"
covid_data['Death_percentage'] = ((covid_data['TotalDeaths']/covid_data['TotalCases'])*100).apply(trunc)
# + id="zjbpYT7fsYB2"
covid_data['Serious_Percentage'] = ((covid_data['Serious,Critical']/covid_data['TotalCases'])*100).apply(trunc)
# + id="Bwu8AsuDsYB5" outputId="e90cbc2f-91ce-4dbc-fef4-6ca692b10840"
covid_data.head()
# + id="RVicYQvWsYB8" outputId="3ecf04fe-856e-4a05-d538-8e5aaca4a903"
from plotly.figure_factory import create_table
table = create_table(covid_data.head(10),colorscale = [[0, '#4d004c'],[.5, '#f2e5ff'],[1, '#ffffff']])
table.layout.width=2800
py.iplot(table)
# + [markdown] id="T7vW2EWJsYCB"
# ### Population of top 15 countries with most covid-cases
# + id="4bN_hj3ssYCC" outputId="f3236332-75d6-4bb9-cbac-0bd5112bdfed"
px.bar(covid_data.head(15),x='Country/Region',y='Population',color = 'Population',
hover_data = ['Country/Region','Continent'])
# + [markdown] id="cGM554YmsYCG"
# ### TotalCases per Population percentage of top 10 countries with most covid_cases
# + id="Dm4GerOGsYCH"
fig = go.Figure([go.Pie(labels=covid_data.head(10)['Country/Region'], values=covid_data.head(10)['Percentage_affected'])])
# + id="8-vdlqCxsYCK" outputId="5e6ea892-b6ab-4d44-f207-d4dc287c05da"
fig.show()
# + [markdown] id="a_Y6fSftsYCO"
# ### Recovery rate of top 10 countries with most covid cases
# + id="4_TotLRPsYCP" outputId="84a62976-470c-4ba5-86f7-02d733e42120"
fig = go.Figure([go.Pie(labels=covid_data.head(12)['Country/Region'], values=covid_data.head(12)['Recovery_percentage'])])
fig.show()
# + [markdown] id="1ZZIsjM-sYCS"
# ### Deaths per TotalCases Percentage of top 10 countries with most covid cases
# + id="pfwZMxCvsYCS" outputId="d53f98ab-b107-4b56-8ec2-2b1c6bc5d629"
fig = go.Figure([go.Pie(labels=covid_data.head(10)['Country/Region'], values=covid_data.head(10)['Death_percentage'])])
fig.show()
# + [markdown] id="y21FjIBrsYCZ"
# ### Serious Cases per Total Cases of top 10 countries with most covid cases
# + id="vHatxojNsYCZ" outputId="c2f3cd0b-2536-48ac-eebe-f68b266799bc"
fig = go.Figure([go.Pie(labels=covid_data.head(10)['Country/Region'], values=covid_data.head(10)['Serious_Percentage'])])
fig.show()
# + id="elmJTf_ksYCe"
continent_group = covid_data.groupby('Continent')['TotalCases'].sum().reset_index()
# + id="Y5DJsePtsYCi" outputId="838d1674-e671-42cf-ff41-64124339160a"
continent_group
# + [markdown] id="aaH2A7CQsYCn"
# ### Total Number of Cases in each continent
# + id="lXrW6_J1sYCo" outputId="c8cadcf3-096f-437d-8035-af92844b8cce"
px.bar(continent_group,x='Continent',y='TotalCases',color = 'Continent',
hover_data = ['TotalCases','Continent'])
# + id="F0LiKiGPsYC9" outputId="7b14bd40-bf16-484d-ddf8-31de18e49514"
px.bar(covid_data.head(15),x='Country/Region',y='TotalCases',color = 'Country/Region',
hover_data = ['Country/Region','Continent'])
# + id="tm0LrPfVsYDC" outputId="8b84b643-96f6-4fad-af89-e3cbac92e072"
px.bar(covid_data.head(15),x='Country/Region',y='TotalDeaths',color = 'Country/Region',
hover_data = ['Country/Region','Continent'])
# + id="bJr_N3lhsYDJ" outputId="7696e087-29d6-457b-8b1d-bb39e903b477"
px.bar(covid_data.head(15),x='Country/Region',y='TotalRecovered',color = 'Country/Region',
hover_data = ['Country/Region','Continent'])
# + id="_3fV50hfsYDN" outputId="bc0758ef-41d8-4684-f038-58f65bcbc46a"
px.bar(covid_data.head(15),x='Country/Region',y='TotalTests',color = 'Country/Region',
hover_data = ['Country/Region','Continent'])
# + id="AqrXB7OosYDS" outputId="d0cab4eb-072b-4208-a635-e728df72eb94"
px.bar(covid_data.head(15),x='Continent',y='TotalTests',color = 'Country/Region',
hover_data = ['Country/Region','Continent'])
# + id="cT9gMemPsYDW" outputId="cfe9599d-2eed-4dc0-bc0f-28dabb9a6c8a"
fig = make_subplots(rows=1, cols=3,subplot_titles=("Total Cases", "Total Deaths", "Total Recovered"),column_widths=[1, 1,1])
fig.add_trace(go.Box(y=covid_data['TotalCases'],name="Total Cases"),row=1, col=1)
fig.add_trace(go.Box(y=covid_data['TotalDeaths'],name="Total Deaths"),row=1, col=2)
fig.add_trace(go.Box(y=covid_data['TotalRecovered'],name="Total Recovered"),row=1, col=3)
fig.show()
# + [markdown] id="SSUBky1hsYDc"
# # THANK YOU
| COVID_19-DATA-ANALYSIS/Covid_19_Data_Analysis(SUYASH).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
# ---
# + title: Does Jameda discriminate against non-paying users? Part 2: New Data, new Insights
# + date: 2021-02-20
# + tags: python, plotly, Jameda, premium, doctors
# + Slug: discrimination-on-jameda-analysis-new-data-new-insights
# + Category: Analytics
# + Authors: MC
# + Summary: Does the physicians rating platform Jameda discriminate against non-paying physicians? In a previous post, we analyzed this claim inconclusively. Using new data, we are able to gain new insights and shed light on the issue.
# ## Motivation
#
# In the [first part]({filename}/jameda_part1.ipynb) of this series, we investigated a claim made in an [article](http://www.zeit.de/2018/04/jameda-aerzte-bewertungsportal-profile-bezahlung/komplettansicht) by the newspaper "Die Zeit". The claim was that the popular German physicians rating platform Jameda favors it's paying users while discriminating against non paying physicians. Using a larger and more robust dataset than the original analysis by "Die Zeit", we confirmed many of their findings. We found that paying physicians on average have much higher ratings and suspiciously low numbers of poor ratings. However, we took a stance in disagreeing with the conclusion of the article which didn't account for alternative explanations for these observations. As these findings are only based on correlation, we argued that this alone can't be seen as proof for Jameda's favoring of paying members. Especially, as there is a very intuitive theory why paying physicians might have better ratings: Paying to be a premium member on the platform might be related to other positive traits of the physician leading to better ratings. For example, doctors who value their reputation highly might be more careful in interacting with their patients and also more willing to be a paying user. Hence, the result of our first analysis was inconclusive.
# However, there still was a credible claim stated by the original article. On Jameda, physicians can report ratings they disagree with. This (temporary) removes the reviews from the site and starts a [validation process](https://www.jameda.de/qualitaetssicherung/). The rating's comment is checked by Jameda and can be removed permanently, if it violates certain rules. It could be that premium members report negative ratings more often. This seems intuitive. Premium members are probably more engaged in cultivating their profiles and also more active in general. In contrast, non paying members might have never looked up their own profile at all. Thus, missing out on the opportunity to report any negative reviews. The author from "<NAME>" asked Jameda whether they remove more negative reviews from premium users' profiles. Jameda stated, that they don't have any data on this.
# Well, no worries Jameda. I got your back! I'll gladly offer some data myself to help you out with this question. With a little delay of about three years, we'll finally conclude our analysis. Using new data, we'll be able to shed light on the original question!
# <br>
# As always, you can download this notebook on <a href="https://mybinder.org/v2/gh/mc51/blog_posts/master?filepath=jameda_part2.ipynb"><img src="https://mybinder.org/badge_logo.svg" alt="Open on Binder" style="display:inline;"></a> and <a href="https://colab.research.google.com/github/mc51/blog_posts/blob/master/jameda_part2.ipynb">
# <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" style="display:inline;"/></a>. Unfortunately, I won't be able to share the underlying data this time. Sorry for that!
# ## The data
#
# The data was scraped once a day and stored to a SQLite database. It is made up of two parts. The first part consists of the information on the physicians. The second part consists of the reviews. (Refer to the [first post]({filename}/jameda_part1.ipynb) for more details on the data content)
# We observed changes in the reviews for a period of about nine months from January 2020 to September 2020. Thus, we were able to identify all reviews that were removed by Jameda during this period because they were reported by a physician. Also, we can see the result of the validation process for some of those. They could have been removed after being reported or could have been re published.
# First, we create a class for reading the data from our SQLite database:
# + tags=["hide"]
# %%HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>
# +
import datetime
import sqlite3
import logging
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.io as pio
from sqlite3 import Error
from pandas.tseries.frequencies import to_offset
from IPython.display import Markdown as md
pio.renderers.default = "notebook_connected"
px.defaults.template = "plotly_white"
pd.options.display.max_columns = 100
pd.options.display.max_rows = 600
pd.options.display.max_colwidth = 100
np.set_printoptions(threshold=2000)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
# Data for original observation period
DATA_OLD = "../data/raw/2020-09-23_jameda.db"
# To check for longer term changes we got some new data
DATA_NEW = "../data/raw/2021-02-13_jameda.db"
DATE_START_WAVE2 = "2021-02-10"
# -
class DB:
def __init__(self, db):
"""
Connect to sqllite DB expose connection and cursor of instance
"""
self.cursor = None
self.conn = self.create_connection(db)
self.conn.row_factory = sqlite3.Row # return column names on fetch
try:
self.cursor = self.conn.cursor()
except Exception as e:
log.exception(f"Error getting cursor for DB connection: {e}")
def create_connection(self, db_path):
"""return a database connection """
try:
conn = sqlite3.connect(db_path)
except Error:
log.exception(f"Error connecting to DB: {db_path}")
return conn
def send_single_statement(self, statement):
""" Send single statement to DB """
try:
self.cursor.execute(statement)
except Error:
log.exception(f"Error sending statement: {statement}")
self.conn.rollback()
return None
else:
log.info(f"OK sending statement: {statement}")
self.conn.commit()
return True
def select_and_fetchall(self, statement):
""" Execute a select statement and return all rows """
try:
self.cursor.execute(statement)
rows = self.cursor.fetchall()
except Exception:
log.exception("Could not select and fetchall")
return None
else:
return rows
def __del__(self):
""" make sure we close connection """
self.conn.close()
# Using the class and its methods, let's read in the data regarding the doctors' profiles:
# from sqlite to df
db = DB(DATA_OLD)
ret = db.select_and_fetchall("SELECT * FROM doctors;")
rows = [dict(row) for row in ret]
docs = pd.DataFrame(rows)
docs["premium"] = 0
# If user has a portrait picture, he is paying member / premium user
docs.loc[docs["portrait"].notna(), "premium"] = 1
docs_unq = (
docs.sort_values(["ref_id", "date_update"])
.groupby("ref_id", as_index=False)
.agg("last")
)
# Clean doctor subject string
docs["fach_string"] = docs["fach_string"].str.replace("[\['\]]", "")
docs.head(2)
# This is very similar to the data we used in the first post. In this analysis, most of the columns can be ignored. We'll focus on the `ref_id` (which is the user id) and whether or not the physician is a paying (`premium = 1`) or non-paying user (`premium = 0`).
# Next, we read in and process the reviews:
# from multiple sqlite DBs to single df
DATA = [DATA_OLD, DATA_NEW]
reviews = pd.DataFrame()
for data in DATA:
db = DB(data)
ret = db.select_and_fetchall("SELECT * FROM reviews;")
rows = [dict(row) for row in ret]
df = pd.DataFrame(rows).sort_values(["ref_id", "b_id", "date_create"])
# columns to dates
df["b_date"] = pd.to_datetime(df["b_date"], unit="s")
df["date_create"] = pd.to_datetime(df["date_create"])
df["date_update"] = pd.to_datetime(df["date_update"])
reviews = reviews.append(df)
# some processing
# force numeric content to numeric type
reviews[
[
"ref_id",
"b_id",
"b_stand",
"gesamt_note_class",
"br_total_votes",
"br_index",
"is_archived",
"kommentar_entfernt",
]
] = reviews[
[
"ref_id",
"b_id",
"b_stand",
"gesamt_note_class",
"br_total_votes",
"br_index",
"is_archived",
"kommentar_entfernt",
]
].apply(
pd.to_numeric
)
# flag wave 1 and 2
reviews["wave"] = np.where(reviews["date_create"] < DATE_START_WAVE2, 1, 2)
reviews_w2 = reviews[reviews["wave"] == 2]
reviews_w1 = reviews[reviews["wave"] == 1]
# skip incomplete days
date_firstday = reviews_w1["date_create"].min().ceil("d")
date_lastday = reviews_w1["date_create"].max().floor("d")
reviews_w1 = reviews_w1.loc[
(reviews_w1["date_create"] >= date_firstday)
& (reviews_w1["date_create"] <= date_lastday),
]
# The `ref_id` of each review can be related back to the corresponding physician. The `b_id` refers to the unique id of a review. Moreover, we'll need `gesamt_note` which is the numerical rating of the review (from 1 = best, to 6 = worst), `b_date` which is the first publication date of a review, `date_create` which is the date we observed this review and `b_stand` which is the status of the review (explained below).
# Here, we strictly look at reviews for which we have multiple observations, i.e. reviews which have changed during the period we scraped them:
# +
# filter for reviews with multiple entries (new entry only created when reviews changed)
num_entries = reviews_w1.groupby("b_id").size()
multi_entry = reviews_w1.loc[
reviews_w1["b_id"].isin(num_entries[num_entries > 1].index),
].sort_values(["ref_id", "b_id", "date_create"])
# filter on relevant columns
cols_change = ["ref_id", "b_date", "b_id", "b_stand", "date_create", "wave"]
multi_entry = multi_entry[cols_change].reset_index(drop=True)
# -
# Now, we come back to the `b_stand` (status) variable. We know that `1` means the status is normal. This is just a regular review, containing a rating and a comment. When `b_stand` is `4` it indicates that the review was reported, temporarily removed, and is being verified by Jameda (the process is explained [here](https://www.jameda.de/qualitaetssicherung/)). A `5` tells us, that the review has a comment but no rating. Here's an example for a reported review:
print(
reviews_w1.loc[reviews_w1["b_stand"] == 4,].iloc[
0
][["titel", "kommentar"]]
)
# These reviews are grayed out on the website. The rating is deleted and the original text in the title and comment is replaced by a standard message. It says something along the lines of: "This review has been reported by the physician and is under review". Also, the rating is not displayed for them anymore.
# Following, for the reviews with multiple entries, we check how `b_stand` changed between observations:
# Compute direction of b_stand change: review removed or re added (after removal)
multi_entry = multi_entry[multi_entry["b_stand"].isin([1, 4, 5])]
multi_entry["b_stand_prev"] = multi_entry.groupby("b_id")["b_stand"].shift(
fill_value=np.nan
)
multi_entry["change"] = multi_entry["b_stand"] - multi_entry["b_stand_prev"]
multi_entry.loc[multi_entry["change"].isin([3, -1]), "removed"] = 1
multi_entry.loc[multi_entry["change"].isin([-3, 1]), "readded"] = 1
multi_entry.head(4)
# Using the change in `b_stand` we can conclude whether a review has been removed (it went from 1 to 4 or 5 to 4) or re added after being removed some time before (change from 4 to 1 or 4 to 5).
# Let's store a data frame of only the reviews which have been removed or re added:
# Only reviews that were added or removed
changed = multi_entry[(multi_entry["removed"] == 1) | (multi_entry["readded"] == 1)]
changed = changed[["b_id", "removed", "readded"]].groupby("b_id").max().reset_index()
changed.head(2)
# keep only unique reviews and add cols from other tables with infos
reviews_unq = reviews_w1[reviews_w1["b_stand"].isin([1, 4, 5])]
reviews_unq = reviews_unq.drop_duplicates("b_id", keep="last")
reviews_unq = reviews_unq.merge(changed, how="left", on="b_id")
doc_infos = docs[
["ref_id", "premium", "ort", "fach_string", "url", "url_hinten"]
].drop_duplicates("ref_id", keep="last")
reviews_unq = reviews_unq.merge(doc_infos, how="left", on="ref_id")
# store original rating (on removal of review grade disappears) and re add to reviews
ratings = reviews_w1[["gesamt_note_class", "b_id"]].groupby("b_id").min().reset_index()
reviews_unq = reviews_unq.merge(ratings, how="left", on="b_id")
reviews_unq = reviews_unq.replace(np.nan, 0)
# remove those without a grade (under review without previous entry)
# reviews_unq = reviews_unq[reviews_unq["gesamt_note_class_y"] > 0]
reviews_unq.head(2)
# Only reviews that were removed With additional cols
removed = reviews_unq.loc[
(reviews_unq["removed"] == 1),
[
"b_id",
"b_date",
"date_create",
"removed",
"readded",
"premium",
"gesamt_note_class_y",
"wave",
],
].reset_index(drop=True)
removed.head(2)
# ## Analysis
#
# After we have cleaned and prepared the data, we can check some of its properties. First, let's see how many new reviews are published each week during our observation period:
# +
# Only reviews that were published during observation wave 1
reviews_unq_new_in_wave1 = reviews_unq.loc[
(reviews_unq["b_date"] >= date_firstday) & (reviews_unq["b_date"] <= date_lastday),
]
# From daily data to weekly aggregation
plt = reviews_unq_new_in_wave1[["b_date", "premium"]].set_index("b_date")
plt["reviews"] = 1
plt["non premium"] = abs(plt["premium"] - 1)
plt = plt.resample("W-MON", label="left").sum()
reviews_new_total = plt["reviews"].sum()
fig = px.bar(
plt,
x=plt.index,
y=["non premium", "premium"],
title=f"New reviews per week in 2020 (Total {reviews_new_total})",
labels={"b_date": "Date published", "variable": "Published reviews"},
barmode="stack",
)
fig.update_xaxes(dtick=7 * 24 * 60 * 60 * 1000, tickformat="%d %b", tick0="2020-01-06")
fig.show()
# + tags=["hide"]
# Share of Premium
reviews_new_total_prem = plt["premium"].sum()
reviews_new_total_noprem = plt["non premium"].sum()
reviews_new_share_prem = (
reviews_new_total_prem / (reviews_new_total_prem + reviews_new_total_noprem) * 100
)
# descriptives
reviews_min = plt["reviews"].min()
reviews_max = plt["reviews"].max()
reviews_mean = plt["reviews"].mean()
md(
f"Each week, there are between {reviews_min} and {reviews_max} newly published reviews. The average week sees about {reviews_mean:.0f} of them. Reviews on premium profiles have a share of {reviews_new_share_prem:.0f}%."
)
# -
# Next, we compare those numbers to the number of reviews removed during the same time span:
freq_removed = reviews_unq["removed"].value_counts()
freq_removed_perc = reviews_unq["removed"].value_counts(normalize=True) * 100
freq_removed_perc_of_new = freq_removed / reviews_new_total * 100
print(
f"Removed reviews: {freq_removed[1]:.0f} ({freq_removed_perc[1]:.2f}% of all"\
f", {freq_removed_perc_of_new[1]:.2f}% of new reviews in period)"
)
# + tags=["hide"]
md(
f"Over the nine month period in which we observed all changes in the reviews on a daily basis, we find only {freq_removed[1]:.0f} removed reviews. That amounts to only {freq_removed_perc[1]:.2f}% of all reviews and {freq_removed_perc_of_new[1]:.2f}% of the newly published reviews during that same observation period."
)
# -
# In general, **the removal of reviews seems not to be very common**. Still, **it could have a substantial impact on total ratings**. As there are only few negative reviews in general, removing those can alter the picture greatly.
# As before, we visualize the removed reviews by week and check for patterns:
# +
# From daily data to weekly aggregation
plt = removed[["date_create", "removed", "premium"]].set_index("date_create")
plt = plt.resample("W-MON", label="left").sum()
plt["non premium"] = plt["removed"] - plt["premium"]
reviews_removed_total = plt["removed"].sum()
fig = px.bar(
plt,
x=plt.index,
y=["non premium", "premium"],
title=f"Removed reviews per week in 2020 (Total {reviews_removed_total:.0f})",
labels={"date_create": "Date", "variable": "Removed Reviews"},
barmode="stack",
)
fig.update_xaxes(dtick=7 * 24 * 60 * 60 * 1000, tickformat="%d %b", tick0="2020-01-06")
fig.show()
# +
# Share of Premium
reviews_removed_prem = plt["premium"].sum()
reviews_removed_prem_share = reviews_removed_prem / reviews_removed_total * 100
# descriptives
reviews_min = int(plt["removed"].min())
reviews_max = int(plt["removed"].max())
reviews_mean = plt["removed"].mean()
# + tags=["hide"]
md(
f"Each week, between {reviews_min} and {reviews_max} reviews are removed. In an average week there are about {reviews_mean:.0f} of them. Out of all removed reviews during the observation period, those on premium profiles have a share of {reviews_removed_prem_share:.0f}%. Hence, **the share of removed reviews is substantially lower then the share of published reviews ({reviews_new_share_prem:.0f}%, see above) on premium profiles.**"
)
# -
# So, there is no problem with reviews being disproportionately removed from premium profiles to improve their ratings? Not so fast! While this seems to hold true, it's not the right question to ask. We've learned before, that in general premium users get way less poor ratings than non paying users (see [first part]({filename}/jameda_part1.ipynb)). Also, it's intuitive that removed reviews will predominantly have low ratings (we'll check that in a minute). Consequently, the real question is: **"Are relatively more critical reviews (i.e. those with low ratings) removed from premium profiles?"**. Thus, we also need to take the ratings into account when comparing groups:
# Filter for poor reviews
reviews_poor = reviews_unq[reviews_unq["gesamt_note_class_y"] >= 4]
# How many of the poor ratings are removed by status
share = reviews_poor.groupby(["premium"])["removed"].value_counts(normalize=True) * 100
prob_removed_premium = share[1][1] / share[0][1]
print(share)
# + tags=["hide"]
md(
f"The answer to the above is: **Yes**. On premium profiles {share[1][1]:.1f}% of poor reviews are removed but only {share[0][1]:.1f}% are removed on non premium profiles. **A poor rating on a premium profile is {prob_removed_premium:.0f} times more likely to be removed compared to one on a non premium profile**."
)
# -
# In the following, we look a bit closer at the reviews that get removed. As stated above, we'd expect them to have strictly negative ratings:
# +
# frequency removed by rating
plt = removed[["gesamt_note_class_y", "removed", "premium"]].reset_index(drop=True)
plt = (
plt.value_counts("gesamt_note_class_y", normalize=True)
.rename("frequency")
.reset_index()
)
fig = px.bar(
plt,
x="gesamt_note_class_y",
y="frequency",
title="Rating frequency of removed reviews",
labels={"gesamt_note_class_y": "Rating"},
)
fig.update_yaxes(tickformat="%")
fig.show()
# -
# Well, our intuition was pretty much right. **By far, most of the removed reviews have a poor rating**. Still, a few of the removed reviews had a good rating. Turns out, those are mostly misrated cases where a positive rating was given to a critical comment. (Notice: A rating of 0 means that the review didn't have a rating at all, i.e. it was just a comment)
# Next, we ask ourselves: How long is the typical time span between a critical rating being published and it being reported (more precisely removed, as we don't now how much time passes from report to removal)? We look at all reviews that were removed during the observation period and compare the time of removal to the time of creation (which can be well before our observation phase):
# compute duration between review published and removed in days
removed["report_duration"] = removed["date_create"] - removed["b_date"]
removed["report_duration_days"] = removed["report_duration"].map(lambda x: x.days)
removed.head(2)
# +
# Visualize time delta from publishing to removal for removed reviews
plt = removed[["report_duration_days", "removed"]].reset_index(drop=True)
fig = px.histogram(
plt,
x="report_duration_days",
title="Removed reviews: days between publishing and removal",
labels={"report_duration_days": "Days"},
histnorm="probability",
nbins=200,
marginal="box",
)
fig.update_yaxes(tickformat="%")
fig.show()
# -
# This chart give us some nice insights about the whole reporting / removal process:
# First, the record for the most short lived comment is only four days. That might be a good proxy for the minimum reaction time of Jameda, i.e. the time between receiving a report and acting on it. About 12% of the removed reviews are removed within 20 days. But in general, **it takes about three months for a review to be removed**. Nonetheless, there are quite a few reviews that get removed much later. In one case, the review was removed after more than seven years!
# If we compare this distribution between paying and non paying physicians, we might learn some more:
# +
# Visualize time delta from publishing to removal for removed reviews
plt = removed[["report_duration_days", "removed", "premium"]].reset_index(drop=True)
plt = plt[(plt["removed"] == 1)]
fig = px.histogram(
plt,
x="report_duration_days",
color="premium",
title="Removed reviews: days between publishing and removal",
labels={"report_duration_days": "Days"},
histnorm="probability",
nbins=200,
marginal="box",
)
fig.update_yaxes(tickformat="%")
fig.show()
# -
# Those distributions look quite different and support our previous hypothesis: Premium users seem in fact to be more concerned about their reputation on Jameda. **Critical reviews on their profiles are removed (reported) much faster**. On median, this is the case after 52 days while for non premium users the median is 139 days.
# As a last analysis, let's see what happens to the removed reviews we observed after some time has passed. Following our original observation period in 2020 (wave 1), we updated our review data in February 2021 (wave 2). After about five months since the end of wave 1, how many of the removed reviews have been re published? How many have been deleted for good?
# Which removed during wave 1 are re added until wave 2
print("Removed during wave one:", removed["b_id"].shape[0])
readded = removed.merge(reviews_w2, on="b_id")
readded = readded[readded["b_stand"].isin([1, 5])]
print("Out of those, re added until wave two:", readded.shape[0])
pct_readded = readded.shape[0] / removed["b_id"].shape[0] * 100
print(f"Percent re added of removed total: {pct_readded:.1f}%")
# Perct of removed is re added by status
pct_readded_by_status = (
readded["premium"].value_counts() / removed["premium"].value_counts() * 100
)
print(f"Percent re added of removed for non premium: {pct_readded_by_status[0]:.1f}%")
print(f"Percent re added of removed for premium: {pct_readded_by_status[1]:.1f}%")
# + jupyter={"source_hidden": true} tags=["hide"]
md(
f"**When a review gets removed, it stays removed in most cases**. Only {pct_readded:.1f}% of all removed reviews are re published after five months or longer in our observation. This share differs by status. For reviews on non premium profiles the share of re added reviews is {pct_readded_by_status[0]:.1f}% but for premium profiles it is only {pct_readded_by_status[1]:.1f}%. This could indicate that Jameda does not validate all reported reviews equally and therefor favors premium users. However, the number of observations is low and there are a few necessary assumptions that can't be checked (e.g. that the share of reported reviews violating the rules is identical). Hence, this is speculative and can't be backed by the data.<br>Nonetheless, **reporting unpleasant reviews seems like a good strategy for physicians in order to improve their ratings.**"
)
# -
# ### Conclusion
#
# This post was a sequel to the [original analysis]({filename}/jameda_part1.ipynb) which investigated whether Jameda favors its paying users. By collecting and analyzing new data over a period of about nine months, we were able to overcome the limitations of the first analysis. In particular, we focused on insights referring to the removal of critical reviews on the profiles of physicians. The main takeaways are these:
#
# 1. Jameda has a lot of active users. Each week a lot of reviews are created by patients and published
# 2. About 42% of the created reviews are published on the profiles of premium physicians
# 3. Critical reviews can be reported by physicians and are removed until Jameda has validated them. The share of removed reviews on premium profiles is only 23% of the total removed reviews
# 4. Removed reviews overwhelmingly have poor ratings
# 5. Removed reviews are seldom. However, they exclusively target poor ratings which are rare. As such, the removal can significantly alter profiles
# 6. On premium profiles, reviews with poor ratings are three times more likely to be removed compared to those on non premium profiles
# 7. Critical reviews on premium profiles are removed much faster than those on non premium profiles
# 8. Once deleted, a rating is very unlikely to ever be re published. Only 7.2% of removed reviews were re published after >5 months
# 9. There is some dubious hint, that removed reviews on premium profiles are more likely to stay removed
#
# The last few points are the most relevant ones for answering our original question. **Differences in the total ratings of physicians on Jameda are not solely due to received ratings**. The removal of reviews plays a role as well: Poor reviews are removed faster and more often from premium users' profiles. This is particularly impactful, because a deleted reviews is very unlikely to ever be re published again. **As a result, at least some profiles will have inflated ratings (on average, those are premium profiles)**. This has serious consequences. Not only is the rating a strong signal for potential patients but Jameda also uses it as a default sorting criterion in the search. Consequently, physicians with higher ratings will get more patients through the platform.
# While this might seem unfair, it's not easy to assign guilt. It's likely a consequence of the greater effort that premium users put in maintaining their good reputation on the platform. They are simply more inclined to report critical reviews. Also, it is not too far-fetched to believe that there are good reasons that at least some of the reviews are removed. While this is not favoring premium users, it certainly is a disadvantage for physicians that are not actively monitoring their profiles. Those are usually the non paying users.
# Jameda's main responsibility is to ensure that the reporting of reviews is not abused. This includes making sure that reviews are validated fast and re published if they don't violate any rules. It's questionable if this is currently the case. Only a small share of removed reviews seems to ever be re added.
# However, one must also give Jameda some credit. It's a very complicated matter of law to decide which reviews are permissible. Erring on the side of removal might be the safest strategy for them. Also, there have been some efforts to penalize abusive physicians (i.e. those that report reviews on baseless grounds). They can get their [quality seal retracted](https://www.jameda.de/qualitaetssicherung/bewertung-loeschen/).
# The most critical aspect is that Jameda must treat all reported reviews equally. If they don't, that would really be a severe case of misconduct. Unfortunately, it might be next to impossible to tell "from the outside".
# To sum up:
# it would probably be too simple to judge Jameda very harshly for the outcome. Nonetheless, it's clear that the outcome is sub optimal for at least some (potential) patients and physicians: **total ratings for doctors on the platform do not always represent the unfiltered aggregate feedback of patients**. Hence, patients' choices will be biased. On average, premium profiles benefit from this and non-premium profiles are at a disadvantage.
# <br><br>
#
| jameda_part2.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 cv2
import numpy as np
# ### Create our body classifier
body_classifier = cv2.CascadeClassifier('Haarcascades/haarcascade_fullbody.xml')
# ### Initiate video capture for video file
#cap = cv2.VideoCapture('Videos/pedestrians.avi')
cap = cv2.VideoCapture('Videos/People_Walking.mp4')
# +
# Loop once video is successfully loaded
while cap.isOpened():
# Read first frame
ret, frame = cap.read()
# Pass frame to our body classifier
bodies = body_classifier.detectMultiScale(frame, 1.2, 3)
if ret == True:
# Extract bounding boxes for any bodies identified
for (x,y,w,h) in bodies:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 255), 2)
cv2.imshow('Pedestrians', frame)
if cv2.waitKey(1) == 27:
break
else:
break
cap.release()
cv2.destroyAllWindows()
# -
| 14_Pedestrian_Detection.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
from sklearn import preprocessing
from sklearn.metrics import precision_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
# +
from sklearn.preprocessing import StandardScaler
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
# %matplotlib inline
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.feature_selection import RFE
from sklearn import metrics
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.metrics import classification_report,confusion_matrix
import sklearn.model_selection as model_selection
from random import sample
from sklearn import preprocessing
from sklearn.model_selection import validation_curve
from sklearn.pipeline import make_pipeline
from sklearn.metrics import make_scorer
from sklearn.metrics import accuracy_score
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
# -
# ### Column Description
#
# ● store_id - The unique identifier of a store.
#
# ● product_id - The unique identifier of a product.
#
# ● date - Sales date (YYYY-MM-DD)
#
# ● sales - Sales quantity
#
# ● revenue - Daily total sales revenue
#
# ● stock - End of day stock quantity
#
# ● price - Product sales price
#
# ● promo_type_1 - Type of promotion applied on channel 1
#
# ● promo_bin_1 - Binned promotion rate for applied promo_type_1
#
# ● promo_type_2 - Type of promotion applied on channel 2
#
# ● promo_bin_2 - Binned promotion rate for applied promo_type_2
#
# ● promo_discount_2 - Discount rate for applied promo type 2
#
# ● promo_discount_type_2 - Type of discount applied
#
# ● product_length - Length of product
#
# ● product_depth - Depth of product
#
# ● product_width - Width of product
#
# ● hierarchy1_id
#
# ● hierarchy2_id
#
# ● hierarchy3_id
#
# ● hierarchy4_id
#
# ● hierarchy5_id
#
# ● storetype_id
#
# ● store_size
#
# ● city_id
#
# ● train_or_test - rows with train tag will be used to train KNNRegressor and rows with test
# tag will be used for accuracy calculation
# ## Code
sales = pd.read_csv("sales.csv")
ph = pd.read_csv("product_hierarchy.csv")
store_cities = pd.read_csv("store_cities.csv")
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
print("Sales size: ", sales.shape)
print("Product Hierarchy size: ", ph.shape)
print("Store Cities size: ", store_cities.shape)
sales.head()
sales.isna().sum()
print("Min Date: ", sales.date.min() )
print("Max Date: ", sales.date.max() )
ph.head()
store_cities.head()
# ### Q3 - Classification #2
# When there is a new product in the system, every business user has a business experience to guess what will be the seasonality curve in the future. Can we replace a business user's experience with an algorithm?
q3_submissions = pd.read_csv("Q3/Q3_submission.csv")
predictions= list(q3_submissions.product_id.values)
sales_products = sales.merge(ph,on='product_id', how='inner')
sales_products.head()
sales.shape
sales_products.shape
print("Unique Products in ph: ",len(ph.product_id.unique()))
print("Unique Products in sales: ",len(sales.product_id.unique()))
q3_train = ph[~ph.product_id.isin(predictions)]
q3_submission = ph[ph.product_id.isin(predictions)]
q3_train.head()
q3_submission.head()
# +
q3_train.sort_values(by="cluster_id",inplace=True)
q3_train.index = q3_train.product_id
q3_train.drop("product_id",axis=1, inplace=True)
q3_submission.index = q3_submission.product_id
q3_submission.drop("product_id",axis=1, inplace=True)
# -
q3_train.head()
q3_submission.head()
q3_train.cluster_id.value_counts()
# **Label Encoding**
le = preprocessing.LabelEncoder()
le.fit(q3_train.cluster_id)
q3_train.cluster_id = le.transform(q3_train.cluster_id)
sales_products.head()
sales_by_4 = sales_products.groupby("hierarchy4_id").sum()
sales_by_3 = sales_products.groupby("hierarchy3_id").sum()
sales_by_2 = sales_products.groupby("hierarchy2_id").sum()
sales_by_1 = sales_products.groupby("hierarchy1_id").sum()
sales_by_4.drop(sales_by_4.columns[5:],axis=1,inplace=True)
sales_by_3.drop(sales_by_3.columns[5:],axis=1,inplace=True)
sales_by_2.drop(sales_by_2.columns[5:],axis=1,inplace=True)
sales_by_1.drop(sales_by_1.columns[5:],axis=1,inplace=True)
sales_by_4.head()
q3_train.head()
q3_submission.head()
train = q3_train.merge(sales_by_4,how="inner",on="hierarchy4_id")
train = train.merge(sales_by_3,how="inner",on="hierarchy3_id")
train = train.merge(sales_by_2,how="inner",on="hierarchy2_id")
train = train.merge(sales_by_1,how="inner",on="hierarchy1_id")
train.head()
train.shape
test = q3_submission.merge(sales_by_4,how="inner",on="hierarchy4_id")
test = test.merge(sales_by_3,how="inner",on="hierarchy3_id")
test = test.merge(sales_by_2,how="inner",on="hierarchy2_id")
test = test.merge(sales_by_1,how="inner",on="hierarchy1_id")
test.head()
test.shape
len(train.columns)
len(test.columns)
train.shape
ph.head()
train.head()
train.shape
# **Label Encoding**
le = preprocessing.LabelEncoder()
le.fit(train.hierarchy5_id)
train.hierarchy5_id = le.transform(train.hierarchy5_id)
le = preprocessing.LabelEncoder()
le.fit(train.hierarchy4_id)
train.hierarchy4_id = le.transform(train.hierarchy4_id)
le = preprocessing.LabelEncoder()
le.fit(train.hierarchy3_id)
train.hierarchy3_id = le.transform(train.hierarchy3_id)
le = preprocessing.LabelEncoder()
le.fit(train.hierarchy2_id)
train.hierarchy2_id = le.transform(train.hierarchy2_id)
le = preprocessing.LabelEncoder()
le.fit(train.hierarchy1_id)
train.hierarchy1_id = le.transform(train.hierarchy1_id)
train.head()
le = preprocessing.LabelEncoder()
le.fit(test.hierarchy5_id)
test.hierarchy5_id = le.transform(test.hierarchy5_id)
le = preprocessing.LabelEncoder()
le.fit(test.hierarchy4_id)
test.hierarchy4_id = le.transform(test.hierarchy4_id)
le = preprocessing.LabelEncoder()
le.fit(test.hierarchy3_id)
test.hierarchy3_id = le.transform(test.hierarchy3_id)
le = preprocessing.LabelEncoder()
le.fit(test.hierarchy2_id)
test.hierarchy2_id = le.transform(test.hierarchy2_id)
le = preprocessing.LabelEncoder()
le.fit(test.hierarchy1_id)
test.hierarchy1_id = le.transform(test.hierarchy1_id)
test.head()
test.isna().sum()
train["product_length"] =train["product_length"].fillna(train["product_length"].median())
train.product_depth.fillna(0,inplace=True)
train.product_width.fillna(0,inplace=True)
test.product_length.fillna(0,inplace=True)
test.product_depth.fillna(0,inplace=True)
test.product_width.fillna(0,inplace=True)
train.isna().sum()
len(train.columns)
len(test.columns)
train.shape
test.shape
train.tail()
test.tail()
# +
# Missing of the entry can also be a valuable information
# So we will create a column that is False when value is missing
# We encoded missingness in categorical columns so we will just create _na columns for numerical types
def fix_missing(df, col, name):
if is_numeric_dtype(col):
if pd.isnull(col).sum():
df[name+"_na"] = pd.isnull(col)
df[name] = col.fillna(col.median())
# We will have codes starting from 0 (for missing)
# def numericalize(df, col, name):
# if not is_numeric_dtype(col):
# print(df[name].cat.categories)
# print(col.cat.codes+1)
# df[name] = col.cat.codes+1
# dic = dict()
# def numericalize(df, col, name):
# if not is_numeric_dtype(col):
# if name == 'hierarchy4_id':
# for i in range(len(df[name].cat.categories)):
# dic[str(df[name].cat.categories[i])] = list(set(df[name].cat.codes))[i]+1
# df[name] = col.cat.codes+1
def proc_df(df, y_fld):
# y = df[y_fld].values
# df.drop([y_fld], axis = 1, inplace = True)
for n, c in df.items():
fix_missing(df, c, n)
# for n, c in df.items():
# numericalize(df, c, n)
y = df[y_fld].values
df.drop([y_fld], axis = 1, inplace = True)
res = [df, y]
return res
# -
# ### Model
X_train = train.drop("cluster_id",axis=1)[:500]
y_train = train.cluster_id[:500].values
X_test = test.drop("cluster_id",axis=1)
y_test = test.cluster_id.values
# Fitting Random Forest Classification to the Training set
classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 42)
classifier.fit(X_train, y_train)
rfc_pred = classifier.predict(X_test)
print ("Random Forest Train Accuracy Baseline:", metrics.accuracy_score(y_train, classifier.predict(scaled_X_train)))
print ("Random Forest Test Accuracy Baseline:", metrics.accuracy_score(y_test, classifier.predict(scaled_X_test)))
#print('Accuracy of random forest classifier on test set: {:.2f}'.format(rfc.score(X_test, y_test)))
# +
# Feature Scaling
scaler = StandardScaler()
scaled_X_train = scaler.fit_transform(X_train)
scaled_X_test = scaler.transform(X_test)
# Fitting Random Forest Classification to the Training set
classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 42)
classifier.fit(scaled_X_train, y_train)
rfc_pred = classifier.predict(X_test)
print ("Random Forest Train Accuracy Baseline:", metrics.accuracy_score(y_train, classifier.predict(scaled_X_train)))
print ("Random Forest Test Accuracy Baseline:", metrics.accuracy_score(y_test, classifier.predict(scaled_X_test)))
#print('Accuracy of random forest classifier on test set: {:.2f}'.format(rfc.score(X_test, y_test)))
# -
# **Dividing the datasets**
train.merge(ph,on="hierarchy5_id",how="inner").head()
train = train.drop(train.columns[30:],axis=1)
test = test.merge(ph,on="hierarchy5_id",how="inner")
test = test.drop(test.columns[30:],axis=1)
test.head()
| Q3 - XGBoost.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
# ---
# # LIBRERIAS
#
# Podemos importar operaciones u otras funciones desde una "librería" (en español se ha vuelto más común hablar de librerías, aunque la traducción correcta de library es biblioteca).
# +
x = min(1, 2, 3)
y = max(1, 2, 3)
print(x)
print(y)
# +
# Imprime el valor de 5 potencia de 4 (5 * 5 * 5 * 5):
x = pow(4, 3)
print(x)
# -
# #### Ejemplo para la importación de la librería math para usar la función raíz cuadrada sqrt.
# +
import math
valor = math.sqrt(64)
print(valor)
# -
# #### Ayuda sobre la función sqrt
help(math.sqrt)
import math
dir(math) # Lista de funciones
help(math) # Ayuda sobre la librería math
# #### Ejercicio para la importación de la librería random.
# Jose y Laura juegan a los dados, y determinaron las siguientes reglas:
#
# 1. Si sale 1, vuelven a lanzar.
# 2. Si sale 6, quedan empatados.
# 3. Si sale 2 ó 3 gana Jose.
# 4. Si sale 4 ó 5 gana Laura.
# +
import random
numero = random.randint(1,6)
accion={
1: "Vuelven a lanzar",
2: "<NAME>",
3: "<NAME>",
4: "Quedan empatados"
}
print("Sacaste un {0}".format(numero))
if numero==1:
print(accion.get(1))
elif numero==2 or numero==3:
print(accion.get(2))
elif numero==4 or numero==5:
print(accion.get(3))
else:
print(accion.get(4))
# -
# ## librería datetime
# ejemplos:
import datetime
now = datetime.datetime.now()
print(now)
# +
import datetime
now = datetime.datetime.now()
print(now.year)
print(now.strftime("%A"))
# -
# [Stftime documentacíon](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)
# +
import datetime
fecha_impuesta = datetime.datetime(2018, 6, 1)
print(fecha_impuesta.strftime("%B"))
# -
# # Librerías de terceros
# ## Librería numpy
#
import numpy
numpy.sqrt([1,4,9])
# #### math
# Is part of the standard python library. It provides functions for basic mathematical operations as well as some commonly used constants.
#
# #### numpy
# on the other hand is a third party package geared towards scientific computing. It is the defacto package for numerical and vector operations in python. It provides several routines optimized for vector and array computations as a result, is a lot faster for such operations than say just using python lists. See http://www.numpy.org/ for more info.
# +
import math
x = math.pi
print(x)
import numpy
x = numpy.pi
print(x)
# +
# Ordena un arreglo de menor a mayor
import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr))
# -
# ## Matplotlib
# Es una librería de visualización de gráficos a bajo nivel.
# +
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints, "o")
plt.show()
# +
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x,y)
plt.show()
# +
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple')
ax.grid()
fig.savefig("test.png")
plt.show()
| 6_Librerias.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 time
# Importing Inventory data from Record.json file
fd = open('Record.json','r')
js = fd.read()
fd.close()
# Converting String data to Dictionary
record = json.loads(js)
# Displaying Menu
print("--------------------MENU---------------------")
for key in record.keys():
print(key, record[key]['Name'], record[key]['Price'], record[key]['Qn'])
print("---------------------------------------------")
print('')
# Taking Inputs from the user about their details and purchase
ui_name = str(raw_input("Enter your name : "))
ui_mail = str(raw_input("Enter Mail ID : "))
ui_ph = str(raw_input("Enter Phone No : "))
ui_pr = str(raw_input("Enter product ID : "))
ui_qn = int(input("Enter Quantity : "))
print("---------------------------------------------")
print('')
# If we're having equal or more quantity then the user wants
if (record[ui_pr]['Qn'] >= ui_qn):
print("Name : ", record[ui_pr]["Name"])
print("Price (Rs): ", record[ui_pr]["Price"])
print("Quantity : ", ui_qn)
print("---------------------------------------------")
print("Billing : ", ui_qn * record[ui_pr]["Price"], "Rs")
print("---------------------------------------------")
# Updating Inventory in Dictionary
record[ui_pr]['Qn'] = record[ui_pr]['Qn'] - ui_qn
# Generating CSV Transection Detail
sale = ui_name+","+ui_mail+","+ui_ph+","+ui_pr+","+record[ui_pr]["Name"]+","+str(ui_qn)+","+str(record[ui_pr]["Price"])+","+str(ui_qn * record[ui_pr]["Price"])+","+time.ctime()+"\n"
# If we're less quantity then the user wants
else:
print("Sorry, We're not having enough quanity of product in our Inventory.")
print("We're only having " + str(record[ui_pr]['Qn']) + " quantity.")
print("---------------------------------------------")
ch == str(raw_input("Press Y to purchase: "))
# If user wants to purchase the whole quantity for that product
if(ch == "Y" or ch == 'y'):
print("---------------------------------------------")
print("Name : ", record[ui_pr]["Name"])
print("Price (Rs): ", record[ui_pr]["Price"])
print("Quantity : ", record[ui_pr]['Qn'])
print("---------------------------------------------")
print("Billing : ", record[ui_pr]['Qn'] * record[ui_pr]["Price"], "Rs")
print("---------------------------------------------")
# Updating Inventory in Dictionary
record[ui_pr]['Qn'] = 0
# Generating CSV Transection Detail
sale = ui_name+","+ui_mail+","+ui_ph+","+ui_pr+","+record[ui_pr]["Name"]+","+str(record[ui_pr]['Qn'])+","+str(record[ui_pr]["Price"])+","+str(record[ui_pr]['Qn'] * record[ui_pr]["Price"])+","+time.ctime()+"\n"
# If user pressed anything except Y or y
else:
print("Thanks!")
# Converting Inventory Dictionary to String
js = json.dumps(record)
# Updating Inventory and Saving in to my Records.json
fd = open('Record.json','w')
fd.write(js)
fd.close()
# Adding Transection on Sales File
fd = open('Sales.txt','a')
fd.write(sale)
fd.close()
print('')
print("---------------------------------------------")
print(" Thanks for your order, Inventory Updated! ")
print("---------------------------------------------")
# -
| 4. Inventory Management System with JSON/9. Conclusion/Inventory Management System - Conclusion.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
# ---
# # Copy Number segments (Broad)
#
# The goal of this notebook is to introduce you to the Copy Number (CN) segments BigQuery table.
#
# This table contains all available TCGA Level-3 copy number data produced by the Broad Institute using the Affymetrix Genome Wide SNP6 array, as of July 2016. The most recent archives (*eg* ``broad.mit.edu_UCEC.Genome_Wide_SNP_6.Level_3.143.2013.0``) for each of the 33 tumor types was downloaded from the DCC, and data extracted from all files matching the pattern ``%_nocnv_hg19.seg.txt``. Each of these segmentation files has six columns: ``Sample``, ``Chromosome``, ``Start``, ``End``, ``Num_Probes``, and ``Segment_Mean``. During ETL the sample identifer contained in the segmentation files was mapped to the TCGA aliquot barcode based on the SDRF file in the associated mage-tab archive.
#
# In order to work with BigQuery, you need to import the python bigquery module (`gcp.bigquery`) and you need to know the name(s) of the table(s) you are going to be working with:
import gcp.bigquery as bq
cn_BQtable = bq.Table('isb-cgc:tcga_201607_beta.Copy_Number_segments')
# From now on, we will refer to this table using this variable ($cn_BQtable), but we could just as well explicitly give the table name each time.
#
# Let's start by taking a look at the table schema:
# %bigquery schema --table $cn_BQtable
# Unlike most other molecular data types in which measurements are available for a common set of genes, CpG probes, or microRNAs, this data is produced using a data-driven approach for each aliquot independently. As a result, the number, sizes and positions of these segments can vary widely from one sample to another.
#
# Each copy-number segment produced using the CBS (Circular Binary Segmentation) algorithm is described by the genomic extents of the segment (chromosome, start, and end), the number of SNP6 probes contained within that segment, and the estimated mean copy-number value for that segment. Each row in this table represents a single copy-number segment in a single sample.
#
# The ``Segment_Mean`` is the base2 log(copynumber/2), centered at 0. Positive values represent amplifications (CN>2), and negative values represent deletions (CN<2). Although within each cell, the number of copies of a particular region of DNA must be an integer, these measurements are not single-cell measurements but are based on a heterogenous sample. If 50% of the cells have 2 copies of a particular DNA segment, and 50% of the cells have 3 copies, this will result in an estimated copy number value of 2.5, which becomes 1.32 after the log transformation.
# Let's count up the number of unique patients, samples and aliquots mentioned in this table. We will do this by defining a very simple parameterized query. (Note that when using a variable for the table name in the FROM clause, you should not also use the square brackets that you usually would if you were specifying the table name as a string.)
# + magic_args="--module count_unique" language="sql"
#
# DEFINE QUERY q1
# SELECT COUNT (DISTINCT $f, 25000) AS n
# FROM $t
# -
fieldList = ['ParticipantBarcode', 'SampleBarcode', 'AliquotBarcode']
for aField in fieldList:
field = cn_BQtable.schema[aField]
rdf = bq.Query(count_unique.q1,t=cn_BQtable,f=field).results().to_dataframe()
print " There are %6d unique values in the field %s. " % ( rdf.iloc[0]['n'], aField)
# Unlike most other molecular data types, in addition to data being available from each tumor sample, data is also typically available from a matched "blood normal" sample. As we can see from the previous queries, there are roughly twice as many samples as there are patients (aka participants). The total number of rows in this table is ~2.5 million, and the average number of segments for each aliquot is ~116 (although the distribution is highly skewed as we will see shortly).
# Let's count up the number of samples using the ``SampleTypeLetterCode`` field:
# + language="sql"
#
# SELECT
# SampleTypeLetterCode,
# COUNT(*) AS n
# FROM (
# SELECT
# SampleTypeLetterCode,
# SampleBarcode
# FROM
# $cn_BQtable
# GROUP BY
# SampleTypeLetterCode,
# SampleBarcode )
# GROUP BY
# SampleTypeLetterCode
# ORDER BY
# n DESC
# -
# As shown in the results of this last query, most samples are primary tumor samples (TP), and in most cases the matched-normal sample is a "normal blood" (NB) sample, although many times it is a "normal tissue" (NT) sample. You can find a description for each of these sample type codes in the TCGA [Code Tables Report](https://tcga-data.nci.nih.gov/datareports/codeTablesReport.htm).
# In order to get a better feel for the data in this table, let's take a look at the range of values and the distributions of segment lengths, mean segment values, and number of probes contributing to each segment.
# + language="sql"
#
# SELECT
# MIN(Length) AS minLength,
# MAX(Length) AS maxLength,
# AVG(Length) AS avgLength,
# STDDEV(Length) AS stdLength,
# MIN(Num_Probes) AS minNumProbes,
# MAX(Num_Probes) AS maxNumProbes,
# AVG(Num_Probes) AS avgNumProbes,
# STDDEV(Num_Probes) AS stdNumProbes,
# MIN(Segment_Mean) AS minCN,
# MAX(Segment_Mean) AS maxCN,
# AVG(Segment_Mean) AS avgCN,
# STDDEV(Segment_Mean) AS stdCN,
# FROM (
# SELECT
# Start,
# END,
# (End-Start+1) AS Length,
# Num_Probes,
# Segment_Mean
# FROM
# $cn_BQtable )
# -
# Segment lengths range from just 1 bp all the way up to entire chromosome arms, and the range of segment mean values is from -8.7 to +10.5 (average = -0.28, standard deviation = 1.0)
# Now we'll use matplotlib to create some simple visualizations.
import numpy as np
import matplotlib.pyplot as plt
# For the segment means, let's invert the log-transform and then bin the values to see what the distribution looks like:
# + magic_args="--module getCNhist" language="sql"
#
# SELECT
# lin_bin,
# COUNT(*) AS n
# FROM (
# SELECT
# Segment_Mean,
# (2.*POW(2,Segment_Mean)) AS lin_CN,
# INTEGER(((2.*POW(2,Segment_Mean))+0.50)/1.0) AS lin_bin
# FROM
# $t
# WHERE
# ( (End-Start+1)>1000 AND SampleTypeLetterCode="TP" ) )
# GROUP BY
# lin_bin
# HAVING
# ( n > 2000 )
# ORDER BY
# lin_bin ASC
# -
CNhist = bq.Query(getCNhist,t=cn_BQtable).results().to_dataframe()
bar_width=0.80
plt.bar(CNhist['lin_bin']+0.1,CNhist['n'],bar_width,alpha=0.8);
plt.xticks(CNhist['lin_bin']+0.5,CNhist['lin_bin']);
plt.title('Histogram of Average Copy-Number');
plt.ylabel('# of segments');
plt.xlabel('integer copy-number');
# The histogram illustrates that the vast majority of the CN segments have a copy-number value near 2, as expected, with significant tails on either side representing deletions (left) and amplifications (right).
# Let's take a look at the distribution of segment lengths now. First we'll use 1Kb bins and look at segments with lengths up to 1 Mb.
# + magic_args="--module getSLhist_1k" language="sql"
#
# SELECT
# bin,
# COUNT(*) AS n
# FROM (
# SELECT
# (END-Start+1) AS segLength,
# INTEGER((END-Start+1)/1000) AS bin
# FROM
# $t
# WHERE
# (END-Start+1)<1000000 AND SampleTypeLetterCode="TP" )
# GROUP BY
# bin
# ORDER BY
# bin ASC
# -
SLhist_1k = bq.Query(getSLhist_1k,t=cn_BQtable).results().to_dataframe()
plt.plot(SLhist_1k['bin'],SLhist_1k['n'],'ro:');
plt.xscale('log');
plt.yscale('log');
plt.xlabel('Segment length (Kb)');
plt.ylabel('# of Segments');
plt.title('Distribution of Segment Lengths');
# As expected, shorter segment lengths dominate, and between 1Kb and 1Mb it appears that segment lengths follow a power-law distribution.
# Let's have a closer look at the shorter segments, under 1Kb in length:
# + magic_args="--module getSLhist" language="sql"
#
# SELECT
# bin,
# COUNT(*) AS n
# FROM (
# SELECT
# (END-Start+1) AS segLength,
# INTEGER((END-Start+1)/1) AS bin
# FROM
# $t
# WHERE
# (END-Start+1)<1000 AND SampleTypeLetterCode="TP" )
# GROUP BY
# bin
# ORDER BY
# bin ASC
# -
SLhist = bq.Query(getSLhist,t=cn_BQtable).results().to_dataframe()
plt.plot(SLhist['bin'],SLhist['n'],'ro:');
plt.xscale('log');
plt.yscale('log');
plt.xlabel('Segment length (bp)');
plt.ylabel('# of Segments');
plt.title('Distribution of Segment Lengths (<1Kb)');
# At this finer scale, we see that the most comment segment length is ~15bp.
# Let's go back and take another look at the medium-length CN segments and see what happens when we separate out the amplifications and deletions. We'll use queries similar to the ``getSLhist_1k`` query above, but add another ``WHERE`` clause to look at amplifications and deletions respectively.
# + magic_args="--module getSLhist_1k_del" language="sql"
#
# SELECT
# bin,
# COUNT(*) AS n
# FROM (
# SELECT
# (END-Start+1) AS segLength,
# INTEGER((END-Start+1)/1000) AS bin
# FROM
# $t
# WHERE
# (END-Start+1)<1000000 AND SampleTypeLetterCode="TP" AND Segment_Mean<-0.7 )
# GROUP BY
# bin
# ORDER BY
# bin ASC
# + magic_args="--module getSLhist_1k_amp" language="sql"
#
# SELECT
# bin,
# COUNT(*) AS n
# FROM (
# SELECT
# (END-Start+1) AS segLength,
# INTEGER((END-Start+1)/1000) AS bin
# FROM
# $t
# WHERE
# (END-Start+1)<1000000 AND SampleTypeLetterCode="TP" AND Segment_Mean>0.7 )
# GROUP BY
# bin
# ORDER BY
# bin ASC
# -
SLhistDel = bq.Query(getSLhist_1k_del,t=cn_BQtable).results().to_dataframe()
SLhistAmp = bq.Query(getSLhist_1k_amp,t=cn_BQtable).results().to_dataframe()
plt.plot(SLhist_1k['bin'],SLhist_1k['n'],'ro:');
plt.plot(SLhistDel['bin'],SLhistDel['n'],'bo-')
plt.plot(SLhistAmp['bin'],SLhistDel['n'],'go-',alpha=0.3)
plt.xscale('log');
plt.yscale('log');
plt.xlabel('Segment length (Kb)');
plt.ylabel('# of Segments');
plt.title('Distribution of Segment Lengths');
# The amplification and deletion distributions are nearly identical and still seem to roughly follow a power-law distribution. We can also infer from this graph that a majority of the segments less than 10Kb in length are either amplifications or deletions, while ~90% of the segments of lengths >100Kb are copy-number neutral.
# Before we leave this dataset, let's look at how we might analyze the copy-number as it relates to a particular gene of interest. This next parameterized query looks for all copy-number segments overlapping a specific genomic region and computes some statistics after grouping by sample.
# + magic_args="--module getGeneCN" language="sql"
#
# SELECT
# SampleBarcode,
# AVG(Segment_Mean) AS avgCN,
# MIN(Segment_Mean) AS minCN,
# MAX(Segment_Mean) AS maxCN,
# FROM
# $t
# WHERE
# ( SampleTypeLetterCode=$sampleType
# AND Num_Probes > 10
# AND Chromosome=$geneChr
# AND ( (Start<$geneStart AND End>$geneStop)
# OR (Start<$geneStop AND End>$geneStop)
# OR (Start>$geneStart AND End<$geneStop) ) )
# GROUP BY
# SampleBarcode
# -
# Now we'll use this query to get copy-number statistics for three widely-studied genes: EGFR, MYC and TP53.
# +
# EGFR gene coordinates
geneChr = "7"
geneStart = 55086725
geneStop = 55275031
egfrCN = bq.Query(getGeneCN,t=cn_BQtable,sampleType="TP",geneChr=geneChr,geneStart=geneStart,geneStop=geneStop).results().to_dataframe()
# MYC gene coordinates
geneChr = "8"
geneStart = 128748315
geneStop = 128753680
mycCN = bq.Query(getGeneCN,t=cn_BQtable,sampleType="TP",geneChr=geneChr,geneStart=geneStart,geneStop=geneStop).results().to_dataframe()
# TP53 gene coordinates
geneChr = "17"
geneStart = 7571720
geneStop = 7590868
tp53CN = bq.Query(getGeneCN,t=cn_BQtable,sampleType="TP",geneChr=geneChr,geneStart=geneStart,geneStop=geneStop).results().to_dataframe()
# -
# And now we'll take a look at histograms of the average copy-number for these three genes. TP53 (in green) shows a significant number of partial deletions (CN<0), while MYC (in blue) shows some partial amplifications -- more frequently than EGFR, while EGFR (pale red) shows a few extreme amplifications (log2(CN/2) > 2). The final figure shows the same histograms on a semi-log plot to bring up the rarer events.
binWidth = 0.2
binVals = np.arange(-2+(binWidth/2.), 6-(binWidth/2.), binWidth)
plt.hist(tp53CN['avgCN'],bins=binVals,normed=False,color='green',alpha=0.9,label='TP53');
plt.hist(mycCN ['avgCN'],bins=binVals,normed=False,color='blue',alpha=0.7,label='MYC');
plt.hist(egfrCN['avgCN'],bins=binVals,normed=False,color='red',alpha=0.5,label='EGFR');
plt.legend(loc='upper right');
plt.hist(tp53CN['avgCN'],bins=binVals,normed=False,color='green',alpha=0.9,label='TP53');
plt.hist(mycCN ['avgCN'],bins=binVals,normed=False,color='blue',alpha=0.7,label='MYC');
plt.hist(egfrCN['avgCN'],bins=binVals,normed=False,color='red',alpha=0.5,label='EGFR');
plt.yscale('log');
plt.legend(loc='upper right');
| notebooks/Copy Number segments.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
# ---
# +
# Code for recording calls
import sys
import math
def remove_html_markup(s):
tag = False
quote = False
out = ""
for c in s:
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
tag = False
elif c == '"':
quote = not quote
elif not tag:
out = out + c
return out
def square_root(x, eps = 0.00001):
assert x >= 0
y = math.sqrt(x)
assert abs(y * y - x) <= eps
return y
def pretty_locals(local_args):
"""Return local_args in a format suitable for calls.
The 'name=value' format is necessary as we don't know the arguments ordering
in the function call."""
ret = ""
for name, value in local_args.iteritems():
if ret != "":
ret = ret + ", "
ret = ret + name + " = " + repr(value)
return ret
def pretty_call(frame):
return (frame.f_code.co_name +
"(" + pretty_locals(frame.f_locals) + ")")
def traceit(frame, event, arg):
global calls
if event == "call":
print pretty_call(frame)
calls.append(pretty_call(frame))
return traceit
# Write a function, `evaluate_calls`
# that evaluates all calls in the CALLS
# variable.
#
# The ouput should be in the form:
# function(args) = value
# for each element in CALLS
CALLS = ["remove_html_markup(s = '<b>foo</b>')", "square_root(x = 2)"]
def evaluate_calls():
global CALLS
for call in CALLS:
print "{} = {}".format(call, repr(eval(call)))
###
# To test your code, run evaluate_calls and see that
# it prints out:
# remove_html_markup(s = '<b>foo</b>') = 'foo'
# square_root(x = 2) = 1.4142135623730951
evaluate_calls()
# -
| src/Record calls.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
# ---
# # Bosons in optical tweezers
# This Notebook is based on a [paper](https://science.sciencemag.org/content/345/6194/306.abstract) from the Regal group. In this paper, the tunneling of bosons between neighboring sites was observed. With the help of two optical tweezers, at first one and later two bosons were trapped. By bringing the tweezers closer to eachother and by lowering the total trap intensity the boson(s) is(are) able to tunnel from one tweezer to the other. The result of the expirment is observed by distancing the tweezers and measuring the occupation number of the tweezer.
#
# In the first part of the paper only one atom was trapped in an optical tweezer and the other tweezer was empty. In the second parts each tweezer was loaded with a boson. We can now measure the probability such that after the tunnneling the bosons are in different tweezers.
#
# In this notebook we will model the experiments within pennlyane.
# +
import pennylane as qml
import numpy as np
import matplotlib.pyplot as plt
import strawberryfields as sf
from strawberryfields import ops
# %config InlineBackend.figure_format='retina'
# -
# # Single Boson
#
# Let us start out with their observations concerning a single Boson, which was initially loaded into the right site. After a given time $t$ they observe the oscillation of the Boson into the left site as seen below.
import pandas as pd
data_kaufman = pd.read_csv("Data/KaufmanData.csv", names=["t", "PL"])
f, ax = plt.subplots(dpi=96)
ax.plot(data_kaufman.t, data_kaufman.PL, "o")
ax.set_xlabel(r"time $t$")
ax.set_ylabel(r"probability $P_L$")
# $$\newcommand{\braket}[3]{\left\langle{#1}\middle|{#2}|{#3}\right\rangle}$$
#
# We will now model these observations through tunnel coupling. The tunnel coupling is given by $J = -\braket{R}{H_{sp}}{L}/\hbar$ where $|L\rangle$ and $|R\rangle$ are the lowest energy states in the left or right well and $H_{sp}$ the Hamiltonian for a single particle. They extracted an experimental tunnel coupling of $J = 2\pi \cdot 262$Hz.
#
# The Tunneling-Hamiltonian for a single boson in a well is given by:
# $\\$
# $H_t=$
# $\left(\begin{array}{rr}
# 0 & J \\
# J & 0 \\
# \end{array}\right)$
def Ham_sq(J):
"""
The Hamiltonian matrix of the tunneling for a single boson
"""
return np.array([[0, J], [J, 0]])
print(Ham_sq(1))
# We now want to create a quantum circuit with Pennylane, that simulates the tunneling of a boson from one well to another. We first need to initialize the quantum circuit by raising the number operator of the left well by one (boson 1 is in the left well corresponds to $|L\rangle=1$, $|R\rangle=0$).
#
# We now have a boson in the left well. After that we use a beamsplitter to represent the tunneling. In the experiment of Cindy Regal the tunneling depended on the time $t$ the wells were swept together. We can simulate the time by tuning the transmittivity of the beamsplitter. This is done by tuning $\theta$ (From the pennylane documentation: "The transmission amplitude of the beamsplitter is $t=cos(\theta)$. The value $\theta=\frac{\pi}{4}$ gives the 50-50 beamsplitter."), and get a curve for the probabilities of the boson (see Plot. 1) being in the right or left well.
# 
#
# We initiate a single boson in the left well and then perform a beamsplitter gate on the system. We can then measure the occupation number $|n\rangle_L$ and $|n\rangle_R$ which is dependent on $\theta$.
# There are two ways to initiate the boson in the left well:
# * [Displacement gate](https://pennylane.readthedocs.io/en/stable/code/api/pennylane.Displacement.html)
# * [Fock state Gate](https://pennylane.readthedocs.io/en/stable/code/api/pennylane.FockState.html)
#
# While using the displacement gate and fock state gate does not differ when only having a single boson in the well, its evaluation differs when considering a two boson system. We will later see why this is the case and how to overcome this issue.
# +
dev_boson = qml.device("strawberryfields.fock", wires=2, cutoff_dim=10)
@qml.qnode(dev_boson)
def single_boson(x, theta, var=False):
"""
Single Boson well tunneling circuit using the displacement gate
"""
qml.Displacement(x, 0, wires=0)
qml.Beamsplitter(theta, 0, wires=[0, 1])
if var:
return [qml.var(qml.NumberOperator(0)), qml.var(qml.NumberOperator(1))]
else:
return [qml.expval(qml.NumberOperator(0)), qml.expval(qml.NumberOperator(1))]
# -
single_boson(1, np.pi / 4)
print(single_boson.draw())
# +
dev_boson = qml.device("strawberryfields.fock", wires=2, cutoff_dim=10)
@qml.qnode(dev_boson)
def single_boson_fock(theta, var=False):
"""
Single Boson well tunneling circuit using the fock state gate
"""
qml.FockState(1, wires=0)
qml.Beamsplitter(theta, 0, wires=[0, 1])
if var:
return [qml.var(qml.NumberOperator(0)), qml.var(qml.NumberOperator(1))]
else:
return [qml.expval(qml.NumberOperator(0)), qml.expval(qml.NumberOperator(1))]
# -
single_boson_fock(np.pi / 4)
print(single_boson_fock.draw())
thetas = np.linspace(0, np.pi, 100)
res_dis = np.array([single_boson(1, theta) for theta in thetas])
res_fock = np.array([single_boson_fock(theta) for theta in thetas])
# And we print out the resulting evolution.
# +
Jexp = 262 * 2 * np.pi
thetaExp = data_kaufman.t * 1e-3 * Jexp
f, ax = plt.subplots(figsize=(10, 5))
ax.plot(thetaExp, data_kaufman.PL, "o", label="data")
ax.plot(
thetas,
res_dis[:, 0],
label="Prob. of Boson in left well, displacement",
linewidth=2,
)
ax.plot(
thetas,
res_dis[:, 1],
label="Prob. of Boson in right well, displacement",
linewidth=2,
)
ax.plot(
thetas,
res_fock[:, 0],
linestyle=(0, (5, 10)),
label="Prob. of Boson in left well, fock state",
color="red",
)
ax.plot(
thetas,
res_fock[:, 1],
linestyle=(0, (5, 10)),
label="Prob. of Boson in right well, fock state",
color="purple",
)
ax.axvline(x=np.pi / 4, linestyle="--", color="green", label="$t_b$")
ax.axvline(x=3 * np.pi / 4, linestyle="--", color="green")
ax.set_title("Probability of finding Boson in left or right well")
ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
ax.set_xlabel("$\\theta$/time")
ax.set_ylabel("Probability")
# -
# We can clearly see, that the results are identical and model the results from the paper quite well.
# ## Variances
#
# We can now investigate the differences between the intial preparation with a displacement or a Fock state. For this we will look at the variance of the measured expectation values. As we will see, only the Fock state explains the epxerimentally observed fluctuations properly, which fairly even for all times.
var_displacement = np.array([single_boson(1, theta, var=True) for theta in thetas])
var_fock = np.array([single_boson_fock(theta, var=True) for theta in thetas])
# +
plt.figure(dpi=96)
plt.plot(thetas, var_displacement[:, :1], label="Variance of left well")
plt.plot(thetas, var_displacement[:, 1:], label="Variance of right well")
plt.plot(
thetas, var_fock[:, 1:], label="Variance of left well, fock State", linewidth=2
)
plt.plot(
thetas,
var_fock[:, :1],
linestyle=(0, (5, 10)),
label="Variance of right well, fock State",
)
plt.axvline(x=np.pi / 4, linestyle="--", color="green", label="$t_b$")
plt.axvline(x=3 * np.pi / 4, linestyle="--", color="green")
plt.title("Variance of Number Operator for different initialisation")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
plt.xlabel("$\\theta$/time")
_ = plt.ylabel("Variance")
# -
# We can clearly see, that the variance has a maximum for the displacement, when the boson is either in the left or the right well. This can be explained by the nature of the displacement gate. It produces a state in which sometimes 0, 1, 2 or more(?) bosons are in the (in our case left) well, but on average 1 boson is present. The beamsplitter shifts the variance as well as the expectation value from one well to the other.
#
# The fock State on the other hand has a variance of 0 when being initiated. In the case of the beamsplitter being exactly reflective or exactly transmissive, the variance is 0. When the beamsplitter is symmetric ($\theta = \frac{\pi}{4}$,$\frac{3\pi}{4}$) the variance has a peak. The variances of both wells are exactly equal.
# ## Two Bosons
#
# We can now initiate the Circuit with a boson in each well. The difference between the two possibilities of initiating the wells become clearer now.
#
# 
#
# +
dev_boson = qml.device("strawberryfields.fock", wires=2, cutoff_dim=10)
@qml.qnode(dev_boson)
def two_bosons(x_1, x_2, theta, var=False):
qml.Displacement(x_1, 0, wires=0)
qml.Displacement(x_2, 0, wires=1)
qml.Beamsplitter(theta, 0, wires=[0, 1])
if var:
return [qml.var(qml.NumberOperator(0)), qml.expval(qml.NumberOperator(1))]
else:
return [qml.expval(qml.NumberOperator(0)), qml.expval(qml.NumberOperator(1))]
# +
dev_boson = qml.device("strawberryfields.fock", wires=2, cutoff_dim=10)
@qml.qnode(dev_boson)
def two_bosons_fock(theta):
qml.FockState(1, wires=0)
qml.FockState(1, wires=1)
qml.Beamsplitter(theta, 0, wires=[0, 1])
return [qml.expval(qml.NumberOperator(0)), qml.expval(qml.NumberOperator(1))]
# +
thetas = np.linspace(0, np.pi, 100)
res = np.array([two_bosons(1, 1, theta) for theta in thetas])
plt.figure(dpi=96)
plt.plot(
thetas,
res[:, 1] * res[:, 0],
label=r"Prob. of Boson in left and Boson in right well ($|S\rangle$)",
color="black",
)
plt.ylim(0, 1.01)
plt.axvline(x=np.pi / 4, linestyle="--", color="green", label="$t_b$")
plt.axvline(x=3 * np.pi / 4, linestyle="--", color="green")
plt.title(r"Probability of two Bosons using displacement")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
plt.xlabel(r"$\theta$/time")
_ = plt.ylabel("Probability")
# +
thetas = np.linspace(0, np.pi, 100)
res = np.array([two_bosons_fock(theta) for theta in thetas])
plt.figure(dpi=96)
plt.plot(
thetas,
res[:, 1] * res[:, 0],
label=r"Prob. of Boson in left and Boson in right well $|S\rangle$",
color="black",
)
plt.ylim(0, 1.1)
plt.axvline(x=np.pi / 4, linestyle="--", color="green", label="$t_b$")
plt.axvline(x=3 * np.pi / 4, linestyle="--", color="green")
plt.title(r"Probability of two Bosons using fock States")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
plt.xlabel(r"$\theta$/time")
_ = plt.ylabel("Probability")
# -
# Since there is a boson in each well on average, and we extract the expectation value of the number operator pennylane returns ```[1, 1]``` for each $\theta$. We want to understand this behavior more thoroughly. To do this we use the strawberry fields package without having pennylane as the "middleman". In the following the same circuit is created with the strawberryfields syntax.
def circuit(theta):
prog = sf.Program(2)
with prog.context as q:
ops.Fock(1) | q[0]
ops.Fock(1) | q[1]
ops.BSgate(theta, 0) | (q[0], q[1])
ops.MeasureFock() | q
eng = sf.Engine("fock", backend_options={"cutoff_dim": 10})
result = eng.run(prog)
return result
# We can now run the circuit multiple times and extract the final values for the number operator of the left and right well.
# +
theta_samples = 6
shots = 5
res = np.zeros((theta_samples, shots, 2))
thetas = np.linspace(0, np.pi, theta_samples)
for n, theta in enumerate(thetas):
print(f"Calculating theta={theta:.2f}", end="\r")
for i in range(shots):
result = circuit(theta)
res[n, i, 0] = result.samples[0, 0]
res[n, i, 1] = result.samples[0, 1]
print(
"""
Each row represents one shot, while the grouped shots represent the results for a specific value of theta
"""
)
print(res)
print(
"""
Mean value of each value of theta
""",
res.mean(axis=1),
)
# -
# At first sight it seems as if there is some fluctuation in the simulated data. However if we run the circuit 1000 times for each value of $\theta$ the average of each $\theta$ of each well approaches $1$.
# +
theta_samples = 15
shots = 1000
res = np.zeros((theta_samples, shots, 2))
thetas = np.linspace(0, np.pi, theta_samples)
for n, theta in enumerate(thetas):
print(f"Calculating theta={theta:.2f}", end="\r")
for i in range(shots):
result = circuit(theta)
res[n, i, 0] = result.samples[0, 0]
res[n, i, 1] = result.samples[0, 1]
print("")
res.mean(axis=1)
# -
# Since we are not interested in the average number operator of each well, but in the distribution of the bosons in the wells ($|L\rangle=2$, $|R\rangle=2$ vs $|L\rangle=1$, $|R\rangle=1$) we need to extract this information from the generated data. This is done by counting all instances where both bosons are either in the left($|L\rangle=2$) or the right well ($|R\rangle=2$) and calculating the ratio. The error is $\frac{1}{\sqrt{N}}$ with N being the number of shots per value of $\theta$.
# +
theta_samples = 15
shots = 300
res_fock = np.zeros((theta_samples, shots, 2))
thetas = np.linspace(0, np.pi, theta_samples)
for n, theta in enumerate(thetas):
print(f"Calculating theta={theta:.2f}", end="\r")
for i in range(shots):
result = circuit(theta)
res_fock[n, i, 0] = result.samples[0, 0]
res_fock[n, i, 1] = result.samples[0, 1]
# -
one_in_each = np.logical_or(res_fock == [2.0, 0.0], res_fock == [0.0, 2.0])
prob = 1 - (one_in_each.sum(axis=1)[:, :1] / shots)
prob_err = np.ones(theta_samples) / np.sqrt(shots)
# +
thetas_fit = np.linspace(0, np.pi, 100)
thetas = np.linspace(0, np.pi, theta_samples)
res_fit = np.array([two_bosons(1, 1, theta) for theta in thetas_fit])
plt.figure(dpi=96)
plt.errorbar(
thetas,
prob,
fmt=".",
yerr=prob_err,
capsize=2,
elinewidth=0.5,
capthick=0.5,
ecolor="gray",
label=r"Prob. of Boson in left and Boson in right well ($|S\rangle$)",
color="black",
)
plt.plot(thetas_fit, res_fit[:, :1] * res_fit[:, 1:], label="Result from displacement")
plt.ylim(0, 1.1)
plt.axvline(x=np.pi / 4, linestyle="--", color="green", label="$t_b$")
plt.axvline(x=3 * np.pi / 4, linestyle="--", color="green")
plt.title(r"Probability of Bosons being in different wells")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
plt.xlabel(r"$\theta$/time")
_ = plt.ylabel("Probability")
# -
# We can see that this matches the result of the displacement gate quite well.
| examples/Example_Hopping_Bosons.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
from numpy.random.mtrand import multivariate_normal
from scipy.linalg import toeplitz
from scipy.optimize import check_grad
from linlearn.model.linear import Features
from linlearn.model.losses import Logistic, sigmoid
from linlearn.solver import gd, svrg
from linlearn.learner import LogisticRegression
def simulate(n_samples, w0, b0=None):
n_features = w0.shape[0]
cov = toeplitz(0.5 ** np.arange(0, n_features))
X = multivariate_normal(np.zeros(n_features), cov, size=n_samples)
logits = X.dot(w0)
if b0 is not None:
logits += b0
p = sigmoid(logits)
y = np.random.binomial(1, p, size=n_samples).astype('float64')
y[:] = 2 * y - 1
return X, y
n_samples = 2000000
n_features = 5
fit_intercept = True
w0 = np.random.randn(n_features)
if fit_intercept:
b0 = -2.
else:
b0 = None
X, y = simulate(n_samples, w0, b0)
if fit_intercept:
w = np.zeros(n_features + 1)
else:
w = np.zeros(n_features)
max_epochs = 10
step = 1e-2
lr = LogisticRegression(fit_intercept=fit_intercept, max_iter=max_epochs,
step=step, smp=True, verbose=True)
lr.fit(X, y)
# lr.predict_proba(X)
# linear = Linear(fit_intercept).fit(X, y)
# logistic = Logistic()
# w = svrg(linear, logistic, w, max_epochs, step)
if fit_intercept:
print(lr.intercept_, b0)
print(lr.coef_)
print(w0)
else:
print(w)
print(w0)
# -
| logistic.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="view-in-github"
# <a href="https://colab.research.google.com/github/zerotodeeplearning/ztdl-masterclasses/blob/master/notebooks/Time_Series_Forecasting.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] colab_type="text" id="2bwH96hViwS7"
# #### Copyright 2020 Catalit LLC.
# + colab={} colab_type="code" id="bFidPKNdkVPg"
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# + [markdown] colab_type="text" id="DvoukA2tkGV4"
# # Time Series Forecasting
# -
import pandas as pd
import numpy as np
# %matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
url = "https://raw.githubusercontent.com/zerotodeeplearning/ztdl-masterclass/master/data/"
df = pd.read_csv(url + 'Ontario_energy_demand_2003-2016.csv.gz')
df.head()
df['Datetime'] = pd.to_datetime(df['Datetime'])
df = df.set_index('Datetime')
df.index = df.index.to_period("h")
df.plot(figsize=(17,5), title="Energy demand in Ontario. All values 2002-2020");
df['2015-01-01':'2015-01-31'].plot(figsize=(17,5), title="Energy demand in Ontario. January 2015");
split_date = pd.Timestamp('01-01-2014')
train = df.loc[:split_date]
test = df.loc[split_date:]
train.shape, test.shape
ax = train.plot(figsize=(17,5), title='Train and Test split in time')
test.plot(ax=ax)
plt.legend(['train', 'test']);
# +
from sklearn.preprocessing import RobustScaler
scaler = RobustScaler()
train_scaled = pd.DataFrame(scaler.fit_transform(train),
index=train.index,
columns=['Scaled'])
test_scaled = pd.DataFrame(scaler.transform(test),
index=test.index,
columns=['Scaled'])
# -
ax = train_scaled.plot(figsize=(17,5), title="Scaled values")
test_scaled.plot(ax=ax)
plt.legend(['Train', 'Test'])
plt.axhline(0, color='blue')
plt.axhline(1, color='cyan')
plt.axhline(-1, color='cyan');
# ### Lag-1 regression
#
# Let's predict the consumption in the next hour using the consumption in the current hour
window_size = 1
for s in range(1, window_size + 1):
train_scaled['shift_{}'.format(s)] = train_scaled['Scaled'].shift(s).fillna(method='bfill')
test_scaled['shift_{}'.format(s)] = test_scaled['Scaled'].shift(s).fillna(method='bfill')
train_scaled.head()
# +
X_train = train_scaled.drop('Scaled', axis=1).values
y_train = train_scaled[['Scaled']].values
X_test = test_scaled.drop('Scaled', axis=1).values
y_test = test_scaled[['Scaled']].values
# -
X_train.shape, y_train.shape, X_test.shape, y_test.shape
# ### Fully connected predictor
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.callbacks import EarlyStopping
# +
model = Sequential([
Dense(12, input_shape=(1,),
activation='relu'),
Dense(1)
])
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mae'])
model.summary()
# -
early_stop = EarlyStopping(monitor='loss', patience=10, verbose=1)
h = model.fit(X_train, y_train, epochs=200,
batch_size=500, verbose=1,
callbacks=[early_stop])
y_pred = model.predict(X_test)
plt.figure(figsize=(15,5))
plt.plot(y_test)
plt.plot(y_pred)
plt.xlim(1200,1300)
plt.plot(y_test, y_pred, '.')
plt.plot((y_test.min(), y_test.max()), (y_test.min(), y_test.max()))
plt.xlabel("True")
plt.ylabel("Predicted");
# +
def evaluate(model, X_train, y_train, X_test, y_test):
res = model.evaluate(X_train, y_train, verbose=0)
df = pd.DataFrame(res, index=['MSE', 'MAE'], columns=['Train'])
df['Test'] = model.evaluate(X_test, y_test, verbose=0)
return df
evaluate(model, X_train, y_train, X_test, y_test).round(3)
# -
# ### Exercise 1: Lagged features
#
# The model above didn't work very well, let's improve it by adding more history to the training window
#
# - Modify the `window_size` parameter to include at least a few hours
# - Add columns to the `train_scaled` dataframe to include additional shifts, your table should look like:
#
# 
#
# - redefine X_train, y_train, X_test, y_test from this new dataset
# - train a Fully connected model with the correct input size
# ### Exercise 2: LSTM
# Reshape the input to `(num_samples, window_size, 1)`. This means we consider each input window as a sequence of `window_size` values that we will pass in sequence to the LSTM. In principle this looks like a more accurate description of our situation. But does it yield better predictions? Let's check it.
#
# - Reshape `X_train` and `X_test` so that they represent a set of univariate sequences
# - train the best recurrent model you can, you'll have to adapt the `input_shape`
# - check the performance of this new model, is it better at predicting the test data?
# - plot your results
# - try using GRU instead of LSTM
| notebooks/Time_Series_Forecasting.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.9 64-bit
# name: python3
# ---
# # Non-Iterative Optimizers
#
# AKA Level 2 optimizers, are unified 3rd party solutions for random expressions. Look at this space:
# +
from tune import Space, Grid, Rand
space = Space(a=Grid(1,2), b=Rand(0,1))
list(space)
# -
# `Grid` is for level 1 optimization, all level 1 parameters will be converted to static values before execution. And level 2 parameters will be optimized during runtime using level 2 optimizers. So for the above example, if we have a Spark cluster and Hyperopt, then we can use Hyperot to search for the best `b` on each of the 2 configurations. And the 2 jobs are parallelized by Spark.
# +
from tune import noniterative_objective, Trial
@noniterative_objective
def objective(a ,b) -> float:
return a**2 + b**2
trial = Trial("dummy", params=list(space)[0])
# -
#
# ## Use Directly
#
# Notice normally you don't use them directly, instead you should use them through top level APIs. This is just to demo how they work.
#
# ### Hyperopt
# +
from tune_hyperopt import HyperoptLocalOptimizer
hyperopt_optimizer = HyperoptLocalOptimizer(max_iter=200, seed=0)
report = hyperopt_optimizer.run(objective, trial)
print(report.sort_metric, report)
# -
# ### Optuna
# + tags=[]
from tune_optuna import OptunaLocalOptimizer
import optuna
optuna.logging.disable_default_handler()
optuna_optimizer = OptunaLocalOptimizer(max_iter=200)
report = optuna_optimizer.run(objective, trial)
print(report.sort_metric, report)
# -
# As you see, we have unified the interfaces for using these frameworks. In addition, we also unified the semantic of the random expressions, so the random sampling behavior will be highly consistent on different 3rd party solutions.
# ## Use Top Level API
#
# In the following example, we directly use the entire `space` where you can mix grid search, random search and Bayesian Optimization.
# +
from tune import suggest_for_noniterative_objective
report = suggest_for_noniterative_objective(
objective, space, top_n=1,
local_optimizer=hyperopt_optimizer
)[0]
print(report.sort_metric, report)
# -
# You can also provide only random expressions in space, and use in the same way so it looks like a common case similar to the examples
# +
report = suggest_for_noniterative_objective(
objective, Space(a=Rand(-1,1), b=Rand(-100,100)), top_n=1,
local_optimizer=optuna_optimizer
)[0]
print(report.sort_metric, report)
# -
# ## Factory Method
#
# In the above example, if we don't set `local_optimizer`, then the default level 2 optimizer will be used which can't handle a configuration with random expressions.
#
# So we have a nice way to make certain optimizer the default one.
# +
from tune import NonIterativeObjectiveLocalOptimizer, TUNE_OBJECT_FACTORY
def to_optimizer(obj):
if isinstance(obj, NonIterativeObjectiveLocalOptimizer):
return obj
if obj is None or "hyperopt"==obj:
return HyperoptLocalOptimizer(max_iter=200, seed=0)
if "optuna" == obj:
return OptunaLocalOptimizer(max_iter=200)
raise NotImplementedError
TUNE_OBJECT_FACTORY.set_noniterative_local_optimizer_converter(to_optimizer)
# -
# Now Hyperopt becomes the default level 2 optimizer, and you can switch to Optuna by specifying a string parameter
# +
report = suggest_for_noniterative_objective(
objective, Space(a=Rand(-1,1), b=Rand(-100,100)), top_n=1
)[0] # using hyperopt
print(report.sort_metric, report)
report = suggest_for_noniterative_objective(
objective, Space(a=Rand(-1,1), b=Rand(-100,100)), top_n=1,
local_optimizer="optuna"
)[0] # using hyperopt
print(report.sort_metric, report)
# -
| docs/notebooks/noniterative_optimizers.ipynb |