code stringlengths 38 801k | repo_path stringlengths 6 263 |
|---|---|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>CS4619: Artificial Intelligence II</h1>
# <h1>Agents</h1>
# <h2>
# <NAME><br>
# School of Computer Science and Information Technology<br>
# University College Cork
# </h2>
# + [markdown] slideshow={"slide_type": "skip"}
# <h1>Initialization</h1>
# $\newcommand{\Set}[1]{\{#1\}}$
# $\newcommand{\Tuple}[1]{\langle#1\rangle}$
# $\newcommand{\v}[1]{\pmb{#1}}$
# $\newcommand{\cv}[1]{\begin{bmatrix}#1\end{bmatrix}}$
# $\newcommand{\rv}[1]{[#1]}$
# $\DeclareMathOperator{\argmax}{arg\,max}$
# $\DeclareMathOperator{\argmin}{arg\,min}$
# $\DeclareMathOperator{\dist}{dist}$
# $\DeclareMathOperator{\abs}{abs}$
# + slideshow={"slide_type": "skip"}
# %reload_ext autoreload
# %autoreload 2
# %matplotlib inline
# + slideshow={"slide_type": "skip"}
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Agents</h1>
# <ul>
# <li>An <b>agent</b> is anything that can be viewed as <b>perceiving</b> its environment through <b>sensors</b>
# and <b>acting</b> upon that environment through <b>effectors</b>.
# </li>
# </ul>
# <figure>
# <img src="images/agent.png" />
# </figure>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Robots</h1>
# <ul>
# <li>Robots are <b>embodied</b> agents, situated in <b>physical</b> environments.</li>
# </ul>
# <div style="display: flex">
# <img src="images/roomba.jpg" />
# <img src="images/amazon.jpg" />
# <img src="images/robocup.jpg" />
# <img src="images/car.jpg" />
# <img src="images/rover.jpg" />
# </div>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Software agents</h1>
# <ul>
# <li>Software agents (sometimes called softbots) are situated in <b>virtual</b> environments.</li>
# </ul>
# <div style="display: flex">
# <img src="images/gameai.jpg" />
# <img src="images/spam.jpg" />
# <img src="images/adsense.png" />
# <img src="images/facebook.jpg" />
# </div>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Sense, Plan, Act</h1>
# <ul>
# <li>Sense
# <ul>
# <li>Use sensors to find things out about the environment</li>
# </ul>
# </li>
# <li>Plan
# <ul>
# <li>Decide on the next action(s)</li>
# </ul>
# </li>
# <li>Act
# <ul>
# <li>Use effector(s) to carry out the chosen action(s)</li>
# </ul>
# </li>
# </ul>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Action function</h1>
# <ul>
# <li>In some ways, these modules have spent a vast amount of time on the <b>Sense</b> phase of the cycle.</li>
# <li>The task of the <b>Plan</b> phase is to implement an <b>action function</b> that maps
# <ul>
# <li>from <b>percept sequences</b></li>
# <li>to the <b>actions</b> the agents can perform.</li>
# </ul>
# </li>
# <li>In intelligent agents, this function exhibits high degrees of
# <ul>
# <li><b>autonomy</b> and</li>
# <li><b>rationality</b>.</li>
# </ul>
# </li>
# </ul>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Environments</h1>
# <ul>
# <li>Fully observable vs. partially observable</li>
# <li>Deterministic vs. stochastic</li>
# <li>Single-step vs. sequential</li>
# <li>Static vs. dynamic</li>
# <li>Discrete vs. continuous</li>
# <li>Single-agent vs. multi-agent</li>
# </ul>
# <uL>
# <li>Exercise: classify the environments of a chess program, a spam filter, a robot vacuum cleaner, and an autonomous
# car
# </li>
# </ul>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Agents</h1>
# <ul>
# <li>Reactive agents</li>
# <li>Deliberative agents</li>
# </ul>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Table-Driven Agents</h1>
# <ul>
# <li>At each point in time:
# <ul>
# <li>$\v{s} = \mathit{SENSE()};$</li>
# <li>$a = \mathit{LOOKUP}(\v{s}, \mathit{table});$</li>
# <li>$\mathit{EXECUTE}(a);$</li>
# </ul>
# </li>
# </ul>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Class exercise: Table-Driven Wall-Following Agent</h1>
# <ol>
# <li>Suppose the agent has 8 touch sensors, each returning 0 or 1
# <table style="border-width: 0">
# <tr style="border-width: 0">
# <td style="border-width: 0"><img src="images/wf_agent.png" /></td>
# <td style="border-width: 0">Sensors return 11000001</td>
# </tr>
# </table>
# How many table entries will there be?
# </li>
# </ol>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Class exercise</h1>
# <ol start="2">
# <li>In fact, only three sensors are needed:
# <figure>
# <img src="images/three_sensors.png" />
# </figure>
# How many table entries will there be?
# </li>
# </ol>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Class exercise</h1>
# <ol start="3">
# <li>The actions are:
# <ul>
# <li>MOVE:
# <ul>
# <li>this moves the agent one cell forward</li>
# </ul>
# </li>
# <li>TURN(d, n) where d = LEFT or d = RIGHT and n = 0, 1, 2, etc.:
# <ul>
# <li>this turns the agent to the left or right, $n$ lots of 45°</li>
# </ul>
# </li>
# </ul>
# Fill in the table so that the agent walks the walls anticlockwise
# <table>
# <tr><th style="border: 1px solid black;">Percept</th><th style="border: 1px solid black;">Action</th></tr>
# <tr><td style="border: 1px solid black;">000</td><td style="border: 1px solid black;"></td></tr>
# <tr><td style="border: 1px solid black;">001</td><td style="border: 1px solid black;"></td></tr>
# <tr><td style="border: 1px solid black;">010</td><td style="border: 1px solid black;"></td></tr>
# <tr><td style="border: 1px solid black;">011</td><td style="border: 1px solid black;"></td></tr>
# <tr><td style="border: 1px solid black;">100</td><td style="border: 1px solid black;"></td></tr>
# <tr><td style="border: 1px solid black;">101</td><td style="border: 1px solid black;"></td></tr>
# <tr><td style="border: 1px solid black;">110</td><td style="border: 1px solid black;"></td></tr>
# <tr><td style="border: 1px solid black;">111</td><td style="border: 1px solid black;"></td></tr>
# </table>
# </li>
# </ol>
# + [markdown] slideshow={"slide_type": "slide"}
# <h1>Discussion</h1>
# <ul>
# <li>Is this agent autonomous?</li>
# <li>When is the table-driven approach a <em>possible</em> approach?</li>
# <li>When is it a <em>practicable</em> approach?</li>
# </ul>
| ai2/lectures/AI2_10_agents.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
# ---
# + jupyter={"outputs_hidden": false}
from network_evaluation_tools import gene_conversion_tools as gct
from network_evaluation_tools import data_import_tools as dit
import pandas as pd
import time
# -
# ## Load Pathway Commons Raw Data (All interactions)
# #### Source: http://www.pathwaycommons.org/archives/PC2/v9/PathwayCommons9.All.hgnc.txt.gz
# Downloaded: June 15, 2017
# Last Updated: May 25, 2017
# Citation: Pathway Commons, a web resource for biological pathway data. Cerami E et al. Nucleic Acids Research (2011).
# A Note about filtering interactions: Pathway Commons also contains interactions between proteins and small molecules from the CHEBI database. These interactions will need to be filtered out as they are not protein-protein interactions.
# Also note: The text file has more lines than the sif file in Pathway Commons. However, the text file has some interactions that are unclear how to resolve so for this case we will use the sif file provided by Pathway Commons
# + jupyter={"outputs_hidden": false}
wd = '/data/'
PC_Raw = pd.read_csv(wd+'PathwayCommons9.All.hgnc.sif', sep='\t', header=None)
print('Raw interactions in Pathway Commons v9:', PC_Raw.shape[0])
# + jupyter={"outputs_hidden": false}
# Filter all interactions that contain a CHEBI: item
PC_filt = PC_Raw[(~PC_Raw[0].str.contains(':')) & (~PC_Raw[2].str.contains(':'))]
PC_edgelist = PC_filt[[0, 2]].values.tolist()
print('Protein-Protein interactions in Pathway Commons v9:', len(PC_edgelist))
# + tags=[]
# Sort each edge representation for filtering
PC_edgelist_sorted = [sorted(edge) for edge in PC_edgelist]
# + jupyter={"outputs_hidden": false}
# Filter edgelist for duplicate nodes and for self-edges
PC_edgelist_filt = gct.filter_converted_edgelist(PC_edgelist_sorted)
# + jupyter={"outputs_hidden": false}
# Save genelist to file
outdir = '/data/'
gct.write_edgelist(PC_edgelist_filt, outdir+'PathwayCommons_Symbol.sif')
# -
| code/make_networks/.ipynb_checkpoints/Pathway Commons Processing-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
# ---
# # Training left vs. right classifier
#
# This notebook contains the code to train the left vs. right classifier based on a corpus of labelled news articles.
#
# The data comes from manual querying of many anglophone news outlets with known (i.e., already labelled) political colour.
#
# To train the model, execute all the cells.
# ## 1. Load data and add labels
# +
import glob
import os
import codecs
import json
from joblib import Parallel, delayed
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# %matplotlib inline
# -
folderpath = '/home/hubert/Documents/kesseca/data/left_right'
filepaths = glob.glob(os.path.join(folderpath, '*.json'))
# Political spectrum labels
political_labels = {"Breitbart": 5,
"Fox News": 4,
"National Review": 5,
"The Blaze": 5,
"CBN News": 5,
"The Washington Times": 5,
"Townhall": 5,
"ABC News": 2,
"CBS News": 2,
"Daily Beast": 1,
"Huffington Post US": 1,
"The New York Times": 2,
"Politico": 2,
"Salon": 1,
"The Guardian": 2,
"Vox": 2,
"The Washington Post": 2,
"BBC.com": 3,
"Bloomberg": 3,
"CNN": 3,
"NPR": 3,
"Associated Press": 3,
"Reuters": 3,
"Wall Street Journal": 3,
"USA Today": 3,
"The Hill": 3}
# +
# Load the JSON files
data = []
for path in filepaths:
with codecs.open(path, 'r', encoding='utf8') as f:
data.append(json.load(f))
# -
file_origin = [f.split('/')[-1][:-5] for f in filepaths]
# +
# Put in a simpler format
labels_political = []
labels_location = []
articles = []
for origin, outlet in zip(file_origin, data):
for article in outlet:
try:
labels_political.append(political_labels[origin])
# labels_location.append(article['location'][0]['country'])
articles.append(article['body'])
except:
print('Failed: ' + origin)
# -
sns.distplot(labels_political, kde=False)
# If we divide into 3 classes (left, center, right) with thresholds of < 3 and > 3, classes are pretty much balanced.
# +
# Find out if there's is a difference in length
y = np.array(labels_political)
X = np.array(articles)
y_left = y[y < 3]
X_left = X[y < 3]
y_right = y[y > 3]
X_right = X[y > 3]
y_center = y[y == 3]
X_center = X[y == 3]
len_left = [len(x) for x in X_left]
len_right = [len(x) for x in X_right]
len_center = [len(x) for x in X_center]
# -
print('Mean number of characters')
print('Left: {:0.1f} +/- {:0.1f}'.format(np.mean(len_left), np.std(len_left)))
print('Center: {:0.1f} +/- {:0.1f}'.format(np.mean(len_center), np.std(len_center)))
print('Right: {:0.1f} +/- {:0.1f}'.format(np.mean(len_right), np.std(len_right)))
# Left-wing articles are longer than right-wing articles, but Center articles are the shortest of all (with the smallest standard deviation). This could be explained by the fact that many center news outlets (e.g., Reuters, Bloomberg, etc.) typically publish short, to-the-point, factual articles.
# ## 2. Preprocess text
# +
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction import text
from sklearn.linear_model import LogisticRegression
text_clf = Pipeline([('vect', text.CountVectorizer(stop_words='english', ngram_range=(1, 2))),
('tfidf', text.TfidfTransformer(sublinear_tf=True)),
('clf', LogisticRegression(class_weight='balanced', C=100))])
# -
# Just keep extreme examples
y_raw = np.array(labels_political)
y = y_raw
y[y < 3] = 0
y[y == 3] = 1
y[y > 3] = 2
# +
# Remove words that shouldn't be descriptive, like news outlet names
banned_words = list(political_labels.keys())
banned_words_lower = [i.lower() for i in banned_words]
banned_words_upper = [i.upper() for i in banned_words]
banned_words = banned_words + banned_words_lower + banned_words_upper
X = []
for article in articles:
for word in banned_words:
article = article.replace(word, '')
assert 'Reuters' not in article
X.append(article)
X = np.array(X)
# -
# Remove center for training binary classifier
ind = y != 1
y = y[ind]
X = X[ind]
# +
# Find best value for C hyperparameter (then update the value above!)
from sklearn.model_selection import GridSearchCV
C_OPTIONS = [1, 10, 100, 1000]
param_grid = [{'clf__C': C_OPTIONS}]
grid = GridSearchCV(text_clf, cv=5, n_jobs=-1, param_grid=param_grid)
grid.fit(X, y)
mean_scores = np.array(grid.cv_results_['mean_test_score'])
mean_scores
# +
# Predict on 25% of the data to print the confusion matrix
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, shuffle=True)
text_clf.fit(X_train, y_train)
y_pred = text_clf.predict(X_test)
# +
from sklearn.metrics import confusion_matrix
conf_mat = confusion_matrix(y_test, y_pred)
fig, ax = plt.subplots(figsize=(10, 10))
sns.heatmap(conf_mat, annot=True, fmt='d')
# xticklabels=category_id_df.Product.values, yticklabels=category_id_df.Product.values)
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.show()
# -
# This is not bad. Most articles are well classified into right/left-wing classes.
# +
# Compute accuracy
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(text_clf, X, y, scoring='accuracy', cv=5)
np.mean(accuracies)
# -
# See what terms are used to distinguish both classes...
count_transformer = text_clf.get_params()['vect']
tfidf_transformer = text_clf.get_params()['tfidf']
clf = text_clf.get_params()['clf']
# +
ind = np.argsort(clf.coef_)[0]
best_words = []
for i in np.concatenate((ind[:10], ind[-10:])):
for key, value in count_transformer.vocabulary_.items():
if value == i:
best_words.append((key, clf.coef_[0, i]))
# +
print('Most useful left-wing words:')
[print(i) for i in best_words[:10]];
print('\nMost useful right-wing words:')
[print(i) for i in best_words[-10:]];
# -
# The most useful words mostly make sense. The distinction between 'Mr. Trump' on the left side and 'President Trump' on the right side, could very well be due to the perception each group has of Donald Trump. Other terms, mostly on the right-wing side, also seem to make sense. e.g., 'illegal'.
# ## Testing on actual data - different versions of the same news
#
# This data was fetched using the Kesseca pipeline - it consists in one translated Radio-Canada article, and of several other articles on the same topic found by the pipeline.
# +
rc_path = '/home/hubert/Documents/kesseca/data/five_articles/trump_firearm/rc.json'
outlet_path = '/home/hubert/Documents/kesseca/data/five_articles/trump_firearm/outlets.json'
# Load the files
with codecs.open(rc_path, 'r', encoding='utf8') as f:
rc_text = f.read()
with codecs.open(outlet_path, 'r', encoding='utf8') as f:
outlet_text = json.load(f)
outlet_text['Radio-Canada'] = rc_text
# +
labels = []
values = []
for key, value in outlet_text.items():
labels.append(key)
values.append(value)
y_pred = text_clf.predict_proba(values)
print('Outlet - P(right-wing)')
print('======================')
[print(i, '-', j[1]) for i, j in zip(labels, y_pred)];
# -
# The index, although not perfect, usually reflects the expected right/left wing bias of each news outlet.
# ## Save model and make it a function
# +
# Save pipeline model to disk
from sklearn.externals import joblib
joblib.dump(text_clf, 'left_right_clf.pkl')
# +
from sklearn.externals import joblib
def classify_left_right(article, clf=None):
"""Classify an article as being left-wing or right-wing.
Args:
article (str or list of str): body of the article(s)
Keyword Args:
clf (sklearn.Pipeline): pipeline object containing the
classification pipeline to run on the text. If not
provided, will attempt to load automatically from the
same directory.
Returns:
(float): probability of the article having a right-wing
bias
"""
if clf is None:
clf = joblib.load('left_right_clf.pkl')
if isinstance(article, str):
article = [article]
y_pred = clf.predict_proba(article)[:, 1]
return y_pred
# +
clf = joblib.load('left_right_clf.pkl')
classify_left_right(outlet_text['Radio-Canada'], clf=clf)
# -
# ## Extract left/right score for chosen articles
#
# For the purpose of demonstrating our pipeline, we have pre-selected 5 relevant articles. Run the classification pipeline on these files here.
# +
outlets = '/home/hubert/Documents/kesseca/data/five_articles/final/1090978.json'
with open(outlets, 'r') as f:
articles = json.load(f)
# +
scores = {}
for key, value in articles.items():
scores[key] = {'score': classify_left_right(value['body'], clf=clf)[0],
'outlet_bias': value['bias'],
'likes': value['facebook_likes']}
scores_df = pd.DataFrame(scores).T
scores_df
# -
sns.regplot(scores_df['score'], scores_df['outlet_bias'])
print(outlets.split('/')[-1])
print(scores_df['score'].to_json())
# +
# Add the new value back into the initial dictionary
out_articles = articles
for key, value in articles.items():
articles[key]['left_right_score'] = scores_df.loc[key, 'score']
with open(outlets, 'w') as outfile:
json.dump(articles, outfile)
# -
# ## Try t-SNE again?
# +
# Get the data
outlets_file = '/home/hubert/Documents/kesseca/data/five_articles/final/1090978.json'
with open(outlets_file, 'r') as f:
articles = json.load(f)
outlets = []
texts = []
scores = []
outlet_biases = []
likes = []
for key, value in articles.items():
outlets.append(key)
texts.append(value['body'])
scores.append(classify_left_right(value['body'], clf=clf)[0])
outlet_biases.append(value['bias'])
likes.append(value['facebook_likes'])
# +
from sklearn.manifold import TSNE
from sklearn.preprocessing import FunctionTransformer
tsne_pipe = Pipeline([('vect', text.CountVectorizer(stop_words='english', ngram_range=(1, 2))),
('tfidf', text.TfidfTransformer(sublinear_tf=True)),
('todense', FunctionTransformer(lambda x: x.todense(), accept_sparse=True)),
('tsne', TSNE(n_components=2, verbose=1, random_state=0, angle=0.5, init='pca',
perplexity=10, learning_rate=10))])
coords = tsne_pipe.fit_transform(texts)
# -
fig, ax = plt.subplots()
ax.scatter(coords[:, 0], coords[:, 1], s=np.array(likes)+10, c=scores)
# Although the plot doesn't look too bad, there are not enough points in the visualization to infer any useful clustering/relationship/patterns in the data. This would probably be more confusing then anything given that we only have a few minutes to present...
#
# Let's aim for something simpler, like a 1D graph.
# +
log_likes = np.log10(np.array(likes) + 10)
log_likes = (log_likes - 1) / (log_likes.max() - log_likes.min())
fig, ax = plt.subplots(figsize=(10, 1))
for s, l in zip(scores, log_likes):
ax.axvline(s, ymin=0, ymax=l)
# ax.scatter(scores, np.log10(np.array(likes) + 10), marker='|')
| scripts/training_left_right_classifier.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" executionInfo={"elapsed": 22517, "status": "ok", "timestamp": 1581440365842, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mBDWyjiBHdeijAV12uYubfUgHbdnQEzBok62Adg=s64", "userId": "11054559934326118576"}, "user_tz": 0} id="bPT6APKNCPFJ" outputId="c61b0282-8b96-4173-c38d-f76ad4d83541"
# # !pip install iteround==1.0.2
# # !pip install pairing==0.1.3
# # !pip install scikit-multilearn==0.2.0
# # !pip install arff==0.9
# # !pip install category_encoders==2.1.0
# # !pip install matplotlib==3.1.3
# # !pip install tensorflow==2.1.0
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 17404, "status": "ok", "timestamp": 1581440372662, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mBDWyjiBHdeijAV12uYubfUgHbdnQEzBok62Adg=s64", "userId": "11054559934326118576"}, "user_tz": 0} id="JBJit23GAheY" outputId="a104e4a1-2299-42e3-faf1-c384b3b25803"
import sys
sys.path.append("../")
from bandipy import simulation
import numpy as np
## For synthetic data generation
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# + [markdown] colab_type="text" id="jHOdz8RbAhed"
# Before running this code, you first need to run the notebook `1_build_an_encoder` with the desired `context_size` (`d` in the paper).
#
# Thus, if you want to change `context_size` value in the following code, please make sure you have already built the required encoder for it.
#
#
#
# > Note: Running the following code takes some minutes, depending on the choosen `users_rng`. e.g. with `users_rng = np.array([1000., 5000., 10000.])`, it takes about 5-10 minutes.
# -
context_size = 10 ## This is `d` in the paper
n_actions = 10 ## This is `A` in the paper
n_samples = 10 ## This is `T` in the paper
early_frac = .70
users_rng = np.array([1e3, 5e3, 1e4, 5e4, 1e5])
## Here we use small number_of_users just for getting fastter results.
# users_rng = np.array([1000., 5000., 10000.])
n_users_rng = users_rng.copy()
n_users_rng /= early_frac
n_users_rng = n_users_rng.astype(int)
reports = list()
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="nBDyQ2HyKU0X" outputId="599cb3c6-bc28-48ed-f5ce-9eaaaba536ff"
tf.random.set_seed(context_size)
def make_mapping_function(n_inputs, n_outputs):
mapping_function = Sequential()
mapping_function.add(Dense(n_outputs,input_dim=n_inputs, activation='linear'))
mapping_function.compile(loss='categorical_crossentropy', optimizer="sgd")
return mapping_function
mapping_function = make_mapping_function(context_size,n_actions)
mapping_function.summary()
mapping_function.save_weights("mapping_function.h5")
mapping_function.load_weights("mapping_function.h5")
for n_users in n_users_rng:
print("___________________"+str(n_users)+"_______________________________")
sim = simulation.Simulation(data_type='syn',
bandit_algorithm='contextual_linear_ucb',
privacy_model = 'crowd_blending_with_sampling',
sim_sig = 'tmp')
report = sim.run_simulation(n_users=n_users, early_frac=early_frac, n_samples=n_samples,
n_actions=n_actions, context_size=context_size,
ctr_scaling_factor=.1,
resp_noise_level=.01,
mapping_function = mapping_function,
alpha =1.,
cb_sampling_rate = .5,
neg_rew_sam_rate = .05,
cb_context_threshold = 10,
dec_digits = 1,
bin_size = 10)
reports.append(report)
np.save("p2b_synthetic_"+str(n_samples)+"_"+str(n_actions)+"_"+str(context_size)+".npy", np.array(reports))
print("\nResults:\n",np.array(reports))
reports = np.array(reports)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 1165, "status": "ok", "timestamp": 1581432706040, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mBDWyjiBHdeijAV12uYubfUgHbdnQEzBok62Adg=s64", "userId": "11054559934326118576"}, "user_tz": 0} id="OZWCcqrMr_Jl" outputId="9bfaa574-dab4-45ba-b34c-05aa20e70376"
reports = np.load("p2b_synthetic_"+str(n_samples)+"_"+str(n_actions)+"_"+str(context_size)+".npy")
reports.shape
# + colab={"base_uri": "https://localhost:8080/", "height": 426} colab_type="code" executionInfo={"elapsed": 978, "status": "ok", "timestamp": 1581433137396, "user": {"displayName": "<NAME>.", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mBDWyjiBHdeijAV12uYubfUgHbdnQEzBok62Adg=s64", "userId": "11054559934326118576"}, "user_tz": 0} id="ev8Wj18QAheh" outputId="5c60a70c-aa0c-4461-db35-507c11cef77b"
import matplotlib.pyplot as plt
def paint_reports(reports, users_rng):
x_ax = np.array(users_rng).astype(int)
fmts = ['bs-', 'ko-', 'r*-']
plt.errorbar(x_ax, reports[:,0,0], reports[:,0,1]//1, fmt=fmts[0], ms=15, ecolor="blue", label="Cold")
plt.errorbar(x_ax, reports[:,1,0], reports[:,1,1]//1, fmt=fmts[1], ms=15, ecolor="black", label="Warm_Non_Private")
plt.errorbar(x_ax, reports[:,2,0], reports[:,2,1]//1, fmt=fmts[2], ms=20, ecolor="red", label="Warm_Private")
users_rng = np.array([1e3, 5e3, 1e4, 5e4, 1e5])
plt.figure(figsize=(14,10))
reports = np.array(reports)
paint_reports(reports, users_rng)
plt.xscale('log')
plt.xlabel('Number of Users', size=20)
plt.ylabel('Average Reward', size=20)
plt.xticks(users_rng,size=20)
plt.yticks(size=20)
plt.legend( ncol=1, loc='upper left', prop={'size': 20})
plt.show()
# + colab={} colab_type="code" id="JWqqZQnUsr1S"
import matplotlib.pyplot as plt
def paint_reports(reports, users_rng):
x_ax = np.array(users_rng).astype(int)
fmts = ['bs-', 'ko-', 'r*-']
plt.errorbar(x_ax, reports[:,0,0], reports[:,0,1]/10, fmt=fmts[0], ms=15, ecolor="blue", label="Cold")
plt.errorbar(x_ax, reports[:,1,0], reports[:,1,1]/10, fmt=fmts[1], ms=15, ecolor="black", label="Warm_Non_Private")
plt.errorbar(x_ax, reports[:,2,0], reports[:,2,1]/10, fmt=fmts[2], ms=20, ecolor="red", label="Warm_Private")
users_rng = np.array([1e3, 5e3, 1e4, 5e4, 1e5])
plt.figure(figsize=(14,10))
reports = np.array(reports)
paint_reports(reports, users_rng)
plt.xscale('log')
plt.xlabel('Number of Users', size=20)
plt.ylabel('Average Reward', size=20)
plt.xticks(users_rng,size=20)
plt.yticks(size=20)
plt.legend( ncol=1, loc='upper left', prop={'size': 20})
plt.show()
| experiments/2_a_synthetic_exp.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
#本章需导入的模块
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import warnings
warnings.filterwarnings(action = 'ignore')
# %matplotlib inline
plt.rcParams['font.sans-serif']=['SimHei'] #解决中文显示乱码问题
plt.rcParams['axes.unicode_minus']=False
from sklearn.datasets import make_classification,make_circles,make_regression
from sklearn.model_selection import train_test_split
import sklearn.neural_network as net
import sklearn.linear_model as LM
from scipy.stats import multivariate_normal
from sklearn.metrics import r2_score,mean_squared_error
from sklearn import svm
# +
N=100
X,Y=make_regression(n_samples=N,n_features=1,random_state=123,noise=50,bias=0)
X_train, X_test, Y_train, Y_test = train_test_split(X,Y,train_size=0.85, random_state=123)
plt.scatter(X_train,Y_train,s=20)
plt.scatter(X_test,Y_test,s=20,marker='*')
plt.title("100个样本观测点的SVR和线性回归")
plt.xlabel("X")
plt.ylabel("Y")
modelLM=LM.LinearRegression()
modelLM.fit(X_train,Y_train)
X[:,0].sort()
fig,axes=plt.subplots(nrows=2,ncols=2,figsize=(12,9))
for C,E,H,L in [(1,0.1,0,0),(1,100,0,1),(100,0.1,1,0),(10000,0.01,1,1)]:
modelSVR=svm.SVR(C=C,epsilon=E)
modelSVR.fit(X_train,Y_train)
axes[H,L].scatter(X_train,Y_train,s=20)
axes[H,L].scatter(X_test,Y_test,s=20,marker='*')
axes[H,L].scatter(X[modelSVR.support_],Y[modelSVR.support_],marker='o',c='b',s=120,alpha=0.2)
axes[H,L].plot(X,modelSVR.predict(X),linestyle='-',label="SVR")
axes[H,L].plot(X,modelLM.predict(X),linestyle='--',label="线性回归",linewidth=1)
axes[H,L].legend()
ytrain=modelSVR.predict(X_train)
ytest=modelSVR.predict(X_test)
axes[H,L].set_title("SVR(C=%d,epsilon=%.2f,训练误差=%.2f,测试MSE=%.2f)"%(C,E,mean_squared_error(Y_train,ytrain),
mean_squared_error(Y_test,ytest)))
axes[H,L].set_xlabel("X")
axes[H,L].set_ylabel("Y")
axes[H,L].grid(True,linestyle='-.')
# -
# 代码说明:
# (1)第10,11行:建立一般线性回归模型,拟合训练集数据。
# (2)第14至29行:利用for循环分别建立四个支持向量回归机。
# 支持向量回归机的惩罚C依次取1,1,100,10000,对错误的惩罚越来越大。同时参数ε依次取0.1,100,0,1,0.01支持,规定了多个误差上限。拟合训练集数据。绘制样本观测点的散点图。标识出支持向量。绘制一般支持向量回归机的回归线和一般线性回归模型的回归线。计算训练误差和测试误差(MSE)。
#
| chapter8-6.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
# ---
# # Let's Have a **BeautifulSoup**
# *<NAME>*
#
# In this document we will see some basic usage of navigating the web with **BeautifulSoup**.
#
# First, let's load in libraries.
import requests
from bs4 import BeautifulSoup
# Let's set a header that will make our scraper look more "human" (just to be safe, and to see how it's done), then download a webpage from Wikipedia containing a [list of Nobel laureates](https://en.wikipedia.org/wiki/List_of_Nobel_laureates).
# +
session = requests.Session()
# Our "human" header; go to https://www.whatismybrowser.com/ to see what the Internet can see about your browser,
# including what your header is. Below are the settings for a browser I used.
header = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Connection": "keep-alive",
"Referrer": "https://www.google.com/",
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:54.0) Gecko/20100101 Firefox/54.0"}
# The URL we are visiting
url = "https://en.wikipedia.org/wiki/List_of_Nobel_laureates"
# Visit the url, using the header just defined
page = session.get(url, headers=header).text
# A preview of the content
print(page)
# -
# Let's create a `BeautifulSoup` object to parse this document.
nobelList = BeautifulSoup(page) # A warning will be thrown since no parser was specified
# BeautifulSoup will choose to use the best parser available in this case
# Now that we have the object let's see some common tools.
nobelList.find("a") # Find a single link
nobelList.findAll("a") # Find all links (returns in a list)
nobelList.findAll("a", {"class": "internal"}) # Find all links with a particular class
nobelList.findAll("a", {"class": "internal"})[0].\
attrs["href"] # For the first link, get its destination
nobelList.find("h1")
nobelList.find("h1").contents # Get the contents of a tag
nobelList.table # Another way to locate elements; this time, a table
nobelList.table.attrs["class"] # This belongs to two classes
nobelList.find("table", {"class": ["wikitable", "sortable"]}) # A way to find elements with multiple classes
# We can drill down through the DOM of a document and each layer has the same methods as the original object.
nobelList.table.children # Child nodes of this node; gives an iterator
# Let's see what nodes are children
for node in nobelList.table.children:
print("\nNode:\n-----")
print("Name: %s" % node.name) # The HTML name of a tag
print(node)
nobelList.table.tr # The first row of the table
nobelList.table.findAll("td")
nobelList.table.parent # Locating the parent node
| Section 4/BeautifulSoup.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 string
import pandas as pd
import xgboost
import numpy as np
from sklearn import model_selection, preprocessing, linear_model, naive_bayes, metrics, svm
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn import decomposition, ensemble
from sklearn.naive_bayes import MultinomialNB
from sklearn import ensemble
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import OneHotEncoder
from sklearn import neighbors
from sklearn.externals import joblib
import mlens
import keras
from keras.preprocessing import text, sequence
from keras import layers, models, optimizers
from imblearn.under_sampling import RandomUnderSampler
from imblearn.over_sampling import ADASYN, SMOTE, RandomOverSampler
from imblearn.combine import SMOTEENN, SMOTETomek
from imblearn.ensemble import BalancedRandomForestClassifier, EasyEnsembleClassifier, RUSBoostClassifier
from imblearn.pipeline import make_pipeline as make_pipeline
from imblearn.metrics import classification_report_imbalanced
from ast import literal_eval
# -
RANDOM_STATE = 42
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' #workaround for macOS mkl issue
BIG_CATEGORY = 'fashion'
# load dataset
data_directory = os.path.join(os.path.split(os.getcwd())[0], 'data')
prob_dir = os.path.join(data_directory, 'probabilities', BIG_CATEGORY)
train = pd.read_csv(os.path.join(data_directory, f'{BIG_CATEGORY}_train_split.csv'))
valid = pd.read_csv(os.path.join(data_directory, f'{BIG_CATEGORY}_valid_split.csv'))
test = pd.read_csv(os.path.join(data_directory, f'{BIG_CATEGORY}_test_split.csv'))
train_x, train_y = train['itemid'].values.reshape(-1,1), train['Category']
valid_x, valid_y = valid['itemid'].values.reshape(-1,1), valid['Category']
test_x = test['itemid'].values.reshape(-1,1)
encoder = preprocessing.LabelEncoder()
train_y = encoder.fit_transform(train_y)
valid_y = encoder.fit_transform(valid_y)
def train_model(classifier, feature_vector_train, label, feature_vector_valid, cross_validate=False,
save_model=False, extract_probs=False, feature_vector_test=None, model_name='sklearn'):
# fit the training dataset on the classifier
#if isinstance(classifier, xgboost.XGBClassifier):
# feature_vector_train = feature_vector_train.to_csc()
# feature_vector_valid = feature_vector_valid.to_csc()
if cross_validate:
kfold = model_selection.StratifiedKFold(n_splits=5, random_state=7, shuffle=True)
results = model_selection.cross_val_score(classifier, feature_vector_train,
label, cv=kfold, n_jobs=-1)
print("CV Accuracy: %.4f%% (%.4f%%)" % (results.mean()*100, results.std()*100))
return results.mean()*100
else:
classifier.fit(feature_vector_train, label)
# predict the labels on validation dataset
predictions = classifier.predict(feature_vector_train)
print('Train Acc: {}'.format(metrics.accuracy_score(predictions, label)))
predictions = classifier.predict(feature_vector_valid)
if extract_probs:
val_preds = classifier.predict_proba(feature_vector_valid)
test_preds = classifier.predict_proba(feature_vector_test)
print(val_preds.shape)
print(test_preds.shape)
os.makedirs(os.path.join(prob_dir, model_name),exist_ok=True)
np.save(os.path.join(prob_dir, model_name, 'valid.npy'), val_preds)
np.save(os.path.join(prob_dir, model_name, 'test.npy'), test_preds)
if save_model:
model_path = os.path.join(data_directory, 'keras_checkpoints',
BIG_CATEGORY, model_name)
os.makedirs(model_path, exist_ok=True)
joblib.dump(classifier, os.path.join(model_path, model_name + '.joblib'))
return metrics.accuracy_score(predictions, valid_y)
accuracy = train_model(make_pipeline(count_vect, naive_bayes.MultinomialNB(alpha=0.25)),
train_x, train_y, valid_x, cross_validate=True,
extract_probs=False, feature_vector_test=test_x, model_name='nb_ngrams_2')
print("NB, Count Vectors: ", accuracy)
accuracy = train_model(neighbors.KNeighborsClassifier(n_neighbors=50, leaf_size=20),
train_x, train_y, valid_x, cross_validate=False, save_model=True, extract_probs=True,
model_name='KNN_itemid_50', feature_vector_test=test_x)
print("NN, Count Vectors: ", accuracy)
accuracy = train_model(ensemble.RandomForestClassifier(n_estimators=150, max_depth=100, min_samples_leaf=10, n_jobs=-1),
train_x, train_y, valid_x, cross_validate=False, save_model=True, extract_probs=True,
model_name='rf_itemid', feature_vector_test=test_x)
print("RF, Count Vectors: ", accuracy)
# +
accuracy = train_model(xgboost.XGBClassifier(max_depth=27, learning_rate=0.1, scale_pos_weight=1,
n_estimators=50, silent=True,
objective="binary:logistic", booster='gbtree',
n_jobs=6, nthread=None, gamma=0.2, min_child_weight=5,
max_delta_step=0, subsample=1, colsample_bytree=0.7, colsample_bylevel=1,
reg_alpha=0, reg_lambda=1),
train_x, train_y, valid_x)
print("Xgb, N-Gram Vectors: ", accuracy)
# -
accuracy = train_model(xgboost.XGBClassifier(max_depth=27, learning_rate=0.05, scale_pos_weight=1,
n_estimators=200, silent=True,
objective="binary:logistic", booster='gbtree',
n_jobs=6, nthread=None, gamma=0.2, min_child_weight=5,
max_delta_step=0, subsample=1, colsample_bytree=0.8, colsample_bylevel=1,
reg_alpha=0, reg_lambda=1),
train_x, train_y, valid_x,
save_model=True, extract_probs=True,
feature_vector_test=test_x, model_name='xgb_itemid_index')
print("Xgb, N-Gram Vectors: ", accuracy)
0.37732730
itemid_train.values.reshape(-1, 1)
accuracy = train_model(ensemble.RandomForestClassifier(n_estimators=50, max_depth=40, min_samples_leaf=10),
train_index, train_y, valid_index)
print("RF, ItemID: ", accuracy)
accuracy = train_model(xgboost.XGBClassifier(
max_depth=15, learning_rate=0.1, n_estimators=100, silent=True,
objective='binary:logistic', booster='gbtree', n_jobs=6, nthread=None,
gamma=0, min_child_weight=1, max_delta_step=0, subsample=1, colsample_bytree=1,
colsample_bylevel=1, reg_alpha=0, reg_lambda=1, scale_pos_weight=1,
base_score=0.5, random_state=0, seed=None, missing=None),
train_x, train_y, valid_x)
print("Xgb, ItemID: ", accuracy)
# +
params = {
'max_depth': [9, 11, 13],
#'learning_rate': [0.05, 0.1, 0.2],
#'n_estimators': range(50, 200, 50),
#'gamma': [i/10.0 for i in range(0, 5)],
#'subsample': [i/10.0 for i in range(6, 10)],
#'colsample_bytree': [i/10.0 for i in range(6, 10)],
#'reg_alpha': [0, 0.001, 0.005, 0.01, 0.05]
}
ensemble = BlendEnsemble(scorer=accuracy_score, random_state=seed, verbose=2)
ensemble.add([
RandomForestClassifier(n_estimators=100, max_depth=58*10, min_samples_leaf=10),
#svm.LinearSVC(dual=False, tol=.01),
LogisticRegression(solver='sag', n_jobs=6, multi_class='multinomial', tol=1e-4, C=1.e4 / 533292),
naive_bayes.MultinomialNB(),
xgboost.XGBClassifier(max_depth=11, learning_rate=0.1, scale_pos_weight=1,
n_estimators=100, silent=True,
objective="binary:logistic", booster='gbtree',
n_jobs=6, nthread=None, gamma=0, min_child_weight=2,
max_delta_step=0, subsample=1, colsample_bytree=1, colsample_bylevel=1,
reg_alpha=0, reg_lambda=1),
], proba=True)
# Attach the final meta estimator
ensemble.add_meta(LogisticRegression(solver='sag', n_jobs=6, multi_class='multinomial',
tol=1e-4, C=1.e4 / 533292))
accuracy = train_model(make_pipeline(tfidf_vect_ngram, GridSearchCV(estimator=ensemble),
train_x, train_y, valid_x), param_grid=params, scoring='accuracy', n_jobs=-1)
# -
train_index
| title_classification/itemid_classification.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="G6PyCLDpfOyA" executionInfo={"status": "ok", "timestamp": 1638474951548, "user_tz": 360, "elapsed": 6988, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "12998546416496698477"}} outputId="4fd9bf8b-dd36-43bf-c6e5-f44de7d160be"
# !pwd
# !ls
# %cd "/content/drive/MyDrive/TC2008B/Reto/"
# !pwd
# %pip install mesa
# %pip install pyngrok --quiet
# + colab={"base_uri": "https://localhost:8080/"} id="YA1lxDKLrICw" executionInfo={"status": "ok", "timestamp": 1638474951551, "user_tz": 360, "elapsed": 25, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "12998546416496698477"}} outputId="e59d9020-c744-4988-8a67-043c2cdd09c5"
from google.colab import drive
drive.mount('/content/drive')
# + colab={"base_uri": "https://localhost:8080/"} id="7ZYp7RhnO9iC" outputId="04561e6f-fbb8-42cb-af53-cfa201352115"
# from retoagentes import Habitacion
# #%cd "/content/drive/MyDrive/TC2008B/Reto/"
#from retoagentes import Habitacion
from retoagentes1 import Habitacion
import time
import datetime
# Install pyngrok to propagate the http server
# Load the required packages
from pyngrok import ngrok
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import json
import os
import numpy as np
# Boid is a dummy implementation that can be replaced with a more sophisticated
# MAS module, for example, MESA
#from boid import Boid
# Start ngrok
ngrok.install_ngrok()
# Terminate open tunnels if exist
ngrok.kill()
# Open an HTTPs tunnel on port 8585 for http://localhost:8585
port = os.environ.get("PORT", 8585)
server_address = ("", port)
#para unity
public_url = ngrok.connect(port="8585", proto="http", options={"bind_tls": True})
print("\n" + "#" * 94)
print(f"## Tracking URL: {public_url} ##")
print("#" * 94, end="\n\n")
ngrok.kill()
#####################################################################################################
tiempo_maximo = 0.05
ticks = 5
model = Habitacion(ticks)
#####################################################################################################
# The way how agents are updated (per step/iteration)
def updateFeatures():
features = []
# For each agent...
#conti = conti + 1
model.step()
features = model.infoAgentes()
#model.datacollector.get_model_vars_dataframe()
return features
# Post the information in `features` for each iteration
def featuresToJSON(info_list):
#import pdb; pdb.set_trace()
featureDICT = []
print(info_list)
for info in info_list:
feature = {
"position" : info['position'], # position
"kind" : info['kind'], # kind
"colour" : info['colour'] # colour
}
featureDICT.append(feature)
return json.dumps(featureDICT)
# This is the server. It controls the simulation.
# Server run (do not change it)
class Server(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n",
str(self.path), str(self.headers))
self._set_response()
self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
def do_POST(self):
content_length = int(self.headers['Content-Length'])
#post_data = self.rfile.read(content_length)
post_data = json.loads(self.rfile.read(content_length))
# If you have issues with the encoder, toggle the following lines:
#logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
#str(self.path), str(self.headers), post_data.decode('utf-8'))
logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
str(self.path), str(self.headers), json.dumps(post_data))
# Here, magick happens
# --------------------
features = updateFeatures()
#print(features)
self._set_response()
resp = "{\"data\":" + featuresToJSON(features) + "}"
#print(resp)
self.wfile.write(resp.encode('utf-8'))
# Server run (do not change it)
def run(server_class=HTTPServer, handler_class=Server, port=8585):
logging.basicConfig(level=logging.INFO)
server_address = ('', port)
httpd = server_class(server_address, handler_class)
public_url = ngrok.connect(port).public_url
logging.info("ngrok tunnel \"{}\" -> \"http://127.0.0.1:{}\"".format(
public_url, port))
logging.info("Starting httpd...\n") # HTTPD is HTTP Daemon!
try:
httpd.serve_forever()
except KeyboardInterrupt: # CTRL + C stops the server
pass
httpd.server_close()
logging.info("Stopping httpd...\n")
run(HTTPServer, Server)
| Main.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
#finds the probability of measuring a state |𝜓⟩ in the state |𝑥⟩
#𝑝(|𝑥⟩)=|⟨𝑥|𝜓⟩| squared
#in other words calculates the probabilities of quantum states
#references:
# [1] https://qiskit.org/textbook/ch-states/representing-qubit-states.html##1-Normalisation
# [2] https://www.wikihow.com/Calculate-Probabilities-of-Quantum-States
#TODO: format sqrt, division
#necessary imports
from math import sqrt
from numpy import dot, inner, conj
#get the state |𝜓⟩
psi = [1/sqrt(2), 1j/sqrt(2)]
#get the state we want to measure that is |𝑥⟩
x = [1, 0]
#TODO: validate |𝑥⟩
# step 1: print out what we want to calculate
print('<', x, '|', psi, '>')
# step 2: To find the probability amplitude for |𝜓⟩ to be found in the state |𝑥⟩; take the inner products
inner_product = inner(x,psi)
print("Take the inner products: ", inner_product)
# step 3: Square the amplitude.
# The probability is the modulus squared.
# Remember that the modulus squared means to multiply the amplitude with its complex conjugate.
conjugate = conj(inner_product)
print("Find the complex conjugate: ", conjugate)
probability = conjugate * inner_product
print("Probability: ", probability)
# -
| Born Rule.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# %matplotlib inline
(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
len(X_train)
X_train.shape
y_test.shape
X_train[0]
plt.matshow(X_train[0])
y_train[0]
# Scaling the data
X_train = X_train / 255
X_test = X_test / 255
X_train[0]
# Converting 3D array into 2D array
X_train_flatten = X_train.reshape(len(X_train),28*28)
X_test_flatten = X_test.reshape(len(X_test),28*28)
X_train_flatten.shape
X_train_flatten[0]
# # Single layer neural network
# +
model = keras.Sequential([
keras.layers.Dense(10, input_shape = (784,), activation = 'sigmoid')
])
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['accuracy'])
model.fit(X_train_flatten, y_train, epochs = 10)
# -
model.evaluate(X_test_flatten, y_test)
y_predicted = model.predict(X_test_flatten)
y_predicted[0]
plt.matshow(X_test[0])
np.argmax(y_predicted[0]) # Highest number in y_predicted[0] array
y_predicted_label = [np.argmax(i) for i in y_predicted]
y_predicted_label[:5] # top 5 values for top 5 x_test values
plt.matshow(X_test[1])
cm = tf.math.confusion_matrix(labels = y_test, predictions = y_predicted_label)
cm
import seaborn as sns
plt.figure(figsize = (10,7))
sns.heatmap(cm, annot = True, fmt = 'd')
plt.xlabel('Predicted')
plt.ylabel('Truth')
# # Hidden layer neural network
# +
model = keras.Sequential([
keras.layers.Dense(100, input_shape = (784,), activation = 'relu'), # Hidden layer with 100 neurons
keras.layers.Dense(10, activation = 'sigmoid')
])
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['accuracy'])
model.fit(X_train_flatten, y_train, epochs = 10)
# -
model.evaluate(X_test_flatten, y_test)
# +
y_predicted_h = model.predict(X_test_flatten)
y_predicted_h_labels = [np.argmax(i) for i in y_predicted_h]
cm_h = tf.math.confusion_matrix(labels = y_test,predictions = y_predicted_h_labels)
plt.figure(figsize= (10,7))
sns.heatmap(cm_h, annot = True, fmt = 'd')
plt.xlabel('predicted')
plt.ylabel('Truth')
# -
# Using flatten function in keras model
model = keras.Sequential([
keras.layers.Flatten(input_shape = (28, 28)),
keras.layers.Dense(100, activation = 'relu'),
keras.layers.Dense(10, activation = 'sigmoid')
])
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['accuracy'])
model.fit(X_train,y_train, epochs = 10)
model.evaluate(X_test,y_test)
# +
model = keras.Sequential([
keras.layers.Flatten(input_shape = (28, 28)),
keras.layers.Dense(100, activation = 'tanh'),
keras.layers.Dense(10, activation = 'sigmoid')
])
tb_callback = tf.keras.callbacks.TensorBoard(log_dir = 'logs/', histogram_freq = 1)
model.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['accuracy'])
model.fit(X_train,y_train, epochs = 10, callbacks = [tb_callback])
# -
| Deep Learning - Neural Network - TensorFlow handwritten digits classifier .ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
import matplotlib
matplotlib.use('agg')
import cPickle as pickle
import os; import sys; sys.path.append('../../')
import gp
import gp.nets as nets
# +
# PATCH_PATH = ('ipmlb')
X_train, y_train, X_test, y_test = gp.Patch.load_small()
print 'Training patches', y_train.shape[0]
print 'Test patches', y_test.shape[0]
# -
| ipy_test/CHANNELTEST/Untitled.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
import numpy as np
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
gsea_df = pd.read_csv('../exp/reactome_2019_GSEA.csv', index_col = 0)
wall_df = pd.read_csv('../exp/pathway_qvalues.csv', index_col = 0)
adj_wall_df = pd.read_csv('../exp/adjusted_distributions_intclust.csv', index_col = 0)
gsea_df
# +
new_name = {}
for i in gsea_df.columns:
new_i = i.lstrip('IntClust ')
new_name[i] = new_i
print(new_name)
gsea_df = gsea_df.rename(columns = new_name)
gsea_df_counts = {}
for column in gsea_df.columns:
columnshape = gsea_df[gsea_df[column] >= 3].shape[0]
gsea_df_counts[column] = columnshape
# -
gsea_df_counts
# +
wall_df_counts = {}
for column in wall_df.columns:
columnshape = wall_df[wall_df[column] >= 3].shape[0]
wall_df_counts[column] = columnshape
# +
adj_wall_df_counts = {}
for column in adj_wall_df.columns:
columnshape = adj_wall_df[adj_wall_df[column] >= 3].shape[0]
adj_wall_df_counts[column] = columnshape
new_name = {}
for i in adj_wall_df.columns:
if i != 'cluster 4ER- log adjusted q-value':
new_i = i.lstrip('cluster ')
new_i = new_i.rstrip(' log adjusted q-value')
else:
new_i = '4ER-'
new_name[i] = new_i
print(new_name)
adj_wall_df = adj_wall_df.rename(columns = new_name)
adj_wall_df_counts = {}
for column in adj_wall_df.columns:
columnshape = adj_wall_df[adj_wall_df[column] >= 3].shape[0]
adj_wall_df_counts[column] = columnshape
adj_wall_df.columns
# -
adj_wall_df
adj_wall_df_counts
anova_df_counts = {'1': 725, '2': 39, '3': 959, '4ER+': 1196, '4ER-': 961, '5': 650, '6': 218, '7': 1150, '8': 1313, '9': 581, '10': 1571}
full_df = pd.DataFrame({'GSEA': gsea_df_counts, 'ANOVA': adj_wall_df_counts})
ax = full_df.plot.bar(rot=0, figsize=(12, 7))
ax.set_xlabel("IntClusts", fontsize=18)
ax.set_ylabel("Pathways with q ≤ 0.001", fontsize=18)
ax.set_title('Comparison of ANOVA and GSEA significant pathways', fontsize=22)
ax.tick_params(labelsize=16)
fig = ax.get_figure()
fig.show()
fig = ax.get_figure()
fig.savefig('gsea_wall_anova_comparison.png')
gsea_df
# +
compare_sig_pathways = {}
for i in gsea_df.columns:
print(i)
gsea_cluster = gsea_df[gsea_df[i] > 3].index.tolist()
anova_cluster = adj_wall_df[adj_wall_df[i] > 3].index.tolist()
count = 0
for index in anova_cluster:
if index in gsea_cluster:
count += 1
compare_sig_pathways[i] = count
compare_sig_pathways
# -
adj_wall_df_counts["1"]
gsea_df_counts["1"]
venn_dict = {}
for i in compare_sig_pathways.keys():
venn_list = [adj_wall_df_counts[i]-compare_sig_pathways[i], gsea_df_counts[i] - compare_sig_pathways[i], compare_sig_pathways[i]]
venn_dict[i] = venn_list
venn_dict
adj_wall_df.sort_values(by="8", ascending=False)
for i in venn_dict.keys():
anova = int(venn_dict[i][0])
overlap = int(venn_dict[i][2])
sum_ = anova + overlap
print(i)
if overlap != 0:
print((overlap/sum_)*100)
for i in venn_dict.keys():
print(f"cluster {i}")
print(venn_dict[i][1]-venn_dict[i][2])
print(venn_dict[i][0]-venn_dict[i][2])
print(venn_dict[i][2])
print("")
overlap_df = pd.DataFrame({'GSEA': gsea_df_counts, 'ANOVA': adj_wall_df_counts, 'Overlap': compare_sig_pathways})
# +
overlap_df = pd.DataFrame(index = gsea_df_counts.keys())
overlap_df['Overlap'] = compare_sig_pathways.values()
overlap_df['GSEA'] = gsea_df_counts.values()
overlap_df['ANOVA'] = adj_wall_df_counts.values()
overlap_df['GSEA exclusive'] = overlap_df['GSEA'] - overlap_df['Overlap']
overlap_df['ANOVA exclusive'] = overlap_df['ANOVA'] - overlap_df['Overlap']
overlap_df
# -
| metabric/src/comparing_gsea_and_wall.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <img src="../../images/qiskit-heading.gif" alt="Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook" width="500 px" align="left">
# # Operators Overview
#
# The latest version of this notebook is available on https://github.com/Qiskit/qiskit-tutorial.
# ## Introduction
#
# This notebook shows how to use the `Operator` class from the *Quantum Information* module of qiskit to create custom matrix operators, custom unitary gates, and to evaluate the unitary matrix for a quantum circuit.
# +
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions import RXGate, CnotGate, XGate
# -
# ## Operator class
#
# The `Operator` class is used in Qiskit to represent matrix operators acting on a quantum system. It has several methods to build composite operators using tensor products of smaller operators, and to compose operators.
#
# ### Creating Operators
#
# The easiest way to create an operator object is to initialize it with a matrix given as a list or a Numpy array. For example to create a 2-qubit Pauli-XX operator
XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
XX
# ### Operator Properties
#
# The operator object stores the underlying matrix, and the input and output dimension of subsystems.
#
# * `data`: To access the underly Numpy array we may use the `Operator.data` property
# * `dims`: To return the total input and output dimension of the operator we may use the `Operator.dim` property. *Note: the output is returned as a tuple `(input_dim, output_dim)` which is the reverse of the shape of the underlying matrix.*
XX.data
input_dim, output_dim = XX.dim
input_dim, output_dim
# ### Input and output dimensions
#
# The operator class also keeps track of subsystem dimensions which can be used for composing operators together. These can be accessed using the `input_dims` and `output_dims` functions.
#
# For $2^N$ by $2^M$ operators the input and output dimension will be automatically assumed to be M-qubit and N-qubit:
op = Operator(np.random.rand(2 ** 1, 2 ** 2))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# If the input matrix is not divisible into qubit subsystems then it will be stored as a single qubit operator. For example if we have a 6 x 6 matrix:
op = Operator(np.random.rand(6, 6))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# The input and output dimension can also be manually specified when initializing a new operator
# Force input dimension to be (4,) rather than (2, 2)
op = Operator(np.random.rand(2 ** 1, 2 ** 2), input_dims=[4])
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# Specify system is a qubit and qutrit
op = Operator(np.random.rand(6, 6),
input_dims=[2, 3], output_dims=[2, 3])
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# We can also extract just the input or output dimens of a subset of subsystems using the `input_dims` and `output_dims` functions:
print('Dimension of input system 0:', op.input_dims([0]))
print('Dimension of input system 1:', op.input_dims([1]))
# ## Converting classes to Operators
#
# Several other classes in Qiskit can be directly converted to an `Operator` object using the operator initialization method. For example:
#
# * `Pauli` objects
# * `Gate` and `Instruction` objects
# * `QuantumCircuits` objects
#
# Note that the last point means we can use the `Operator` class as a unitary simulator to compute the final unitary matrix for a quantum circuit without having to call a simulator backend. If the circuit contains any unsupported operations an exception will be raised. Unsupported operations are: measure, reset, conditional operations, or a gate that does not have a matrix definition or decomposition in terms of gate with matrix definitions.
# +
# Create an Operator from a Pauli object
pauliXX = Pauli(label='XX')
Operator(pauliXX)
# -
# Create an Operator for a Gate object
Operator(CnotGate())
# Create an operator from a parameterized Gate object
Operator(RXGate(np.pi / 2))
# +
# Create an operator from a QuantumCircuit object
qr = QuantumRegister(10)
circ = QuantumCircuit(qr)
circ.h(qr[0])
for j in range(1, 10):
circ.cx(qr[j-1], qr[j])
# Convert circuit to an operator by implicit unitary simulation
Operator(circ)
# -
# ## Using Operators in circuits
#
# Unitary `Operators` can be directly inserted into a `QuantumCircuit` using the `QuantumCircuit.append` method. This converts the `Operator` into a `UnitaryGate` object which is added to the circuit.
#
# If the operator is not unitary an exception will be raised. This can be checked using the `Operator.is_unitary()` function which will return `True` if the operator is unitary and `False` otherwise.
# +
# Create an operator
XX = Operator(Pauli(label='XX'))
# Check unitary
print('Operatator is unitary:', XX.is_unitary())
# Add to a circuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circ = QuantumCircuit(qr, cr)
circ.append(XX, [qr[0], qr[1]])
circ.measure(qr, cr)
print(circ)
backend = BasicAer.get_backend('qasm_simulator')
job = execute(circ, backend, basis_gates=['u1','u2','u3','cx'])
job.result().get_counts(0)
# -
# Note that in the above example we initialize the operator from a `Pauli` object. However, the `Pauli` object may also be directly inserted into the circuit itself and will be converted into a sequence of single qubit Pauli gates:
# +
# Add to a circuit
circ2 = QuantumCircuit(qr, cr)
circ2.append(Pauli(label='XX'), [qr[0], qr[1]])
circ2.measure(qr, cr)
print(circ2)
# Simulate
job2 = execute(circ2, backend)
job2.result().get_counts(0)
# -
# ## Combing Operators
#
# Operators my be combined using several methods.
#
# ### Tensor Product
#
# Two operators $A$ and $B$ may be combined into a tensor product operator $A\otimes B$ using the `Operator.tensor` function. Note that if both A and B are single-qubit operators, then `A.tensor(B)` = $A\otimes B$ will have the subsystems indexed as matrix B on subsystem 0, and matrix $A$ on subsystem 1.
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.tensor(B)
# ### Tensor Expansion
#
# A closely related operation is `Operator.expand` which acts like a tensor product but in the reverse order. Hence for two operators $A$ and $B$ we have `A.expand(B)` = $B\otimes A$ where the subsystems indexed as matrix A on subsystem 0, and matrix $B$ on subsystem 1.
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.expand(B)
# ### Composition
#
# We can also compose two operators $A$ and $B$ to implement matrix multiplication using the `Operator.compose` method. We have that `A.compose(B)` returns the operator with matrix $B.A$:
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.compose(B)
# We can also compose in the reverse order by applying $B$ in front of $A$ using the `front` kwarg of `compose`: `A.compose(B, front=True)` = $A.B$:
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.compose(B, front=True)
# ### Subsystem composotion
#
# Note that the previous compose requires that the total output dimension of the first operator $A$ is equal to total input dimension of the composed operator $B$ (and similaly the output dimension of $B$ equal to the input dimension of $A$ when composing with `front=True`).
#
# We can also compose a smaller operator with a selection of subsystems on a larger operator using the `qargs` kwarg of `compose` either with or without `front=True`. In this case the relevant input and output dimenions of the subsystems being composed must match. *Note that the smaller operator must always be the arguement of `compose` method.*
#
# For example to compose a 2-qubit gate with a 3-qubit Operator:
# Compose XZ with an 3-qubit identity operator
op = Operator(np.eye(2 ** 3))
XZ = Operator(Pauli(label='XZ'))
op.compose(XZ, qargs=[0, 2])
# Compose YX in front of the previous operator
op = Operator(np.eye(2 ** 3))
YX = Operator(Pauli(label='YX'))
op.compose(XZ, qargs=[0, 2], front=True)
# ### Linear combinations
#
# Operators may also be combined using standard linear operators for addition, subtraction and scalar multiplication by complex numbers.
# +
XX = Operator(Pauli(label='XX'))
YY = Operator(Pauli(label='YY'))
ZZ = Operator(Pauli(label='ZZ'))
op = 0.5 * (XX + YY - 3 * ZZ)
op
# -
# An import point is that while `tensor`, `expand` and `compose` will preserve the unitarity of unitary operators, linear combinations will not. Hence adding two unitary operators will in general result in a non-unitary operator:
op.is_unitary()
# ### Implicit conversion to operators
#
# Note that for all the following methods, if the second object is not already an `Operator` object, it will be implicitly converted into one by the method. This means matrices can be passed in directly without being explicitly convert to an `Operator` first. If the conversion is not possible an exception will be raised
# Compose with a matrix passed as a list
Operator(np.eye(2)).compose([[0, 1], [1, 0]])
# ## Comparison of Operators
#
# Operators implement an equality method that can be used to check if two operators are approximately equal.
Operator(Pauli(label='X')) == Operator(XGate())
# Note that this checks each matrix element of the operators is approximately equal so two unitaries which differ by a global phase will not be considered equal
Operator(XGate()) == np.exp(1j * 0.5) * Operator(XGate())
# ### Process Fidelity
#
# We may also compare operators using the `process_fidelity` function from the *Quantum Information* module. This is an information theoretic quantity for how close to quantum channels are two each other, and in the case of unitary operators it does not depend on global phase.
# +
# Two operators which differ only by phase
op_a = Operator(XGate())
op_b = np.exp(1j * 0.5) * Operator(XGate())
# Compute process fidelity
F = process_fidelity(op_a, op_b)
print('Process fidelity =', F)
# -
# Note that process fidelity is generally only a valid measure of closeness if the input operators are unitary (or CP in the case of quantum channels), and an exception will be raised if the inputs are not CP.
| qiskit/terra/operators_overview.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
from sklearn.datasets import load_iris
#读取iris数据集。
X, y = load_iris(return_X_y=True)
# +
from sklearn.preprocessing import StandardScaler
#初始化数据标准化处理器
ss = StandardScaler()
#标准化训练数据特征。
X = ss.fit_transform(X)
# +
from sklearn.neural_network import BernoulliRBM
#初始化RBM神经网络,设定降维维度为2。
rbm = BernoulliRBM(n_components=2)
#对数据特征进行降维处理。
X = rbm.fit_transform(X)
# +
from matplotlib import pyplot as plt
colors = ['red', 'blue', 'green']
markers = ['o', '^', 's']
plt.figure(dpi=150)
#可视化降维的数据。
for i in range(len(X)):
plt.scatter(X[i, 0], X[i, 1], c = colors[y[i]], marker = markers[y[i]])
plt.show()
| Chapter_5/Section_5.2.1.5.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
print(keras.__version__)
# +
from sklearn.datasets import load_sample_image
# Load sample images
china = load_sample_image("china") / 255
flower = load_sample_image("flower.jpg") / 255
images = np.array([china, flower])
batch_size, height, width, channels = images.shape
# -
# Create 2 filters
filters = np.zeros(shape=(7,7, channels, 2), dtype=np.float32)
filters[:, 3, :, 0] = 1 # vertical line
filters[3, :, :, 1] = 1 # horizontal line
outputs = tf.nn.conv2d(images, filters, strides=1, padding="same")
output = tf.nn.max_pool(images,
ksize=(1, 1, 1, 3),
strides=(1, 1, ,1, 3),
padding="valid")
depth_pool = keras.layers.Lambda(
lamda X: tf.nn.max_pool(X, ksize=(1, 1, 1, 3), strides=(1, 1, 1, 3), padding="valid"))
model = keras.models.Sequential([
keras.layers.Conv2D(64, 7, activation="relu", padding="same", input_shape=[28, 28, 1]),
keras.layers.MaxPooling2D(2),
keras.layers.Conv2D(128, 3, activation="relu", padding="same"),
keras.layers.Conv2D(128, 3, activation="relu", padding="same"),
keras.layers.MaxPooling2D(2),
keras.layers.Conv2D(256, 3, activation="relu", padding="same"),
keras.layers.Conv2D(256, 3, activation="relu", padding="same"),
keras.layers.MaxPooling2D(2),
keras.layers.Flatten(),
keras.layers.Dense(128, activation="relu"),
keras.layers.Dropout(0.5),
keras.layers.Dense(64, activation="relu"),
keras.layers.Dropout(0.5),
keras.layers.Dense(10, activation="softmax")
])
class ResidualUnit(keras.layers.Layer):
def __init__(self, filters, strides=1, activation="relu", **kwargs):
super().__init__(**kwargs)
self.activation = keras.activations.get(activation)
self.main_layers = [
keras.layers.Conv2D(filters, 3, strides=strides,
padding="same", use_bias=False),
keras.layers.BatchNormalization(),
self.activation,
keras.layers.Conv2D(filters, 3, strides=1,
padding="same", use_bias=False),
keras.layers.BatchNormalization()]
self.skip_layers = []
if strides > 1:
self.skip_layers = [
keras.layers.Conv2D(filters, 1, strides=strides,
padding="same", use_bias=False),
keras.layers.BatchNormalization()
]
def call(self, inputs):
Z = inputs
for layer in self.main_layers:
Z = layer(Z)
skip_Z = inputs
for layer in self.skip_layers:
skip_Z = layer(skip_Z)
return self.activation(Z + skip_Z)
model = keras.models.Sequential()
model.add(keras.layers.Conv2D(64, 7, strides=2, input_shape=[224, 224, 3],
padding="same", use_bias=False))
model.add(keras.layers.BatchNormalization())
model.add(keras.layers.Activation("relu"))
model.add(keras.layers.MaxPool2D(pool_size=3, strides=2, padding="same"))
prev_filters = 64
for filters in [64] * 3 + [128] * 4 + [256] * 6 + [512] * 3:
strides = 1 if filters == prev_filters else 2
model.add(ResidualUnit(filters, strides=strides))
prev_filters = filters
model.add(keras.layers.GlobalAvgPool2D())
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(10, activation="softmax"))
| chapter14/tf_implementation_of_convolution.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
# ---
# # Regular expressions
#
# ## Lab 03
#
# ### February 23, 2018
#
# This notebook covers the basics of regular expressions.
#
# Regular expressions (regex or regexp) are search patterns described as strings. They allow pattern matching in arbitrary strings.
#
# Regex are implemented in Python's `re` module.
#
# The `re` module operates via two objects:
#
# 1. **pattern** objects, which are a compiled regular expressions and
# 2. **match** objects that describe successful pattern matches.
# +
import re
r = re.compile("abc")
type(r), r
# -
m = r.search("aabcd")
type(m), m
# or `None` is returned when no matching pattern was found in the string
m2 = r.search("def")
m2
# The match object's `span` method returns the starting and ending index of the match:
m = r.search("aabcde")
m.span()
m.start(), m.end()
# these can be directly used to extract the matching substring:
# +
s = "aabcdef"
m = r.search(s)
s[m.start():m.end()]
# -
# Pattern objects do not have to be created but compilation offers some speed-up.
re.search("ab", "abcd")
# # Basic regular expressions
#
# Below we show the most commonly used regex types. For a full list see the official documentation [here](https://docs.python.org/3/library/re.html).
#
# We will not compile the regular expressions for the sake of brevity.
#
# For capturing a range of characters, use `[]`:
re.search("[bB]", "abc")
re.search("[bB]", "aBb")
# ## Qualifiers
#
# Qualifiers control how many times a pattern is searched for.
#
# `?` matches zero or one time:
re.search("a?bc", "bc")
re.search("a?bc", "aabc")
# `*` matches zero or more times in a greedy manner (match as many as possible):
re.search("a*bc", "aaabc")
# `+` matches one or more times:
re.search("a+bc", "daaaabc")
# `{N}` will match exactly $N$ times:
re.search("a{3}bc", "aabc")
re.search("a{3}bc", "aaaabc")
# `{N,M}` will match at least $N$ and at most $M$ times:
re.search("a{3,5}bc", "aaaabc")
re.search("a{3,5}bc", "aaaaabc")
# ## Special characters
#
# `.` matches any character besides newline:
re.search("a.c", "abc")
print(re.search("a.c", "ac"))
# `^` (Caret) matches the beginning of the string and in MULTILINE mode, immediately after each newline:
re.search("^a", "abc"), re.search("^a", "bc\na")
re.search("^a", "bc\nab", re.MULTILINE)
# `$` matches the end of the string or before newline in MULTILINE mode:
re.search("c$", "abc")
re.search("a$", "aba\nc", re.MULTILINE)
# ## `|` in patterns
#
# `|` allows matching any of several patterns
re.search("ab|cd", "ab").span()
re.search("ab|cd", "decd").span()
# ## Character ranges
#
# `[A-F]` matches every character between A and F:
re.search("[A-F]{3}", "abBCDEef")
# `[A-Za-z]` matches every English letter:
re.search("[A-Za-z]+", "abAaz12")
# `[0-9]` matches digits:
re.search("[0-9]{3}", "ab12345cd")
# `-` needs to be escaped if we want to include it in the character range:
re.search("[0-9\-]+", "1-2")
# ## Character classes
#
# Some character classes are predefined such as ascii letters or whitespaces.
#
# `\s` matches any Unicode whitespace:
re.search("\s+", "ab \t\n\n")
# `\S` (capital S) matches anything else:
re.search("\S+", "ab \t\n\n")
# `\w` matches any Unicode word character that can be part of a word in any language, and `\W` matches anything else:
re.search("\w+", "tükörfúrógép")
re.search("\w+", "tükör fúrógép")
# negative character classes match characters **NOT** in the class
re.search("[^abc]+", "abcdef").group(0)
# ## Capture groups
#
# Patterns may contain groups, marked by parentheses. Groups can be accessed by their indices, or all of them can be retrieved by the groups method:
patt = re.compile("([hH]ell[oó]) (.*)!")
match = patt.search("Hello people!")
match.group()
match.groups()
match.group(0)
match.group(1)
match.group(2)
# Groups can also be named, in this case they can be retrieved in a dict maping group names to matched substrings using groupdict:
patt = re.compile("(?P<greeting>[hH]ell[oó]) (?P<name>.*)!")
match = patt.search("Hello people!")
match.group("name")
match.groupdict()
# ## Other `re` methods
#
# `re.match` matches only at the beginning of the string
re.match("ab", "abcd")
print(re.match("ab", "zabcd"))
# `re.findall` matches every occurrence of a pattern in a string. Unlike most other methods, `findall` directly returns the string patterns instead of patter objects.
re.findall("[AaBb]+", "ab Abcd")
# `re.finditer` returns an iterator that iterates over every match:
for match in re.finditer("[AaBb]+", "ab Abcd"):
print(match.span(), match.group(0))
# `re.sub` replaces an occurrence:
re.sub("[Aa]", "b", "acA")
# `re.split` splits a string at every pattern match
re.split("\s+", "words with\t whitespace")
# we can keep the separators as well:
re.split("(\s+)", "words with\t whitespace")
| course_material/03_Object_oriented_programming/03_Regular_Expressions.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
# ---
# # Heart Disease Prediction
#
# In this machine learning project, I have collected the dataset from Kaggle (https://www.kaggle.com/ronitf/heart-disease-uci) and I will be using Machine Learning to make predictions on whether a person is suffering from Heart Disease or not.
# ### Import libraries
#
# Let's first import all the necessary libraries. I'll use `numpy` and `pandas` to start with. For visualization, I will use `pyplot` subpackage of `matplotlib`, use `rcParams` to add styling to the plots and `rainbow` for colors. For implementing Machine Learning models and processing of data, I will use the `sklearn` library.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib.cm import rainbow
# %matplotlib inline
import warnings
warnings.filterwarnings('ignore')
# For processing the data, I'll import a few libraries. To split the available dataset for testing and training, I'll use the `train_test_split` method. To scale the features, I am using `StandardScaler`.
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Next, I'll import all the Machine Learning algorithms I will be using.
# 1. K Neighbors Classifier
# 2. Support Vector Classifier
# 3. Decision Tree Classifier
# 4. Random Forest Classifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
# ### Import dataset
#
# Now that we have all the libraries we will need, I can import the dataset and take a look at it. The dataset is stored in the file `dataset.csv`. I'll use the pandas `read_csv` method to read the dataset.
dataset = pd.read_csv('dataset.csv')
# The dataset is now loaded into the variable `dataset`. I'll just take a glimpse of the data using the `desribe()` and `info()` methods before I actually start processing and visualizing it.
dataset.info()
# Looks like the dataset has a total of 303 rows and there are no missing values. There are a total of `13 features` along with one target value which we wish to find.
dataset.describe()
# The scale of each feature column is different and quite varied as well. While the maximum for `age` reaches 77, the maximum of `chol` (serum cholestoral) is 564.
# ### Understanding the data
#
# Now, we can use visualizations to better understand our data and then look at any processing we might want to do.
rcParams['figure.figsize'] = 20, 14
plt.matshow(dataset.corr())
plt.yticks(np.arange(dataset.shape[1]), dataset.columns)
plt.xticks(np.arange(dataset.shape[1]), dataset.columns)
plt.colorbar()
# Taking a look at the correlation matrix above, it's easy to see that a few features have negative correlation with the target value while some have positive.
# Next, I'll take a look at the histograms for each variable.
dataset.hist()
# Taking a look at the histograms above, I can see that each feature has a different range of distribution. Thus, using scaling before our predictions should be of great use. Also, the categorical features do stand out.
# It's always a good practice to work with a dataset where the target classes are of approximately equal size. Thus, let's check for the same.
rcParams['figure.figsize'] = 8,6
plt.bar(dataset['target'].unique(), dataset['target'].value_counts(), color = ['red', 'green'])
plt.xticks([0, 1])
plt.xlabel('Target Classes')
plt.ylabel('Count')
plt.title('Count of each Target Class')
# The two classes are not exactly 50% each but the ratio is good enough to continue without dropping/increasing our data.
# ### Data Processing
#
# After exploring the dataset, I observed that I need to convert some categorical variables into dummy variables and scale all the values before training the Machine Learning models.
# First, I'll use the `get_dummies` method to create dummy columns for categorical variables.
dataset = pd.get_dummies(dataset, columns = ['sex', 'cp', 'fbs', 'restecg', 'exang', 'slope', 'ca', 'thal'])
# Now, I will use the `StandardScaler` from `sklearn` to scale my dataset.
standardScaler = StandardScaler()
columns_to_scale = ['age', 'trestbps', 'chol', 'thalach', 'oldpeak']
dataset[columns_to_scale] = standardScaler.fit_transform(dataset[columns_to_scale])
# The data is not ready for our Machine Learning application.
# ### Machine Learning
#
# I'll now import `train_test_split` to split our dataset into training and testing datasets. Then, I'll import all Machine Learning models I'll be using to train and test the data.
y = dataset['target']
X = dataset.drop(['target'], axis = 1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 0)
# #### K Neighbors Classifier
#
# The classification score varies based on different values of neighbors that we choose. Thus, I'll plot a score graph for different values of K (neighbors) and check when do I achieve the best score.
knn_scores = []
for k in range(1,21):
knn_classifier = KNeighborsClassifier(n_neighbors = k)
knn_classifier.fit(X_train, y_train)
knn_scores.append(knn_classifier.score(X_test, y_test))
# I have the scores for different neighbor values in the array `knn_scores`. I'll now plot it and see for which value of K did I get the best scores.
plt.plot([k for k in range(1, 21)], knn_scores, color = 'red')
for i in range(1,21):
plt.text(i, knn_scores[i-1], (i, knn_scores[i-1]))
plt.xticks([i for i in range(1, 21)])
plt.xlabel('Number of Neighbors (K)')
plt.ylabel('Scores')
plt.title('K Neighbors Classifier scores for different K values')
# From the plot above, it is clear that the maximum score achieved was `0.87` for the 8 neighbors.
print("The score for K Neighbors Classifier is {}% with {} nieghbors.".format(knn_scores[7]*100, 8))
# #### Support Vector Classifier
#
# There are several kernels for Support Vector Classifier. I'll test some of them and check which has the best score.
svc_scores = []
kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for i in range(len(kernels)):
svc_classifier = SVC(kernel = kernels[i])
svc_classifier.fit(X_train, y_train)
svc_scores.append(svc_classifier.score(X_test, y_test))
# I'll now plot a bar plot of scores for each kernel and see which performed the best.
colors = rainbow(np.linspace(0, 1, len(kernels)))
plt.bar(kernels, svc_scores, color = colors)
for i in range(len(kernels)):
plt.text(i, svc_scores[i], svc_scores[i])
plt.xlabel('Kernels')
plt.ylabel('Scores')
plt.title('Support Vector Classifier scores for different kernels')
# The `linear` kernel performed the best, being slightly better than `rbf` kernel.
print("The score for Support Vector Classifier is {}% with {} kernel.".format(svc_scores[0]*100, 'linear'))
# #### Decision Tree Classifier
#
# Here, I'll use the Decision Tree Classifier to model the problem at hand. I'll vary between a set of `max_features` and see which returns the best accuracy.
dt_scores = []
for i in range(1, len(X.columns) + 1):
dt_classifier = DecisionTreeClassifier(max_features = i, random_state = 0)
dt_classifier.fit(X_train, y_train)
dt_scores.append(dt_classifier.score(X_test, y_test))
# I selected the maximum number of features from 1 to 30 for split. Now, let's see the scores for each of those cases.
plt.plot([i for i in range(1, len(X.columns) + 1)], dt_scores, color = 'green')
for i in range(1, len(X.columns) + 1):
plt.text(i, dt_scores[i-1], (i, dt_scores[i-1]))
plt.xticks([i for i in range(1, len(X.columns) + 1)])
plt.xlabel('Max features')
plt.ylabel('Scores')
plt.title('Decision Tree Classifier scores for different number of maximum features')
# The model achieved the best accuracy at three values of maximum features, `2`, `4` and `18`.
print("The score for Decision Tree Classifier is {}% with {} maximum features.".format(dt_scores[17]*100, [2,4,18]))
# #### Random Forest Classifier
#
# Now, I'll use the ensemble method, Random Forest Classifier, to create the model and vary the number of estimators to see their effect.
rf_scores = []
estimators = [10, 100, 200, 500, 1000]
for i in estimators:
rf_classifier = RandomForestClassifier(n_estimators = i, random_state = 0)
rf_classifier.fit(X_train, y_train)
rf_scores.append(rf_classifier.score(X_test, y_test))
# The model is trained and the scores are recorded. Let's plot a bar plot to compare the scores.
colors = rainbow(np.linspace(0, 1, len(estimators)))
plt.bar([i for i in range(len(estimators))], rf_scores, color = colors, width = 0.8)
for i in range(len(estimators)):
plt.text(i, rf_scores[i], rf_scores[i])
plt.xticks(ticks = [i for i in range(len(estimators))], labels = [str(estimator) for estimator in estimators])
plt.xlabel('Number of estimators')
plt.ylabel('Scores')
plt.title('Random Forest Classifier scores for different number of estimators')
# The maximum score is achieved when the total estimators are 100 or 500.
print("The score for Random Forest Classifier is {}% with {} estimators.".format(rf_scores[1]*100, [100, 500]))
# ### Conclusion
#
# In this project, I used Machine Learning to predict whether a person is suffering from a heart disease. After importing the data, I analysed it using plots. Then, I did generated dummy variables for categorical features and scaled other features.
# I then applied four Machine Learning algorithms, `K Neighbors Classifier`, `Support Vector Classifier`, `Decision Tree Classifier` and `Random Forest Classifier`. I varied parameters across each model to improve their scores.
# In the end, `K Neighbors Classifier` achieved the highest score of `87%` with `8 nearest neighbors`.
| Heart Disease Prediction.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Linear Discriminant
#
# Like the Naive Bayes notebook, this was just playing around with what I can do with simple models.
#
# Simple models do really well on the attack/no-attack problem, even without
# adjusting for imbalanced classes. Total breakdown in the multi-label case.
# +
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.metrics import balanced_accuracy_score, confusion_matrix
from sklearn.ensemble import BaggingClassifier
from mlxtend.plotting import plot_confusion_matrix
from data_read import data_read
from consistent_labels import get_attack_labels
# -
# %matplotlib inline
# %load_ext watermark
# %watermark -iv -p sklearn,mlxtend
# +
# load the data
labels = ['label', 'attack_cat']
df = data_read('train', 'fixed')
Y = df.loc[:,labels]
Y.label = Y.label.astype(int)
X = df.drop(columns=labels)
df = data_read('test', 'fixed')
Y_test = df.loc[:,labels]
Y_test.label = Y_test.label.astype(int)
X_test = df.drop(columns=labels)
# +
lda = LinearDiscriminantAnalysis(n_components = 1)
lda.fit(X, Y.label)
Xt = lda.transform(X)
y_pred = lda.predict(X_test)
cm = confusion_matrix(Y_test.label, y_pred)
cm
# -
plot_confusion_matrix(cm, show_normed=True, show_absolute=False)
balanced_accuracy_score(Y_test.label, y_pred, adjusted=True)
# # Multi-label
#
# We can't label attacks with something that doesn't learn
# nonlinear relationships
Y_attackcat = Y.attack_cat.map(get_attack_labels())
Y_test_attackcat = Y_test.attack_cat.map(get_attack_labels())
# +
lda = LinearDiscriminantAnalysis(n_components = 1)
lda.fit(X, Y_attackcat)
Xt = lda.transform(X)
y_pred = lda.predict(X_test)
cm = confusion_matrix(Y_test_attackcat, y_pred)
# -
plot_confusion_matrix(cm, show_normed=True, show_absolute=False)
balanced_accuracy_score(Y_test_attackcat, y_pred, adjusted=True)
# # Bagging
#
# Nope, random linear discriminants is not a thing. Especially with no imblannced learning fixes! One fun thing about the end of the bootcamp
# is how much faster I am at trying random stuff just to see what happens.
# +
clf = BaggingClassifier(LinearDiscriminantAnalysis(n_components=1),
n_estimators=100, max_features=.50, max_samples=.50,
n_jobs=-1, random_state=22)
clf.fit(X, Y_attackcat)
y_pred = clf.predict(X_test)
cm = confusion_matrix(Y_test_attackcat, y_pred)
# -
plot_confusion_matrix(cm, show_normed=True, show_absolute=False, figsize=(6,6))
balanced_accuracy_score(Y_test_attackcat, y_pred, adjusted=True)
| src/LinearDiscriminant.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="Re6r5-Tzmuyw" outputId="1223a139-600f-4dc1-c329-c55aa5111b8e"
# To perform text summarization of a Wikipedia Page
import bs4 as bs
import urllib.request
import re
import heapq
import nltk
nltk.download('punkt')
nltk.download('stopwords')
# + [markdown] id="Fh1659A4nnWM"
# Fetching Articles from Wikipedia and Displaying it
# + id="PbsW49MWm6DQ"
# Scrape the data from url and read it
scraped_data = urllib.request.urlopen('https://en.wikipedia.org/wiki/Big_Bang')
article = scraped_data.read()
# + id="3bz_cQrwm64t"
# Parse the data
parsed_article = bs.BeautifulSoup(article,'lxml')
# + colab={"base_uri": "https://localhost:8080/"} id="WPuMuaI0m61R" outputId="60142b49-b15b-4681-d088-1767e829bd23"
# Select text inside paragraph <p> tags
paragraphs = parsed_article.find_all('p')
article_text = ""
for p in paragraphs:
article_text += p.text
print(article_text)
# + [markdown] id="ZafuR9YdnyhG"
# Preprocessing and Showing the output of preprocessing
# + colab={"base_uri": "https://localhost:8080/"} id="cNCzjXOYm6xn" outputId="4be81a24-4f62-4fb0-b544-75a7fb5b8d5f"
# Removing Square Brackets and Extra Spaces
article_text = re.sub(r'\[[0-9]*\]', ' ', article_text)
article_text = re.sub(r'\s+', ' ', article_text)
print(article_text)
# + colab={"base_uri": "https://localhost:8080/"} id="paGldkETm6uH" outputId="e0c42644-91ed-4048-ed31-0e5dc8ca23ea"
# Removing special characters and digits
formatted_article_text = re.sub('[^a-zA-Z]', ' ', article_text )
formatted_article_text = re.sub(r'\s+', ' ', formatted_article_text)
print(formatted_article_text)
# + [markdown] id="2qN0YkbDoOuU"
# Converting Text into Sentences
# + colab={"base_uri": "https://localhost:8080/"} id="0fJ4YS35m6im" outputId="8b82deb9-9ddb-4a9e-ab10-a8492d75e7ff"
# Generating a list of all sentences
sentence_list = nltk.sent_tokenize(article_text)
print(sentence_list)
# + [markdown] id="Ypo84BVZotin"
# Finding the Weighted Frequency of Occurrence and Displaying the Output
# + colab={"base_uri": "https://localhost:8080/"} id="IcjklEJQoyoU" outputId="50c3ca31-ef4d-4ad5-eba4-7632de349fdd"
stopwords = nltk.corpus.stopwords.words('english')
word_frequencies = {}
for word in nltk.word_tokenize(formatted_article_text):
if word not in stopwords:
if word not in word_frequencies.keys():
word_frequencies[word] = 1
else:
word_frequencies[word] += 1
maximum_frequncy = max(word_frequencies.values())
for word in word_frequencies.keys():
word_frequencies[word] = (word_frequencies[word]/maximum_frequncy)
print(word_frequencies)
# + [markdown] id="5YiPbfcTpUHb"
# Calculating the Sentence Scores and Displaying the output
# + colab={"base_uri": "https://localhost:8080/"} id="qmP1C5gDpYuO" outputId="9ce30ac6-96fb-47fa-bbc5-ee0b19d3a94d"
sentence_scores = {}
for sent in sentence_list :
for word in nltk.word_tokenize(sent.lower()) :
if word in word_frequencies.keys() :
if len(sent.split(' ')) < 30 :
if sent not in sentence_scores.keys() :
sentence_scores[sent] = word_frequencies[word]
else :
sentence_scores[sent] += word_frequencies[word]
print(sentence_scores)
# + [markdown] id="id9gUgw6pxuT"
# Displaying the Summary
#
# + colab={"base_uri": "https://localhost:8080/"} id="U1RXCLzApw4j" outputId="dfdf695f-5f7b-41ba-ce8d-a257235dfb6e"
summary_sentences = heapq.nlargest(7, sentence_scores, key=sentence_scores.get)
summary = ' '.join(summary_sentences)
print(summary)
| text_mining.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
# ---
# # TensorFlow2 教程-卷积变分自编码器
#
# 本教程通过构建卷积变分自编码器生成手写数字图片
#
# 首先先导入相关的库
#
# +
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import os
import time
import numpy as np
import glob
import matplotlib.pyplot as plt
import PIL
import imageio
print(tf.__version__)
from IPython import display
# -
# ## 一、载入MNIST数据集
# MNIST数据是手写数字识别的图像数据集,是经典的深度学习数据集。其中每个图片大小为28*28,即可用一个784维的向量来表示图片。其中向量的每个数值在0-255之间,表示像素强度。
# 我们使用MNIST数据集来进行卷积变分自编码的实验,我们首先需要对图像数据进行预处理。这里我们使用伯努利分别来对所有像素进行建模,同时对数据集进行静态二值化处理。
(train_images, _), (test_images, _) = tf.keras.datasets.mnist.load_data()
# +
# 构建数据集
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
test_images = test_images.reshape(test_images.shape[0], 28, 28, 1).astype('float32')
# 化到0-1之间
train_images /= 255.0
test_images /= 255.0
# 二值化
train_images[train_images>=0.5] = 1.0
train_images[train_images<0.5] = 0.0
test_images[test_images>=0.5] = 1.0
test_images[test_images<0.5] = 0.0
# 超参数
TRAIN_BUF=60000
BATCH_SIZE = 100
TEST_BUF = 10000
# +
# 分批和打乱数据
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(TRAIN_BUF).batch(BATCH_SIZE)
test_dataset = tf.data.Dataset.from_tensor_slices(test_images).shuffle(TEST_BUF).batch(BATCH_SIZE)
# -
# ## 二、构建生成网络和推理网络
# 我们使用卷积网络来构建生成网络和推理网络。并使用x和z分别表示观测值和潜在变量
# #### 生成网络
# 生成网络将隐变量作为输入,并输出用于观测条件分布的参数p(x|z).我们对隐变量使用单位高斯先验分布。
# #### 推理网络
# 这里定义了近似后验分布q(z|x) ,该后验分布以观测值作为输入,并输出用于潜在表示的条件分布的一组参数。在本示例中,我们仅将此分布建模为对角高斯模型。在这种情况下,推断网络将输出因式分解的高斯均值和对数方差参数
# #### 采样
# 我们从q(z|x)中采样,方法是先从单位高斯中采样,然后乘以标注差并加上平均值。这样可以确保梯度能确保梯度能传回推理网络。
# #### 网络结构
# 对于推理网络,我们使用了两个卷积层加一个全连接层,而对于生成网络,我们使用全连接层加3个反卷积层。
# 注意:训练VAE过程中要避免使用批归一化,因为这样会导致额外的随机性,从而加剧随机抽样的不稳定性
#
class CVAE(tf.keras.Model):
def __init__(self, latent_dim):
super(CVAE, self).__init__()
self.latent_dim = latent_dim
self.inference_net = tf.keras.Sequential(
[
tf.keras.layers.InputLayer(input_shape=(28, 28, 1)),
tf.keras.layers.Conv2D(
filters=32, kernel_size=3, strides=(2, 2), activation='relu'),
tf.keras.layers.Conv2D(
filters=64, kernel_size=3, strides=(2, 2), activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(latent_dim+latent_dim)
])
self.generative_net = tf.keras.Sequential(
[
tf.keras.layers.InputLayer(input_shape=(latent_dim,)),
tf.keras.layers.Dense(units=7*7*32, activation='relu'),
tf.keras.layers.Reshape(target_shape=(7, 7, 32)),
tf.keras.layers.Conv2DTranspose(
filters=64, kernel_size=3, strides=(2, 2),
padding='SAME', activation='relu'
),
tf.keras.layers.Conv2DTranspose(
filters=32, kernel_size=3, strides=(2, 2),
padding='SAME', activation='relu'
),
# 不使用激活函数
tf.keras.layers.Conv2DTranspose(
filters=1, kernel_size=3, strides=(1, 1),
padding='SAME'
),
])
@tf.function
def sample(self, eps=None):
if eps is None:
eps = tf.random.normal(shape=(100, self.latent_dim))
return self.decode(eps, apply_sigmoid=True)
def encode(self, x):
mean, logvar = tf.split(self.inference_net(x), num_or_size_splits=2,
axis=1)
return mean, logvar
def reparameterize(self, mean, logvar):
eps = tf.random.normal(shape=mean.shape)
return eps * tf.exp(logvar * 0.5) + mean
def decode(self, z, apply_sigmoid=False):
logits = self.generative_net(z)
if apply_sigmoid:
probs = tf.sigmoid(logits)
return probs
return logits
# ### 三、定义损失函数和优化器
#
# VAE 通过最大化边际对数似然的证据下界(ELBO)进行训练:
# $\log p(x) \ge \text{ELBO} = \mathbb{E}_{q(z|x)}\left[\log \frac{p(x, z)}{q(z|x)}\right].$$
#
# 实际上,我们优化了此期望的单样本蒙卡特罗估计:
#
# $$\log p(x| z) + \log p(z) - \log q(z|x),$$
# 其中 $z$ 从 $q(z|x)$ 中采样。
#
# 注意:我们也可以分析性地计算 KL 项,但简单起见,这里我们将所有三个项合并到蒙卡特罗估计器中。
# +
optimizer = tf.keras.optimizers.Adam(1e-4)
def log_normal_pdf(sample, mean, logvar, raxis=1):
log2pi = tf.math.log(2.0 * np.pi)
return tf.reduce_sum(
-0.5*((sample -mean)**2.0 * tf.exp(-logvar)+logvar+log2pi),
axis=raxis
)
@tf.function
def compute_loss(model, x):
mean, logvar = model.encode(x)
z = model.reparameterize(mean, logvar)
x_logit = model.decode(z)
cross_ent = tf.nn.sigmoid_cross_entropy_with_logits(logits=x_logit, labels=x)
logpx_z = -tf.reduce_sum(cross_ent, axis=[1,2,3])
logpz = log_normal_pdf(z, 0.0, 0.0)
logpz_x = log_normal_pdf(z, mean, logvar)
return -tf.reduce_mean(logpx_z+logpz-logpz_x)
@tf.function
def compute_apply_gradients(model, x, optimizer):
with tf.GradientTape() as tape:
loss = compute_loss(model, x)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
# -
# ### 四、训练
# 我们从迭代数据集开始:
# - 在每次迭代期间,我们将图像传递给编码器,以获得近似后验q(z|x) 的一组均值和对数方差参数。
# - 然后,我们从 q(z|x) 中采样分布。
#
# - 最后,我们将重新参数化的样本传递给解码器,以获取生成分布 p(x|z) 的 logit。
#
# 注意:由于我们使用的是由 keras 加载的数据集,其中训练集中有 6 万个数据点,测试集中有 1 万个数据点,因此我们在测试集上的最终 ELBO 略高于对 Larochelle 版 MNIST 使用动态二值化的文献中的报告结果。
#
# ### 五、生成图片
# - 进行训练后,可以生成一些图片了
# - 我们首先从单位高斯先验分布 p(z) 中采样一组隐向量z
# - 随后生成器将隐向量z 转换为观测值的 logit,得到分布 p(x|z)
# - 这样我们就可以得到生成的图片
# +
epochs = 100
latent_dim = 50
num_examples_to_generate = 16
# 保持随机向量恒定以进行生成(预测),以便看到改进。
random_vector_for_generation = tf.random.normal(
shape=[num_examples_to_generate, latent_dim])
model = CVAE(latent_dim)
# -
# 使用输入生成图片
def generate_and_save_images(model, epoch, test_input):
predictions = model.sample(test_input)
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
plt.imshow(predictions[i, :, :, 0], cmap='gray')
plt.axis('off')
# tight_layout 最小化两个子图之间的重叠
plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))
plt.show()
generate_and_save_images(model, 0, random_vector_for_generation)
for epoch in range(1, epochs+1):
start_time = time.time()
for train_x in train_dataset:
compute_apply_gradients(model, train_x, optimizer)
end_time = time.time()
if epoch % 1 == 0:
loss = tf.keras.metrics.Mean()
for test_x in test_dataset:
loss(compute_loss(model, test_x))
elbo = -loss.result()
display.clear_output(wait=False)
print('Epoch: {}, Test set ELBO: {}, '
'time elapse for current epoch {}'.format(epoch,
elbo,
end_time - start_time))
generate_and_save_images(model, epoch, random_vector_for_generation)
### 五、生成图片
def display_image(epoch_no):
return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))
plt.imshow(display_image(epochs))
plt.axis('off')# 显示图片
# 生成gif
anim_file = 'cvae.gif'
with imageio.get_writer(anim_file, mode='I') as writer:
filenames = glob.glob('image*.png')
filenames = sorted(filenames)
last = -1
for i, filename in enumerate(filenames):
frame = 2*(i**0.5)
if round(frame) > round(last):
last = frame
else:
continue
image = imageio.imread(filename)
writer.append_data(image)
image = imageio.imread(filename)
writer.append_data(image)
import IPython
if IPython.version_info >= (6,2,0,''):
display.Image(filename=anim_file)
| jwolf-AI/tensorflow2_tutorials_chinese-master/024-AutoEncoder/cnn_vae.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
# ---
"""
KD-tree implementation on Michigan Data
"""
import numpy as np
import pandas as pd
from sklearn.neighbors import NearestNeighbors
from sklearn.model_selection import train_test_split
from time import time
import math
#Read in the data
df = pd.read_csv('Final Data');
y = df['Power Outage'];
df = df.drop(['Power Outage'], axis=1);
x = df[['5 second wind speed squared','Fog/Ice','2 min wind speed squared', 'Thunder','Avg Wind Speed Squared']];
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state = 23);
x_train.head();
# +
#Benchmark against kNN
from sklearn.neighbors import NearestNeighbors
nbrs = NearestNeighbors(n_neighbors=3, algorithm='brute').fit(x_train);
# +
def euclidean(point1, point2):
"""
Finds the euclidean distance between two points (tuples of k dimensions each)
"""
distance = 0
for i in range(len(point1)):
distance += (point1[i] - point2[i]) ** 2
return math.sqrt(distance)
def closestPoint(allNeighbors, point):
"""
Brute force way to find the closest point
"""
minDistance = None
minPoint = None
for current in allNeighbors:
currentDistance = euclidean(point, current)
if minDistance is None or currentDistance < minDistance:
minDistance = currentDistance
minPoint = current
return minPoint
def build_kdtree(points, depth=0):
"""
Builds a kdtree
"""
n = len(points)
# if no points, can't build a kdtree
if n <=0:
return None
axis = depth % k
# sort the points based on the axis
sorted_points = sorted(points, key=lambda point: point[axis])
# the middle index is the splitting point
mid = n//2
# return the point, left subtree and right subtree
return {
'point': sorted_points[mid],
'left': build_kdtree(sorted_points[:mid], depth + 1),
'right': build_kdtree(sorted_points[mid + 1:], depth + 1)
}
def kdTreeClosest(root, point, depth=0, nearest=None):
"""
Finds the nearest neighbor in the kdtree
"""
if root is None:
return nearest
axis = depth % k
currentBest = None
# the next branch to recurse on
branch = None
# distance between the searching point and the best result (nearest)
if nearest is None or euclidean(point, nearest) > euclidean(point, root['point']):
currentBest = root['point']
else:
currentBest = nearest
# find which tree to recurse on
# if item on left, recurse on left
if point[axis] < root['point'][axis]:
branch = root['left']
else:
# recurse right
branch = root['right']
return kdTreeClosest(branch, point, depth+1, currentBest)
# +
trainTuples = [tuple(z) for z in x_train.values]
k = len(trainTuples[0])
trainOut = y_train.values
kdTree = build_kdtree(trainTuples)
# -
testTuples = [tuple(z) for z in x_test.values]
testOut = y_test.values
#Find nearest neighbours
pred = []
for key, val in enumerate(testTuples):
kdClosest = kdTreeClosest(kdTree, val)
kdIndex = trainTuples.index(kdClosest)
kdOut = trainOut[kdIndex]
realOut = testOut[key]
pred.append(kdOut)
#Plot results
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test.values, pred);
cm = pd.DataFrame(confusion_matrix(y_test, pred));
print("Accuracy: ", accuracy)
sns.heatmap(cm, annot=True);
plt.show();
| Final Implementation/KD-trees/Custom implementation/KDTree-Michigan.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 pysec import xbrl
from xbrl import XBRLParser, GAAP, GAAPSerializer
xbrl_parser = XBRLParser()
xbrl = xbrl_parser.parse(file("/Users/User/Documents/apty-20180131.xml"))
gaap_obj = xbrl_parser.parseGAAP(xbrl, doc_date="20131228", context="current", ignore_errors=0)
serializer = GAAPSerializer()
result = serializer.dump(gaap_obj)
print(result.data)
# +
# Import requests to retrive Web Urls example HTML. TXT
import requests
# Import BeautifulSoup
from bs4 import BeautifulSoup
# import re module for REGEXes
import re
# import pandas
import pandas as pd
# -
r = requests.get('https://www.sec.gov/Archives/edgar/data/789019/000156459018019062/msft-10k_20180630.htm')
# r = requests.get('https://www.sec.gov/Archives/edgar/data/320193/000032019318000145/0000320193-18-000145.txt')
raw_10k = r.text
print(raw_10k[0:1300])
# Regex to find <DOCUMENT> tags
doc_start_pattern = re.compile(r'<DOCUMENT>')
doc_end_pattern = re.compile(r'</DOCUMENT>')
# Regex to find <TYPE> tag prceeding any characters, terminating at new line
type_pattern = re.compile(r'<TYPE>[^\n]+')
# +
# Create 3 lists with the span idices for each regex
### There are many <Document> Tags in this text file, each as specific exhibit like 10-K, EX-10.17 etc
### First filter will give us document tag start <end> and document tag end's <start>
### We will use this to later grab content in between these tags
doc_start_is = [x.end() for x in doc_start_pattern.finditer(raw_10k)]
doc_end_is = [x.start() for x in doc_end_pattern.finditer(raw_10k)]
### Type filter is interesting, it looks for <TYPE> with Not flag as new line, ie terminare there, with + sign
### to look for any char afterwards until new line \n. This will give us <TYPE> followed Section Name like '10-K'
### Once we have have this, it returns String Array, below line will with find content after <TYPE> ie, '10-K'
### as section names
doc_types = [x[len('<TYPE>'):] for x in type_pattern.findall(raw_10k)]
# +
document = {}
# Create a loop to go through each section type and save only the 10-K section in the dictionary
for doc_type, doc_start, doc_end in zip(doc_types, doc_start_is, doc_end_is):
if doc_type == '10-K':
document[doc_type] = raw_10k[doc_start:doc_end]
# -
document['10-K'][0:500]
# +
# Write the regex
regex = re.compile(r'(>Item(\s| | )(1A|6|1B|7A|7|8)\.{0,1})|(ITEM\s(1A|6|1B|7A|7|8))')
# Use finditer to math the regex
matches = regex.finditer(document['10-K'])
# Write a for loop to print the matches
for match in matches:
print(match)
# +
# Matches
matches = regex.finditer(document['10-K'])
# Create the dataframe
test_df = pd.DataFrame([(x.group(), x.start(), x.end()) for x in matches])
test_df.columns = ['item', 'start', 'end']
test_df['item'] = test_df.item.str.lower()
# Display the dataframe
test_df.head()
# +
# Get rid of unnesesary charcters from the dataframe
test_df.replace(' ',' ',regex=True,inplace=True)
test_df.replace(' ',' ',regex=True,inplace=True)
test_df.replace(' ','',regex=True,inplace=True)
test_df.replace('\.','',regex=True,inplace=True)
test_df.replace('>','',regex=True,inplace=True)
# display the dataframe
test_df.head()
# +
# Drop duplicates
pos_dat = test_df.sort_values('start', ascending=True).drop_duplicates(subset=['item'], keep='last')
# Display the dataframe
pos_dat
# +
# Set item as the dataframe index
pos_dat.set_index('item', inplace=True)
# display the dataframe
pos_dat
# +
# Get Item 1a
item_1a_raw = document['10-K'][pos_dat['start'].loc['item1a']:pos_dat['start'].loc['item1b']]
# Get Item 7
item_7_raw = document['10-K'][pos_dat['start'].loc['item7']:pos_dat['start'].loc['item7a']]
item_6_raw = document['10-K'][pos_dat['start'].loc['item6']:pos_dat['start'].loc['item7']]
# Get Item 7a
item_7a_raw = document['10-K'][pos_dat['start'].loc['item7a']:pos_dat['start'].loc['item8']]
# -
item_6_raw[0:1000]
### First convert the raw text we have to exrtacted to BeautifulSoup object
item_1a_content = BeautifulSoup(item_1a_raw, 'lxml')
item_6_content = BeautifulSoup(item_6_raw, 'lxml')
### By just applying .pretiffy() we see that raw text start to look oragnized, as BeautifulSoup
### apply indentation according to the HTML Tag tree structure
print(item_7_content.prettify()[0:1000])
### Our goal is though to remove html tags and see the content
### Method get_text() is what we need, \n\n is optional, I just added this to read text
### more cleanly, it's basically new line character between sections.
print(item_7_content.get_text("\n\n")[0:1500])
# **Section 2: Numerical Data**
| CS696/Data/unstructuredDataExtraction/.ipynb_checkpoints/text_data_parse_sec-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
# ---
# # Introduction to TensorFlow
#
# Welcome to this week's programming assignment! Up until now, you've always used Numpy to build neural networks, but this week you'll explore a deep learning framework that allows you to build neural networks more easily. Machine learning frameworks like TensorFlow, PaddlePaddle, Torch, Caffe, Keras, and many others can speed up your machine learning development significantly. TensorFlow 2.3 has made significant improvements over its predecessor, some of which you'll encounter and implement here!
#
# By the end of this assignment, you'll be able to do the following in TensorFlow 2.3:
#
# * Use `tf.Variable` to modify the state of a variable
# * Explain the difference between a variable and a constant
# * Train a Neural Network on a TensorFlow dataset
#
# Programming frameworks like TensorFlow not only cut down on time spent coding, but can also perform optimizations that speed up the code itself.
# ## Table of Contents
# - [1- Packages](#1)
# - [1.1 - Checking TensorFlow Version](#1-1)
# - [2 - Basic Optimization with GradientTape](#2)
# - [2.1 - Linear Function](#2-1)
# - [Exercise 1 - linear_function](#ex-1)
# - [2.2 - Computing the Sigmoid](#2-2)
# - [Exercise 2 - sigmoid](#ex-2)
# - [2.3 - Using One Hot Encodings](#2-3)
# - [Exercise 3 - one_hot_matrix](#ex-3)
# - [2.4 - Initialize the Parameters](#2-4)
# - [Exercise 4 - initialize_parameters](#ex-4)
# - [3 - Building Your First Neural Network in TensorFlow](#3)
# - [3.1 - Implement Forward Propagation](#3-1)
# - [Exercise 5 - forward_propagation](#ex-5)
# - [3.2 Compute the Cost](#3-2)
# - [Exercise 6 - compute_cost](#ex-6)
# - [3.3 - Train the Model](#3-3)
# - [4 - Bibliography](#4)
# <a name='1'></a>
# ## 1 - Packages
import h5py
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.python.framework.ops import EagerTensor
from tensorflow.python.ops.resource_variable_ops import ResourceVariable
import time
# <a name='1-1'></a>
# ### 1.1 - Checking TensorFlow Version
#
# You will be using v2.3 for this assignment, for maximum speed and efficiency.
tf.__version__
# <a name='2'></a>
# ## 2 - Basic Optimization with GradientTape
#
# The beauty of TensorFlow 2 is in its simplicity. Basically, all you need to do is implement forward propagation through a computational graph. TensorFlow will compute the derivatives for you, by moving backwards through the graph recorded with `GradientTape`. All that's left for you to do then is specify the cost function and optimizer you want to use!
#
# When writing a TensorFlow program, the main object to get used and transformed is the `tf.Tensor`. These tensors are the TensorFlow equivalent of Numpy arrays, i.e. multidimensional arrays of a given data type that also contain information about the computational graph.
#
# Below, you'll use `tf.Variable` to store the state of your variables. Variables can only be created once as its initial value defines the variable shape and type. Additionally, the `dtype` arg in `tf.Variable` can be set to allow data to be converted to that type. But if none is specified, either the datatype will be kept if the initial value is a Tensor, or `convert_to_tensor` will decide. It's generally best for you to specify directly, so nothing breaks!
#
# Here you'll call the TensorFlow dataset created on a HDF5 file, which you can use in place of a Numpy array to store your datasets. You can think of this as a TensorFlow data generator!
#
# You will use the Hand sign data set, that is composed of images with shape 64x64x3.
train_dataset = h5py.File('datasets/train_signs.h5', "r")
test_dataset = h5py.File('datasets/test_signs.h5', "r")
# +
x_train = tf.data.Dataset.from_tensor_slices(train_dataset['train_set_x'])
y_train = tf.data.Dataset.from_tensor_slices(train_dataset['train_set_y'])
x_test = tf.data.Dataset.from_tensor_slices(test_dataset['test_set_x'])
y_test = tf.data.Dataset.from_tensor_slices(test_dataset['test_set_y'])
# -
type(x_train)
# Since TensorFlow Datasets are generators, you can't access directly the contents unless you iterate over them in a for loop, or by explicitly creating a Python iterator using `iter` and consuming its
# elements using `next`. Also, you can inspect the `shape` and `dtype` of each element using the `element_spec` attribute.
print(x_train.element_spec)
print(next(iter(x_train)))
# The dataset that you'll be using during this assignment is a subset of the sign language digits. It contains six different classes representing the digits from 0 to 5.
unique_labels = set()
for element in y_train:
unique_labels.add(element.numpy())
print(unique_labels)
# You can see some of the images in the dataset by running the following cell.
images_iter = iter(x_train)
labels_iter = iter(y_train)
plt.figure(figsize=(10, 10))
for i in range(25):
ax = plt.subplot(5, 5, i + 1)
plt.imshow(next(images_iter).numpy().astype("uint8"))
plt.title(next(labels_iter).numpy().astype("uint8"))
plt.axis("off")
# There's one more additional difference between TensorFlow datasets and Numpy arrays: If you need to transform one, you would invoke the `map` method to apply the function passed as an argument to each of the elements.
def normalize(image):
"""
Transform an image into a tensor of shape (64 * 64 * 3, )
and normalize its components.
Arguments
image - Tensor.
Returns:
result -- Transformed tensor
"""
image = tf.cast(image, tf.float32) / 255.0
image = tf.reshape(image, [-1,])
return image
new_train = x_train.map(normalize)
new_test = x_test.map(normalize)
new_train.element_spec
print(next(iter(new_train)))
# <a name='2-1'></a>
# ### 2.1 - Linear Function
#
# Let's begin this programming exercise by computing the following equation: $Y = WX + b$, where $W$ and $X$ are random matrices and b is a random vector.
#
# <a name='ex-1'></a>
# ### Exercise 1 - linear_function
#
# Compute $WX + b$ where $W, X$, and $b$ are drawn from a random normal distribution. W is of shape (4, 3), X is (3,1) and b is (4,1). As an example, this is how to define a constant X with the shape (3,1):
# ```python
# X = tf.constant(np.random.randn(3,1), name = "X")
#
# ```
# Note that the difference between `tf.constant` and `tf.Variable` is that you can modify the state of a `tf.Variable` but cannot change the state of a `tf.constant`.
#
# You might find the following functions helpful:
# - tf.matmul(..., ...) to do a matrix multiplication
# - tf.add(..., ...) to do an addition
# - np.random.randn(...) to initialize randomly
# + deletable=false nbgrader={"cell_type": "code", "checksum": "397d354ecaa1a28936096002cde11279", "grade": false, "grade_id": "cell-002e5736767021c0", "locked": false, "schema_version": 3, "solution": true, "task": false}
# GRADED FUNCTION: linear_function
def linear_function():
"""
Implements a linear function:
Initializes X to be a random tensor of shape (3,1)
Initializes W to be a random tensor of shape (4,3)
Initializes b to be a random tensor of shape (4,1)
Returns:
result -- Y = WX + b
"""
np.random.seed(1)
"""
Note, to ensure that the "random" numbers generated match the expected results,
please create the variables in the order given in the starting code below.
(Do not re-arrange the order).
"""
# (approx. 4 lines)
# X = ...
# W = ...
# b = ...
# Y = ...
# YOUR CODE STARTS HERE
X = np.random.randn(3, 1)
W = np.random.randn(4, 3)
b = np.random.randn(4, 1)
Y = tf.add(tf.matmul(W, X), b)
# YOUR CODE ENDS HERE
return Y
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "3526a7fd39649d2a6516031720e46748", "grade": true, "grade_id": "cell-b4318ea155f136ab", "locked": true, "points": 10, "schema_version": 3, "solution": false, "task": false}
result = linear_function()
print(result)
assert type(result) == EagerTensor, "Use the TensorFlow API"
assert np.allclose(result, [[-2.15657382], [ 2.95891446], [-1.08926781], [-0.84538042]]), "Error"
print("\033[92mAll test passed")
# -
# **Expected Output**:
#
# ```
# result =
# [[-2.15657382]
# [ 2.95891446]
# [-1.08926781]
# [-0.84538042]]
# ```
# <a name='2-2'></a>
# ### 2.2 - Computing the Sigmoid
# Amazing! You just implemented a linear function. TensorFlow offers a variety of commonly used neural network functions like `tf.sigmoid` and `tf.softmax`.
#
# For this exercise, compute the sigmoid of z.
#
# In this exercise, you will: Cast your tensor to type `float32` using `tf.cast`, then compute the sigmoid using `tf.keras.activations.sigmoid`.
#
# <a name='ex-2'></a>
# ### Exercise 2 - sigmoid
#
# Implement the sigmoid function below. You should use the following:
#
# - `tf.cast("...", tf.float32)`
# - `tf.keras.activations.sigmoid("...")`
# + deletable=false nbgrader={"cell_type": "code", "checksum": "00b8d3d2338bb2ed68c9e316e5de9581", "grade": false, "grade_id": "cell-038bb4b7e61dd070", "locked": false, "schema_version": 3, "solution": true, "task": false}
# GRADED FUNCTION: sigmoid
def sigmoid(z):
"""
Computes the sigmoid of z
Arguments:
z -- input value, scalar or vector
Returns:
a -- (tf.float32) the sigmoid of z
"""
# tf.keras.activations.sigmoid requires float16, float32, float64, complex64, or complex128.
# (approx. 2 lines)
# z = ...
# a = ...
# YOUR CODE STARTS HERE
z = tf.cast(z,tf.float32)
a = tf.keras.activations.sigmoid(z)
# YOUR CODE ENDS HERE
return a
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "ad1c73949744ba2205a0ad0d6f395915", "grade": true, "grade_id": "cell-a04f348c3fdbc2f2", "locked": true, "points": 10, "schema_version": 3, "solution": false, "task": false}
result = sigmoid(-1)
print ("type: " + str(type(result)))
print ("dtype: " + str(result.dtype))
print ("sigmoid(-1) = " + str(result))
print ("sigmoid(0) = " + str(sigmoid(0.0)))
print ("sigmoid(12) = " + str(sigmoid(12)))
def sigmoid_test(target):
result = target(0)
assert(type(result) == EagerTensor)
assert (result.dtype == tf.float32)
assert sigmoid(0) == 0.5, "Error"
assert sigmoid(-1) == 0.26894143, "Error"
assert sigmoid(12) == 0.9999939, "Error"
print("\033[92mAll test passed")
sigmoid_test(sigmoid)
# -
# **Expected Output**:
# <table>
# <tr>
# <td>
# type
# </td>
# <td>
# class 'tensorflow.python.framework.ops.EagerTensor'
# </td>
# </tr><tr>
# <td>
# dtype
# </td>
# <td>
# "dtype: 'float32'
# </td>
# </tr>
# <tr>
# <td>
# Sigmoid(-1)
# </td>
# <td>
# 0.2689414
# </td>
# </tr>
# <tr>
# <td>
# Sigmoid(0)
# </td>
# <td>
# 0.5
# </td>
# </tr>
# <tr>
# <td>
# Sigmoid(12)
# </td>
# <td>
# 0.999994
# </td>
# </tr>
#
# </table>
# <a name='2-3'></a>
# ### 2.3 - Using One Hot Encodings
#
# Many times in deep learning you will have a $Y$ vector with numbers ranging from $0$ to $C-1$, where $C$ is the number of classes. If $C$ is for example 4, then you might have the following y vector which you will need to convert like this:
#
#
# <img src="images/onehot.png" style="width:600px;height:150px;">
#
# This is called "one hot" encoding, because in the converted representation, exactly one element of each column is "hot" (meaning set to 1). To do this conversion in numpy, you might have to write a few lines of code. In TensorFlow, you can use one line of code:
#
# - [tf.one_hot(labels, depth, axis=0)](https://www.tensorflow.org/api_docs/python/tf/one_hot)
#
# `axis=0` indicates the new axis is created at dimension 0
#
# <a name='ex-3'></a>
# ### Exercise 3 - one_hot_matrix
#
# Implement the function below to take one label and the total number of classes $C$, and return the one hot encoding in a column wise matrix. Use `tf.one_hot()` to do this, and `tf.reshape()` to reshape your one hot tensor!
#
# - `tf.reshape(tensor, shape)`
# + deletable=false nbgrader={"cell_type": "code", "checksum": "44bfa91af0e57ca117ebf3acce902a28", "grade": false, "grade_id": "cell-15d9db613d8007bb", "locked": false, "schema_version": 3, "solution": true, "task": false}
# GRADED FUNCTION: one_hot_matrix
def one_hot_matrix(label, depth=6):
"""
Computes the one hot encoding for a single label
Arguments:
label -- (int) Categorical labels
depth -- (int) Number of different classes that label can take
Returns:
one_hot -- tf.Tensor A single-column matrix with the one hot encoding.
"""
# (approx. 1 line)
# one_hot = ...
# YOUR CODE STARTS HERE
one_hot = tf.one_hot(label, depth, axis=0)
one_hot = tf.reshape(one_hot, [-1, ])
# YOUR CODE ENDS HERE
return one_hot
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "f377cdff475cec1b37293b70e26b74a4", "grade": true, "grade_id": "cell-100c1b3328215913", "locked": true, "points": 10, "schema_version": 3, "solution": false, "task": false}
def one_hot_matrix_test(target):
label = tf.constant(1)
depth = 4
result = target(label, depth)
print("Test 1:",result)
assert result.shape[0] == depth, "Use the parameter depth"
assert np.allclose(result, [0., 1. ,0., 0.] ), "Wrong output. Use tf.one_hot"
label_2 = [2]
result = target(label_2, depth)
print("Test 2:", result)
assert result.shape[0] == depth, "Use the parameter depth"
assert np.allclose(result, [0., 0. ,1., 0.] ), "Wrong output. Use tf.reshape as instructed"
print("\033[92mAll test passed")
one_hot_matrix_test(one_hot_matrix)
# -
# **Expected output**
# ```
# Test 1: tf.Tensor([0. 1. 0. 0.], shape=(4,), dtype=float32)
# Test 2: tf.Tensor([0. 0. 1. 0.], shape=(4,), dtype=float32)
# ```
new_y_test = y_test.map(one_hot_matrix)
new_y_train = y_train.map(one_hot_matrix)
print(next(iter(new_y_test)))
# <a name='2-4'></a>
# ### 2.4 - Initialize the Parameters
#
# Now you'll initialize a vector of numbers with the Glorot initializer. The function you'll be calling is `tf.keras.initializers.GlorotNormal`, which draws samples from a truncated normal distribution centered on 0, with `stddev = sqrt(2 / (fan_in + fan_out))`, where `fan_in` is the number of input units and `fan_out` is the number of output units, both in the weight tensor.
#
# To initialize with zeros or ones you could use `tf.zeros()` or `tf.ones()` instead.
#
# <a name='ex-4'></a>
# ### Exercise 4 - initialize_parameters
#
# Implement the function below to take in a shape and to return an array of numbers using the GlorotNormal initializer.
#
# - `tf.keras.initializers.GlorotNormal(seed=1)`
# - `tf.Variable(initializer(shape=())`
# + deletable=false nbgrader={"cell_type": "code", "checksum": "da48416c74797c83152e1080b08afb9d", "grade": false, "grade_id": "cell-1d5716c48a16debf", "locked": false, "schema_version": 3, "solution": true, "task": false}
# GRADED FUNCTION: initialize_parameters
def initialize_parameters():
"""
Initializes parameters to build a neural network with TensorFlow. The shapes are:
W1 : [25, 12288]
b1 : [25, 1]
W2 : [12, 25]
b2 : [12, 1]
W3 : [6, 12]
b3 : [6, 1]
Returns:
parameters -- a dictionary of tensors containing W1, b1, W2, b2, W3, b3
"""
initializer = tf.keras.initializers.GlorotNormal(seed=1)
#(approx. 6 lines of code)
# W1 = ...
# b1 = ...
# W2 = ...
# b2 = ...
# W3 = ...
# b3 = ...
# YOUR CODE STARTS HERE
W1 = tf.Variable(initializer((25, 12288)), name='W1')
b1 = tf.Variable(initializer((25, 1)), name='b1')
W2 = tf.Variable(initializer((12, 25)), name='W2')
b2 = tf.Variable(initializer((12, 1)), name='b2')
W3 = tf.Variable(initializer((6, 12)), name='W3')
b3 = tf.Variable(initializer((6, 1)), name='b3')
# YOUR CODE ENDS HERE
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2,
"W3": W3,
"b3": b3}
return parameters
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "dd3fe0b5ed777771156c071d9373e47a", "grade": true, "grade_id": "cell-11012e1fada40919", "locked": true, "points": 10, "schema_version": 3, "solution": false, "task": false}
def initialize_parameters_test(target):
parameters = target()
values = {"W1": (25, 12288),
"b1": (25, 1),
"W2": (12, 25),
"b2": (12, 1),
"W3": (6, 12),
"b3": (6, 1)}
for key in parameters:
print(f"{key} shape: {tuple(parameters[key].shape)}")
assert type(parameters[key]) == ResourceVariable, "All parameter must be created using tf.Variable"
assert tuple(parameters[key].shape) == values[key], f"{key}: wrong shape"
assert np.abs(np.mean(parameters[key].numpy())) < 0.5, f"{key}: Use the GlorotNormal initializer"
assert np.std(parameters[key].numpy()) > 0 and np.std(parameters[key].numpy()) < 1, f"{key}: Use the GlorotNormal initializer"
print("\033[92mAll test passed")
initialize_parameters_test(initialize_parameters)
# -
# **Expected output**
# ```
# W1 shape: (25, 12288)
# b1 shape: (25, 1)
# W2 shape: (12, 25)
# b2 shape: (12, 1)
# W3 shape: (6, 12)
# b3 shape: (6, 1)
# ```
parameters = initialize_parameters()
# <a name='3'></a>
# ## 3 - Building Your First Neural Network in TensorFlow
#
# In this part of the assignment you will build a neural network using TensorFlow. Remember that there are two parts to implementing a TensorFlow model:
#
# - Implement forward propagation
# - Retrieve the gradients and train the model
#
# Let's get into it!
# <a name='3-1'></a>
# ### 3.1 - Implement Forward Propagation
#
# One of TensorFlow's great strengths lies in the fact that you only need to implement the forward propagation function and it will keep track of the operations you did to calculate the back propagation automatically.
#
#
# <a name='ex-5'></a>
# ### Exercise 5 - forward_propagation
#
# Implement the `forward_propagation` function.
#
# **Note** Use only the TF API.
#
# - tf.math.add
# - tf.linalg.matmul
# - tf.keras.activations.relu
#
# + deletable=false nbgrader={"cell_type": "code", "checksum": "e52024ce85f80538e02ad44ff9a6e334", "grade": false, "grade_id": "cell-23b6d82b3443e298", "locked": false, "schema_version": 3, "solution": true, "task": false}
# GRADED FUNCTION: forward_propagation
def forward_propagation(X, parameters):
"""
Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR
Arguments:
X -- input dataset placeholder, of shape (input size, number of examples)
parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3"
the shapes are given in initialize_parameters
Returns:
Z3 -- the output of the last LINEAR unit
"""
# Retrieve the parameters from the dictionary "parameters"
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
W3 = parameters['W3']
b3 = parameters['b3']
#(approx. 5 lines) # Numpy Equivalents:
# Z1 = ... # Z1 = np.dot(W1, X) + b1
# A1 = ... # A1 = relu(Z1)
# Z2 = ... # Z2 = np.dot(W2, A1) + b2
# A2 = ... # A2 = relu(Z2)
# Z3 = ... # Z3 = np.dot(W3, A2) + b3
# YOUR CODE STARTS HERE
Z1 = tf.math.add(tf.linalg.matmul(W1, tf.cast(X, dtype="float32")), b1)
A1 = tf.keras.activations.relu(Z1)
Z2 = tf.math.add(tf.linalg.matmul(W2, A1), b2)
A2 = tf.keras.activations.relu(Z2)
Z3 = tf.math.add(tf.linalg.matmul(W3, A2), b3)
# YOUR CODE ENDS HERE
return Z3
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "a08bdfe634f0c4a49794b64d287ce6c9", "grade": true, "grade_id": "cell-728b002a6a88ceb1", "locked": true, "points": 0, "schema_version": 3, "solution": false, "task": false}
def forward_propagation_test(target, examples):
minibatches = examples.batch(2)
for minibatch in minibatches:
forward_pass = target(tf.transpose(minibatch), parameters)
print(forward_pass)
assert type(forward_pass) == EagerTensor, "Your output is not a tensor"
assert forward_pass.shape == (6, 2), "Last layer must use W3 and b3"
assert np.allclose(forward_pass,
[[-0.13430887, 0.14086473],
[ 0.21588647, -0.02582335],
[ 0.7059658, 0.6484556 ],
[-1.1260961, -0.9329492 ],
[-0.20181894, -0.3382722 ],
[ 0.9558965, 0.94167566]]), "Output does not match"
break
print("\033[92mAll test passed")
forward_propagation_test(forward_propagation, new_train)
# -
# **Expected output**
# ```
# tf.Tensor(
# [[-0.13430887 0.14086473]
# [ 0.21588647 -0.02582335]
# [ 0.7059658 0.6484556 ]
# [-1.1260961 -0.9329492 ]
# [-0.20181894 -0.3382722 ]
# [ 0.9558965 0.94167566]], shape=(6, 2), dtype=float32)
# ```
# <a name='3-2'></a>
# ### 3.2 Compute the Cost
#
# All you have to do now is define the loss function that you're going to use. For this case, since we have a classification problem with 6 labels, a categorical cross entropy will work!
#
# <a name='ex-6'></a>
# ### Exercise 6 - compute_cost
#
# Implement the cost function below.
# - It's important to note that the "`y_pred`" and "`y_true`" inputs of [tf.keras.losses.categorical_crossentropy](https://www.tensorflow.org/api_docs/python/tf/keras/losses/categorical_crossentropy) are expected to be of shape (number of examples, num_classes).
#
# - `tf.reduce_mean` basically does the summation over the examples.
# + deletable=false nbgrader={"cell_type": "code", "checksum": "ec62b123a471aa12f20842442c73ec68", "grade": false, "grade_id": "cell-e6cc4d7fefeed231", "locked": false, "schema_version": 3, "solution": true, "task": false}
# GRADED FUNCTION: compute_cost
def compute_cost(logits, labels):
"""
Computes the cost
Arguments:
logits -- output of forward propagation (output of the last LINEAR unit), of shape (6, num_examples)
labels -- "true" labels vector, same shape as Z3
Returns:
cost - Tensor of the cost function
"""
#(1 line of code)
# cost = ...
# YOUR CODE STARTS HERE
logits = tf.transpose(logits)
labels = tf.reshape(tf.transpose(labels),[logits.shape[0],6])
cost = tf.reduce_mean(tf.keras.losses.categorical_crossentropy(labels, logits,from_logits=True))
# YOUR CODE ENDS HERE
return cost
# + deletable=false editable=false nbgrader={"cell_type": "code", "checksum": "d42866ad09b737ac5f667013b78efcfc", "grade": true, "grade_id": "cell-9bf72affa2e7b1b5", "locked": true, "points": 10, "schema_version": 3, "solution": false, "task": false}
def compute_cost_test(target, Y):
pred = tf.constant([[ 2.4048107, 5.0334096 ],
[-0.7921977, -4.1523376 ],
[ 0.9447198, -0.46802214],
[ 1.158121, 3.9810789 ],
[ 4.768706, 2.3220146 ],
[ 6.1481323, 3.909829 ]])
minibatches = Y.batch(2)
for minibatch in minibatches:
result = target(pred, tf.transpose(minibatch))
break
print(result)
assert(type(result) == EagerTensor), "Use the TensorFlow API"
assert (np.abs(result - (0.25361037 + 0.5566767) / 2.0) < 1e-7), "Test does not match. Did you get the mean of your cost functions?"
print("\033[92mAll test passed")
compute_cost_test(compute_cost, new_y_train )
# -
# **Expected output**
# ```
# tf.Tensor(0.4051435, shape=(), dtype=float32)
# ```
# <a name='3-3'></a>
# ### 3.3 - Train the Model
#
# Let's talk optimizers. You'll specify the type of optimizer in one line, in this case `tf.keras.optimizers.Adam` (though you can use others such as SGD), and then call it within the training loop.
#
# Notice the `tape.gradient` function: this allows you to retrieve the operations recorded for automatic differentiation inside the `GradientTape` block. Then, calling the optimizer method `apply_gradients`, will apply the optimizer's update rules to each trainable parameter. At the end of this assignment, you'll find some documentation that explains this more in detail, but for now, a simple explanation will do. ;)
#
#
# Here you should take note of an important extra step that's been added to the batch training process:
#
# - `tf.Data.dataset = dataset.prefetch(8)`
#
# What this does is prevent a memory bottleneck that can occur when reading from disk. `prefetch()` sets aside some data and keeps it ready for when it's needed. It does this by creating a source dataset from your input data, applying a transformation to preprocess the data, then iterating over the dataset the specified number of elements at a time. This works because the iteration is streaming, so the data doesn't need to fit into the memory.
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001,
num_epochs = 1500, minibatch_size = 32, print_cost = True):
"""
Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.
Arguments:
X_train -- training set, of shape (input size = 12288, number of training examples = 1080)
Y_train -- test set, of shape (output size = 6, number of training examples = 1080)
X_test -- training set, of shape (input size = 12288, number of training examples = 120)
Y_test -- test set, of shape (output size = 6, number of test examples = 120)
learning_rate -- learning rate of the optimization
num_epochs -- number of epochs of the optimization loop
minibatch_size -- size of a minibatch
print_cost -- True to print the cost every 10 epochs
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
"""
costs = [] # To keep track of the cost
train_acc = []
test_acc = []
# Initialize your parameters
#(1 line)
parameters = initialize_parameters()
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
W3 = parameters['W3']
b3 = parameters['b3']
optimizer = tf.keras.optimizers.Adam(learning_rate)
# The CategoricalAccuracy will track the accuracy for this multiclass problem
test_accuracy = tf.keras.metrics.CategoricalAccuracy()
train_accuracy = tf.keras.metrics.CategoricalAccuracy()
dataset = tf.data.Dataset.zip((X_train, Y_train))
test_dataset = tf.data.Dataset.zip((X_test, Y_test))
# We can get the number of elements of a dataset using the cardinality method
m = dataset.cardinality().numpy()
minibatches = dataset.batch(minibatch_size).prefetch(8)
test_minibatches = test_dataset.batch(minibatch_size).prefetch(8)
#X_train = X_train.batch(minibatch_size, drop_remainder=True).prefetch(8)# <<< extra step
#Y_train = Y_train.batch(minibatch_size, drop_remainder=True).prefetch(8) # loads memory faster
# Do the training loop
for epoch in range(num_epochs):
epoch_cost = 0.
#We need to reset object to start measuring from 0 the accuracy each epoch
train_accuracy.reset_states()
for (minibatch_X, minibatch_Y) in minibatches:
with tf.GradientTape() as tape:
# 1. predict
Z3 = forward_propagation(tf.transpose(minibatch_X), parameters)
# 2. loss
minibatch_cost = compute_cost(Z3, tf.transpose(minibatch_Y))
# We acumulate the accuracy of all the batches
train_accuracy.update_state(tf.transpose(Z3), minibatch_Y)
trainable_variables = [W1, b1, W2, b2, W3, b3]
grads = tape.gradient(minibatch_cost, trainable_variables)
optimizer.apply_gradients(zip(grads, trainable_variables))
epoch_cost += minibatch_cost
# We divide the epoch cost over the number of samples
epoch_cost /= m
# Print the cost every 10 epochs
if print_cost == True and epoch % 10 == 0:
print ("Cost after epoch %i: %f" % (epoch, epoch_cost))
print("Train accuracy:", train_accuracy.result())
# We evaluate the test set every 10 epochs to avoid computational overhead
for (minibatch_X, minibatch_Y) in test_minibatches:
Z3 = forward_propagation(tf.transpose(minibatch_X), parameters)
test_accuracy.update_state(tf.transpose(Z3), minibatch_Y)
print("Test_accuracy:", test_accuracy.result())
costs.append(epoch_cost)
train_acc.append(train_accuracy.result())
test_acc.append(test_accuracy.result())
test_accuracy.reset_states()
return parameters, costs, train_acc, test_acc
parameters, costs, train_acc, test_acc = model(new_train, new_y_train, new_test, new_y_test, num_epochs=100)
# **Expected output**
#
# ```
# Cost after epoch 0: 0.057612
# Train accuracy: tf.Tensor(0.17314816, shape=(), dtype=float32)
# Test_accuracy: tf.Tensor(0.24166666, shape=(), dtype=float32)
# Cost after epoch 10: 0.049332
# Train accuracy: tf.Tensor(0.35833332, shape=(), dtype=float32)
# Test_accuracy: tf.Tensor(0.3, shape=(), dtype=float32)
# ...
# ```
# Numbers you get can be different, just check that your loss is going down and your accuracy going up!
# Plot the cost
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per fives)')
plt.title("Learning rate =" + str(0.0001))
plt.show()
# Plot the train accuracy
plt.plot(np.squeeze(train_acc))
plt.ylabel('Train Accuracy')
plt.xlabel('iterations (per fives)')
plt.title("Learning rate =" + str(0.0001))
# Plot the test accuracy
plt.plot(np.squeeze(test_acc))
plt.ylabel('Test Accuracy')
plt.xlabel('iterations (per fives)')
plt.title("Learning rate =" + str(0.0001))
plt.show()
# **Congratulations**! You've made it to the end of this assignment, and to the end of this week's material. Amazing work building a neural network in TensorFlow 2.3!
#
# Here's a quick recap of all you just achieved:
#
# - Used `tf.Variable` to modify your variables
# - Trained a Neural Network on a TensorFlow dataset
#
# You are now able to harness the power of TensorFlow to create cool things, faster. Nice!
# <a name='4'></a>
# ## 4 - Bibliography
#
# In this assignment, you were introducted to `tf.GradientTape`, which records operations for differentation. Here are a couple of resources for diving deeper into what it does and why:
#
# Introduction to Gradients and Automatic Differentiation:
# https://www.tensorflow.org/guide/autodiff
#
# GradientTape documentation:
# https://www.tensorflow.org/api_docs/python/tf/GradientTape
| C02W03/Tensorflow_introduction.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 geopandas as gpd
import matplotlib.pyplot as plt
import geoplot
import pandas as pd
import numpy as np
import os
from shapely.geometry import Point
import re
from math import *
import csv
import xlrd
import copy
import json
import mapclassify
# load the districution data
covid = open('./data/covid_districution.json', 'r')
covid_districution = json.loads(covid.read())
covid.close()
bed = open('./data/bed_districution.json', 'r')
bed_districution = json.loads(bed.read())
bed.close()
pop = open('./data/pop_districution.json', 'r')
pop_districution = json.loads(pop.read())
pop.close()
# +
# discrepancy
import numpy as np
def find_sign_change_array(a):
asign = np.sign(a)
sz = asign == 0
if sz.any():
asign[sz] = np.roll(asign, 1)[sz]
sz = asign == 0
signchange = ((np.roll(asign, 1) - asign) != 0).astype(int)
signchange[0] = 0
return signchange
def get_regions(a):
sgn = find_sign_change_array(a)
regs= []
i = 0
for j,s in enumerate(sgn):
if s==1:
regs += [(i,j,np.sign(a[i]))]
i = j
if i<j:
regs += [(i,j,np.sign(a[i]))]
return regs
def compute_discrepancy(source0, target0, weights=None):
weights = np.ones(len(source0)) if weights is None else weights
source = weights * source0
target = weights * target0
dif = source - target
reg = get_regions(dif)
top = np.array([max([i,j]) for i,j in zip(source,target)])
tot_disc = dif.sum()/float(target.sum())
disc=[]
for (i,j,s) in reg:
d = dif[i:j].sum() / float(top[i:j].sum())
disc += [(i,j,d)]
return tot_disc, disc
# effort
from scipy.stats import wasserstein_distance
def compute_effort_emd(source, target, weights=None):
return wasserstein_distance(source, target, u_weights=weights, v_weights=weights)
# -
# calculate discrepancy and effort
discrepancy_bed_covid, discrepancy_pop_covid, discrepancy_bed_pop = {}, {}, {}
effort_bed_covid, effort_pop_covid, effort_bed_pop = {}, {}, {}
for s in covid_districution.keys():
discr_bed_covid = compute_discrepancy(bed_districution[s], covid_districution[s])
discr_bed_pop = compute_discrepancy(bed_districution[s], pop_districution[s])
discr_pop_covid = compute_discrepancy(pop_districution[s], covid_districution[s])
discrepancy_bed_covid[s] = discr_bed_covid
discrepancy_bed_pop[s] = discr_bed_pop
discrepancy_pop_covid[s] = discr_pop_covid
eff_bed_covid = compute_effort_emd(bed_districution[s], covid_districution[s])
eff_bed_pop = compute_effort_emd(bed_districution[s], pop_districution[s])
eff_pop_covid = compute_effort_emd(pop_districution[s], covid_districution[s])
effort_bed_covid[s] = eff_bed_covid
effort_bed_pop[s] = eff_bed_pop
effort_pop_covid[s] = eff_pop_covid
# # bed & covid
# +
# descrepancy_bed_covid
df_discrepancy_bed_covid = pd.DataFrame.from_dict(discrepancy_bed_covid, orient="index", columns=["bed_covid_discrepancy","bed_covid_details"])
df_discrepancy_bed_covid = df_discrepancy_bed_covid.reset_index().rename(columns={"index":"STATE"})
df_discrepancy_bed_covid["bed_covid_discrepancy"] = df_discrepancy_bed_covid["bed_covid_discrepancy"].fillna(0)
# df_discrepancy_bed_covid
# effort_bed_covid
df_effort_bed_covid = pd.DataFrame.from_dict(effort_bed_covid, orient="index", columns=["bed_covid_effort"])
df_effort_bed_covid = df_effort_bed_covid.reset_index().rename(columns={"index":"STATE"})
df_effort_bed_covid["bed_covid_effort"] = df_effort_bed_covid["bed_covid_effort"].fillna(0)
# df_effort_bed_covid
# +
plt.rcParams['figure.figsize'] = (80, 4.0)
plt.figure()
plt.bar(df_discrepancy_bed_covid["STATE"],df_discrepancy_bed_covid["bed_covid_discrepancy"])
plt.xlabel("State")
plt.ylabel("Discrepancy")
plt.show()
plt.figure()
plt.bar(df_effort_bed_covid["STATE"],df_effort_bed_covid["bed_covid_effort"])
plt.xlabel("State")
plt.ylabel("Effort")
plt.show()
# -
# count for discrepancy (<0, =0, >0)
df_discrepancy_bed_covid['level'] = df_discrepancy_bed_covid.apply(lambda x: np.sign(x.bed_covid_discrepancy), axis = 1)
# df_discrepancy_bed_covid
count_dis_bed_covid = df_discrepancy_bed_covid.groupby("level")["STATE"].size()
count_dis_bed_covid
# # population & covid
# +
# discrepancy_pop_covid
df_discrepancy_pop_covid = pd.DataFrame.from_dict(discrepancy_pop_covid, orient="index", columns=["pop_covid_discrepancy","pop_covid_details"])
df_discrepancy_pop_covid = df_discrepancy_pop_covid.reset_index().rename(columns={"index":"STATE"})
df_discrepancy_pop_covid["pop_covid_discrepancy"] = df_discrepancy_pop_covid["pop_covid_discrepancy"].fillna(0)
# df_discrepancy_pop_covid
# effort_pop_covid
df_effort_pop_covid = pd.DataFrame.from_dict(effort_pop_covid, orient="index", columns=["pop_covid_effort"])
df_effort_pop_covid = df_effort_pop_covid.reset_index().rename(columns={"index":"STATE"})
df_effort_pop_covid["pop_covid_effort"] = df_effort_pop_covid["pop_covid_effort"].fillna(0)
# df_effort_pop_covid
# +
plt.rcParams['figure.figsize'] = (80, 4.0)
plt.figure()
plt.bar(df_discrepancy_pop_covid["STATE"],df_discrepancy_pop_covid["pop_covid_discrepancy"])
plt.xlabel("State")
plt.ylabel("Discrepancy")
plt.show()
plt.figure()
plt.bar(df_effort_pop_covid["STATE"],df_effort_pop_covid["pop_covid_effort"])
plt.xlabel("State")
plt.ylabel("Effort")
plt.show()
# -
# count for discrepancy (<0, =0, >0)
df_discrepancy_pop_covid['level'] = df_discrepancy_pop_covid.apply(lambda x: np.sign(x.pop_covid_discrepancy), axis = 1)
# df_discrepancy_bed_covid
count_dis_pop_covid = df_discrepancy_pop_covid.groupby("level")["STATE"].size()
count_dis_pop_covid
# # bed & population
# +
# discrepancy_bed_pop
df_discrepancy_bed_pop = pd.DataFrame.from_dict(discrepancy_bed_pop, orient="index", columns=["bed_pop_discrepancy","bed_pop_details"])
df_discrepancy_bed_pop = df_discrepancy_bed_pop.reset_index().rename(columns={"index":"STATE"})
df_discrepancy_bed_pop["bed_pop_discrepancy"] = df_discrepancy_bed_pop["bed_pop_discrepancy"].fillna(0)
# df_discrepancy_bed_pop
# effort_bed_pop
df_effort_bed_pop = pd.DataFrame.from_dict(effort_bed_pop, orient="index", columns=["bed_pop_effort"])
df_effort_bed_pop = df_effort_bed_pop.reset_index().rename(columns={"index":"STATE"})
df_effort_bed_pop["bed_pop_effort"] = df_effort_bed_pop["bed_pop_effort"].fillna(0)
# df_effort_bed_pop
# +
plt.rcParams['figure.figsize'] = (80, 4.0)
plt.figure()
plt.bar(df_discrepancy_bed_pop["STATE"],df_discrepancy_bed_pop["bed_pop_discrepancy"])
plt.xlabel("State")
plt.ylabel("Discrepancy")
plt.show()
plt.figure()
plt.bar(df_effort_bed_pop["STATE"],df_effort_bed_pop["bed_pop_effort"])
plt.xlabel("State")
plt.ylabel("Effort")
plt.show()
# -
# count for discrepancy (<0, =0, >0)
df_discrepancy_bed_pop['level'] = df_discrepancy_bed_pop.apply(lambda x: np.sign(x.bed_pop_discrepancy), axis = 1)
# df_discrepancy_bed_covid
count_dis_bed_pop = df_discrepancy_bed_pop.groupby("level")["STATE"].size()
count_dis_bed_pop
# # merge all results
df_final = pd.DataFrame(columns=["STATE"])
dfs=[df_discrepancy_bed_covid, df_discrepancy_pop_covid, df_discrepancy_bed_pop, df_effort_bed_covid, df_effort_pop_covid, df_effort_bed_pop]
for df in dfs:
df_final = df_final.merge(df, on=['STATE'], how='outer')
df_final = df_final.drop(["bed_covid_details","pop_covid_details","bed_pop_details","level_x","level_y","level"],axis=1)
# drop DC
df_final = df_final.drop([7])
df_final = df_final.reset_index(drop=True)
df_final
# max->min
import copy
ranks = copy.copy(df_final)
ranks[list(df_final.columns[1:])] = df_final[list(df_final.columns[1:])].rank(method="min", ascending=False)
ranks
outputpath = "./data/discr_eff/"
if not os.path.exists(outputpath):
os.makedirs(outputpath)
df_final.to_csv(os.path.join(outputpath, "discr_eff_val.csv"))
ranks.to_csv(os.path.join(outputpath, "discr_eff_rank.csv"))
# # evaluate
# +
import os
evaluatepath = "./data/discr_eff/"
avaliable_bed = pd.read_csv(os.path.join(evaluatepath, "Summary_stats_all_locs.csv"),header=0)
avaliable_bed = avaliable_bed[["location_name", "available_all_nbr"]]
# avaliable_bed
healthrank_path = "./data/discr_eff/"
state_rank = pd.read_excel(os.path.join(healthrank_path, "stateRank.xlsx"),header=None)
# drop Alaska and Hawaii
state_rank = state_rank.drop([0,10])
state_rank = state_rank.reset_index(drop=True)
state_rank["OverallRank"] = state_rank[5].rank(method="min", ascending=False)
# state_rank
new_rank = pd.merge(ranks, avaliable_bed, left_on =["STATE"], right_on=["location_name"], how="left")
new_rank["bedRank"] = new_rank["available_all_nbr"].rank(method="min", ascending=False)
dis1 = list(ranks.bed_covid_discrepancy)
# r_dis_pc = list(ranks.pop_covid_discrepancy)
# r_dis_bp = list(ranks.bed_pop_discrepancy)
eff1 = list(ranks.bed_covid_effort)
# r_eff_pc = list(ranks.pop_covid_effort)
# r_eff_bp = list(ranks.bed_pop_effort)
# dis_ranks = [r_dis_bc, r_dis_pc, r_dis_bp]
# eff_ranks = [r_eff_bc, r_eff_pc, r_eff_bp]
healthrank = list(state_rank.OverallRank)
bedrank = list(new_rank.bedRank)
from scipy import stats
print("Bed Rank:")
print("discrepancy:")
print(stats.spearmanr(dis1, bedrank),stats.kendalltau(dis1, bedrank))
print("\n effort:")
print(stats.spearmanr(eff1, bedrank),stats.kendalltau(eff1, bedrank))
print("\nHealth Rank:")
print("discrepancy:")
print(stats.spearmanr(dis1, healthrank),stats.kendalltau(dis1, healthrank))
print("\n effort:")
print(stats.spearmanr(eff1, healthrank),stats.kendalltau(eff1, healthrank))
# -
| discrepancy_effort.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
# ---
# # Übungsblatt 1: Fehlerrechnung
#
# * [Aufgabe 1](#Aufgabe-1)
# * [Aufgabe 2](#Aufgabe-2)
# * [Aufgabe 3](#Aufgabe-3)
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')#
# ---
# ## Aufgabe 1
# Gegeben sei eine parametrische Funktion $y = f(x)$, $y = 1 + a_1x + a_2x^2$ mit Parametern $a_1 = 2.0 ± 0.2$, $a_2 = 1.0 ± 0.1$ und Korrelationskoeffizient $ρ = −0.8$.
#
# ---
a1, a1_err = 2.0, 0.2
a2, a2_err = 1.0, 0.1
rho = -0.8
# ---
# ### 1.1
# Geben Sie die Kovarianzmatrix von $a_1$ und $a_2$ an.
#
# ---
a1_var = a1_err**2
a2_var = a2_err**2
cov_a1_a2 = rho*a1_err*a2_err
cov = np.matrix([[a1_var,cov_a1_a2],[cov_a1_a2,a2_var]])
cov
# ---
# ### 1.2
# Bestimmen Sie analytisch die Unsicherheit von $y$ als Funktion von $x$:
#
# ---
# ---
# #### 1.2.1
# unter Vernachlässigung der Korrelation
#
# ---
def delta_f(x,delta_a1,delta_a2):
return np.sqrt((x*delta_a1)**2+(x**2*delta_a2)**2)
# ---
# #### 1.2.2
# mit Berücksichtigung der Korrelation
#
# ---
def delta_f_cov(x,delta_a1,delta_a2,cov_a1_a2):
return np.sqrt((x*delta_a1)**2+(x**2*delta_a2)**2+ 2*x**3*cov_a1_a2)
# ---
# ### 1.3
# Bestimmen Sie per Monte Carlo die Unsicherheit von $y$ als Funktion von $x$:
# #### 1.3.1
# Generieren Sie Wertepaare $(a_1, a_2)$ gemäß ihrer Kovarianzmatrix und visualisieren Sie diese, z.B. mit einem Scatter-Plot.
#
# _Hinweis_: Wenn $x_1$ und $x_2$ zwei gaussverteilte Zufallszahlen mit Mittelwert null und Varianz eins sind, erhält man ein Paar korrelierter gaussverteilter Zufallszahlen $(y_1, y_2)$ mit Mittelwert null und Varianz eins durch $(y_1 = x_1; y_2 = x_1ρ + x_2\sqrt{1 − \rho^2})$.
#
# ---
x1,y1 = np.random.multivariate_normal(np.array([a1,a2]), cov,size=100000).T
plt.scatter(x1,y1)
plt.show()
# ---
# #### 1.3.2
# Bestimmen Sie die Verteilung von $y$ für $x = \{−1, 0, +1\}$ und vergleichen Sie Mittelwert und Varianz (Standardabweichung) mit den Resultaten der analytischen Rechnung.
#
# ---
def y(x,a,b):
return a*x+b*x**2+1
for x in [-1,0,1]:
y_ = y(x,x1,y1)
print("MC sigma:", y_.std(), "Theorie ", delta_f_cov(x, a1_err, a2_err, cov[0,1]))
print("MC Mean:", y_.mean(), "Theorie ",y(x,a1,a2))
plt.hist(y_,100,histtype="stepfilled")
plt.show()
# ---
# ## Aufgabe 2
# Betrachten Sie folgende Reparametrisierung von $y = f(x)$:
#
# $$y = 1 + \frac{x(1+x)}{b_1} + \frac{x(1-x)}{b_2}$$
#
# ### 2.1
# Bestimmen Sie analytisch die transformierten Parameter $b_1$ und $b_2$ und deren Kovarianzmatrix
#
# ---
# +
B = np.matrix([[-2/9,-2/9],[-2,2]])
b1 = 2/3
b2 = 2
cov_b = B*cov*B.T
cov_b
# -
# ---
# ### 2.2
# Bestimmen Sie die Kovarianzmatrix der transformierten Parameter per Monte Carlo
#
# ---
# +
b1_mc = 2/(x1+y1)
b2_mc = 2/(x1-y1)
plt.hist(b2_mc,100)
plt.show()
# -
# ---
# ### 2.3
# Bestimmen Sie analytisch die Unsicherheit von $y$ als Funktion von $x$:
#
# ---
# ---
# #### 2.3.1
# unter Verwendung der analytisch bestimmten Kovarianzmatrix von $(b_1, b_2)$
#
# ---
# ---
# #### 2.3.2
# unter Verwendung der numerisch bestimmten Kovarianzmatrix von $(b_1, b_2)$
#
# ---
# ---
# ## Aufgabe 3
# Lösen Sie die obigen Teilaufgaben für $y = f(x)$ mit
#
# $$y = \ln\left(1 + a_1x + a_2x^2\right) \quad \text{bzw.} \quad y = \ln\left(1 + \frac{x(1+x)}{b_1} + \frac{x(x-1)}{b_2}\right)$$
#
| assignments/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
# ---
# BloomTech Data Science
#
# *Unit 2, Sprint 1, Module 1*
#
# ---
# +
# %%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'
# If you're working locally:
else:
DATA_PATH = '../data/'
# -
# # Module Project: Regression I
#
# During the guided project, we predicted how much it would cost to buy a condo in Tribecca. For the module project, your goal will be similar: predict how much it costs to rent an apartment in New York City.
#
# Dataset source: [renthop.com](https://www.renthop.com/).
#
# ## Directions
#
# > Do Not Copy-Paste. You must *type* each of these exercises in, manually. If you copy and paste, you might as well not even do them. The point of these exercises is to train your hands, your brain, and your mind in how to read, write, and see code. If you copy-paste, you are cheating yourself out of the effectiveness of the lessons.
# >
# > — <NAME>, [Learn Python the Hard Way](https://learnpythonthehardway.org/)
#
# The tasks for this project are as follows:
#
# - **Task 1:** Import `csv` file using wrangle function.
# - **Task 2:** Conduct exploratory data analysis (EDA) and plot the relationship between one feature and the target `'price'`.
# - **Task 3:** Split data into feature matrix `X` and target vector `y`.
# - **Task 4:** Establish the baseline mean absolute error for your dataset.
# - **Task 5:** Build and train a `Linearregression` model.
# - **Task 6:** Check the mean absolute error of our model on the training data.
# - **Task 7:** Extract and print the intercept and coefficient from your `LinearRegression` model.
#
# **Note**
#
# You should limit yourself to the following libraries for this project:
#
# - `matplotlib`
# - `numpy`
# - `pandas`
# - `sklearn`
# ## I. Wrangle Data
# +
def wrangle(filepath):
df = pd.read_csv(filepath)
# Remove the most extreme 1% prices,
# the most extreme .1% latitudes, &
# the most extreme .1% longitudes
df = df[(df['price'] >= np.percentile(df['price'], 0.5)) &
(df['price'] <= np.percentile(df['price'], 99.5)) &
(df['latitude'] >= np.percentile(df['latitude'], 0.05)) &
(df['latitude'] < np.percentile(df['latitude'], 99.95)) &
(df['longitude'] >= np.percentile(df['longitude'], 0.05)) &
(df['longitude'] <= np.percentile(df['longitude'], 99.95))]
return df
filepath = DATA_PATH + 'apartments/renthop-nyc.csv'
# -
# **Task 1:** Use the above `wrangle` function to import the `renthop-nyc.csv` file into a DataFrame named `df`.
df = ...
# **Task 2:** Use your `pandas` and dataviz skills to explore the dataset. As part of this process, make a scatter plot that shows the relationship between one of the numerical features in the dataset and the target `'price'`.
#
# **Remember:** You should plot your feature on the `X` axis and your target on the `y` axis.
# # II. Split Data
#
# **Task 3:** Choose one feature from the dataset and assign it to your feature matrix `X`. Then assign the column `'price'` to the target vector `y`.
#
# **Remember:** Your feature matrix needs to be two-dimensional, but your feature matrix must be one-dimensional.
X = ...
y = ...
# # III. Establish Baseline
#
# **Task 4:** Since this is a **regression** problem, you need to calculate the baseline the mean absolute error for your model. First, calculate the mean of `y`. Next, create a list `y_pred` that has the same length as `y` and where every item in the list is the mean. Finally, use `mean_absolute_error` to calculate your baseline.
baseline_mae = ...
print('Baseline MAE:', baseline_mae)
# # IV. Build Model
#
# **Task 5:** Build and train a `LinearRegression` model named `model` using your feature matrix `X` and your target vector `y`.
# +
# Step 1: Import predictor class
# Step 2: Instantiate predictor
model = ...
# Step 3: Fit predictor on the (training) data
# -
# # V. Check Metrics
#
# **Task 6:** How does your model perform in comparison to your baseline? Calculate the mean absolute error for your model's predictions.
# +
training_mae = ...
print('Training MAE:', training_mae)
# -
# # VI. Communicate Results
#
# You've just created a linear model. That means that your model makes predictions using an equation that looks like $\texttt{apt price} = \texttt{intercept}~+~\texttt{coefficient}~\times~\texttt{your feature}$. But what are the values of the intercept and coefficient that your model is using?
#
# **Task 7:** Print out the intercept and coefficient associated with `model`.
| module1-regression-1/LS_DS_211_assignment.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
from tensor2tensor.data_generators import problem
from tensor2tensor.data_generators import text_problems
from tensor2tensor.data_generators import translate
from tensor2tensor.utils import registry
from tensor2tensor import problems
import tensorflow as tf
import os
import logging
logger = logging.getLogger()
tf.logging.set_verbosity(tf.logging.DEBUG)
# +
import youtokentome as yttm
bpe = yttm.BPE(model='truecase.yttm')
class Encoder:
def __init__(self, bpe):
self.bpe = bpe
self.vocab_size = len(self.bpe.vocab())
def encode(self, s):
s = self.bpe.encode(s, output_type=yttm.OutputType.ID)
s = [i + [1] for i in s]
return s
def decode(self, ids, strip_extraneous=False):
ids = [[k for k in i if k > 1] for i in ids]
return self.bpe.decode(list(ids))
encoder = Encoder(bpe)
# -
@registry.register_problem
class TrueCase(text_problems.Text2TextProblem):
@property
def approx_vocab_size(self):
return 32000
@property
def is_generate_per_split(self):
return False
def feature_encoders(self, data_dir):
encoder = Encoder(bpe)
return {'inputs': encoder, 'targets': encoder}
DATA_DIR = os.path.expanduser('t2t-true-case/data')
TMP_DIR = os.path.expanduser('t2t-true-case/tmp')
TRAIN_DIR = os.path.expanduser('t2t-true-case/train-small')
# +
PROBLEM = 'true_case'
t2t_problem = problems.problem(PROBLEM)
train_steps = 500000
eval_steps = 10
batch_size = 4096 * 2
save_checkpoints_steps = 25000
ALPHA = 0.1
schedule = 'continuous_train_and_eval'
MODEL = 'transformer'
HPARAMS = 'transformer_small'
# +
import tensorflow as tf
import os
ckpt_path = tf.train.latest_checkpoint(TRAIN_DIR)
ckpt_path
# -
from tensor2tensor import models
from tensor2tensor import problems
from tensor2tensor.layers import common_layers
from tensor2tensor.utils import trainer_lib
from tensor2tensor.utils import t2t_model
from tensor2tensor.utils import registry
from tensor2tensor.utils import metrics
from tensor2tensor.data_generators import problem
from tensor2tensor.data_generators import text_problems
from tensor2tensor.data_generators import translate
from tensor2tensor.utils import registry
# +
class Model:
def __init__(self, HPARAMS = "transformer_small", DATA_DIR = 't2t/data'):
self.X = tf.placeholder(tf.int32, [None, None])
self.Y = tf.placeholder(tf.int32, [None, None])
self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)
maxlen_decode = tf.reduce_max(self.X_seq_len)
maxlen_decode = 50 + tf.reduce_max(self.X_seq_len)
#self.maxlen_decode = tf.placeholder(tf.int32, None)
x = tf.expand_dims(tf.expand_dims(self.X, -1), -1)
y = tf.expand_dims(tf.expand_dims(self.Y, -1), -1)
features = {
"inputs": x,
"targets": y,
"target_space_id": tf.constant(1, dtype=tf.int32),
}
self.features = features
Modes = tf.estimator.ModeKeys
hparams = trainer_lib.create_hparams(HPARAMS, data_dir=DATA_DIR, problem_name=PROBLEM)
hparams.max_length = 512
translate_model = registry.model('transformer')(hparams, Modes.PREDICT)
self.translate_model = translate_model
logits, _ = translate_model(features)
self.logits = logits
with tf.variable_scope(tf.get_variable_scope(), reuse=True):
self.fast_result = translate_model._greedy_infer(features, maxlen_decode)["outputs"]
self.beam_result = translate_model._beam_decode_slow(
features, maxlen_decode, beam_size=3,
top_beams=1, alpha=0.5)["outputs"]
self.fast_result = tf.identity(self.fast_result, name = 'greedy')
self.beam_result = tf.identity(self.beam_result, name = 'beam')
tf.reset_default_graph()
sess = tf.InteractiveSession()
model = Model()
var_lists = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
saver = tf.train.Saver(var_list = var_lists)
saver.restore(sess, ckpt_path)
# -
str1 = 'KUALA LUMPUR - MenteRi Di Jabatan PErdaNa MEnTeri, DaTuk Seri Dr Mujahid YUsof Rawa HAri ini MengaKhiri lAwataN kERja lApaN HarI kE JordAn, TUrki dan BosNiA Herzegovina, lAwAtan yaNg BerTUJUAN menGEratkAn LaGi huBungAn Dua haLa DEngAN KEtIGA-tIga NEgaRa berKeNAan.'
str2 = 'kuala lumpur - menteri di jabatan perdana menteri, datuk seri dr mujahid yusof rawa hari ini mengakhiri lawatan kerja lapan hari ke jordan, turki dan bosnia herzegovina, lawatan yang bertujuan mengeratkan lagi hubungan dua hala dengan ketiga-tiga negara berkenaan.'
str3 = 'KUALA LUMPUR - Menteri di Jabatan Perdana Menteri , Datuk Seri Dr <NAME> hari ini mengakhiri lawatan kerja lapan hari ke Jordan , Turki dan Bosnia Herzegovina , lawatan yang bertujuan mengeratkan lagi hubungan dua hala dengan ketiga-tiga negara berkenaan .'
str4 = 'Beliau mengambil nama gelaran <NAME> Alex sang Itik sempena nama tempat kelahirannya'
long = 'bermula tahun depan bakal anggota polis perlu lulus ujian penilaian agama dan moral sebelum diterima bekerja menurut PDRM yang bagi pastikan Setiap anggotanya yang diambil bertugas mempunyai tahap integriti serta moral dan agama yang tinggi kerana anggota polis takkan dinilai masih hujan secara dalam talian dan temuduga bilangan mangsa banjir di Kota Tinggi Johor naik dikit kepada hampir 720 Orang Sabah juga mula dilanda banjir menyaksikan hampir 400 penduduk di Sipitang Beaufort dan Membakut berlindung di pusat pemindahan Kementerian Sumber Manusia bercadang memberikan insentif 500 sebulan kepada pekerja yang ikuti latihan kemahiran tvet ia bertujuan menambah bilangan pekerja berkemahiran di negara ini dan cadangan itu akan dibentangkan kepada kabinet untuk kelulusan <NAME> memaklumkan adalah kerana Darat Malaysia maut dalam letusan ku number of Edward Island New Zealand kelmarin belum dapat disahkan setakat ini yang dapat disahkan adalah seorang Malaysia cedera dan kini kritikal dan di rawat di hospital kerajaan penjawat awam kerajaan Perlis bakal terima bantuan khas kewangan 600 seseorang dan Barang akan dibuat Rabu minggu depan beranikah berita hiburan kumpulan Stone mengakui kedudukan antara yang terbawah di pentas Maharaja Lawak Mega 2019 memberi tekanan kepada mereka namun kumpulan itu memaklumkan Astro Gempak mereka lebih tertekan apabila menerima komen tidak membina daripada juri tu dia anggota yg Mamat Sepah Aziz Senario dan Acong dan anda boleh tonton aksi mereka di pentas MLM 2019 siap Jumaat 9.00 malam di Astro Warna'
def padding_sequence(seq, maxlen = None, padding = 'post', pad_int = 0):
if not maxlen:
maxlen = max([len(i) for i in seq])
padded_seqs = []
for s in seq:
if padding == 'post':
padded_seqs.append(s + [pad_int] * (maxlen - len(s)))
if padding == 'pre':
padded_seqs.append([pad_int] * (maxlen - len(s)) + s)
return padded_seqs
# +
import re
import random
punctuation = '!()&%{}[];:\'",./?\\<>'
def remove_punc(string):
string = re.sub('[^A-Za-z0-9 ]+', ' ', string)
string = re.sub(r'[ ]+', ' ', string).strip()
return string
remove_punc(str3).lower()
# -
encoded = padding_sequence(encoder.encode([long, str1, str2, remove_punc(str3).lower()]))
greedy = sess.run(model.fast_result,
feed_dict = {model.X: encoded})
encoder.decode(greedy)
saver = tf.train.Saver(tf.trainable_variables())
saver.save(sess, 'transformer-small/model.ckpt')
strings = ','.join(
[
n.name
for n in tf.get_default_graph().as_graph_def().node
if ('Variable' in n.op
or 'Placeholder' in n.name
or 'greedy' in n.name
or 'beam' in n.name
or 'alphas' in n.name
or 'self/Softmax' in n.name)
and 'adam' not in n.name
and 'beta' not in n.name
and 'global_step' not in n.name
and 'modality' not in n.name
and 'Assign' not in n.name
]
)
strings.split(',')
def freeze_graph(model_dir, output_node_names):
if not tf.gfile.Exists(model_dir):
raise AssertionError(
"Export directory doesn't exists. Please specify an export "
'directory: %s' % model_dir
)
checkpoint = tf.train.get_checkpoint_state(model_dir)
input_checkpoint = checkpoint.model_checkpoint_path
absolute_model_dir = '/'.join(input_checkpoint.split('/')[:-1])
output_graph = absolute_model_dir + '/frozen_model.pb'
clear_devices = True
with tf.Session(graph = tf.Graph()) as sess:
saver = tf.train.import_meta_graph(
input_checkpoint + '.meta', clear_devices = clear_devices
)
saver.restore(sess, input_checkpoint)
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess,
tf.get_default_graph().as_graph_def(),
output_node_names.split(','),
)
with tf.gfile.GFile(output_graph, 'wb') as f:
f.write(output_graph_def.SerializeToString())
print('%d ops in the final graph.' % len(output_graph_def.node))
freeze_graph('transformer-small', strings)
def load_graph(frozen_graph_filename):
with tf.gfile.GFile(frozen_graph_filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def)
return graph
g = load_graph('transformer-small/frozen_model.pb')
x = g.get_tensor_by_name('import/Placeholder:0')
greedy = g.get_tensor_by_name('import/greedy:0')
beam = g.get_tensor_by_name('import/beam:0')
test_sess = tf.InteractiveSession(graph = g)
g, b = test_sess.run([greedy, beam], feed_dict = {x:encoded})
encoder.decode(g)
encoder.decode(b)
| session/true-case/true-case-small.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.6 - AzureML
# language: python
# name: python3-azureml
# ---
# # Working with Compute Targets
#
# You've used the Azure Machine Learning SDK to run many experiments, all of them on your local compute (in this case, the Azure Machine Learning notebook VM). Now it's time to see how you can leverage cloud computing to increase the scalability of your compute contexts.
#
# ## Connect to Your Workspace
#
# The first thing you need to do is to connect to your workspace using the Azure ML SDK.
#
# > **Note**: If the authenticated session with your Azure subscription has expired since you completed the previous exercise, you'll be prompted to reauthenticate.
# +
import azureml.core
from azureml.core import Workspace
# Load the workspace from the saved config file
ws = Workspace.from_config()
print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))
# -
# ## Prepare Data for an Experiment
#
# In this lab, you'll use a dataset containing details of diabetes patients. Run the cell below to create this dataset (if you created it in the previous lab, the code will create a new version)
# +
from azureml.core import Dataset
default_ds = ws.get_default_datastore()
if 'diabetes dataset' not in ws.datasets:
default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'], # Upload the diabetes csv files in /data
target_path='diabetes-data/', # Put it in a folder path in the datastore
overwrite=True, # Replace existing files of the same name
show_progress=True)
#Create a tabular dataset from the path on the datastore (this may take a short while)
tab_data_set = Dataset.Tabular.from_delimited_files(path=(default_ds, 'diabetes-data/*.csv'))
# Register the tabular dataset
try:
tab_data_set = tab_data_set.register(workspace=ws,
name='diabetes dataset',
description='diabetes data',
tags = {'format':'CSV'},
create_new_version=True)
print('Dataset registered.')
except Exception as ex:
print(ex)
else:
print('Dataset already registered.')
# -
# ## Create a Compute Target
#
# In many cases, your local compute resources may not be sufficient to process a complex or long-running experiment that needs to process a large volume of data; and you may want to take advantage of the ability to dynamically create and use compute resources in the cloud.
#
# Azure ML supports a range of compute targets, which you can define in your workpace and use to run experiments; paying for the resources only when using them. When you set up the workspace in the first exercise, you created a compute cluster, so let's verify that exists (and if not, create it) so we can use it to run training experiments.
#
# > **Important**: Change *your-compute-cluster* to the name of your compute cluster in the code below before running it!
# +
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
cluster_name = "your-compute-cluster" # change to your compute cluster name
# Verify that cluster exists
try:
training_cluster = ComputeTarget(workspace=ws, name=cluster_name)
print('Found existing cluster, use it.')
except ComputeTargetException:
# If not, create it
compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS2_V2', max_nodes=2)
training_cluster = ComputeTarget.create(ws, cluster_name, compute_config)
training_cluster.wait_for_completion(show_output=True)
# -
# ## Run an Experiment on Remote Compute
#
# Now that you have created your compute, you can use it to run experiments. The following code creates a folder for experiment files (which may already exist from the previous lab, but run it anyway!)
# +
import os
# Create a folder for the experiment files
experiment_folder = 'diabetes_training_tree'
os.makedirs(experiment_folder, exist_ok=True)
print(experiment_folder, 'folder created')
# -
# Next, create the Python script file for the experiment. This will overwrite the script you used in the previous lab.
# +
# %%writefile $experiment_folder/diabetes_training.py
# Import libraries
from azureml.core import Run
import pandas as pd
import numpy as np
import joblib
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
# Get the experiment run context
run = Run.get_context()
# load the diabetes data (passed as an input dataset)
print("Loading Data...")
diabetes = run.input_datasets['diabetes'].to_pandas_dataframe()
# Separate features and labels
X, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values
# Split data into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)
# Train a decision tree model
print('Training a decision tree model')
model = DecisionTreeClassifier().fit(X_train, y_train)
# calculate accuracy
y_hat = model.predict(X_test)
acc = np.average(y_hat == y_test)
print('Accuracy:', acc)
run.log('Accuracy', np.float(acc))
# calculate AUC
y_scores = model.predict_proba(X_test)
auc = roc_auc_score(y_test,y_scores[:,1])
print('AUC: ' + str(auc))
run.log('AUC', np.float(auc))
# plot ROC curve
fpr, tpr, thresholds = roc_curve(y_test, y_scores[:,1])
fig = plt.figure(figsize=(6, 4))
# Plot the diagonal 50% line
plt.plot([0, 1], [0, 1], 'k--')
# Plot the FPR and TPR achieved by our model
plt.plot(fpr, tpr)
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve')
run.log_image(name = "ROC", plot = fig)
plt.show()
os.makedirs('outputs', exist_ok=True)
# note file saved in the outputs folder is automatically uploaded into experiment record
joblib.dump(value=model, filename='outputs/diabetes_model.pkl')
run.complete()
# -
# Now you're ready to run the experiment on the compute you created.
#
# > **Note**: The experiment will take quite a lot longer because a container image must be built with the conda environment, and then the cluster nodes must be started and the image deployed before the script can be run. For a simple experiment like the diabetes training script, this may seem inefficient; but imagine you needed to run a more complex experiment that takes several hours - dynamically creating more scalable compute may reduce the overall time significantly.
# +
from azureml.core import Environment, Experiment
from azureml.core.conda_dependencies import CondaDependencies
from azureml.train.estimator import Estimator
from azureml.widgets import RunDetails
# Create a Python environment for the experiment
diabetes_env = Environment("diabetes-experiment-env")
diabetes_env.python.user_managed_dependencies = False # Let Azure ML manage dependencies
diabetes_env.docker.enabled = True # Use a docker container
# Create a set of package dependencies
diabetes_packages = CondaDependencies.create(conda_packages=['scikit-learn','ipykernel','matplotlib', 'pandas'],
pip_packages=['azureml-sdk','pyarrow'])
# Add the dependencies to the environment
diabetes_env.python.conda_dependencies = diabetes_packages
# Register the environment (just in case previous lab wasn't completed)
diabetes_env.register(workspace=ws)
registered_env = Environment.get(ws, 'diabetes-experiment-env')
# Get the training dataset
diabetes_ds = ws.datasets.get("diabetes dataset")
# Create an estimator
estimator = Estimator(source_directory=experiment_folder,
inputs=[diabetes_ds.as_named_input('diabetes')],
compute_target = cluster_name, # Use the compute target created previously
environment_definition = registered_env,
entry_script='diabetes_training.py')
# Create an experiment
experiment = Experiment(workspace = ws, name = 'diabetes-training')
# Run the experiment
run = experiment.submit(config=estimator)
# Show the run details while running
RunDetails(run).show()
# -
# While you're waiting for the experiment to run, you can check on the status of the compute in the widget above or in [Azure Machine Learning studio](https://ml.azure.com). You can also check the status of the compute using the code below.
cluster_state = training_cluster.get_status()
print(cluster_state.allocation_state, cluster_state.current_node_count)
# Note that it will take a while before the status changes from *steady* to *resizing* (now might be a good time to take a coffee break!). To block the kernel until the run completes, run the cell below.
run.wait_for_completion()
# After the experiment has finished, you can get the metrics and files generated by the experiment run. This time, the files will include logs for building the image and managing the compute.
# Get logged metrics
metrics = run.get_metrics()
for key in metrics.keys():
print(key, metrics.get(key))
print('\n')
for file in run.get_file_names():
print(file)
# Now you can register the model that was trained by the experiment.
# +
from azureml.core import Model
# Register the model
run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model',
tags={'Training context':'Azure ML compute'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']})
# List registered models
for model in Model.list(ws):
print(model.name, 'version:', model.version)
for tag_name in model.tags:
tag = model.tags[tag_name]
print ('\t',tag_name, ':', tag)
for prop_name in model.properties:
prop = model.properties[prop_name]
print ('\t',prop_name, ':', prop)
print('\n')
# -
# >**More Information**: For more information about compute targets in Azure Machine Learning, see the [documentation](https://docs.microsoft.com/azure/machine-learning/concept-compute-target).
| 05B - Working with Compute Targets.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
# ---
# # Pre-calculate the adjacency matrix and the ProteinGCN embeddings
# +
# %load_ext memory_profiler
import os, random, math, argparse
import torch
from model_ABDG_v2 import ProteinGCN
# from data import
from data import ProteinDataset,ProteinDockingDataset, get_train_val_test_loader,collate_pool, collate_pool_docking
from utils import randomSeed
import config as cfg
import numpy as np
import tqdm
# +
import prody as pd
pd.confProDy(verbosity='none')
import dgl
from scipy.spatial import KDTree
# How to make the adjacencies file
# For a given PDB pair
#[(Ligand), (Receptor)]
# [(356, 45, 44, 'A'), (730, 96, 91, 'A')]
# (atom index, residue index from pdb, unique residue number across chains, chain letter)
def find_adjacencies(pdb_l,pdb_r, dist_cutoff=4.5):
geometry_l = pdb_l.getCoords()
elements_l = pdb_l.getNames()
residues_l = pdb_l.getResnums()
#Chains are characters, 'A','B' etc., just convert to index 0,1,2...
chains_l = pdb_l.getChids()
_,chains_idx_l = np.unique(pdb_l.getChids(),return_inverse=True)
#Use the chains to make the residues unique
reschain_l = np.transpose([residues_l,chains_idx_l]) #Make Nx2 vector
#Note the 0-indexed residues here
_,residues_idx_l = np.unique(reschain_l,axis=0,return_inverse=True)
#Residues_l is now a zero-indexed vector of all unique residues
geometry_r = pdb_r.getCoords()
elements_r = pdb_r.getNames()
residues_r = pdb_r.getResnums()
chains_r = pdb_r.getChids()
_,chains_idx_r = np.unique(pdb_r.getChids(),return_inverse=True)
#Use the chains to make the residues unique
reschain_r = np.transpose([residues_r,chains_idx_r]) #Make Nx2 vector
_,residues_idx_r = np.unique(reschain_r,axis=0,return_inverse=True)
#Residues_idx_l is now a zero-indexed vector of all unique residues
# top_residue_chain = 0
# for i in np.arange(1,residues_r.shape[0]):
# if not chains_r[i] == chains_r[i-1]:
# top_residue_chain = residues_r[i-1]
# residues_r[i] = residues_r[i]+ top_residue_chain
combo = np.concatenate( (geometry_l,geometry_r),axis=0)
r_idx_min = geometry_l.shape[0] #any node index with this or higher is an R
kdtree = KDTree(combo)
neighborhood = kdtree.query_ball_point(geometry_l, r=dist_cutoff)
# To later populate some sort of adjacency matrix, we'll create a tuple of the form
# [(ligand atom index, ligand residue, ligand chain), (receptor atom index, receptor residue, receptor chain)]
# This can later be processed into any sort of adjacency matrix or mask
#Get the list of all l atoms that are within 4.5A of the R atoms
in_interface_l = np.where([any(np.array(f)>=r_idx_min) for f in neighborhood])[0]
#print(f"Found {len(in_interface_l)} atoms that are near R")
adjacencies = []
for l_idx in in_interface_l: # l_idx = ligand atom index
#Get the local neighborhood as defined by the threshold
local_n = np.array(neighborhood[l_idx])
#Get the receptor index
indices_r = local_n[np.where(local_n>=r_idx_min)] - r_idx_min
#Create the list of tuples to be analyzed later
for r_idx in indices_r:
# print(l_idx,r_idx, residues_r.shape,residues_l.shape)
adjacencies.append([(l_idx,residues_l[l_idx],residues_idx_l[l_idx],chains_l[l_idx]), (r_idx,residues_r[r_idx],residues_idx_r[r_idx],chains_r[r_idx])])
return adjacencies
#Get list of all directories in the DB5 Root
DB5ROOT_dir = "/mnt/disks/amanda200/DB5/raw/"
protein_dirs = os.listdir(DB5ROOT_dir)
#Because we want ground truth information, get the bound confirm
all_dirs = []
for directory in protein_dirs:
if not "DS_Store" in directory:
all_dirs.append(directory)
#For DB5, all_dirs are the PDBIDS, ie, 2A9K
PDBIDs = all_dirs
# for PDBID in PDBIDs:
# pdb_path_l = os.path.join(DB5ROOT_dir,PDBID,f'{PDBID}_l_b_cleaned.pdb')
# pdb_path_r = os.path.join(DB5ROOT_dir,PDBID,f'{PDBID}_r_b_cleaned.pdb')
# pdb_l = pd.parsePDB(pdb_path_l)
# pdb_r = pd.parsePDB(pdb_path_r)
# adjacencies = find_adjacencies(pdb_l,pdb_r)
# savepath = os.path.join(DB5ROOT_dir,PDBID,f'{PDBID}_b_adjacencies.npy')
# np.save(savepath,adjacencies)
# print(f"Saved file: {savepath} which had {len(adjacencies)} entries")
# +
args = {'name': 'abdg_demo',
'pkl_dir': '/home/ambeck/6.883ProteinDocking/data/firstDB5try/',
'pdb_dir': '/mnt/disks/amanda200/DB5/raw/',
'protein_dir': '/mnt/disks/amanda200/DB5/raw/',
'useDB5Bound':True,
'save_dir': './data/pkl/results/',
'id_prop': 'protein_id_prop.csv',
'atom_init': 'protein_atom_init.json',
'pretrained': './pretrained/pretrained.pth.tar',
'avg_sample': 500,
'seed': 1234,
'epochs': 0,
'batch_size': 1,
'train': 0.0,
'val': 0.0,
'test': 1.0,
'testing': False,
'lr': 0.001, 'h_a': 64, 'h_g': 32,
'n_conv': 4, 'save_checkpoints': True,
'print_freq': 10,
'workers': 1,
}
print('Torch Device being used: ', cfg.device)
# create the savepath
savepath = args["save_dir"] + str(args["name"]) + '/'
if not os.path.exists(savepath):
os.makedirs(savepath)
randomSeed(args["seed"])
# create train/val/test dataset separately
assert os.path.exists(args["protein_dir"]), '{} does not exist!'.format(args["protein_dir"])
dirs_label = [d[:10] for d in os.listdir(args["pkl_dir"]) if not d.startswith('.DS_Store')]
# all_dirs = [d for d in os.listdir(args["protein_dir"]) if not d.startswith('.DS_Store')]
base_dir=set(dirs_label)
dir_r = []
dir_l = []
dir_r.extend(d+'r_u_cleane.pkl' for d in base_dir)
dir_l.extend(d+'l_u_cleane.pkl' for d in base_dir)
all_dirs = []
for r,l in zip(dir_r, dir_l):
all_dirs.append(r)
all_dirs.append(l)
dir_len = len(all_dirs)
indices = list(range(dir_len))
random.shuffle(indices)
train_size = math.floor(args["train"] * dir_len)
val_size = math.floor(args["val"] * dir_len)
test_size = math.floor(args["test"] * dir_len)
if val_size == 0:
print(
'No protein directory given for validation!! Please recheck the split ratios, ignore if this is intended.')
if test_size == 0:
print('No protein directory given for testing!! Please recheck the split ratios, ignore if this is intended.')
test_dirs = all_dirs[:test_size]
train_dirs = all_dirs[test_size:test_size + train_size]
val_dirs = all_dirs[test_size + train_size:test_size + train_size + val_size]
print('Testing on {} protein directories:'.format(len(test_dirs)))
def loadProteinDataSetAndModel():
dataset = ProteinDataset(args["pkl_dir"], args["id_prop"], args["atom_init"], random_seed=args["seed"])
# dataset = ProteinDockingDataset(args["pkl_dir"],args["pdb_dir"], args["id_prop"],args['useDB5Bound'], args["atom_init"])
print('Dataset length: ', len(dataset))
# load all model args from pretrained model
if args["pretrained"] is not None and os.path.isfile(args["pretrained"]):
print("=> loading model params '{}'".format(args["pretrained"]))
model_checkpoint = torch.load(args["pretrained"], map_location=lambda storage, loc: storage)
model_args = argparse.Namespace(**model_checkpoint['args'])
# override all args value with model_args
args["h_a"] = model_args.h_a
args["h_g"] = model_args.h_g
args["n_conv"] = model_args.n_conv
args["random_seed"] = model_args.seed
args["lr"] = model_args.lr
print("=> loaded model params '{}'".format(args["pretrained"]))
else:
print("=> no model params found at '{}'".format(args["pretrained"]))
args["random_seed"] = args["seed"]
structures, _, _ = dataset[0] #Getting the size from the ligand
h_b = structures[1].shape[-1]
args['h_b'] = h_b # Dim of the bond embedding initialization
# Use DataParallel for faster training
print("Let's use", torch.cuda.device_count(), "GPUs and Data Parallel Model.")
# print(kwargs)
model = ProteinGCN(**args)
return model, dataset
# -
# dataset = ProteinDockingDataset(args["pkl_dir"],args["pdb_dir"], args["id_prop"],args['useDB5Bound'], args["atom_init"])
dataset = ProteinDataset(args["pkl_dir"], args["id_prop"],args["atom_init"])
model, dataset = loadProteinDataSetAndModel()
test_loader = get_train_val_test_loader(dataset, train_dirs, val_dirs, test_dirs,
collate_fn = collate_pool,
num_workers = args["workers"],
batch_size = args["batch_size"],
pin_memory = False,
predict=True)
# +
def getInputHACK(inputs):
return [inputs[0], inputs[1], inputs[2], inputs[4], inputs[5]]
def loadAdjacencyMatrix(pdb,pdb_dir,chooseBound=True):
#DB5 specific
boundchar = 'b'
if not chooseBound:
boundchar = 'u'
#The contents of the numpy file looks like this:
#(437, 56, 55, 'A'), (520, 69, 65, 'A')
#actually, they are all saved as strings due to some quirk with the saving
adjacencies_full = np.load(os.path.join(pdb_dir, pdb, f'{pdb}_{boundchar}_adjacencies.npy'),allow_pickle=True)
#Return just amino acids indices, which is not unique.
#Note that we're *not* using the residue index in the pdb but instead a 0-indexed unique ID
adjacencies_short = [[int(a[0][2]), int(a[1][2])] for a in adjacencies_full]
adjacencies_short = np.array(adjacencies_short)
# Get only the unques
adjacencies_short_unique = np.unique(adjacencies_short,axis=0)
# print(adjacencies_short_unique)
return adjacencies_short_unique
# +
PDB_DIR = '/mnt/disks/amanda200/DB5/raw/'
OUTPUT_DIR = '/mnt/disks/amanda200/bounddb5_processed/'
max_amino_r = 0
max_amino_l = 0
for PDBID in PDBIDs:
adjacencies = loadAdjacencyMatrix(PDBID,PDB_DIR)
# torch.save(adjacencies,os.path.join(OUTPUT_DIR,'adjacencies',f"{PDBID}.pkl"))
max_amino_r = max(max_amino_r,max(adjacencies[:,1]))
max_amino_l = max(max_amino_l,max(adjacencies[:,0]))
print(f"completed {PDBID} with size {adjacencies.shape}")
print(max_amino_l,max_amino_r)
# +
#Collate_pool is called to produce this out of the enumerate
#input_data = (final_protein_atom_fea, final_nbr_fea, final_nbr_fea_idx, None, final_atom_amino_idx, final_atom_mask)
#batch_data = (batch_protein_ids, np.concatenate(batch_amino_crystal))
#target tuples = (final_target, torch.cat(final_amino_target))
ligands_unembedded = {}
ligands_embedded = {}
receptors_unembedded = {}
receptors_embedded = {}
adjacencies = {}
PDB_DIR = '/mnt/disks/amanda200/DB5/raw/'
OUTPUT_DIR = '/mnt/disks/amanda200/bounddb5_processed/'
for protein_batch_iter, (input_data, batch_data, target_tuples) in enumerate(test_loader):
print(f"{protein_batch_iter}: {batch_data[0]}")
pdb = batch_data[0][0].split('_')[0]
isligand = batch_data[0][0].split('_')[2]=='l'
isbound = batch_data[0][0].split('_')[3]=='b'
if not isbound: #Skipping unbound for now
continue
pgcn_data = getInputHACK(input_data)
if isligand:
torch.save(pgcn_data,os.path.join(OUTPUT_DIR,'ligand',f"{pdb}.pkl"))
else:
torch.save(pgcn_data,os.path.join(OUTPUT_DIR,'receptor',f"{pdb}.pkl"))
amino_emb, protein_emb_temp = model(pgcn_data)
if isligand:
torch.save((amino_emb, protein_emb_temp),os.path.join(OUTPUT_DIR,'emb_ligand',f"{pdb}.pkl"))
else:
torch.save((amino_emb, protein_emb_temp),os.path.join(OUTPUT_DIR,'emb_receptor',f"{pdb}.pkl"))
adjacencies = loadAdjacencyMatrix(pdb,PDB_DIR)
torch.save(adjacencies,os.path.join(OUTPUT_DIR,'adjacencies',f"{pdb}.pkl"))
# -
print(isligand)
print(pgcn_data[2].size())
print(amino_emb.size())
print(protein_emb_temp.size())
adjacencies
PDB_DIR = '/mnt/disks/amanda200/DB5/raw/'
OUTPUT_DIR = '/mnt/disks/amanda200/bounddb5_processed/'
pdb_list=[]
batch=0
for protein_batch_iter, (input_data, batch_data, target_tuples) in enumerate(test_loader):
pdb = batch_data[0][0].split('_')[0]
pdb_list.append(pdb)
batch+=1
print(batch)
np.save(pdb_list,os.path.join(OUTPUT_DIR, 'names.npy'))
| Saving DB5 into loadable format.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
# ---
# 
# # What is BERT?
# * BERT stands for Bidirectional Encoders Representations from Transformers.
# * Bidirectional - to understand the text you’re looking you’ll have to look back (at the previous words) and forward (at the next words)
# * Transformers - The Attention Is All You Need paper presented the Transformer model. The Transformer reads entire sequences of tokens at once. In a sense, the model is non-directional, while LSTMs read sequentially (left-to-right or right-to-left). The attention mechanism allows for learning contextual relations between words (e.g. his in a sentence refers to Jim).
# * (Pre-trained) contextualized word embeddings - The ELMO paper introduced a way to encode words based on their meaning/context. Nails has multiple meanings - fingernails and metal nails.
#
# In this notebook we will be using transformers library by hugging face.
# + _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19"
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All"
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
# + _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0"
import torch
from tqdm.notebook import tqdm
# -
# Reading SMILE twitter emotion dataset
df = pd.read_csv("/kaggle/input/smile-twitter-emotion-dataset/smile-annotations-final.csv",
names = ['Id','Text','Category'])
df.set_index('Id',inplace = True)
df[:4]
df.Text.iloc[0]
# * Counts of Emotions in the dataset
df.Category.value_counts()
# We will be filtering the emotions with single emotions and ignoring the rest.
df = df[(df.Category!="nocode")]
df = df[~(df.Category.str.contains("\|"))]
df.Category.value_counts()
possible_label = df.Category.unique()
dict_label = {}
for index,possible_label in enumerate(possible_label):
dict_label[possible_label] = index
dict_label
df["Label"] = df["Category"].replace(dict_label)
df.head()
# +
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['figure.figsize'] = (5,5)
sns.countplot(df["Label"],hue = df["Label"],palette = 'dark')
plt.legend(loc = 'upper right')
plt.show()
# -
labels = [0,1,2,3,4,5]
sizes = df["Label"].value_counts()
colors = plt.cm.copper(np.linspace(0, 1, 5))
explode = [0.1, 0.1,0.1, 0.2, 0.5, 0.9]
cmap = plt.get_cmap('Spectral')
plt.pie(sizes,labels = labels,colors = colors,shadow = True,explode = explode)
plt.legend()
plt.show()
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(df.index.values,
df.Label.values,
test_size = 0.15,
random_state=17,
stratify = df.Label.values)
# +
# df["data_type "] = ['not_set']*df.shape[0]
# df.head()
# -
# for i in df.index:
# if i in X_train:
# df["data_type"].replace("not_set","train")
# elif i in X_test:
# df["data_type"].replace("not_set","test")
# df.head()
df.loc[X_train,'data_type'] = 'train'
df.loc[X_test,'data_type'] = 'test'
df.head()
df.groupby(['Category','Label','data_type']).count()
# # Modeling
from transformers import BertTokenizer
from torch.utils.data import TensorDataset
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',
do_lower_case = True)
# Encoding text by tokenizing using BERT Tokenizer
# * In order to use BERT text embeddings as input to train text classification model, we need to tokenize our text reviews. Tokenization refers to dividing a sentence into individual words. To tokenize our text, we will be using the BERT tokenizer
# +
encoder_train = tokenizer.batch_encode_plus(df[df["data_type"]=='train'].Text.values,
add_special_tokens = True,
return_attention_masks = True,
pad_to_max_length = True,
max_length = 256,
return_tensors = 'pt')
encoder_test = tokenizer.batch_encode_plus(df[df["data_type"]=='test'].Text.values,
add_special_tokens = True,
return_attention_masks = True,
pad_to_max_length = True,
max_length = 256,
return_tensors = 'pt')
input_ids_train = encoder_train['input_ids']
attention_masks_train = encoder_train["attention_mask"]
labels_train = torch.tensor(df[df['data_type']=='train'].Label.values)
input_ids_test = encoder_test['input_ids']
attention_masks_test = encoder_test["attention_mask"]
labels_test = torch.tensor(df[df['data_type']=='test'].Label.values)
# -
data_train = TensorDataset(input_ids_train,attention_masks_train,labels_train)
data_test = TensorDataset(input_ids_test,attention_masks_test,labels_test)
len(data_train),len(data_test)
# * We will use sequence classification model as we have to classify multi label text from the dataset.
from transformers import BertForSequenceClassification
model = BertForSequenceClassification.from_pretrained('bert-base-uncased',
num_labels = len(dict_label),
output_attentions = False,
output_hidden_states = False)
# From torch we will use data loader,randomsampler to load data in an iterable format but extracting different subsamples from dataset.
# +
from torch.utils.data import RandomSampler,SequentialSampler,DataLoader
dataloader_train = DataLoader(
data_train,
sampler= RandomSampler(data_train),
batch_size = 16
)
dataloader_test = DataLoader(
data_test,
sampler= RandomSampler(data_test),
batch_size = 32
)
# +
from transformers import AdamW,get_linear_schedule_with_warmup
optimizer = AdamW(model.parameters(),lr = 1e-5,eps = 1e-8)
epochs = 10
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps = 0,
num_training_steps = len(dataloader_train)*epochs
)
# -
# Defining Model metrics
# +
from sklearn.metrics import f1_score
def f1_score_func(preds,labels):
preds_flat = np.argmax(preds,axis=1).flatten()
labels_flat = labels.flatten()
return f1_score(labels_flat,preds_flat,average = 'weighted')
# -
def accuracy_per_class(preds,labels):
label_dict_reverse = {v:k for k,v in dict_label.items()}
preds_flat = np.argmax(preds,axis=1).flatten()
labels_flat = labels.flatten()
for label in np.unique(labels_flat):
y_preds = preds_flat[labels_flat==label]
y_true = labels_flat[labels_flat==label]
print(f"Class:{label_dict_reverse}")
print(f"Accuracy:{len(y_preds[y_preds==label])}/{len(y_true)}\n")
# +
import random
seed_val = 17
random.seed(seed_val)
np.random.seed(seed_val)
torch.manual_seed(seed_val)
torch.cuda.manual_seed_all(seed_val)
# +
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
print(f"Loading:{device}")
# -
# Defining Evaluation
def evaluate(dataloader_val):
model.eval()
loss_val_total = 0
predictions,true_vals = [],[]
for batch in tqdm(dataloader_val):
batch = tuple(b.to(device) for b in batch)
inputs = {'input_ids': batch[0],
'attention_mask':batch[1],
'labels': batch[2]
}
with torch.no_grad():
outputs = model(**inputs)
loss = outputs[0]
logits = outputs[1]
loss_val_total +=loss.item()
logits = logits.detach().cpu().numpy()
label_ids = inputs['labels'].cpu().numpy()
predictions.append(logits)
true_vals.append(label_ids)
loss_val_avg = loss_val_total/len(dataloader_val)
predictions = np.concatenate(predictions,axis=0)
true_vals = np.concatenate(true_vals,axis=0)
return loss_val_avg,predictions,true_vals
# * Training Data
for epoch in tqdm(range(1,epochs+1)):
model.train()
loss_train_total=0
progress_bar = tqdm(dataloader_train,desc = "Epoch: {:1d}".format(epoch),leave = False,disable = False)
for batch in progress_bar:
model.zero_grad()
batch = tuple(b.to(device) for b in batch)
inputs = {
"input_ids":batch[0],
"attention_mask":batch[1],
"labels":batch[2]
}
outputs = model(**inputs)
loss = outputs[0]
# logits = outputs[1]
loss_train_total +=loss.item()
loss.backward()
torch.nn.utils.clip_grad_norm(model.parameters(),1.0)
optimizer.step()
scheduler.step()
progress_bar.set_postfix({'training_loss':'{:.3f}'.format(loss.item()/len(batch))})
# torch.save(model.state_dict(),f'/kaggle/output/BERT_ft_epoch{epoch}.model')To save the model after each epoch
tqdm.write('\nEpoch {epoch}')
loss_train_avg = loss_train_total/len(dataloader_train)
tqdm.write(f'Training Loss: {loss_train_avg}')
val_loss,predictions,true_vals = evaluate(dataloader_test)
test_score = f1_score_func(predictions,true_vals)
tqdm.write(f'Val Loss:{val_loss}\n Test Score:{test_score}')
# # Using the saved model
# +
# from transformers import BertForSequenceClassification
# model = BertForSequenceClassification.from_pretrained('bert-base-uncased',
# num_labels = len(dict_label),
# output_attentions = False,
# output_hidden_states = False)
# -
model.to(device)
# +
# #using saved model
# model.load_state_dict(torch.load("Path of saved model"))# in case want to use the saved model
# _,predictions,true_vals = evaluate(dataloader_test)
# accuracy_per_class(predictions,true_vals)
# -
_,predictions,true_vals = evaluate(dataloader_test)
accuracy_per_class(predictions,true_vals)
| 8_Natural_Language_Processing/Application of NLP/sentiment-analysis-using-bert.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 required libraries
import sys
sys.path.insert(0, '../../../BERT-FAQ/')
from evaluation import Evaluation
# +
rank_results_filepath="../../../BERT-FAQ/data/CovidFAQ/rank_results"
ev = Evaluation()
df = ev.get_eval_df(rank_results_filepath)
# -
df
| notebook/CovidFAQ/09.Evaluation.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
# ---
# ### About:
# 5/11/2021 Program calculate the correlation coefficient between state and age population in 2013
#
# (1) between internet speeds
# (2) between states
# (3) between states & internet speeds??? -> Self Assigned
#
# #### NOTE: Make sure to unzip the xlsx files
#
# @author: <NAME> @AIA
#
# @credit: Qasim, Andrei @AIA
import numpy as np
from numpy.random import randn
from numpy.random import seed
from numpy import array_split
import pandas as pd
from sklearn import metrics as mt
from sklearn import model_selection as md
from matplotlib import pyplot as plt
import seaborn as sns
import sklearn.datasets as ds
import random
# ### Correlation Calculation
def correlation_cal(df):
# Instead of just dropping the missing values, we will fill in N/A values
if df.isna().values.any():
while True:
missing_type = input("Please enter the type of missing value replacement: mean, medium, mode, or drop from the row")
missing_type = missing_type.lower()
if(missing_type in ['mean', 'median', 'mode', 'drop']):
if(missing_type == 'mean'):
df.fillna(df.mean(), inplace=True)
elif(missing_type == 'median'):
df.fillna(df.median(), inplace=True)
elif(missing_type == 'mode'):
df.fillna(df.mode(), inplace=True)
else:
df.dropna()
break
else:
print("Please input the option from the list")
# Calculate input data correlation
while True:
corr_type = input("Please enter type of correlation: Pearson, Spearman, or Kendall: ")
corr_type = corr_type.lower()
if corr_type in ['pearson', 'spearman', 'kendall']:
break
else:
print("Please try again")
# Plot correlation matrix
corrMatrix = df.corr(method=corr_type)
_, ax = plt.subplots(figsize=(12, 10))
sns.heatmap(corrMatrix, ax = ax, cmap="YlGnBu", linewidths = 0.1) # cmap can also be "YlGnBu"
# # (1) Correlation Calculation Between Population Range
# #### Preprocess Data
# !ls
def parse_data_bis(file, sheetname):
""" Function load csv files into csv pandas by internet speed
Function parse data by internet speed for all 50 states + nation (row 0)
"""
dataset = pd.read_excel(file, sheet_name = sheetname, skiprows = [51,52,53,54,55,56,57,58,59,60,61,62], usecols=[1,2,3,4,5,6,7])
return dataset
df_bis = parse_data_bis("sheet.xlsx", "2013") # Due to long name access, I made a copy of preprocessed_data.xlsx and change to sheet
df_bis.head()
# ### Run 1: Correlation Pearson - Mean
# Run Correlation Pearson
correlation_cal(df_bis)
# ### Run 2: Correlation Spearman - Mean
# Run Correlation Spearman
correlation_cal(df_bis)
# ### Run 3: Correlation Kendall - Mean
# Run Correlation Kendall
correlation_cal(df_bis)
# ### Analysis - Self Assigned
#
# 1/ What are the two significant correlation coefficient for Pearson, Spearman, Kendall?
#
# 2/ What are other analysis we can do with these graphs?
#
# 3/ Any other metric besides Pearson, Spearman, Kendall?
# # (2) Correlation Calculation Between States
def parse_data_bs(file, sheetname):
""" Function load csv files into csv pandas by internet speed
Function parse data by states and nation for all 10 types of internet speeds
"""
dataset = pd.read_excel(file, sheet_name = sheetname, skiprows=[0,51,52,53,54,55,56,57,58,59,60,61,62], usecols=[0,1,2,3,4,5,6,7], drop=True)
dataset.set_index("Alabama", inplace=True)
dataset = dataset.T
return dataset
df_bs = parse_data_bs("sheet.xlsx", "2013")
df_bs.head()
# ### Run 1: Correlation Pearson - Mean
#
# Run Correlation Pearson
correlation_cal(df_bs)
# ### Run 2: Correlation Spearman - Mean
# Run Correlation Spearman
correlation_cal(df_bs)
# ### Run 3: Correlation Kendall - Mean
# Run Correlation Kendall
correlation_cal(df_bs)
# ### Analysis - Self Assigned
#
# 1/ What are the two significant correlation coefficient for Pearson, Spearman, Kendall?
#
# 2/ What are other analysis we can do with these graphs?
#
# 3/ Any other metric besides Pearson, Spearman, Kendall?
| correlation/Correlation Analysis - Environmental Descriptors/Corr - Age Pop/Correlation-2013.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
# ---
# ---
# layout: post
# author: csiu
# date: 2017-03-02
# title: "Day06: Jupyter Notebook, meet Jekyll blog post"
# categories: update
# tags:
# - 100daysofcode
# - setup
# excerpt: Integrating code
# ---
# DAY 06 - Mar 2, 2017
#
# ### Data Science meetup
#
# Today I went to the [Data Science meetup for "Using NLP & Machine Learning to understand and predict performance"](https://www.meetup.com/DataScience/events/237733099/). Fascinating stuff. Somewhat similar to my thesis work and the talk inspired a few ideas for future projects.
speaker = '<NAME>'
topics_mentioned_at_meetup = [
"latent dirichlet allocation",
"collapsed gibbs sampling",
"bayesian inference",
"topic modelling",
"porter stemmer",
"flesch reading ease",
"word2vec"
]
# *Anyways, I just got home and now (as I'm typing this) have 35 minutes to do something and post it for Day06.*
#
# ### Jupyter Notebook meet Jekyll blog post
#
# Going back to a comment I recently recieved about including and embedding code to my jekyll blog posts. I thought I would tackle this problem now. The issue is that I use Jupyter Notebooks to explore and analyze data but I haven't really looked at its integration with the Jekyll blog post.
for t in topics_mentioned_at_meetup:
print("- '{}' was mentioned".format(t))
# ### Integration with Jekyll
#
# 1. Add yaml front matter to the top of the Jupyter Notebook
# 2. Convert Jupyter Notebook to markdown by `jupyter nbconvert --to markdown NOTEBOOK.ipynb`
# 3. Delete empty first line of markdown
| misc/2017-03-02-day06.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
# ---
# See results_notebook.py for a more complicated analysis example (used to replicate some analyses from a previous SERP-related paper).
#
# This file is meant to provide a very quick starting point for writing up other analyses.
# # Current data format
# Currently, the node.js scraping code (see collect.js)
# saves 3 result files per SERP scraped:
# * a .json file with
# device object used by puppeteer ("device"), date collection started ("dateStr"),
# date of collection ("dataAtSave"), user-specified query category (queryCat),
# file queries came from ("queryFile"), device name ("deviceName"),
# url accessed ("link"), the search engine or website ("platform"),
# the query made ("target"), and finally, a huge array of link elements ("linkElements")
# * a .png file that is a full screenshot of the SERP
# * a .mhtml snapshot of the website that can be opened in a web browser (this is experimental, apparently)
#
# Files are named by datetime of script start to avoid accidental overwrite.
#
# This script (analysis.py) includes code which stitches together a visual representation of
# links and their coordinates (obtained using getBoundingClientRect) alongside screenshots
# so search can perform visual validation -- compare the link representation (easy to do quant analyses)
# with the png representation and make sure they match up!
# we'll use pandas and friends for this quick analysis.
# +
# defaults
import json
import glob
from pprint import pprint
from collections import defaultdict
from urllib.parse import unquote
import os
# scipy
import pandas as pd
import numpy as np
# plotting / images
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
from PIL import Image
# helpers for this project
from helpers import (
infinite_defaultdict, recurse_print_infinitedict, extract,
is_mobile,
)
from my_constants import CONSTANTS
DO_COORDS = False
SAVE_PLOTS = False
# -
# new data will be in results/*. This is an example!
filename = 'nov5_example/Chrome on Windows/https---www.google.com-search?q=protests/Thu Nov 05 2020 14-12-08 GMT-0600 (Central Standard Time).json'
with open(filename, 'r', encoding='utf8') as f:
d = json.load(f)
d.keys()
# print all details except the actual links (which is huge)
{k: v for k, v in d.items() if k != 'linkElements'}
df = pd.DataFrame(d['linkElements'])
df.head()
from analyze_links import analyze_links_df
analyzed = analyze_links_df(df)
analyzed.head()
analyzed.domain.value_counts()
tmp = analyzed.sort_values('top')[['top', 'left', 'domain', 'href']]
# drop "google" domains
tmp[~tmp.domain.str.contains('google')]
| notebooks/Nov5Example_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
# ---
# # **Data Processing for the Airbnb Berlin Dataset from http://insideairbnb.com/berlin**
# ##### Qustions we want to answer:
# 1. **What's the average price per (grouped) neighborhood in Berlin?**
# 2. **What's the occupancy rate of airbnb listings in Berlin?**
# 3. **What's the average revenue of airbnb listings in Berlin?**
# 4. **Does being a Superhost effect the average revenue?**
# 5. **How does this compare to the average revenue from normal rent in those neighbourhoods?**
#
# +
# Imports
import pandas as pd
import geopandas as gpd
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
from pyproj import CRS
import seaborn as sns
import numpy as np
pd.set_option('display.max_columns', None)
#This allows for multiple outputs from one cell to be shown
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
pd.set_option('display.max_columns', None)
import os
os.chdir('C:/Users/felix/Desktop/NanoDegree')
# Magic Functions
# %matplotlib inline
# -
#Read in pre-processed data
listings_df = pd.read_csv('listings_processed.csv', parse_dates=["host_since", "last_scraped",'first_review', 'last_review'])
calendar_df = pd.read_csv('calendar_processed.csv', parse_dates=['date'])
#Check columns and provide them for copy past actions
listings_df.columns
calendar_df.columns
#Read in geo info about neighbourhoods on detailed lvl = "neighbourhood" and grouped lvl = "neighbourhood_group"
#and check out crs system used:
neighbourhoods_geo = gpd.read_file('neighbourhoods.geojson')
neighbourhoods_geo
neighbourhoods_geo.crs
# # 1. **What's the average price per (grouped) neighborhood in Berlin?**
# ##### Before we get started answering the questions, lets filter the data for a "fair" comparison.
# 1. Entire homes or apartments highly available year-round probably don't have the owner present.
# 2. Those are the listings we want to look at for comparsison to normal renting.
# 3. availability_365 can be used to filter for those.
# 4. We have to keep in mind that if a listing is already booked it will reduce availability_365.
# 5. For this analysis we will choose >150 days as our high availability filter:
#
#check statistics on the availability:
listings_df.availability_365.describe()
#Figure out if we have enough listings with high abailability:
listings_df = listings_df.loc[(listings_df.availability_365 > 90)]
listings_df.shape
# ## Price Comparison on detailed neighbourhood level
#Create subset to compare avg prices on lvl of (detailed) neighbourhood listings and sort decending:
neighbourhoods_detailed_avg_price = listings_df.groupby(by = ['neighbourhood_cleansed', 'neighbourhood_group_cleansed']).price.mean().sort_values(ascending=False).reset_index()
neighbourhoods_detailed_avg_price
#check number of listings in each neighbourhood
listings_df.neighbourhood_cleansed.value_counts()
# +
#visualize the number of listings in each neighbourhood in a barchart using seaborn:
fig, ax = plt.subplots(figsize = (15,5))
plot = sns.countplot(x='neighbourhood_cleansed',
data=listings_df,
order= listings_df.neighbourhood_cleansed.value_counts().index)
ax.set_xticks([]);
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.title('Number of AirBnb Listings per Neighbourhood', fontsize = 20)
# +
# Visualize avg price per night of listings within each neighbourhood &
# ordering by decending avg price and incl. std dev using seaborn :
plot = sns.catplot(x="neighbourhood_cleansed",
y = "price",
data = listings_df,
height = 5, aspect = 3,
kind="bar", order = neighbourhoods_detailed_avg_price.neighbourhood_cleansed)
plot.set_axis_labels("Neighbourhoods", "Price")
plot.ax.set_xticks([]);
plt.title('Average Price of Neighbourhood Listings for Berlin', fontsize = 20)
# +
#Lots of neighbourhoods have a high std dev -->reason: buckets with very small sample size!:
#e.g. multiple neighbourhoods only have 1 Value - so Price here isn't a true average, indicated by missing std.
# -
#To visualize only "true" averages we will drop neighbourhoods with <10 listings:
less_than_8 = listings_df.neighbourhood_cleansed.value_counts().loc[(listings_df.neighbourhood_cleansed.value_counts() < 8)]
neighbourhoods_detailed_avg_price = neighbourhoods_detailed_avg_price[~neighbourhoods_detailed_avg_price.neighbourhood_cleansed.isin(less_than_8.index)]
#Attach geo info from neighbourhoods_geo to allocate neighbourhood_cleansed on a map:
neighbourhoods_detailed_avg_price_geo = neighbourhoods_detailed_avg_price.merge(neighbourhoods_geo['geometry'],left_on=['neighbourhood_cleansed'],right_on=neighbourhoods_geo['neighbourhood'])
neighbourhoods_detailed_avg_price_geo = gpd.GeoDataFrame(neighbourhoods_detailed_avg_price_geo, geometry='geometry')
#Using geopandas to visualize above shown avg prices on a map:
fig, ax = plt.subplots(figsize = (20,20))
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=-3)
neighbourhoods_detailed_avg_price_geo.plot(column='price', legend = True, ax=ax, cax=cax, cmap='RdYlGn_r')
# ## Price Comparison on grouped neighbourhood level
#Create Abbriviations for the neighbourhood groups:
temp = listings_df.neighbourhood_group_cleansed.str.split(" ", expand=True)
temp = temp[0].str.split("-", expand=True)
listings_df['neighbourhood_group_cleansed_short'] = temp[0]
listings_df['neighbourhood_group_cleansed_short'].unique()
#check how many listings remain for each neighbouthood:
listings_df['neighbourhood_group_cleansed_short'].value_counts()
# Get mean price per night of listings within each grouped neighbourhood:
neighbourhoods_avg_price = listings_df.groupby(by = ['neighbourhood_group_cleansed_short', 'neighbourhood_group_cleansed']).price.mean().sort_values(ascending=False).reset_index()
neighbourhoods_avg_price
#Setting colour palette for the 12 neigbourhood groups:
sns.set_palette(sns.color_palette('RdYlGn', 12))
# +
#visualize the number of listings in each neighbourhood in a barchart using seaborn:
fig, ax = plt.subplots(figsize = (15,5))
plot = sns.countplot(x='neighbourhood_group_cleansed_short',
data=listings_df,
order= listings_df.neighbourhood_group_cleansed_short.value_counts().index)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.title('Number of AirBnb Listings per grouped Neighbourhood', fontsize = 20)
# -
#taking a first statistical look at the pricings:
listings_df.price.describe()
#check number of listings in each neighbourhood
listings_df.groupby('neighbourhood_group_cleansed_short').price.mean().sort_values()
# +
# Visualize avg price per night of listings within each groupneighbourhood &
# ordering by decending avg price incl std dev using seaborn :
plot = sns.catplot(x="neighbourhood_group_cleansed_short", y = "price",
data = listings_df,
height = 5, aspect = 3,
kind="bar",
order= listings_df.neighbourhood_group_cleansed_short.value_counts().index)
(plot.set_axis_labels("Neighbourhoods", "Price"))
plt.title('Average Price of Listings in Berlin\'s Neighbourhoods', fontsize = 20)
# +
#Still a high std dev for some grouped neighbourhoods but significantly less than on detailed neighbourhood lvl
# -->probably due to more samples / bucket
# -
#Attach geo info from neighbourhoods_geo to allocate neighbourhood_group_cleansed_short on a map:
neighbourhoods_avg_price_gdf = neighbourhoods_avg_price.merge(neighbourhoods_geo['geometry'],left_on=['neighbourhood_group_cleansed'],right_on=neighbourhoods_geo['neighbourhood_group'])
neighbourhoods_avg_price_gdf = gpd.GeoDataFrame(neighbourhoods_avg_price_gdf, geometry='geometry')
#Use the dissolve function to combine MULTIPOLYGONS (describing the detailed neighbourhoods) to lvl of grouped neighbourhoods:
neighbourhoods_avg_price_gdf = neighbourhoods_avg_price_gdf.dissolve(by ='neighbourhood_group_cleansed').reset_index()
#Attach a col carrying the center coordinat of each grouped neighbourhood:
neighbourhoods_avg_price_gdf['coords'] = neighbourhoods_avg_price_gdf['geometry'].apply(lambda x: x.representative_point().coords[:])
neighbourhoods_avg_price_gdf['coords'] = [coords[0] for coords in neighbourhoods_avg_price_gdf['coords']]
# +
#Using geopandas to visualize above shown avg prices on a map:
fig, ax = plt.subplots(figsize = (20,20))
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=-3)
neighbourhoods_avg_price_gdf.apply(
lambda x: ax.annotate(text=x.neighbourhood_group_cleansed_short,
xy=x.geometry.centroid.coords[0], ha='center'),axis=1);
neighbourhoods_avg_price_gdf.plot(column='price', legend = True, ax=ax, cax=cax, cmap='RdYlGn_r')
# -
# ### For the further analysis we will stick with comparison by grouped neighbourhoods.
# # 2. What's the occupancy rate of active airbnb listings in Berlin?
# ### We'll estimate the occupancy rate based on reviews:
# +
##We can only take listings into account the have at least 1 review.
#Also we want the review_timespan to be at least 90 days:
print("{} listing's review-timespan is less than 90 days and will therefore be dropped.".format(
(listings_df.review_timespan < 90).sum()))
listings_occupancy = listings_df.loc[(listings_df.review_timespan >= 90)]
# +
#We only want to take listings into account where the host has been around for over 90 days.
print("{} listings have not been around for atleast 90 days and will therefore be dropped.".format(
(listings_occupancy.host_4_Xdays < 90).sum()))
listings_occupancy = listings_occupancy.loc[(listings_occupancy.host_4_Xdays >= 90)]
# +
#Let's check if reviews_per_month was calculated similar to:
# "reviews_per_month = number_of_reviews / review_timespan"
#to be sure we know what we are working with:
listings_occupancy['reviews_per_month_self'] = (listings_occupancy.number_of_reviews /
(listings_occupancy.review_timespan / 30.42))
(listings_occupancy.reviews_per_month - listings_occupancy['reviews_per_month_self']).describe()
# +
#Not the same but close. We will continue working with the given column reviews_per_month.
# +
# We want to use minimum_nights for our estimation.
#But before we do so, let's have a look at the values:
listings_occupancy.minimum_nights.describe()
# -
#How many listings are effected when flattening the attribute?:
(listings_occupancy.minimum_nights >30).sum()/listings_occupancy.shape[0]
#Some listings have the minimum_nights set to values as high as 1124. Those outliers don't seem plausible.
#Instead of dropping them we will overwrite those values with the average of minimum_nights <=7:
mean_of_upto_7_days = listings_occupancy.loc[(listings_occupancy.minimum_nights <=7),['minimum_nights']].mean()[0]
listings_occupancy.loc[(listings_occupancy.minimum_nights >7),['minimum_nights']] = mean_of_upto_7_days
# statistics on the price, reviews_per_month and minimum_nights columns:
listings_occupancy[['reviews_per_month', 'minimum_nights']].describe()
# +
#Next, we'll multiply the reviews_per_month with the minimum_nights column indication how long a reviewer stayed at least.
#The result is a very conservative estimate of how many days per month the listings are occupied.
listings_occupancy['occ_per_month'] = (listings_occupancy.reviews_per_month *
listings_occupancy.minimum_nights)
listings_occupancy['occ_per_month'].describe()
# -
print('The considered listings have an average stay of {:.2f} days.'.format(
listings_occupancy['minimum_nights'].mean()))
# +
#Not the same but close. We will continue working with the given column reviews_per_month for now.
#Now let's create subset to compare avg reviews_per_month and sort decending:
neighbourhoods_avg_occ = listings_occupancy.groupby(by = ['neighbourhood_group_cleansed_short',
'neighbourhood_group_cleansed']
).occ_per_month.mean().sort_values(ascending=False).reset_index()
neighbourhoods_avg_occ
# +
#visualize the number of listings in each neighbourhood in a barchart using seaborn:
sns.set_palette('RdYlGn',12)
fig, ax = plt.subplots(figsize = (15,5))
plot = sns.countplot(x='neighbourhood_group_cleansed_short',
data=listings_occupancy,
order = neighbourhoods_avg_occ.neighbourhood_group_cleansed_short)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.title('Number of AirBnb Listings per grouped Neighbourhood', fontsize = 20)
# -
#checking statistics on listings_occupancy:
listings_occupancy.groupby('neighbourhood_group_cleansed_short').occ_per_month.describe()[['count', 'mean', 'std', 'min','max']]
# +
#Attaach geo info from neighbourhoods_geo to allocate neighbourhood_group_cleansed_short on a map:
neighbourhoods_avg_occ_gdf = neighbourhoods_avg_occ.merge(
neighbourhoods_geo['geometry'],
left_on=['neighbourhood_group_cleansed'],
right_on=neighbourhoods_geo['neighbourhood_group'])
neighbourhoods_avg_occ_gdf = gpd.GeoDataFrame(neighbourhoods_avg_occ_gdf, geometry='geometry')
# -
#Use the dissolve function to combine MULTIPOLYGONS (describing the detailed neighbourhoods) to lvl of grouped neighbourhoods:
neighbourhoods_avg_occ_gdf = neighbourhoods_avg_occ_gdf.dissolve(by ='neighbourhood_group_cleansed_short').reset_index()
# +
#Attach a col carrying the center coordinat of each grouped neighbourhood:
neighbourhoods_avg_occ_gdf['coords'] = neighbourhoods_avg_occ_gdf['geometry'].apply(
lambda x: x.representative_point().coords[:])
neighbourhoods_avg_occ_gdf['coords'] = [coords[0] for coords in neighbourhoods_avg_occ_gdf['coords']]
# -
#Using geopandas to visualize above shown avg prices on a map:
fig, ax = plt.subplots(figsize = (20,20))
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=-3)
neighbourhoods_avg_occ_gdf.apply(lambda x: ax.annotate(text=x.neighbourhood_group_cleansed_short, xy=x.geometry.centroid.coords[0], ha='center'),axis=1);
neighbourhoods_avg_occ_gdf.plot(column='occ_per_month', legend = True, ax=ax, cax=cax, cmap='RdYlGn_r')
# # 3. **What's the average revenue of active airbnb listings in Berlin?**
#create sub_df of listings_occupancy to work with:
listings_revenue = listings_occupancy
#Calculate avg_rev_per_month column:
listings_revenue['avg_rev_per_month'] = listings_revenue.occ_per_month * listings_revenue.price
#Calculate the average revenue and sort valued decending:
neighbourhoods_avg_rev = listings_revenue.groupby(
by = ['neighbourhood_group_cleansed_short','neighbourhood_group_cleansed']
).avg_rev_per_month.mean().sort_values(ascending=False).reset_index()
#Merging neighbourhoods_avg_occ_gdf and neighbourhoods_avg_price:
neighbourhoods_avg_rev_gdf = neighbourhoods_avg_occ_gdf.merge(
neighbourhoods_avg_price['price'],
left_on = 'neighbourhood_group_cleansed_short',
right_on = neighbourhoods_avg_price['neighbourhood_group_cleansed_short'])
#Again, calculate the average revenue for the gdf:
neighbourhoods_avg_rev_gdf['avg_rev_per_month'] = neighbourhoods_avg_rev_gdf.occ_per_month * neighbourhoods_avg_rev_gdf.price
#Using geopandas to visualize above shown avg prices on a map:
fig, ax = plt.subplots(figsize = (20,20))
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=-3)
neighbourhoods_avg_rev_gdf.apply(lambda x: ax.annotate(text=x.neighbourhood_group_cleansed_short, xy=x.geometry.centroid.coords[0], ha='center'),axis=1);
neighbourhoods_avg_rev_gdf.plot(column='avg_rev_per_month', legend = True, ax=ax, cax=cax, cmap='RdYlGn_r')
# +
#Using geopandas to visualize above shown avg prices on a map:
fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3,figsize = (20,15))
fig.suptitle('Overview: Average Price, Occupancy & Revenue',fontsize = 16,fontweight = 'bold')
sns.set_palette('RdYlGn',12)
ax1.set_title("Average Listing Price [in $]",fontsize = 12,fontweight = 'bold')
ax2.set_title("Average monthly Occupancy [in days]",fontsize = 12,fontweight = 'bold')
ax3.set_title("Average monthly Revenue [in $]",fontsize = 12,fontweight = 'bold')
ax4.spines["top"].set_visible(False)
ax4.spines["right"].set_visible(False)
ax5.spines["top"].set_visible(False)
ax5.spines["right"].set_visible(False)
ax6.spines["top"].set_visible(False)
ax6.spines["right"].set_visible(False)
neighbourhoods_avg_price_gdf.plot(column='price', ax=ax1, cmap='RdYlGn_r')
neighbourhoods_avg_occ_gdf.plot(column='occ_per_month', ax=ax2, cmap='RdYlGn_r')
neighbourhoods_avg_rev_gdf.plot(column='avg_rev_per_month', ax=ax3, cmap='RdYlGn_r')
sns.barplot(x="price", y = "neighbourhood_group_cleansed_short",orient ="h", data = listings_df, order = neighbourhoods_avg_price.neighbourhood_group_cleansed_short, ax=ax4)
sns.barplot(x="occ_per_month", y = "neighbourhood_group_cleansed_short",orient ="h", data = listings_occupancy, order = neighbourhoods_avg_occ.neighbourhood_group_cleansed_short, ax=ax5)
sns.barplot(x="avg_rev_per_month", y = "neighbourhood_group_cleansed_short",orient ="h", data = listings_revenue, order = neighbourhoods_avg_rev.neighbourhood_group_cleansed_short, ax=ax6)
ax4.set_ylabel('')
ax4.set_xlabel('Average Price [in $]')
ax5.set_ylabel('')
ax5.set_xlabel('Average Occupancy [in days]')
ax6.set_ylabel('')
ax6.set_xlabel('Average Revenue [in $]')
plt.tight_layout(pad=2)
# -
# # 4. **Does being a Superhost effect the average revenue?**
#check number of superhost listings in the df:
listings_revenue.host_is_superhost.sum()
print("{:.2f}% of the considered listings are superhost listings.".format((listings_revenue.host_is_superhost.sum()/listings_revenue.shape[0])*100))
#Map the binary host_is_superhost column to more meaningful strings:
listings_revenue['Superhost?'] = listings_revenue.host_is_superhost.map({1 : 'Superhosts', 0 : 'Not_Superhosts'})
# +
#visualize the data using seaborn:
sns.set_palette("hls", 3)
plot = sns.catplot(x="neighbourhood_group_cleansed_short",
y = "avg_rev_per_month",
data = listings_revenue, height = 5, aspect = 3,
kind="bar",
order = neighbourhoods_avg_price.neighbourhood_group_cleansed_short,
hue = 'Superhost?',
legend_out = False)
(plot.set_axis_labels("Neighbourhoods", "Price [in $]"))
plt.title('Superhost-Impact on the average monthly Revenue', fontsize = 20)
# -
#checking the statistics for our listings_revenue data
#we can see that the std is very high for all neighbourhoods,
#caused on the one hand by low sample sizes and on the other by
#outlier listings (max values) having significantly higher revenue that the average.
listings_revenue.groupby('neighbourhood_group_cleansed_short').avg_rev_per_month.describe()[['count', 'mean', 'std', 'min','max']]
# We can see that being a Superhost has a positive impact on revenue.
print("On average being a Superhost increases revenue by {:.0f}$ in Berlin.".format(
(listings_revenue.loc[listings_revenue.host_is_superhost == 1,].avg_rev_per_month.mean() -
listings_revenue.loc[listings_revenue.host_is_superhost == 0,].avg_rev_per_month.mean()).sum()))
#checking the avg_rev_per_month_Superhosts for each neighbourhood:
avg_rev_per_month_Superhosts = listings_revenue.loc[listings_revenue.host_is_superhost == 1,].groupby('neighbourhood_group_cleansed').avg_rev_per_month.mean()
avg_rev_per_month_Superhosts = avg_rev_per_month_Superhosts.reset_index().sort_values('neighbourhood_group_cleansed')
avg_rev_per_month_Superhosts
# # 5. **How does this compare to the average revenue from normal rent in the neighbourhoods?**
# ##### To answer this question we will use some data from from the web:
# We will use a combination of: <br>
# [statistic_mietwohnung_fanzielle-belastung-in-berlin-2019](https://de.statista.com/themen/1605/wohnimmobilien-in-berlin/) for the average rent paid<br>
# [Berliner Betriebskostenübersicht 2019](https://www.berliner-mieterverein.de/magazin/online/mm0719/berliner-betriebskostenuebersicht-2019-waermekosten-gesunken-kalte-betriebskosten-gestiegen-071921.htm#:~:text=2%2C56%20Euro%20pro%20Quadratmeter,Durchschnittsmieter%20jeden%20Monat%20an%20Betriebskosten.&text=Auff%C3%A4llig%20ist%2C%20dass%20die%20Kosten,niedriger%20als%20vor%20zwei%20Jahren.) for the average utility costs per qm in Berlin<br>
# [Informationen zu den Immobilienpreisen in Berlin 2019](https://web.mcmakler.de/immobilienpreise/berlin?address=¢er=13.657244983654437%2C52.35353625911344&marker=&tp_channel=DE_MCM_AFF_LG_WHGBOERSE&utm_campaign=wohnungsboerse&utm_content=preisatlas&utm_medium=affiliate&utm_source=wohnungsboerse&zoom=12) for the average rent per qm in Berlin
#
# For Eur to USD conversion we will use the ratio $\frac{EUR}{USD} = \frac{1}{1.18}$ (as of Nov 19 2020).
#
#loading statistics:
normal_rent_df = pd.read_csv('Berlin_Rent_and_Utilitiy.csv', sep=";")
normal_rent_df = normal_rent_df.sort_values('neighbourhood_grouped').reset_index(drop= True)
#calculating the normal_net_cold_rent to represent the revenue for a landlord:
normal_rent_df['normal_net_cold_rent'] = (normal_rent_df.Rent_per_month -
(normal_rent_df.Rent_per_month *
(normal_rent_df.Berlin_avg_utility_cost_per_qm/normal_rent_df.Berlin_avg_rent_per_qm)))*1.18
normal_rent_df
# +
#merging normal_rent_df with the Airbnb neighbourhoods_avg_rev_gdf:
compare_avg_rev = neighbourhoods_avg_rev_gdf.merge(
normal_rent_df['normal_net_cold_rent'] ,
left_on='neighbourhood_group_cleansed',
right_on=normal_rent_df['neighbourhood_grouped'])
compare_avg_rev['avg_rev_per_month_Superhosts'] = avg_rev_per_month_Superhosts.avg_rev_per_month
# -
#Calculate the mean for the 3 possibilities we checked out:
compare_avg_rev[['avg_rev_per_month', 'avg_rev_per_month_Superhosts','normal_net_cold_rent']].mean()
#Preparing data to plot using seaborn:
compare_avg_rev.columns = ['Neighbourhoods_Grouped', 'geometry',
'neighbourhood_group_cleansed', 'occ_per_month', 'coords', 'price',
'AirBnb Listings', 'Long Term Lease',
'AirBnb Superhost Listings']
#Preparing data to plot using seaborn:
compare_avg_rev_plot = pd.melt(compare_avg_rev[['Neighbourhoods_Grouped',
'AirBnb Listings', 'Long Term Lease',
'AirBnb Superhost Listings']],
id_vars='Neighbourhoods_Grouped',
var_name='Revenue_Options', value_name='monthly avg Revenue [in $]')
# +
#Plotting the average revenues:
sns.set_palette("hls", 3)
sns.catplot(x='Neighbourhoods_Grouped',
y='monthly avg Revenue [in $]',
hue='Revenue_Options',
data=compare_avg_rev_plot,
kind='bar',
height = 5,
aspect = 3,
legend_out = False,
order = compare_avg_rev.sort_values(by = 'Long Term Lease', ascending=False).Neighbourhoods_Grouped)
plt.title('Neighbourhood\'s average Revenue Comparison \n (assuming every guest leaves a review)', fontsize = 20)
# +
#Let's assume only every second guest leaves a review.
#The estimated occupancy rate would double, and so would the revenue for Airbnb listings:
double_avg_rev = compare_avg_rev
double_avg_rev['AirBnb Listings'] = double_avg_rev['AirBnb Listings'] *2
double_avg_rev['AirBnb Superhost Listings'] = double_avg_rev['AirBnb Superhost Listings'] *2
# -
#Preparing data to plot using seaborn:
double_avg_rev_plot = pd.melt(
compare_avg_rev[['Neighbourhoods_Grouped',
'AirBnb Listings',
'Long Term Lease',
'AirBnb Superhost Listings']],
id_vars='Neighbourhoods_Grouped',
var_name='Revenue_Options', value_name='monthly avg Revenue [in $]')
# +
#Plotting the average revenues:
sns.set_palette("hls", 3)
sns.catplot(x='Neighbourhoods_Grouped',
y='monthly avg Revenue [in $]',
hue='Revenue_Options',
data=double_avg_rev_plot,
kind='bar',
height = 5,
aspect = 3,
legend_out = False,
order = compare_avg_rev.sort_values(by = 'Long Term Lease', ascending=False).Neighbourhoods_Grouped)
plt.title('Neighbourhood\'s average Revenue \n (assuming half the guests leave a review)', fontsize = 20)
| Data Analysis.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] toc=true
# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#Yelp-Data-Challenge---Restaurant-Recommender" data-toc-modified-id="Yelp-Data-Challenge---Restaurant-Recommender-1">Yelp Data Challenge - Restaurant Recommender</a></span><ul class="toc-item"><li><span><a href="#1.-Clean-data-and-get-rating-data" data-toc-modified-id="1.-Clean-data-and-get-rating-data-1.1">1. Clean data and get rating data</a></span></li><li><span><a href="#2.-define-and-select-active-users" data-toc-modified-id="2.-define-and-select-active-users-1.2">2. define and select active users</a></span></li><li><span><a href="#3.-colleborative-filtering-recommender" data-toc-modified-id="3.-colleborative-filtering-recommender-1.3">3. colleborative filtering recommender</a></span></li><li><span><a href="#4.-Recommend-with-Pearsons'-R-correlations" data-toc-modified-id="4.-Recommend-with-Pearsons'-R-correlations-1.4">4. Recommend with Pearsons' R correlations</a></span></li></ul></li></ul></div>
# -
# # Yelp Data Challenge - Restaurant Recommender
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
% matplotlib inline
plt.style.use("ggplot")
df = pd.read_csv('mydata/last_2_years_restaurant_reviews.csv')
df.head()
df_title = df[['business_id','name']]
df_title.set_index('business_id', inplace = True)
df_title.shape
df_title = df_title.drop_duplicates()
# ## 1. Clean data and get rating data
# #### Select relevant columns in the original dataframe
# Get business_id, user_id, stars for recommender
selected_features = ['user_id', 'business_id', 'stars']
df_sel = df[selected_features]
df_sel.info()
df_sel.head(10)
# ## 2. define and select active users
# #### There are many users that haven't given many reviews, exclude these users from the item-item similarity recommender
# According to the following analysis, we totally have 155423 users in the data, and almost two third of them (101861 users) only wrote one review, one seventh of them (25052 users) only wrote two reviews. I decide to exclude users with only one review before building item based recommendor though it means cutting a large portion of data. I assume that users with more than one rating records are active users.
# For those who only has one review, I would recommend based on the popularity of businesses, or use content based recommendor. For example, I would recommend them popular restaurants near the one she or he rated.
df_1 = df_sel.groupby('user_id', as_index = False).count()
df_1.shape
df_1.rename(columns={'stars': '# of reviews'}, inplace=True)
del df_1['business_id']
df_1.head()
df_2 = df_1.groupby('# of reviews').count()
df_2.rename(columns = {'user_id': '# of users'})
cond_count = df_1['# of reviews'] > 1
df_rec = df_1[cond_count]
df_rec.head()
df_rec.info()
active_users = df_rec['user_id']
active_users.head()
df_active = df_sel[df_sel['user_id'].isin(active_users)]
df_active.head(3)
df_active.shape
# After selection, we will use df_active in the recommendor. We are using around two third of the original data, which sounds fine.
# ## 3. colleborative filtering recommender
# +
# #!pip install surprise
# +
# #!pip install seaborn
# +
from surprise import Reader, Dataset, SVD, evaluate
import seaborn as sns
sns.set_style("darkgrid")
reader = Reader()
# get just top 100K rows for faster run time
data = Dataset.load_from_df(df_active, reader)
data.split(n_folds=3)
svd = SVD()
evaluate(svd, data, measures=['RMSE', 'MAE'])
# -
#pick a lucky user
lucky_user_id = '2S6gWE-K3DHNcKYYSgN7xA'
df_lucky
# #### all restaurants reviewed by the lucky user
df_lucky = df[df['user_id'] == lucky_user_id][['business_id','user_id','stars']]
#df_4 = df[(df['user_id'] == 4) & (df['Rating'] == 5)]
df_lucky = df_lucky.set_index('business_id')
df_lucky = df_lucky.join(df_title)['name']
print(df_lucky)
# #### let's predict what restaurants this user will love
# +
user_lucky = df_title.copy()
user_lucky = user_lucky.reset_index()
#user_785314 = user_785314[~user_785314['Movie_Id'].isin(drop_movie_list)]
# getting full dataset
data = Dataset.load_from_df(df[['user_id', 'business_id', 'stars']], reader)
trainset = data.build_full_trainset()
svd.train(trainset)
user_lucky['Estimate_Score'] = user_lucky['business_id'].apply(lambda x: svd.predict(4, x).est) # I know the index of this lucky user is 4
user_lucky = user_lucky.drop('business_id', axis = 1)
user_lucky = user_lucky.sort_values('Estimate_Score', ascending=False)
print(user_lucky.head())
# -
# ## 4. Recommend with Pearsons' R correlations
# +
df_p = pd.pivot_table(df,values='stars',index='user_id',columns='business_id')
print(df_p.shape)
# +
f = ['count','mean']
df_business_summary = df.groupby('business_id')['stars'].agg(f)
df_business_summary.index = df_business_summary.index.map(str)
# -
def recommend(business_title, min_count):
print("For business ({})".format(business_title))
print("- Top 10 restaurants recommended based on Pearsons'R correlation - ")
i = str(df_title.index[df_title['name'] == business_title][0])
target = df_p[i]
similar_to_target = df_p.corrwith(target)
corr_target = pd.DataFrame(similar_to_target, columns = ['PearsonR'])
corr_target.dropna(inplace = True)
corr_target = corr_target.sort_values('PearsonR', ascending = False)
corr_target.index = corr_target.index.map(int)
corr_target = corr_target.join(df_title).join(df_business_summary)[['PearsonR', 'Name', 'count', 'mean']]
print(corr_target[corr_target['count']>min_count][:10].to_string(index=False))
df_title.index[df_title['name'] == "<NAME>"][0]
recommend("Lip Smacking Foodie Tours", 0)
| ml_class/HW#7-_Restaurant_Recommender.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
# ---
# # Algorithmic Trading Basics
#
# <img align="left" width="80" height="200" src="https://img.shields.io/badge/python-v3.6-blue.svg">
# <br>
# ## Notebook by [<NAME>](https://marcotavora.me/)
#
# ### Table of contents
#
# 1. [Summary](#Summary)
# 1. [Definitions](#Definitions)
# 3. [Modules](#Modules)
# 4. [Time Series](#Time-Series)
# 5. [Strategy](#Strategy)
# 6. [Moving Windows](#Moving-Windows)
# ## Summary
# [[go back to the top]](#Table-of-contents)
#
# I will briefly describe:
# - How to build a [trend trading](https://en.wikipedia.org/wiki/Trend_following) strategy
# - How to backtest it
# - How we can optimize it
#
# ### Definitions
# [[go back to the top]](#Table-of-contents)
#
#
# Trend trading can be [defined as](https://en.wikipedia.org/wiki/Trend_following):
#
# > ... a trading strategy according to which one should buy an asset when its price trend goes up, and sell when its trend goes down, expecting price movements to continue.
#
# Again borrowing from [Wikipedia](#https://en.wikipedia.org/wiki/Backtesting), backtesting:
# > ... seeks to estimate the performance of a strategy or model if it had been employed during a past period. This requires simulating past conditions with sufficient detail, making one limitation of backtesting the need for detailed historical data.
# ### Modules
# [[go back to the top]](#Table-of-contents)
# %run modules_algo_trading_v10.ipynb
# ## Data from `yahoo` or `Quandl`
# [[go back to the top]](#Table-of-contents)
start, end = datetime.datetime(2006, 10, 1), datetime.datetime(2012, 1, 1)
apple = pdr.get_data_yahoo('AAPL', start=start, end=end)
apple.head()
# #### Checking for null values
apple.isnull().any().unique()
start, end ="2006-10-01", "2011-01-01"
apple = quandl.get("WIKI/AAPL", start_date=start, end_date=end)
apple.columns = [el.lower().replace('.', '').replace(' ', '_') for el in apple.columns]
apple.head()
plt.rcParams['figure.figsize'] = 16, 8
apple['close'].plot(grid=False, rot=90);
plt.show();
# ## Moving Average Crossover Strategy
# [[go back to the top]](#Table-of-contents)
#
#
# In general, a trading strategy involves going into long and/or short positions following some plan. One example, maybe the simplest, is the **moving average crossover** strategy. Following this strategy, one decides to buy or sell when the time series of two moving averages, with different lookback periods, cross. More concretely:
# - When the short moving average (SMA) becomes greater than the long moving average (LMA), one enter (i.e. buys, or goes long)
# - When the long moving average (LMA) becomes greater than the short moving average (SMA), one exits
#
# Roughly speaking, the *rationale* behind this strategy is the following. Short-term trends are captured using SMA. When the SMA crosses above the LMA, one identifies a short-term upward trend and the stock is purchased. When the LMA crosses above the SMA one does the opposite.
#
# An example of the use of moving averages follows. Consider the first five rows and a window of size 3:
ten_rows = apple[['close']].head()
ten_rows
ten_rows['close'].rolling(window=3, min_periods=1,center=False).mean()
# The third entry is:
window_size = 3
(ten_rows.iloc[0,:] + ten_rows.iloc[1, :] + ten_rows.iloc[2, :])/window_size
# Note that the rows with index smaller than the window are unaltered since the moving average needs are least 3 elements (the window size) to be calculated.
import fix_yahoo_finance as yf
yf.pdr_override()
# The code implementation of this strategy consists in the following steps:
# - First set the sizes of the short moving window `smw` and long moving window `lmw`
# - Create an empty `DataFrame` for signals (called `sig` here) and fill the columns of `sig` with the SMA and LMA values from the `close` price column
#
# The close price column is:
apple[['close']].head()
# The two steps above are:
# +
smw, lmw = 40, 100
signal_df = pd.DataFrame(index=apple.index,
columns = ['sma','lma' ])
signal_df['signal'], signal_df['sma'], signal_df['lma'] = 0.0, 0.0, 0.0
signal_df['sma'] = apple['close'].rolling(window=smw,
min_periods=1,
center=False).mean()
signal_df['lma'] = apple['close'].rolling(window=lmw,
min_periods=1,
center=False).mean()
# -
# - Fill the `signal` column inserting 1s when the value of column `sma` is larger than `lma` only for the period greater than `smw`.
#
# For that we use the `np.where` function. A simple example of the latter is:
lst = np.arange(5,10)
print('lst is:', lst)
print('Insert 1s in the positions of the elements in lst that are smaller than 7 and insert 0s otherwise:')
print(np.where(lst < 7, 1, 0))
signal_df['signal'][smw:] = np.where(signal_df['sma'][smw:] > signal_df['lma'][smw:], 1.0, 0.0)
signal_df.iloc[smw:, :].head(6)
# - Create a column of positions `pos`. Rows correspondig to long positions will have 1s. Notice below e.g. that on 2000-02-07, `sma`>`lma` and one changes the position (buys the stock). In the following day, one still has `sma`>`lma` so the position is kept and the entry in the position column will be 0. The meaning of the `.diff` method is illustrated below. Since:
#
# signal_df.iloc[smw:, :]['sma'][4] = 103.934
# signal_df.iloc[smw:, :]['sma'][3] = 103.206
#
# -> signal_df.iloc[smw:, :]['sma'][4]-signal_df.iloc[smw:, :]['sma'][3] = 0.728
round(signal_df.iloc[smw:, :]['sma'].diff()[4], 3)
round(signal_df.iloc[smw:, :]['sma'][4] - signal_df.iloc[smw:, :]['sma'][3], 3)
signal_df['pos'] = signal_df['signal'].diff()
signal_df.iloc[smw:, :].head(20)
apple.head()
apple.shape
ylabel, col, cols_ma ='price', 'close', ['sma', 'lma']
afa.plot_function_new(apple, signal_df, ylabel, col, cols_ma, 0, apple.shape[0])
# A subsection of the plot makes the strategy clearer:
afa.plot_function_new(apple, signal_df, ylabel, col, cols_ma, 950, 1050)
# ## Backtesting Steps
# [[go back to the top]](#Table-of-contents)
# Steps:
# - We first set the initial capital to, say, 2MM
# - Buy a $N$ shares
# - Initialize the portfolio with value owned initially and store the difference in shares owned
# - Add a `holdings` column containing the values of the positions bought times the adjusted closed price
#
# `cash`, `total` and `return` to portfolio
# - Plot equity curve
# - Plot the "buy" and "sell" trades versus the equity curve
aux = pd.concat([signal_df[['signal']].iloc[smw+3:smw+10, :], apple[['adj_close']].iloc[smw+3:smw+10, :]], axis=1)
aux['holdings'] = 100*aux['signal']*aux['adj_close']
aux
initial_capital, N = 1000000.0, 100
pos = pd.DataFrame(index=signal_df.index).fillna(0.0)
pos['AAPL'] = 100*signal_df['signal']
ptf = pos.multiply(apple['adj_close'], axis=0)
ptf.iloc[smw+3:smw+10, :]
pos_diff = pos.diff()
ptf['holdings'] = (pos.multiply(apple['adj_close'], axis=0)).sum(axis=1)
ptf['cash'] = initial_capital - (pos_diff.multiply(apple['adj_close'], axis=0)).sum(axis=1).cumsum()
ptf['tot'] = (ptf['cash'] + ptf['holdings'])/1000000
ptf['return'] = (ptf['tot'].pct_change())
ptf
df, ylabel, col = ptf, 'portfolio value (MM)', 'tot'
afa.plot_function_3(df, signal_df, ylabel, col, pos, 0, -1)
ptf[['return']].plot();
# ### Sharpe Ratio and Maximum Drawdown
# [[go back to the top]](#Table-of-contents)
#
# The Sharpe ration reads:
#
# $${S_a} = \frac{{E[{R_a} - {R_b}]}}{{{\sigma _a}}} = \frac{{E[{R_a} - {R_b}]}}{{\sqrt {{\rm{var}}[{R_a} - {R_b}]} }},$$
#
# where $R_{a}$ is the asset return and $R_b$ is the risk free rate. From Wikipedia:
#
# > The Sharpe ratio characterizes how well the return of an asset compensates the investor for the risk taken. When comparing two assets versus a common benchmark, the one with a higher Sharpe ratio provides better return for the same risk (or, equivalently, the same return for lower risk).
#
# Using $R_b=0$ for simplicity:
returns = ptf['return']
sharpe_ratio = np.sqrt(252)*(returns.mean() / returns.std())
print('sharpe_ratio is:',round(sharpe_ratio, 3))
# The maximum drawdown measures the largest drop in portfolio value of a portfolio.
# +
import auxiliar as af
window = 252
rolling_max = apple['adj_close'].rolling(window, min_periods=1).max()
daily_drawdown = (apple['adj_close']/rolling_max - 1.0)
max_daily_drawdown = daily_drawdown.rolling(window, min_periods=1).min()
daily_drawdown.plot()
# -
max_daily_drawdown.plot()
plt.show();
daily_drawdown.plot()
max_daily_drawdown.plot()
plt.show();
af.s_to_df(max_daily_drawdown, 'daily_drawdown').sort_values(by = 'daily_drawdown', ascending=True)
| trading-algorithms/notebooks/algorithmic-trading-basic-strategies.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# %config InlineBackend.figure_format = 'svg'
## Disable Warnings
tf.logging.set_verbosity(tf.logging.ERROR)
# -
# ### Download MNIST Data Set and load into those variables
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
fig, axes= plt.subplots(1,4, figsize=(7,3))
for img, label, ax in zip(x_train[:4], y_train[:4], axes):
ax.set_title(label)
ax.imshow(img)
ax.axis('off')
plt.show()
# ### We must flatten the images and scale them from 0-1
x_train = x_train.reshape(60000, 784) / 255
x_test = x_test.reshape(10000, 784) / 255
# ### Create a one hot-array for the y-values
# ### Creates an array of 10 elements
# +
with tf.Session() as sesh:
y_train = sesh.run(tf.one_hot(y_train, 10))
y_test = sesh.run(tf.one_hot(y_test, 10))
y_train[:4]
# +
# hyper parameters
learning_rate = 0.01
epochs = 50
# Divide the total number of pictues by the batch size to get num of batches
batch_size = 100
batches = int(x_train.shape[0] / batch_size)
# -
# Y is a 10 element list. x is a 784 element long list since we flattened it. w is a matrix of size 784 x 10. b is a 10 element matrix. y = wx + b
# ## Inputs:
# ### X is the "flattened / normalized: images
# ### Y is the "one hot' labels
# +
X = tf.placeholder(tf.float32, [None, 784])
Y = tf.placeholder(tf.float32, [None, 10])
W = tf.Variable(np.random.randn(784, 10).astype(np.float32))
B = tf.Variable(np.random.randn(10).astype(np.float32))
# -
# ### Softmax function converts all prediction scores to probabilities and makes the sum of the probabilities equal to 1.
pred = tf.nn.softmax(tf.add(tf.matmul(X,W), B))
| .ipynb_checkpoints/Logistic-Regression-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: TensorFlow-GPU
# language: python
# name: tf-gpu
# ---
import numpy as np
import scipy as sc
import pandas as pd
import matplotlib.pylab as plt
vetor_x = np.array([sc.cos(x) for x in np.linspace(0, 120, 28*28*10000)])
plt.plot(vetor_x)
from tensorflow.keras import layers, losses
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras.models import Model
import tensorflow as tf
# +
latent_dim = 16
class Autoencoder(Model):
def __init__(self, encoding_dim):
super(Autoencoder, self).__init__()
self.latent_dim = latent_dim
self.encoder = tf.keras.Sequential([
layers.Flatten(),
layers.Dense(latent_dim, activation='relu'),
])
self.decoder = tf.keras.Sequential([
layers.Dense(784, activation='sigmoid'),
layers.Reshape((28, 28))
])
def call(self, x):
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded
autoencoder = Autoencoder(latent_dim)
# -
autoencoder.compile(optimizer='adam', loss='mae')
# +
from sklearn.model_selection import train_test_split
x_train, x_test = train_test_split(vetor_x.reshape(28,28,10000).T)
# +
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
print (x_train.shape)
print (x_test.shape)
# -
autoencoder.fit(x_train, x_train,
epochs=100,
shuffle=True,
validation_data=(x_test, x_test))
encoded_imgs = autoencoder.encoder(x_test).numpy()
decoded_imgs = autoencoder.decoder(encoded_imgs).numpy()
n = 10
plt.figure(figsize=(20, 4))
for i in range(n):
# display original
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i])
plt.title("original")
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# display reconstruction
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow(decoded_imgs[i])
plt.title("reconstructed")
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
plt.plot(decoded_imgs[0][0])
plt.plot(x_test[0][0], c='g')
| notebook/checagem de sanindade.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="5QGOnWkVRR1P" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 547} outputId="fbbe6526-c904-4111-d6cf-3a58fa7cd44d"
"""
create by: <NAME>
Date: 2020.6.26
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder
from sklearn.metrics import mean_squared_error
from math import sqrt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge
from sklearn.linear_model import ElasticNet
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
df = pd.read_csv('nyc-rolling-sales.csv')
# df.head(100)
df.head()
# + [markdown] id="Eo5gK6nE-G6L" colab_type="text"
# #1) Data Clean
# + [markdown] id="TUBrhCUO_6gV" colab_type="text"
# First of all, we want to drop thoese useless columns and to check whether there are any duplicate values in our dataset. If there is any, we will need to drop them.
# + id="2m-kVUmMSGNy" colab_type="code" colab={}
# "Unname: 0" column looks like useless, drop it.
del df['Unnamed: 0']
#"EASE-MENT" column is empty, we are going to drop it.
del df['EASE-MENT']
#del df['SALE DATE']
# + id="Cvqw8SvN_457" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="4011cdb1-9697-4b8e-b86f-c4b25bccab78"
sum(df.duplicated(df.columns))
df = df.drop_duplicates(df.columns, keep='last')
df.shape
# + [markdown] id="I7UWV8-UBFzA" colab_type="text"
# Now, Let's look into details.
# + id="htSGOtHWUvQf" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 476} outputId="c41c042e-c60c-41f8-86a0-2ea6f4aa119f"
df.info()
# + [markdown] id="20mGNQvqLwJd" colab_type="text"
# After browsing the information of dataset, we can see they use "-" to represent the missing values. Before prediction, we should clean these rows in the data table. Some of them should not be counted as the sale of real estate. For example, in column "SALE PRICE", these properties with 0 value might be transferred as a gift.
#
# Before cleaning missing values, We need to convert some of the columns(for example, SALE PRICE is object, SALE DATE is object, etc) to appropriate datatype.
# + id="y6Ti1ywdEuNz" colab_type="code" colab={}
df['SALE PRICE'] = pd.to_numeric(df['SALE PRICE'], errors='coerce')
#df['SALE DATE'] = pd.to_datetime(df['SALE DATE'], errors='coerce')
df['LAND SQUARE FEET'] = pd.to_numeric(df['LAND SQUARE FEET'], errors='coerce')
df['GROSS SQUARE FEET']= pd.to_numeric(df['GROSS SQUARE FEET'], errors='coerce')
df['TAX CLASS AT PRESENT'] = df['TAX CLASS AT PRESENT'].astype('category')
df['TAX CLASS AT PRESENT'] = df['TAX CLASS AT PRESENT'].astype('category')
df['BOROUGH'] = df['BOROUGH'].astype('category')
# + id="dqpzQNboMZdl" colab_type="code" colab={}
df['SALE DATE'] = df['SALE DATE'].apply(lambda x: int(x[:4]+x[5:7]+x[8:10]))
df['SALE DATE'] = df['SALE DATE'].astype(int)
# + id="j95V0sE0S-tw" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="7e0c2cb0-434a-4315-d891-1f7bac16896d"
df.shape
# + id="74ejJcPNHlFX" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 476} outputId="1eab9950-0ac7-45f9-99f7-feb7f98dbca2"
df.info()
# + id="7bxrLnLiEG_7" colab_type="code" colab={}
variables = df.columns
data = []
for variable in variables:
l = df[variable].count()
data.append(l)
available_per = np.round(pd.Series(data)/len(df), 3)
# + id="tKiqJIuZEiGI" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 392} outputId="046207bd-9d44-47b7-9bb2-b04d3f650062"
plt.figure(figsize=(8,6))
plt.barh(variables, available_per)
plt.title("Percent of available data", fontsize=15)
plt.show()
# + [markdown] id="SDz8IvrdF4Oz" colab_type="text"
# As shown in the figure, SALE PRICE, GROSS SQUARE FEET and LAND SQUARE FEET have the lowest percent of available data. But again, SALE PRICE is the value we wanted to predict, and as the data set description states:
#
# *Many sales occur with a nonsensically small dollar amount: $0 most commonly. These sales are actually transfers of deeds between parties: for example, parents transferring ownership to their home to a child after moving out for retirement.* We may want to drop those rows.
#
# For SQUARE FEET, in this case, we will use mean values to fill them up.
# + id="A_MFibUyM3Fp" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="85293d92-a319-43c5-abff-6cef163ac28f"
df=df[df['SALE PRICE']!=0]
df['LAND SQUARE FEET']=df['LAND SQUARE FEET'].fillna(df['LAND SQUARE FEET'].mean())
df['GROSS SQUARE FEET']=df['GROSS SQUARE FEET'].fillna(df['GROSS SQUARE FEET'].mean())
df.shape
# + id="r0aWxeKKOdH0" colab_type="code" colab={}
# Splitting dataset
test=df[df['SALE PRICE'].isna()]
sale_house=df[~df['SALE PRICE'].isna()]
# + id="e1FDQ8zL7YiG" colab_type="code" colab={}
test = test.drop(columns='SALE PRICE')
# + id="PqKUdXdd7dXQ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 564} outputId="20518262-1156-41e1-f1f3-8f2a47977bf7"
print(test.shape)
test.head()
# + [markdown] id="Wnal5oAeNIG7" colab_type="text"
# Now Let's recap and revisit the details of the remaining dataset.
# + id="_y_fK8Pw70Bd" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 974} outputId="cf9e6453-b5d2-4418-9401-1bf67356b79f"
print(sale_house.shape)
sale_house.head(10)
# + id="OP5UYq4fOx_9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 351} outputId="b5f6d0e5-ea84-4f30-ca5e-b004e965c1e9"
sale_house.describe()
# + [markdown] id="em3V3l818Kxy" colab_type="text"
# According to the above chart, we can observe that
#
# 1) The min value for ZIP CODE is 0, we don't have ZIP CODE that equals to 0
#
# 2) The Building Year of some properties are 0, this should be incorrect as well.
#
# 3) Some properties have 0 SQUARE FEET...
#
# Let's fix them
#
# ####TODO
# + [markdown] id="nLKmBT8ri_kX" colab_type="text"
# ZIP CODE
# + id="MsR7OfLejGWJ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 516} outputId="6e2a6845-e018-4e93-ba14-1621d117f0ec"
plt.figure(figsize=(10,8))
plt.title(' ZIP CODE ')
plt.xlim(0,12000)
sale_house['ZIP CODE'].value_counts().sort_index().plot.line()
# + id="q8WV6zVej4-_" colab_type="code" colab={}
sale_house = sale_house[(sale_house['ZIP CODE'] != 0)]
# + id="3IOsH6YtkYrR" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 286} outputId="857437e8-c55f-4306-be57-74a8f66c3eb3"
sale_house['ZIP CODE'].value_counts().sort_index().plot.line()
# + [markdown] id="ElMJbcRSc7ra" colab_type="text"
# BUILDING YEAR
# + id="OcCfBJo6dCUZ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 516} outputId="16756a0d-9d9e-45fe-e64a-036797d66dc0"
plt.figure(figsize=(10,8))
plt.title(' Year Built ')
plt.xlim(1500,2020)
sale_house['YEAR BUILT'].value_counts().sort_index().plot.line()
# + id="ua6tt2U2gLFL" colab_type="code" colab={}
sale_house = sale_house[(sale_house['YEAR BUILT'] > 1875)]
# + id="ibyJ9XSJiXXK" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 282} outputId="6a6c6055-c8a9-41ad-bf2a-003c6b3d5ae2"
sale_house['YEAR BUILT'].value_counts().sort_index().plot.line()
# + [markdown] id="m6vleZKW9UK1" colab_type="text"
# Finally, it's time check the outliers in our datasets, let's first look into the column sale price.
#
# ####SALE PRICE
# + id="5LPz59-c9dlc" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 350} outputId="f1c09b13-7ad7-4c29-f02b-88a4cf8ec5cf"
plt.figure(figsize=(10,5))
sns.boxplot(x='SALE PRICE', data=sale_house)
plt.ticklabel_format(style='plain', axis='x')
plt.title('SALE PRICE in USD')
plt.show()
# + id="Y42-Cfcn9nfj" colab_type="code" colab={}
sale_house = sale_house[(sale_house['SALE PRICE'] > 0) & (sale_house['SALE PRICE'] < 500000000)]
# + id="4RlLJs9__bwD" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 307} outputId="a20c9382-c9e8-4925-8dde-d3e3ccb6ecd4"
sns.distplot(sale_house['SALE PRICE'])
# + id="vcsEPct4_kPP" colab_type="code" colab={}
sale_house = sale_house[(sale_house['SALE PRICE'] > 0) & (sale_house['SALE PRICE'] < 5000000)]
# + id="9h9dHhas_skG" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 307} outputId="b862c7bb-2efa-4158-a2cd-567a47fa0907"
sns.distplot(sale_house['SALE PRICE'])
# + [markdown] id="k9UfItZ5_9u8" colab_type="text"
# ####SQUARE FEET
# + id="cKNAb2HFAQb8" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 798} outputId="45e86008-b9c8-41ba-b987-dc8aa0acaa42"
sale_house = sale_house[sale_house['GROSS SQUARE FEET'] < 10000]
sale_house = sale_house[sale_house['LAND SQUARE FEET'] < 10000]
plt.figure(figsize=(10,6))
sns.regplot(x='GROSS SQUARE FEET', y='SALE PRICE', data=sale_house, fit_reg=False, scatter_kws={'alpha':0.3})
plt.figure(figsize=(10,6))
sns.regplot(x='LAND SQUARE FEET', y='SALE PRICE', data=sale_house, fit_reg=False, scatter_kws={'alpha':0.3})
# + [markdown] id="CilCOp1OAx5W" colab_type="text"
# ####UNIT NUMBER
# + id="SBWj9jY8AVOn" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 700} outputId="385eb6f5-6017-4fb9-b182-5f6ff54df5f7"
sale_house[["TOTAL UNITS", "SALE PRICE"]].groupby(['TOTAL UNITS'], as_index=False).count().sort_values(by='SALE PRICE', ascending=False)
# + id="wLs9YzluA3pX" colab_type="code" colab={}
sale_house = sale_house[(sale_house['TOTAL UNITS'] > 0) & (sale_house['TOTAL UNITS'] != 2261)]
# + id="tY2u_0RMA-_F" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 404} outputId="cb9efbd3-8f67-4c15-8b96-fa984c0c4386"
plt.figure(figsize=(10,6))
sns.boxplot(x='TOTAL UNITS', y='SALE PRICE', data=sale_house)
plt.title('Total Units vs Sale Price')
plt.show()
# + [markdown] id="jzTyJ11ic3ys" colab_type="text"
# #2) Preparation
# + id="glwjK_96BTTT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="4b0be505-864e-4e0a-e73a-782daacc347e"
#"Apartment Number" only has few values, so we are going to drop it.
print("The percent of rows with null in apartment number:" +str(sum(df['APARTMENT NUMBER']==' ')/len(df)))
del sale_house['APARTMENT NUMBER']
del sale_house['ADDRESS']
del sale_house['NEIGHBORHOOD']
del sale_house['BUILDING CLASS AT PRESENT']
del sale_house['BUILDING CLASS AT TIME OF SALE']
# + id="fIuac0OuPMs-" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 852} outputId="b3c64017-6eac-4bff-a042-8991f8dfb7c2"
cor = sale_house.corr()
fig, ax = plt.subplots(figsize=(12,12))
sns.heatmap(cor,annot=True, ax = ax)
# + [markdown] id="4TeZJpNBddbW" colab_type="text"
# Removing highing correlated independent variable from datasets.
# + id="JpRlhINndvj4" colab_type="code" colab={}
# sale_house.drop(['RESIDENTIAL UNITS','GROSS SQUARE FEET',],inplace=True, axis=1)
# sale_house.head()
# + id="s2OQJ0MXd1IS" colab_type="code" colab={}
#one hot encoded
#https://machinelearningmastery.com/why-one-hot-encode-data-in-machine-learning/
one_hot_features = ['BOROUGH', 'BUILDING CLASS CATEGORY','TAX CLASS AT PRESENT','TAX CLASS AT TIME OF SALE']
# + id="KT9VYrsWd5qy" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="9a6107ca-2057-4a0f-9fbb-75e9d9474f0c"
# Convert categorical variables into dummy/indicator variables (i.e. one-hot encoding).
one_hot_encoded = pd.get_dummies(sale_house[one_hot_features])
one_hot_encoded.info(verbose=True, memory_usage=True, null_counts=True)
# + id="IYR_n7VKeBTi" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 351} outputId="1fe8cfb0-5d59-4df3-b590-f1d19736bc59"
numeric_data=sale_house.select_dtypes(include=[np.number])
numeric_data.describe()
# + id="EnM7qgYGeHyg" colab_type="code" colab={}
df = sale_house
scaler = StandardScaler()
scaler.fit(df[numeric_data.columns])
scaled = scaler.transform(df[numeric_data.columns])
for i, col in enumerate(numeric_data.columns):
df[col] = scaled[:,i]
# + id="jhGGAXpgeT-0" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 343} outputId="4e70e14f-df31-4118-b95c-b61c602333f0"
df.drop(one_hot_features,axis=1,inplace=True)
df = pd.concat([df, one_hot_encoded] ,axis=1)
df.head()
# + id="0lBz50Ujebua" colab_type="code" colab={}
# classifying data into independent and dependent variable
X = df.drop(['SALE PRICE'],axis = 1).values
y = df['SALE PRICE'].values
# + id="M2ke98sJeeB6" colab_type="code" colab={}
# creating test and training set data, 70% train, 30% test
X_train,X_test,y_train,y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)
# + [markdown] id="zEIhN0Q09_-J" colab_type="text"
# #3) Predition
# + [markdown] id="bPvvtPLXgXbd" colab_type="text"
# ##3.0)Helper Function
# + id="LJr7swCEgWKf" colab_type="code" colab={}
def rmse(y_test,y_pred):
return np.sqrt(mean_squared_error(y_test,y_pred))
# + [markdown] id="74cEg17tf-m8" colab_type="text"
# ##3.1) Linear
# + id="bh90cNyal8kG" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="a77329a6-8e67-4f37-a555-9e16fbda1e9e"
linear=LinearRegression()
linear.fit(X_train, y_train)
y_pred = linear.predict(X_test)
result_linear = rmse(y_test, y_pred)
result_linear
# + [markdown] id="Bw0-mV6ggCiY" colab_type="text"
# ##3.2)Ridge, Lasso
# + id="ub5SG-zEegva" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="4231b95c-dfd2-4a81-9ec6-db96d8d7fca3"
# fitting linear regression to training set
regressor = Ridge(alpha=0.01, normalize=True)
regressor.fit(X_train,y_train)
# + id="BQff_gtvfZhp" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="e19b6399-3984-4113-f62b-02d67f9e12b2"
y_pred = regressor.predict(X_test)
result_ridge = rmse(y_test, y_pred)
result_ridge
# + id="ZVUCZyaZg4pW" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="fdbef0a5-6c17-4eea-9a9d-7d6e0f3dcd3e"
#3.6)Lasso
Lassoregressor = Lasso(alpha = 0.01, normalize =True)
Lassoregressor.fit(X_train,y_train)
y_predict = Lassoregressor.predict(X_test)
result_Lasso = rmse(y_test, y_predict)
result_Lasso
# + [markdown] id="jt6Sq1GNgJ9O" colab_type="text"
# ##3.3)Random Forest
# + id="IwDCfHKrKCzg" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 119} outputId="5f19f6fd-3eb7-427a-f501-f6aa1758fe53"
from sklearn.tree import DecisionTreeRegressor
dtree = DecisionTreeRegressor()
dtree.fit(X_train, y_train)
# + id="ZJdqOQVTMHJX" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="858087ff-fd49-4ae2-fd07-d77d7e72be2e"
y_pred = dtree.predict(X_test)
result_dt = rmse(y_test, y_pred)
result_dt
# + id="tLVsW_Y-NQf-" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 136} outputId="86c3e7db-5753-40cc-d332-956d54f4716f"
dforest = RandomForestRegressor(n_estimators=100, criterion='mse', bootstrap=True, n_jobs=-1)
dforest.fit(X_train, y_train)
# + id="m6I68PflPaH1" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="24842594-3da1-48cf-c2e0-3f6ff784311d"
y_pred = dforest.predict(X_test)
result_rf = rmse(y_test, y_pred)
result_rf
# + [markdown] id="ZLQx6ESrgOAU" colab_type="text"
# ##3.4)Gradient boosting
# + id="a_0VaQyEvZzT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="f8ff1b2b-2f90-4596-9a51-a1cfe877e9d7"
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import GridSearchCV
reg = GradientBoostingRegressor(n_estimators=100)
reg.fit(X_train, y_train)
pre = reg.predict(X_test)
result_gl = rmse(y_test, pre)
result_gl
# + [markdown] id="aS7_IqiUMkQa" colab_type="text"
# ## 3.5)AdaBoost
# + id="PtIbX0TEMqB4" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="c0ac6318-99b3-48e3-b284-6d47451fccf7"
from sklearn.ensemble import AdaBoostRegressor
from sklearn.model_selection import GridSearchCV
reg = AdaBoostRegressor(n_estimators=100,learning_rate=0.05)
reg.fit(X_train, y_train)
pre = reg.predict(X_test)
result_ada = rmse(y_test, pre)
result_ada
# + [markdown] id="A7JEu6n3GAKr" colab_type="text"
# ##3.6) Stacked
# + id="25oSQEzDGgSz" colab_type="code" colab={}
from sklearn.linear_model import ElasticNet, Lasso, BayesianRidge, LassoLarsIC
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.kernel_ridge import KernelRidge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import RobustScaler
from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.metrics import mean_squared_error
import xgboost as xgb
import lightgbm as lgb
# + [markdown] id="MBJp44UciEp0" colab_type="text"
# This time we add a cross validation approach.
# + id="rL5iKnCcusWI" colab_type="code" colab={}
n_folds = 5
def rmsle_cv(model):
kf = KFold(n_folds, shuffle=True, random_state=42).get_n_splits(X_train)
rmse= np.sqrt(-cross_val_score(model, X_train, y_train, scoring="neg_mean_squared_error", cv = kf))
return(rmse)
# + id="mk973mMbyHG3" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="84e2548f-69af-4967-ca6f-0fbf9470f4cb"
lasso = make_pipeline(RobustScaler(), Lasso(alpha =0.0005, random_state=1))
score = rmsle_cv(lasso)
print("\nLasso score: {:.4f} ({:.4f})\n".format(score.mean(), score.std()))
# + id="dNNFPpG1ytyd" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="bf86b207-e41b-4b5c-d9bc-6c268a920093"
ridge = make_pipeline(RobustScaler(), Ridge(alpha =0.01, random_state=1))
score = rmsle_cv(ridge)
print("\nridge score: {:.4f} ({:.4f})\n".format(score.mean(), score.std()))
# + id="4I13ZBSqy_eV" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="93e99987-33dd-47b2-ab8b-acb9279dfcf6"
elastic = make_pipeline(RobustScaler(), ElasticNet(alpha =0.01, random_state=1))
score = rmsle_cv(elastic)
print("\nElastic score: {:.4f} ({:.4f})\n".format(score.mean(), score.std()))
# + id="kq58t6F5tjHC" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="2952a876-afa8-4e14-9ff0-127a01aac0b6"
dforest = RandomForestRegressor(n_estimators=100, criterion='mse', bootstrap=True, n_jobs=-1)
score = rmsle_cv(dforest)
print("\nRandomF score: {:.4f} ({:.4f})\n".format(score.mean(), score.std()))
# + id="cbmXNZRMzJvO" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="754a4ff1-b134-470a-fd6f-457c1705b6fe"
model_gb = GradientBoostingRegressor(n_estimators=100)
score = rmsle_cv(model_gb)
print("GB score: {:.4f} ({:.4f})\n" .format(score.mean(), score.std()))
# + id="ChvNyd51zZzj" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="78680e20-ad4d-41ab-a92d-971965af717f"
ada = AdaBoostRegressor(n_estimators=100,learning_rate=0.05)
score = rmsle_cv(ada)
print("AdaBoost Ridge score: {:.4f} ({:.4f})\n".format(score.mean(), score.std()))
# + id="lr8kGxx47V0P" colab_type="code" colab={}
class StackingAveragedModels(BaseEstimator, RegressorMixin, TransformerMixin):
def __init__(self, base_models, meta_model, n_folds=5):
self.base_models = base_models
self.meta_model = meta_model
self.n_folds = n_folds
# Fit the data on clones of the original models
def fit(self, X, y):
self.base_models_ = [list() for x in self.base_models]
self.meta_model_ = clone(self.meta_model)
kfold = KFold(n_splits=self.n_folds, shuffle=True, random_state=156)
# Train cloned base models then create out-of-fold predictions
# that are needed to train the cloned meta-model
out_of_fold_predictions = np.zeros((X.shape[0], len(self.base_models)))
for i, model in enumerate(self.base_models):
for train_index, holdout_index in kfold.split(X, y):
instance = clone(model)
self.base_models_[i].append(instance)
instance.fit(X[train_index], y[train_index])
y_pred = instance.predict(X[holdout_index])
out_of_fold_predictions[holdout_index, i] = y_pred
# Now train the cloned meta-model using the out-of-fold predictions as new feature
self.meta_model_.fit(out_of_fold_predictions, y)
return self
#Do the predictions of all base models on the test data and use the averaged predictions as
#meta-features for the final prediction which is done by the meta-model
def predict(self, X):
meta_features = np.column_stack([
np.column_stack([model.predict(X) for model in base_models]).mean(axis=1)
for base_models in self.base_models_ ])
return self.meta_model_.predict(meta_features)
# + id="yoZegQ487Wx-" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="0b26adfe-4018-4340-ed58-5d17ee075907"
stacked_averaged_models = StackingAveragedModels(base_models = (model_gb, ridge, elastic, ada, dforest),
meta_model = lasso)
score = rmsle_cv(stacked_averaged_models)
print("Stacking Averaged models score: {:.4f} ({:.4f})".format(score.mean(), score.std()))
# + id="jrk-002181TW" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="c11875c4-d179-40af-84fa-69bc99f6fa6d"
stacked_averaged_models.fit(X_train, y_train)
stacked_train_pred = stacked_averaged_models.predict(X_train)
stacked_pred = np.expm1(stacked_averaged_models.predict(X_test))
print(rmse(y_train, stacked_train_pred))
| work history/NYC_Property_updated.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %load_ext autoreload
# %autoreload 2
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns
import sys
sys.path.append('modeling')
from viz import viz_interactive, viz
from modeling import exponential_modeling
from bokeh.plotting import figure, show, output_notebook, output_file, save
from functions import merge_data
import load_data
from plotly.offline import init_notebook_mode, iplot
from fit_and_predict import add_preds
import json
from functions import update_severity_index as severity_index
from functions import emerging_index
plt.style.use('dark_background')
df = load_data.load_county_level()
df = df.sort_values('tot_deaths', ascending=False)
df = add_preds(df, NUM_DAYS_LIST=[1, 2, 3, 4, 5], cached_dir='data') # adds keys like "Predicted Deaths 1-day"
important_vars = load_data.important_keys(df)
print(df.keys())
df['tot_deaths_per_capita'] = df['tot_deaths'] / df['PopulationEstimate2018']
df['tot_cases_per_capita'] = df['tot_cases'] / df['PopulationEstimate2018']
# ## how many deaths/cases are there
df[['tot_deaths', 'tot_cases', 'StateName', 'CountyName', 'Predicted Deaths 1-day']].head(10)
# s = f'Predicted Deaths {2}-day' # tot_deaths
s = 'tot_deaths'
num_days = 1
nonzero = df[s] > 0
plt.figure(dpi=300, figsize=(7, 3))
plt.plot(df[s].values, '.', ms=3)
plt.ylabel(s)
plt.xlabel('Counties')
# plt.yscale('log')
plt.tight_layout()
plt.show()
# +
R, C = 1, 2
NUM_COUNTIES = 9
plt.figure(dpi=500, figsize=(8, 4))
# cs = sns.diverging_palette(20, 220, n=NUM_COUNTIES)
cs = sns.color_palette("husl", NUM_COUNTIES)
for i in range(NUM_COUNTIES):
row = df.iloc[i]
deaths = np.array([x for x in row['deaths'] if x > 0])
cases = np.array([x for x in row['cases'] if x > 0])
CASES_ALIGNMENT = 100
idx_align = np.where(cases > CASES_ALIGNMENT)[0][0]
n = cases.size
DEATHS_ALIGNMENT = 10
idx_align_deaths = np.where(deaths > DEATHS_ALIGNMENT)[0][0]
n2 = deaths.size
plt.subplot(R, C, 1)
plt.plot(np.arange(n) - idx_align, cases, alpha=0.5, label=row['CountyName'] + ' County')#, color=cs[i])
# plt.yscale('log')
plt.ylabel('Cumulative confirmed cases')
plt.xlabel(f'Days since {CASES_ALIGNMENT} cases')
plt.legend()
plt.subplot(R, C, 2)
plt.plot(np.arange(n2) - idx_align_deaths, deaths, alpha=0.5, color=cs[i])
# plt.yscale('log')
plt.ylabel('Cumulative deaths')
plt.xlabel(f'Days since {DEATHS_ALIGNMENT} deaths')
plt.tight_layout()
plt.show()
# -
# # correlations
# +
d = df[[k for k in important_vars if not 'PopMale' in k and not 'PopFmle' in k and not 'MortalityAge' in k and not 'PopTotal' in k] +
['tot_cases', 'tot_cases_per_capita', 'tot_deaths', 'tot_deaths_per_capita']]
viz.corrplot(d)
plt.savefig('results/correlations_heatmap.png')
plt.show()
# -
corrs = d.corr()
keys = np.array(corrs.index)
k = np.where(keys == 'tot_deaths')[0][0]
corrs_row = corrs.iloc[k]
args = np.argsort(corrs_row)
plt.figure(dpi=300, figsize=(6, 5))
plt.barh(keys[args][:-1], corrs_row[args][:-1]) # 1 to drop outcome itself
plt.xlabel('Correlation (spearman) with tot_deaths')
plt.tight_layout()
# plt.savefig('results/correlations.png')
plt.show()
# +
ks = ['PopulationDensityperSqMile2010', "TotalM.D.'s,TotNon-FedandFed2017", 'unacast_n_grade']
R, C = 1, len(ks)
plt.figure(dpi=300, figsize=(C * 3, R * 3))
for c in range(C):
plt.subplot(R, C, c + 1)
if c == 0:
plt.ylabel('tot_deaths')
plt.loglog(d[ks[c]], d['tot_deaths'], '.')
plt.xlabel(ks[c])
plt.tight_layout()
plt.show()
# -
# # interactive plots
ks = [k for k in important_vars if not 'PopMale' in k
and not 'PopFmle' in k
and not 'MortalityAge' in k]
# **individual states no slider**
# +
# filter by state
for state in ['NY', 'WA', 'CA']:
d = df[df["StateNameAbbreviation"] == state]
p = viz_interactive.plot_counties(d,
variable_to_distribute='tot_cases',
variables_to_display=ks,
state=state,
logcolor=False)
# output_file(f"results/{state.lower()}.html", mode='inline')
# show(p)
# save(p)
# -
# **counties slider**
# add lat and lon to the dataframe
county_lat_lon = pd.read_csv('data/county_pop_centers.csv', dtype={'STATEFP': str, 'COUNTYFP': str})
county_lat_lon['fips'] = (county_lat_lon['STATEFP'] + county_lat_lon['COUNTYFP']).astype(np.int64)
# join to df and rename columns
df = df.join(county_lat_lon.set_index('fips'), on='countyFIPS', how='left').rename(
columns={'LATITUDE' : 'lat', 'LONGITUDE' : 'lon'}
)
# Just plot the bubbles...
viz_interactive.plot_counties_slider(df)
# ...or plot choropleth too. Much slower and the map is less responsive
# read in county geojson
counties_json = json.load(open("data/geojson-counties-fips.json", "r"))
viz_interactive.plot_counties_slider(df, n_past_days=1, filename="results/deaths_choropleth.html",
plot_choropleth=True, counties_json=counties_json)
# **political leaning**
# filter by state
for state in ['NY', 'WA', 'CA']:
d = df[df["StateNameAbbreviation"] == state]
p = viz_interactive.plot_counties(d,
variable_to_distribute='dem_to_rep_ratio',
variables_to_display=ks,
state=state,
logcolor=False)
show(p)
# **viz curves**
df_tab = df[['tot_deaths', 'tot_cases', 'CountyName', 'StateName',
'PopulationDensityperSqMile2010',
'deaths', 'cases']].head(12)
# df_tab = df_tab.rename(columns={'PopulationEstimate2018': 'Population\n(thousands})'})
df_tab = df_tab.rename(columns={'PopulationDensityperSqMile2010': 'PopDensity'})
df_tab = df_tab.rename(columns={'tot_deaths': '#Deaths', 'tot_cases': '#Cases'})
df_tab = df_tab.rename(columns={'CountyName': 'County', 'StateName': 'State'})
print(df_tab.keys())
# df_tab['Population']
keys_table = [k for k in df_tab.keys() if not k in ['deaths', 'cases']]
viz_interactive.viz_curves(df_tab,
key_toggle='County',
keys_table=keys_table,
filename='results/county_curves.html')
print('done!')
# **Emerging counties index**
target_days=[1,2,3,4,5]
n_days_past=5
emerging_index.add_emerging_index(df, target_days=target_days, n_days_past=n_days_past, min_deaths=15)
df.sort_values('emerging_index', ascending=False)[['CountyName', 'StateNameAbbreviation', 'emerging_index',
'#Deaths_4/2/2020', '#Deaths_4/3/2020',
'#Deaths_4/4/2020', '#Deaths_4/5/2020',
'#Deaths_4/6/2020', '#Deaths_4/7/2020',
'Predicted Deaths 1-day', 'Predicted Deaths 2-day',
'Predicted Deaths 3-day', 'Predicted Deaths 4-day',
'Predicted Deaths 5-day']].head(10)
viz_interactive.plot_emerging_hotspots_grid(df, target_days=target_days, n_days_past=n_days_past)
emerging_index.add_emerging_index(df, 'emerging_index_2', target_days=target_days,
n_days_past=n_days_past, min_deaths=15)
df['emerging_index_diff'] = df['emerging_index'] - df['emerging_index_2']
df['emerging_index_rank'] = df['emerging_index'].rank()
df.sort_values('emerging_index_2', ascending=False)[['CountyName', 'StateNameAbbreviation', 'emerging_index',
'emerging_index_rank', 'emerging_index_2', 'emerging_index_diff',
'#Deaths_4/2/2020', '#Deaths_4/3/2020',
'#Deaths_4/4/2020', '#Deaths_4/5/2020',
'#Deaths_4/6/2020', '#Deaths_4/7/2020',
'Predicted Deaths 1-day', 'Predicted Deaths 2-day',
'Predicted Deaths 3-day', 'Predicted Deaths 4-day',
'Predicted Deaths 5-day']].head(20)
| county_quickstart.ipynb |
// -*- coding: utf-8 -*-
// ---
// jupyter:
// jupytext:
// text_representation:
// extension: .cpp
// format_name: light
// format_version: '1.5'
// jupytext_version: 1.14.4
// kernelspec:
// display_name: C++14
// language: C++14
// name: xeus-cling-cpp14
// ---
// + [markdown] slideshow={"slide_type": "slide"}
// 
// + [markdown] slideshow={"slide_type": "subslide"}
// ## <NAME>
// + [markdown] slideshow={"slide_type": "fragment"}
// * Ingeniero aeroespacial
// + [markdown] slideshow={"slide_type": "fragment"}
// * Desarrollador de software (**C++**, **Fortran**, **Python**, **Javascript**)
// + [markdown] slideshow={"slide_type": "fragment"}
// * **Github**: https://github.com/newlawrence
// + [markdown] slideshow={"slide_type": "fragment"}
// * **Twitter**: [@newlawrence](https://twitter.com/newlawrence?lang=es)
// + [markdown] slideshow={"slide_type": "slide"}
// # ¿Era necesario otro párser más de expresiones matemáticas?
// + [markdown] slideshow={"slide_type": "fragment"}
// La respuesta...
// + [markdown] slideshow={"slide_type": "fragment"}
// ### No
//
// Existen muchos, y muy buenos, pársers de expresiones matemáticas ahí fuera...
// + [markdown] slideshow={"slide_type": "subslide"}
// |# | Library | Author | License | Numeric Type |
// | --- | :-------------------------------------------------------- | :-----------------------------| :---------------------------------------------------------| :--------------------:|
// | 00 | [ATMSP](http://sourceforge.net/projects/atmsp/) | <NAME> | [GPL v3](http://www.opensource.org/licenses/gpl-3.0.html) | double, MPFR |
// | 01 | [ExprTk](http://www.partow.net/programming/exprtk/) | <NAME> | [MIT](https://opensource.org/licenses/MIT) | double, float, MPFR |
// | 02 | [FParser](http://warp.povusers.org/FunctionParser/) | <NAME> & <NAME> | [LGPL](http://www.gnu.org/copyleft/lesser.html) | double |
// | 03 | [Lepton](https://simtk.org/home/lepton) | <NAME> | [MIT](https://opensource.org/licenses/MIT) | double |
// | 04 | [MathExpr](http://www.yann-ollivier.org/mathlib/mathexpr) | <NAME> | [Copyright Notice 1997-2000](http://www.yann-ollivier.org/mathlib/mathexpr#C) | double |
// | 05 | [METL](https://github.com/TillHeinzel/METL) | <NAME> | [Apache](https://opensource.org/licenses/Apache-2.0) | double |
// | 06 | [MTParser](http://www.codeproject.com/Articles/7335/An-extensible-math-expression-parser-with-plug-ins)| <NAME> | [CPOL](http://www.codeproject.com/info/cpol10.aspx)| double |
// | 07 | [muParser](http://muparser.beltoforion.de) | <NAME> | [MIT](http://www.opensource.org/licenses/mit-license.php) | double, float |
// | 08 | [muParserX](http://muparserx.beltoforion.de) | <NAME> | [MIT](http://www.opensource.org/licenses/mit-license.php) | double, float |
// | 09 | [TinyExpr](https://github.com/codeplea/tinyexpr) | <NAME> | [Zlib](https://opensource.org/licenses/Zlib) | double |
//
// **Fuente:** [Math Parser Benchmark Project](https://github.com/ArashPartow/math-parser-benchmark-project)
// + [markdown] slideshow={"slide_type": "subslide"}
// Aunque se usan todos, más o menos, así:
// + [markdown] slideshow={"slide_type": "fragment"}
// ```c++
// double x, y;
// te_variable vars[] = {{"x", &x}, {"y", &y}};
// int err;
//
// te_expr *expr = te_compile("sqrt(x^2+y^2)", vars, 2, &err);
// if (expr) {
// x = 3; y = 4;
// const double h1 = te_eval(expr); /* Returns 5. */
// te_free(expr);
// } else {
// printf("Parse error at %d\n", err);
// }
// ```
//
// Ejemplo de uso del párser [**TinyExpr**](https://github.com/codeplea/tinyexpr).
// + [markdown] slideshow={"slide_type": "subslide"}
// ¿En realidad hace falta toda esta maquinaria para definir una función?
// + [markdown] slideshow={"slide_type": "fragment"}
// ```c++
// template <typename T>
// struct foo : public exprtk::ifunction<T> {
// foo() : exprtk::ifunction<T>(3) {}
//
// T operator()(const T& v1, const T& v2, const T& v3) {
// return T(1) + (v1 * v2) / T(v3);
// }
// };
// ```
//
// Ejemplo de uso del párser [**ExprTk**](https://github.com/ArashPartow/exprtk).
// + [markdown] slideshow={"slide_type": "subslide"}
// ¿No puede existir algo...
// + [markdown] slideshow={"slide_type": "fragment"}
// ...así?
//
// ```c++
// auto expr = parser.parse("sqrt(x^2+y^2)");
// expr(3, 4);
//
// parser.functions.insert({
// "f",
// [](double v1, double v2, double v3) { return 1 + (v1 * v2) / v3 }
// });
// ```
// + [markdown] slideshow={"slide_type": "subslide"}
// ## ¿Qué ofrece Calculate?
// + [markdown] slideshow={"slide_type": "fragment"}
// * Sólo archivos de cabecera.
// + [markdown] slideshow={"slide_type": "fragment"}
// * Genérica.
// + [markdown] slideshow={"slide_type": "fragment"}
// * Símbolos definidos por el usuario.
// + [markdown] slideshow={"slide_type": "fragment"}
// * Reglas del analizador léxico personalizables.
// + [markdown] slideshow={"slide_type": "fragment"}
// * Interfaz no intrusiva.
// + [markdown] slideshow={"slide_type": "fragment"}
// * **C++** moderno (estándar **C++14**).
// + [markdown] slideshow={"slide_type": "subslide"}
// ## ¿De qué elementos se compone Calculate?
// + [markdown] slideshow={"slide_type": "fragment"}
// * Clase **Parser**.
// + [markdown] slideshow={"slide_type": "fragment"}
// * Clase **Lexer**.
// + [markdown] slideshow={"slide_type": "fragment"}
// * Subclases de **Symbol**: **Constant**, **Function**, **Operator**.
// + [markdown] slideshow={"slide_type": "fragment"}
// * Clase **Expression**.
// + [markdown] slideshow={"slide_type": "slide"}
// # Uso básico de la biblioteca
// + slideshow={"slide_type": "skip"}
#pragma cling add_include_path("calculate2.1.1rc6")
// + slideshow={"slide_type": "fragment"}
#include "calculate.hpp"
// + [markdown] slideshow={"slide_type": "fragment"}
// ## Instanciar un parser
// + slideshow={"slide_type": "fragment"}
auto parser = calculate::Parser{};
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Crear expresiones atendiendo a su notación
// + [markdown] slideshow={"slide_type": "fragment"}
// **Calculate** permite parsear expresiones escritas tanto en notación infija como posfija:
// + slideshow={"slide_type": "fragment"}
double result;
// + slideshow={"slide_type": "fragment"}
auto e1 = parser.from_infix("1+2*3");
result = e1;
result
// + slideshow={"slide_type": "fragment"}
auto e2 = parser.from_postfix("1 2 3 * +");
result = e2;
result
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Crear expresiones con variables
// + [markdown] slideshow={"slide_type": "fragment"}
// Aquellos símbolos que no se encuentren cargados en un párser harán saltar una excepción:
// + slideshow={"slide_type": "skip"}
#include <iostream>
// + slideshow={"slide_type": "fragment"}
try {
parser.from_infix("x");
}
catch (const calculate::BaseError& error) {
std::cout << error.what() << std::endl;
}
// + [markdown] slideshow={"slide_type": "subslide"}
// Es posible especificar qué símbolos se han de tratar como variables al momento de construir un objeto expresión. Las expresiones se evalúan como si de funciones regulares se tratase.
// + slideshow={"slide_type": "fragment"}
auto e3 = parser.from_infix("x+y", "x", "y");
e3(1, 2) // x == 1, y == 2
// + slideshow={"slide_type": "fragment"}
auto e4 = parser.from_postfix("x y +", "x", "y");
e4(1, 2) // x == 1, y == 2
// + [markdown] slideshow={"slide_type": "subslide"}
// Los objetos de la clase **Parser** proveen además de un método adicional **parse** que va añadiendo a la lista de variables aquellos símbolos que no están previamente cargados según van apareciendo en la expresión:
// + slideshow={"slide_type": "fragment"}
auto e5 = parser.parse("a-b");
for (const auto& variable : e5.variables())
std::cout << variable << " ";
std::cout << std::endl;
e5(1, 2) // a == 1, b == 2
// + [markdown] slideshow={"slide_type": "slide"}
// # La clase Parser
// + [markdown] slideshow={"slide_type": "fragment"}
// * Posee un tipo objetivo **Parser::Type** (**double** por defecto).
// + [markdown] slideshow={"slide_type": "fragment"}
// * Provee de los métodos para crear expresiones.
// + [markdown] slideshow={"slide_type": "fragment"}
// * Permite generar las expresiones precalculando las ramas constantes de las mismas.
// + [markdown] slideshow={"slide_type": "fragment"}
// * Dispone de unos contenedores para los distintos tipos de símbolos: **constantes**, **operadores** y **funciones**.
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Optimizar una expresión
// + slideshow={"slide_type": "fragment"}
parser.parse("1+2+x").infix()
// + [markdown] slideshow={"slide_type": "fragment"}
// Para generar expresiones precalculando aquellas ramas constantes se modifica el atributo **optimize** del objeto **parser**:
// + slideshow={"slide_type": "fragment"}
parser.optimize = true;
parser.parse("1+2+x").infix()
// + [markdown] slideshow={"slide_type": "subslide"}
// ### ¡Atención!
// + [markdown] slideshow={"slide_type": "fragment"}
// **Calculate** no dispone de capacidades **CAS**, sólo puede optimizar aquellas ramas para el árbol que ella misma genera. No es capaz de transformar dicho árbol a una forma canónica para llevar a cabo optimizaciones más evidentes desde el punto de vista matemático.
// + slideshow={"slide_type": "fragment"}
parser.parse("1+x+2").infix()
// + slideshow={"slide_type": "skip"}
parser.optimize = false;
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Contenedores de símbolos
// + [markdown] slideshow={"slide_type": "fragment"}
// Los objetos de la clase **Parser** tienen contenedores específicos para:
// + slideshow={"slide_type": "fragment"}
{ parser.constants; } // Constantes
// + slideshow={"slide_type": "fragment"}
{ parser.functions; } // Funciones
// + slideshow={"slide_type": "fragment"}
{ parser.operators; } // Operadores
// + [markdown] slideshow={"slide_type": "subslide"}
// Los contenedores proveen una interfaz equivalente a la de la clase **unordered_map** de la **STL** (con algunas licencias en cuanto a la implementación):
// + slideshow={"slide_type": "fragment"}
result = parser.constants["pi"];
result
// + slideshow={"slide_type": "fragment"}
for (const auto& operator_pair : parser.operators)
std::cout << operator_pair.first << " ";
std::cout << std::endl;
// + [markdown] slideshow={"slide_type": "subslide"}
// Por ejemplo, añadir una constante es tan sencillo como:
// + slideshow={"slide_type": "fragment"}
parser.constants.insert({"G", {6.674e-11}}); // Gravitación universal
// + slideshow={"slide_type": "fragment"}
auto f_grav = parser.from_infix("G * m1 * m2 / r^2", "m1", "m2", "r");
f_grav(1, 5.972e24, 6371e3) // Gravedad terrestre en superficie
// + [markdown] slideshow={"slide_type": "slide"}
// # Las subclases de la clase Símbolo
// + [markdown] slideshow={"slide_type": "fragment"}
// Como ya se vio, las expresiones pueden estar formadas por tres tipos de símbolos diferentes (sin contar los paréntesis y la coma de separación propios de la notación posfija):
// + [markdown] slideshow={"slide_type": "fragment"}
// * Constantes
// + [markdown] slideshow={"slide_type": "fragment"}
// * Funciones
// + [markdown] slideshow={"slide_type": "fragment"}
// * Operadores
// + [markdown] slideshow={"slide_type": "fragment"}
// *Existe un cuarto tipo, las **Variables**, pero estas pertenecen al funcionamiento interno del párser y sólo existen para proporcionar la habilidad a las expresiones de funcionar como invocables. A efectos prácticos, funcionan como las constantes.*
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Constantes
// + [markdown] slideshow={"slide_type": "fragment"}
// Envuelven valores del tipo al que esté orientado el párser (**double** en el caso del parser por defecto).
// + slideshow={"slide_type": "fragment"}
calculate::Parser::Constant c{1};
double{c}
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Funciones
// + [markdown] slideshow={"slide_type": "fragment"}
// Son capaces de envolver cualquier tipo de invocable, siempre que todos sus argumentos (un número indefinido de ellos) y el resultado sean del tipo al que está orientado el párser:
// -
double sum(double x, double y) { return x + y; }
// + slideshow={"slide_type": "fragment"}
calculate::Parser::Function f{sum};
f(2, 2)
// + [markdown] slideshow={"slide_type": "subslide"}
// En el caso de funtores, estos han de tener su operador llamada declarado como constante (las funciones matemáticas no tienen efectos secundarios).
// + slideshow={"slide_type": "fragment"}
class Plus {
double _x;
public:
Plus(double x) : _x{x} {}
double operator()(double x) const { return x + _x; }
};
// + slideshow={"slide_type": "fragment"}
f = Plus(2);
f(2)
// + [markdown] slideshow={"slide_type": "subslide"}
// Dado que el número de argumentos del operador llamada de los objetos de la clase **Function** es indefinido, los errores en el número de ellos pasan al tiempo de ejecución:
// + slideshow={"slide_type": "fragment"}
try {
f(2, 2);
}
catch (const calculate::BaseError& error) {
std::cout << error.what() << std::endl;
}
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Operadores
// + [markdown] slideshow={"slide_type": "fragment"}
// Al igual que las funciones, envuelven invocables, pero además poseen dos atributos adicionales:
// + [markdown] slideshow={"slide_type": "fragment"}
// * Su precedencia (dada por un entero sin signo).
// + [markdown] slideshow={"slide_type": "fragment"}
// * Su asociatividad (por la izquierda, por la derecha o ambas).
// + [markdown] slideshow={"slide_type": "subslide"}
// Por ejemplo, el operador **+** por defecto:
// + slideshow={"slide_type": "fragment"}
calculate::Parser::Operator plus = parser.operators["+"];
// + [markdown] slideshow={"slide_type": "fragment"}
// Tiene menor precedencia que el operador **\*** por defecto:
// + slideshow={"slide_type": "fragment"}
bool{plus.precedence() < parser.operators["*"].precedence()}
// + [markdown] slideshow={"slide_type": "fragment"}
// Y es asociativo por ambos lados:
//
// $(1 + 2) + 3 == 1 + (2 + 3)$
// + slideshow={"slide_type": "fragment"}
bool{plus.associativity() == calculate::Parser::Associativity::FULL}
// + [markdown] slideshow={"slide_type": "slide"}
// # El Analizador Léxico
// + [markdown] slideshow={"slide_type": "fragment"}
// La clase **Lexer** contiene el conjunto de reglas que se utilizan para separar y clasificar los elementos que conforman la expresión:
// + slideshow={"slide_type": "fragment"}
auto& lexer = parser.lexer();
for (const auto& t : lexer.tokenize_infix("1+sin(2*pi*x)"))
std::cout << t.token << " ";
std::cout << std::endl;
// + [markdown] slideshow={"slide_type": "subslide"}
// A su vez, el analizador léxico tiene definidas las funciones para convertir del tipo objetivo del párser a cadena:
// + slideshow={"slide_type": "fragment"}
lexer.to_string(1.234)
// + [markdown] slideshow={"slide_type": "fragment"}
// Y viceversa:
// + slideshow={"slide_type": "fragment"}
lexer.to_value("1.234")
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Expresiones regulares
// + [markdown] slideshow={"slide_type": "fragment"}
// El analizador léxico se sirve de expresiones regulares para determinar qué debe ser tratado como un número, qué como el nombre de una constante o función, y qué como un operador:
// + slideshow={"slide_type": "fragment"}
lexer.number
// + slideshow={"slide_type": "fragment"}
lexer.name
// + slideshow={"slide_type": "fragment"}
lexer.sign
// + [markdown] slideshow={"slide_type": "fragment"}
// [Ejemplo interactivo](https://regex101.com/r/5Z1KBc/1).
// + [markdown] slideshow={"slide_type": "subslide"}
// **Calculate** permite crear parsers especificando otros conjuntos de expresiones regulares:
// + slideshow={"slide_type": "fragment"}
auto l1 = calculate::lexer_from_regexes<calculate::Parser::Type>(
calculate::defaults::number<calculate::Parser::Type>,
calculate::defaults::name,
R"(^(?:[^A-Za-z\d.(),_\s]|(?:\.(?!\d)))$)"
);
auto p1 = calculate::Parser{l1};
// + [markdown] slideshow={"slide_type": "fragment"}
// En el ejemplo, se ha modificado la lógica que dictamina qué es un operador. El párser por defecto tiende a unir todos los símbolos no alfanuméricos que encuentra al estilo de **Haskell**, por lo que la siguiente prueba no sería posible saltando una excepción indicando que el operador **\*-** no está definido:
// + slideshow={"slide_type": "fragment"}
p1.parse("2*-1").infix()
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Símbolos propios de la notación posfija
// + [markdown] slideshow={"slide_type": "fragment"}
// La notación posfija requiere de dos elementos que modifiquen la prioridad de las operaciones (los paréntesis):
// + slideshow={"slide_type": "fragment"}
lexer.left
// + slideshow={"slide_type": "fragment"}
lexer.right
// + [markdown] slideshow={"slide_type": "fragment"}
// A su vez, también necesita de un símbolo adicional para separar los argumentos de las funciones (la coma):
// + slideshow={"slide_type": "fragment"}
lexer.separator
// + [markdown] slideshow={"slide_type": "subslide"}
// **Calculate** permite modificar también todos estos elementos para adaptarlos a las necesidades del usuario:
// + slideshow={"slide_type": "fragment"}
auto l2 = calculate::Lexer<calculate::Parser::Type>{
calculate::defaults::number<calculate::Parser::Type>,
calculate::defaults::name,
R"(^(?:[^A-Za-z\d.\[\];_\s]|(?:\.(?!\d)))+$)",
"[", "]", ";" // Símbolos deseados
};
auto p2 = calculate::Parser{l2};
// + [markdown] slideshow={"slide_type": "fragment"}
// En el ejemplo, se ha modificado la expresión regular que determina qué es un símbolo para que excluya a los nuevos símbolos de prioridad (ahora corchetes) y al nuevo separador (ahora el punto y coma):
// + slideshow={"slide_type": "fragment"}
p2.parse("pow[a;b]")(2, 3)
// + [markdown] slideshow={"slide_type": "slide"}
// # Los objetos de la clase Expresión
// + [markdown] slideshow={"slide_type": "fragment"}
// Los objetos expresión son el producto último de la biblioteca **Calculate**. Son la representación del concepto matemático y exponen una serie de métodos que los hacen sentir como tal, más allá del hecho de ser funtores en en el sentido de **C++**.
// + slideshow={"slide_type": "fragment"}
auto expr1 = parser.parse("1+2*3-4/5");
// + [markdown] slideshow={"slide_type": "fragment"}
// ¿Cuál es el nodo raíz de la anterior expresión?
// + slideshow={"slide_type": "fragment"}
expr1.token()
// + [markdown] slideshow={"slide_type": "subslide"}
// La principal característica de las expresiones es que son, a su vez los nodos de su propio árbol.
// + slideshow={"slide_type": "fragment"}
expr1.branches()
// + [markdown] slideshow={"slide_type": "fragment"}
// Las ramas de una expresión son objetos expresión:
// + slideshow={"slide_type": "fragment"}
expr1[0].infix()
// + slideshow={"slide_type": "fragment"}
expr1[1].infix()
// + [markdown] slideshow={"slide_type": "subslide"}
// Gracias a ello, es posible navegar por el propio árbol interno de la expresión:
// + slideshow={"slide_type": "skip"}
expr1.begin() // Cling and its oddities
// + slideshow={"slide_type": "fragment"}
void print_tree(const calculate::Parser::Expression& expr) {
using NodeIterator = calculate::Parser::Expression::const_iterator;
std::stack<std::pair<NodeIterator, NodeIterator>> nodes;
std::string indent;
nodes.push({expr.begin(), expr.end()});
std::cout << expr.token() << std::endl;
while (!nodes.empty()) {
auto node = nodes.top().first, end = nodes.top().second;
nodes.pop();
if (node != end) {
std::cout << indent << "\\_ " << node->token() << std::endl;
nodes.push({node + 1, end});
if (node->branches()) {
nodes.push({node->begin(), node->end()});
indent += " ";
}
}
else
if (indent.length() > 3)
indent.erase(indent.length() - 3);
else
indent = "";
}
}
// + [markdown] slideshow={"slide_type": "subslide"}
// Así, de la expresión:
// + slideshow={"slide_type": "fragment"}
expr1.infix()
// + [markdown] slideshow={"slide_type": "fragment"}
// He aquí el árbol:
// + slideshow={"slide_type": "fragment"}
print_tree(expr1)
// + [markdown] slideshow={"slide_type": "subslide"}
// Las variables de las subexpresiones (y, por lo tanto, el número de argumentos) también se adaptan según se navega por el árbol.
// + slideshow={"slide_type": "fragment"}
auto expr2 = parser.parse("x+y");
expr2.variables()
// + [markdown] slideshow={"slide_type": "fragment"}
// Si bien, es necesario realizar copias de las subexpresiones ya que la generación de nuevas variables para las subexpresiones es cara y no se realiza cuando simplemente se piden las referencias:
// + slideshow={"slide_type": "fragment"}
auto expr3 = expr2[0];
expr3.variables()
// + slideshow={"slide_type": "fragment"}
auto expr4 = expr2[1];
expr4.variables()
// + [markdown] slideshow={"slide_type": "slide"}
// # Extendiendo Calculate
// + [markdown] slideshow={"slide_type": "fragment"}
// **Calculate** no es sólo una biblioteca orientada al parseo de expresiones matemáticas al uso; también aporta la capacidad de crear pársers personalizados basados en las notaciones **infija** y **posfija** y el algortimo de [Shunting Yard](https://es.wikipedia.org/wiki/Algoritmo_shunting_yard) para convertir de la una en la otra.
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Parser de números complejos
// + [markdown] slideshow={"slide_type": "fragment"}
// **Calculate** provee por defecto de un párser de expresiones cuyo tipo de dato objetivo son los números complejos cuyo funcionamiento es idéntico al, hasta ahora, expuesto párser orientado a números reales.
// + slideshow={"slide_type": "fragment"}
auto complex_parser = calculate::ComplexParser{};
// Identidad de Euler
std::real(complex_parser.parse("exp(-1i * pi) + 1")())
// + [markdown] slideshow={"slide_type": "subslide"}
// ## Creación de un párser de números enteros
// + [markdown] slideshow={"slide_type": "fragment"}
// **Calculate** no dispone por defecto de un párser de números enteros, pero crear uno es muy sencillo. Sólo hay que heredar de la clase plantilla **BaseParser** y proveer en el constructor todas aquellas constantes, funciones y operadores que se desee vengan precargados.
// + slideshow={"slide_type": "fragment"}
namespace calculate {
class IntegerParser : public BaseParser<int> {
public:
IntegerParser() : BaseParser<Type>{lexer_from_defaults<Type>()} {
using namespace defaults;
operators.insert({
{"+", {add<Type>, Precedence::low, Associativity::FULL}},
{"-", {sub<Type>, Precedence::low, Associativity::LEFT}},
{"*", {mul<Type>, Precedence::normal, Associativity::FULL}},
{"/", {div<Type>, Precedence::normal, Associativity::LEFT}},
});
}
};
}
// + slideshow={"slide_type": "fragment"}
auto integer_parser = calculate::IntegerParser{};
int{integer_parser.parse("1 + 2 * 3")}
// + [markdown] slideshow={"slide_type": "subslide"}
// ### ¡Atención!
// + [markdown] slideshow={"slide_type": "fragment"}
// El procedimiento para crear pársers cuyo tipo de dato objetivo **no sea numérico** requiere de implementar a su vez un analizador léxico para dicho tipo dato.
// + [markdown] slideshow={"slide_type": "fragment"}
// [Prueba de concepto](https://wandbox.org/permlink/GsI6ZenLXJW5xpXl) de la creación de un párser cuyo tipo de dato objetivo son cadenas.
// + [markdown] slideshow={"slide_type": "slide"}
// # ¡Eso es todo!
// + [markdown] slideshow={"slide_type": "fragment"}
// *The most dangerous phrase in the language is "we've always done it this way." -* ***<NAME> <NAME>***
| 180726_calculate/calculate.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
# ---
# +
# default_exp inference
# -
# # Inference
#
# > This contains the code required for inference.
# export
from fastai.learner import load_learner
from fastai.callback.core import GatherPredsCallback
from fastai.learner import Learner
from fastcore.basics import patch
from fastcore.meta import delegates
#export
@patch
def get_X_preds(self: Learner, X, y=None, bs=64, with_input=False, with_decoded=True, with_loss=False):
if with_loss and y is None:
print("cannot find loss as y=None")
with_loss = False
dl = self.dls.valid.new_dl(X, y=y)
if bs: setattr(dl, "bs", bs)
else: assert dl.bs, "you need to pass a bs != 0"
output = list(self.get_preds(dl=dl, with_input=with_input, with_decoded=with_decoded, with_loss=with_loss, reorder=False))
if with_decoded and len(self.dls.tls) >= 2 and hasattr(self.dls.tls[-1], "tfms") and hasattr(self.dls.tls[-1].tfms, "decodes"):
output[2 + with_input] = self.dls.tls[-1].tfms.decode(output[2 + with_input])
return tuple(output)
# Get the predictions and targets, optionally with_input and with_loss.
#
# with_decoded will also return the decoded predictions (it reverses the transforms applied).
#
# The order of the output is the following:
#
# - input (optional): if with_input is True
# - **probabiblities** (for classification) or **predictions** (for regression)
# - **target**: if y is provided. Otherwise None.
# - **predictions**: predicted labels. Predictions will be decoded if with_decoded=True.
# - loss (optional): if with_loss is set to True and y is not None.
from tsai.data.external import get_UCR_data
dsid = 'OliveOil'
X, y, splits = get_UCR_data(dsid, split_data=False)
X_test = X[splits[1]]
y_test = y[splits[1]]
learn = load_learner("./models/test.pth")
# ⚠️ Warning: load_learner (from fastai) requires all your custom code be in the exact same place as when exporting your Learner (the main script, or the module you imported it from).
test_probas, test_targets, test_preds = learn.get_X_preds(X_test, with_decoded=True)
test_probas, test_targets, test_preds
test_probas2, test_targets2, test_preds2 = learn.get_X_preds(X_test, y_test, with_decoded=True)
test_probas2, test_targets2, test_preds2
test_probas3, test_targets3, test_preds3, test_losses3 = learn.get_X_preds(X_test, y_test, with_loss=True, with_decoded=True)
test_probas3, test_targets3, test_preds3, test_losses3
from fastcore.test import test_eq
test_eq(test_probas, test_probas2)
test_eq(test_preds, test_preds2)
test_eq(test_probas, test_probas3)
test_eq(test_preds, test_preds3)
#hide
from tsai.imports import create_scripts
from tsai.export import get_nb_name
nb_name = get_nb_name()
create_scripts(nb_name);
| nbs/052a_inference.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] deletable=true editable=true
# Higher Order Methods
# ====================
#
# The Heun Method is an example of a more general class of numerical solvers known as Runge-Kutta solvers. See the slides for details, but basically you can classify RK solvers by the way they step in time and how they weight the extrapolated results in the final answer.
#
# <img width="250" src="https://raw.githubusercontent.com/sspickle/sci-comp-notebooks/master/imgs/butcher-tab.png">
#
# One particular choise of weights that is very popular is the RK4 table:
#
# <img width="250" src="https://raw.githubusercontent.com/sspickle/sci-comp-notebooks/master/imgs/rk4-table.png">
#
# Which leads to the RK4Step function:
#
# def RK4Step(s, dt, t, derivs):
# f1 = derivs(s, t)*dt
# f2 = derivs(s+f1/2.0, t+dt/2.0)*dt
# f3 = derivs(s+f2/2.0, t+dt/2.0)*dt
# f4 = derivs(s+f3, t+dt)*dt
# return s + (f1+2*f2+2*f3+f4)/6.0
#
# Symplectic Methods
# ==================
#
# Some kinds of systems have properties that make even high order RK methods unsatisfactory. These are systems where Energy (and other quantities) are conserved. These are called "Hamiltonian" systems due to the extensive history of applying the Hamiltonian (Energy oriented) formalism to their solution. See the slides for more details of the Hamiltonian formalism. The RK algorithms focus on reducing trucation error, but do not respect any inherantly conserved quantities. *Symplectic* methods are designed to exactly conserve these quantities at the possible expense of some truncation error. The simplest of these is the *SymplecticEuler* method (sometimes knows as the *Cromer* method). A second order version is the *Verlet* method, or the "Leapfrog" method.
#
# def EulerStep(s, t, derivs, dt):
# return s + derivs(s,t)*dt
#
# def SymplecticEulerStep(s, t, derivs, dt):
# s1 = s + derivs(s,t,0)*dt # q-step
# return s1 + derivs(s1,t,1)*dt # p-step
#
# def VerletStep(s, t, derivs, dt):
# dth = dt/2.0 # half of h
# s = s + derivs(s, t, 0)*dth # changes only positon
# s = s + derivs(s, t+dth, 1)*dt # changes only velocity
# return s + derivs(s, t+dt, 0)*dth # change only position
#
# Notice that when the SymplecticEulerStep and VerletStep methods call derivs they add a third argument. This argument tells the derivs function whether the step is a "space step, or q-step" (pass a zero) or a "velocity step, or p-step" (pass a one). If the derivs function detects that a third argument has been passed it should return zero in the rate of change of the "other" part of the state (e.g., if it's a "space step" then the rate of change of the velocity (or momentum) should be zero). In this way the VerletStep function can carefully craft a sequence of steps that take care to conserve area in phase space (and energy in the long run, even though they may be less accurate in the short run).
#
# Below are some examples of EulerStep, SymplecticEulerStep, RK4Step and VerletStep applied to the simple harmonic oscillator.
# + deletable=true editable=true
# %pylab inline
# + deletable=true editable=true
def EulerStep(s, t, derivs, dt):
"""
Step whichever way derivs says to go.
"""
return s + derivs(s,t)*dt
def SymplecticEulerStep(s, t, derivs, dt):
"""
Take two steps, one in only "q", one in only "p" direction.
"""
s1 = s + derivs(s,t,0)*dt # q-step (only change position)
return s1 + derivs(s1,t,1)*dt # p-step (only change momentum)
# + deletable=true editable=true
k=1.0
m=1.0
def derivs_sho(s, t, step=None):
"""
Simple harmonic oscillator derivs for symplectic and non-symplectic
The 'state' array (s) now has an ensemble of oscillators with slightly
different initial conditions. The first n elements are the positions
and the second half are the velocities.
"""
n=int(len(s)/2) # the first half of s is 'q', second half 'p'
v=s[n:]
if step==0:
return append(v, zeros(n)) # for q-steps, just update the position
# no need to compute 'a'
else:
x=s[:n] # only extract x and compute a if we need it.
a=-k*x/m
if step is None: # it must be an RK4 step
return append(v,a)
else: # velocity step
return append(zeros(n),a) # for p-steps, just updated the velocity
# + deletable=true editable=true
rcParams['figure.figsize']=(7.,7.)
DO_SYMPLECTIC=False # Change "DO_SYMPLECTIC" to True or False to switch between
# SymplecticEuler and Euler "step" functions.
delta=0.1 # how far apart in phase space are the points
s0= array([1.0,0.0])
s1=s0 + array([delta, 0])
s2=s0 + array([delta,delta])
s3=s0 + array([0, delta]) # four points in phase space
t = 0.0
dt = pi/10
s = array(list(flatten(array([s0,s1,s2,s3,s0]).T))) # state of four objects -> [x1,x2,x3,x4,x5,v1,v2,v3,v4,v5]
# (fifth object is same as first to "close the box")
print("s(at t=0)=",s)
n = int(len(s)/2)
clf()
if DO_SYMPLECTIC:
title("Harmonic Oscillator Phase Space: Symplectic Euler")
wsize=1.4
else:
title("Harmonic Oscillator Phase Space: Euler")
wsize=2.5
axes().set_aspect('equal')
axis([-wsize,wsize,-wsize,wsize])
xlabel("position")
ylabel("momentum (or velocity since m=1)")
plot(s[:n], s[n:], 'r-',s[:n],s[n:],'b.')
while t<1.9*pi:
if DO_SYMPLECTIC:
s=SymplecticEulerStep(s, t, derivs_sho, dt)
else:
s=EulerStep(s, t, derivs_sho, dt)
t+=dt
plot(s[:n], s[n:], 'r-',s[:n],s[n:],'b.')
# + deletable=true editable=true
def VerletStep(s, t, derivs, dt):
dth = dt/2.0 # half of h
s = s + derivs(s, t, 0)*dth # changes only positon
s = s + derivs(s, t+dth, 1)*dt # changes only velocity from s1
return s + derivs(s, t+dt, 0)*dth # change only position
def RK4Step(s, t, derivs, dt):
"""
Take a single RK4 step.
"""
dth=dt/2.0
f1 = derivs(s, t)
f2 = derivs(s+f1*dth, t+dth)
f3 = derivs(s+f2*dth, t+dth)
f4 = derivs(s+f3*dt, t+dt)
return s + (f1+2*f2+2*f3+f4)*dt/6.0
# + deletable=true editable=true
x=1.0
v=0.0
t=0.0
dt=0.3
tlist=[t] # times
erlist=[0.5] # RK4 Energies
evlist=[0.5] # Verlet Energies
sr=array([x,v]) # state (RK4)
sv=array([x,v]) # state (Verlet)
while t<3000*pi:
sr = RK4Step(sr, t, derivs_sho, dt) # take each "type" of step
sv = VerletStep(sv, t, derivs_sho, dt)
t += dt
tlist.append(t)
Er = 0.5*sr[1]**2 + 0.5*sr[0]**2 # compute energies
Ev = 0.5*sv[1]**2 + 0.5*sv[0]**2
erlist.append(Er)
evlist.append(Ev)
title("SHO Energies")
xlabel("time (s)")
ylabel("energy (J)")
plot(tlist, erlist, 'r-', label="RK4")
plot(tlist, evlist, 'g-', label="Verlet")
legend(loc=3)
# + [markdown] deletable=true editable=true
# Notice that the RK4 method, being 4th order, is much more "accurate" in the short term (the variations in energy are much smaller) in the long run the energy drifts a lot. The Verlet method has more short term error, but over the long run, the energy remains bounded near the original energy.
#
# Project 4: Orbital Mechanics
# =============================
#
# You will compute the orbit of an asteroid under the influence of the Sun and Jupiter. Use the RK4 and Verlet algorithm and investigate the long term conservation of energy for both algorithms. Below find an example of approximately computing Earth's orbit about the Sun. You should be able to swich out RK4 and Verlet step functions.
#
# What do I have to do?
# ---------------------
#
# Please write a report describing your efforts. Be sure to include the following:
#
# * The calculation of the orbital trajectory of an asteroid whose orbital period is half of Jupiter's period.
#
# * Investigate the "long term" behavior of the results using RK4 algorithm compared to Verlet.
#
# * A graph of energy vs. time for such an asteroid using both RK4 and Verlet methods.
#
# * Any general conclusion you can draw from your results regarding the virtues and/or drawbacks of these methods.
#
# + deletable=true editable=true
GMs = (2*pi)**2 # measure time in years, distance in AU
def derivs_grav(s, t, step=None):
"""
Compute motion of Earth about the Sun
"""
r=s[:2]
v=s[2:]
if step==0: # Verlet space-step
return append(v,zeros(2))
else:
rnorm = sqrt(sum(r*r))
a = -GMs*r/rnorm**3
if step is None: # RK step
return append(v,a)
else: # Verlet velocity-step
return append(zeros(2),a)
v = array([0.0,2*pi])
r = array([1.0,0.0])
s=append(r,v)
t=0.0
dt=0.01
tlist=[t]
xlist=[s[0]]
ylist=[s[1]]
while t<1.1:
s = RK4Step(s, t, derivs_grav, dt)
t += dt
tlist.append(t)
xlist.append(s[0])
ylist.append(s[1])
title("Earth Orbit")
xlabel("x-position (AU)")
ylabel("y-position (AU)")
axes().set_aspect('equal')
axis([-1.1,1.1,-1.1,1.1])
plot(xlist, ylist)
# + deletable=true editable=true
title("Earth Orbit")
xlabel("time (years)")
ylabel("y-position (AU)")
plot(tlist, ylist)
grid()
# + [markdown] deletable=true editable=true
# Starter Code
# ============
#
# Below you'll find a derivs_grav function that computes the motion of an asteroid and Jupiter about the sun. It's set up to take combined q/p steps (appropriate for an RK scheme). You can use this directly to study the motion with RK4Step and investigate solutions for different initial conditions.
# + deletable=true editable=true
#
# This is a derivs function for the RK4 method
# You need to modify it to work with the Symplectic Integrators
#
G = (2*pi)**2 # measure time in years, distance in AU
Ms = 1.0 # mass in solar masses
Mj = Ms/1047 # jupiter's mass is much less than the Sun's
Ma = Mj/1e7 # typical asteroid mass.. *really* small.
GMs = G*Ms # save multiplying later ...
GMj = G*Mj
GMa = G*Ma
def derivs_grav(s, t, step=None):
"""
Compute motion of asteriod and Jupiter about the Sun
"""
rsa=s[:2] # position of asteroid relative to sun
rsj=s[2:4] # for symplectic integrators it's handy to have all r's together
va=s[4:6] # followed by all v's in the state array.
vj=s[6:8]
rja=rsa-rsj
rsjm3 = (rsj*rsj).sum()**(1.5) # compute |r_{sj}|**3 for vector force calculation
rsam3 = (rsa*rsa).sum()**(1.5) # similar for r_{sa}
rjam3 = (rja*rja).sum()**(1.5) # similar for r_{ja}
aj = -(GMs*rsj/rsjm3 - GMa*rja/rjam3)
aa = -(GMs*rsa/rsam3 + GMj*rja/rjam3)
return array([va[0],va[1],vj[0],vj[1],aa[0],aa[1],aj[0],aj[1]])
# + deletable=true editable=true
Rj=5.2 # AU
Ra=3.0 # AU
s=array([Ra,0,Rj,0,0,sqrt(GMs/Ra),0,sqrt(GMs/Rj)]) # assume circular orbits
xalist=[] # empty lists
yalist=[]
tlist=[]
xjlist=[]
yjlist=[]
t=0.0
dt=0.3
while t<50:
s=RK4Step(s, t, derivs_grav, dt)
t+=dt
tlist.append(t)
xalist.append(s[0])
yalist.append(s[1])
xjlist.append(s[2])
yjlist.append(s[3])
title("Jupiter/Asteriod Orbit")
xlabel("x-position (AU)")
ylabel("y-position (AU)")
axes().set_aspect('equal')
plot(xalist, yalist,'b.',label="asteroid")
plot(xjlist, yjlist,'g.',label="jupiter")
legend()
| P04-HigherOrderMethods.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
# language: python
# name: python3
# ---
# # CHEM 1000 - Spring 2022
# <NAME>, University of Pittsburgh
#
# ## Recitation
#
# For this recitation, we'll focus on:
# - Graphical Interpolation for Optimization
# - Lagrange Multipliers Practice
# ---
#
# The goal of Chapter 6 is to give a cursory overview of the vastly expanding field that is "optimization algorithms". All fields, in some form, deal with optimizing something with known constraints. It is to your advantage to hold onto the conceptual aspects of this content.
#
# Please follow along with recitation and complete the following questions to gain credit for this assignment.
# ### Part A: Simionescu Function
#
# Sometimes determining the analytical solution to a function is not practical. In this case, one might wish to better understand the function graphically to then interpolate the extrema. Today we will be working with another function, the Simionescu function, which is unique not for the function itself, but how the constraint is defined. Here, f(x, y) is the function and g(x, y) is the constraint.
#
# $$
# f(x, y)=0.1xy
# $$
#
# $$
# g(x, y)=x^{2}+y^{2}-(1+0.2cos(8tan^{-1}(x/y)))^{2}
# $$
#
# #### Run the code in each cell and answer the three questions below to get credit for this recitation.
#
# 1. Calculate all partial derivatives.
# 2. Describe the constraint on the basis of symmetry.
# 3. Where are the maxima and minima?
from sympy import init_session
init_session()
# +
# Calculate derivatives here with sympy. Note that arctan(x) = atan(x).
dfdx =
dfdy =
dgdx =
dgdy =
# -
# Use this website to plot the constraint function. Describe what you see? What symmetries do you notice? Why do you think this constraint makes optimization difficult? Think critically about how a computer might search for minima and maxima...
#
# https://www.desmos.com/calculator
# +
# Write your description of the constraint function below.
# -
# We can extend our original function in three dimensions by setting it equal to z.
#
# $$
# f(x,y) = 0.1xy = z
# $$
#
# Follow along with recitation to learn how to graphically determine the maxima and minima. In the cell below, write (approximately) what values correspond to the maxima and minima.
maxima =
minima =
# ### Part B: Company Startup
#
# Let's say that you are starting a company and need to hire staff and order materials. The materials (m) you need can be ordered in bulk at 50 dollars for each crate. You need to hire staff (s) to convert the materials into some product (think assembly line) at 20 dollars per hour. After consulting an entrepeneur and an engineer, you find that similar companies have used this model:
#
# $$
# f(m,s) = 5m^{2}s+2s^{2}m
# $$
#
# #### Run the code in each cell and answer the three questions below to get credit for this recitation.
#
# 1. Your company has a startup fund of 600 dollars. Optimize your initial spending given the model above.
# 2. Your friend is also starting a company and has been instructed to use the same model. However, you decided to give your friend two crates of material and to transfer one of your workers to their company to start production. Modify the model with these initial conditions.
# 3. Your friend has applied for a startup fund and was awarded 480 dollars. Optimize spending to maximize their efficiency.
# +
# Calculate your optimal spending.
f = 5*s*m**2 + 2*m*s**2
g =
h =
# +
# Write your new model here...
f_new =
# +
# Calculate the optimal spending for your friend.
f_new =
g =
h =
| recitation/06-optimizations.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
# ---
# # How to use GPU
import torch
import torch.nn as nn
# ## Convert to CUDA tensor: cuda()
# +
x = torch.cuda.FloatTensor(2, 2)
x
# +
x = torch.FloatTensor(2, 2)
x
# -
x.cuda()
d = torch.device('cuda:0')
x.cuda(device=d)
x.device
# ## Convert to CUDA tensor: to()
x.to(device=d)
# ## Convert to CPU tensor from CUDA tensor
x = torch.cuda.FloatTensor(2, 2)
x = x.cpu()
d = torch.device('cpu')
x = x.to(d)
# ## Move model from CPU to GPU.
def print_params(model):
for p in model.parameters():
print(p)
# +
linear = nn.Linear(2, 2)
print_params(linear)
# +
linear = linear.cuda()
print_params(linear)
# +
linear = linear.cpu()
print_params(linear)
# +
d = torch.device('cuda:0')
linear = linear.to(d)
print_params(linear)
# -
# Note that nn.Module class does not have 'device' property.
linear.device
# ## Tricks
x = torch.cuda.FloatTensor(2, 2)
x.new(2, 2)
torch.zeros_like(x)
torch.ones_like(x)
list(linear.parameters())[0].new(2, 2)
| 05-linear_layer/05-05-use_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
# ---
# # Exercices sur les dictionnaires
# [Aide en vidéo (dictionnaire et fichier...)](https://vimeo.com/490115205)
# ## Exercice 1 - occurence encore!
# La fonction `occurences(chaine)` renvoie un dictionnaire contenant les paires «caractère: nb d'apparition» où caractère est l'un de ceux de la chaîne fournie en argument.
#
# Par exemple `ocurrences("tagada")` renvoie le dictionnaire `{'t': 1, 'a': 3, 'g': 1, 'd': 1}`.
# Notez qu'il est possible de parcourir les caractères d'une chaîne à l'aide d'une boucle `for car in chaine`; par exemple:
une_chaine = "Python"
for car in une_chaine:
print(car)
# Définir la fonction `occurences`.
# + jupyter={"source_hidden": true}
def occurences(chaine):
d = {} # partons d'un dictionnaire vide comme accumulateur
for car in chaine:
if not car in d: # pas d'entrée pour ce caractère
d[car] = 1 # on insère la paire «car: 1»
else: # on l'a déjà vue
d[car] = d[car] + 1 # mise à jour de la valeur associée à car
return d
occurences("tagada tsoin tsoin")
# -
# <a href="http://pythontutor.com/visualize.html#code=def%20occurences%28chaine%29%3A%0A%20%20%20%20d%20%3D%20%7B%7D%20%23%20partons%20d'un%20dictionnaire%20vide%20comme%20accumulateur%0A%20%20%20%20for%20car%20in%20chaine%3A%0A%20%20%20%20%20%20%20%20if%20not%20car%20in%20d%3A%20%23%20pas%20d'entr%C3%A9e%20pour%20ce%20caract%C3%A8re%0A%20%20%20%20%20%20%20%20%20%20%20%20d%5Bcar%5D%20%3D%201%20%23%20on%20ins%C3%A8re%20la%20paire%20%C2%ABcar%3A%201%C2%BB%0A%20%20%20%20%20%20%20%20else%3A%20%23%20on%20l'a%20d%C3%A9j%C3%A0%20vue%0A%20%20%20%20%20%20%20%20%20%20%20%20d%5Bcar%5D%20%3D%20d%5Bcar%5D%20%2B%201%20%23%20mise%20%C3%A0%20jour%20de%20la%20valeur%20associ%C3%A9e%20%C3%A0%20car%0A%20%20%20%20return%20d%0A%0Aoccurences%28%22tagada%20tsoin%20tsoin%22%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false">Voir avec python tutor</a>
# ## Exercice 2 - mots d'un fichier.
# La fonction `effectif_mots(chemin_fichier)` renvoie un dictionnaire contenant des paires de la forme «mot: nb d'apparition» où mot est l'un de ceux qui apparaît dans le fichier dont le chemin est fourni en argument.
#
# On rappelle que la fonction `str.split()` découpe une chaîne à chaque «blanc» et renvoie la liste des portions de chaîne obtenues; par exemple:
phrases = """
On n'est pas sérieux, quand on a dix-sept ans.
Un beau soir, foin des bocks et de la limonade,
Des cafés tapageurs aux lustres éclatants !
On va sous les tilleuls verts de la promenade.
"""
phrases.lower().split() # lower() pour n'avoir que des minuscules.
# Écrire cette fonction et l'appliquer au fichier *ltdme80j.txt* situé dans le dossier OS_et_shell.
# **Solution «brute»**
# + jupyter={"source_hidden": true}
def effectif_mots(chemin_fichier):
#1. lisons le fichier
with open(chemin_fichier, "r") as fichier:
contenu = fichier.read()
#2. Découpons ce contenu (chaîne) au niveau des blancs
mots = contenu.split()
#3. mots est une liste et une liste se parcourt comme une chaîne...
# donc, on peut réutiliser la fonction précédente!
return occurences(mots)
import os
# Attention, le chemin dépend de l'emplacement de ce notebook et du fichier
# 'ltdme80j': il faudra probablement adapter...
chem_ltdme80j = os.path.join('..', '03_OS_et_shell', 'ltdme80j.txt')
effectif_mots(chem_ltdme80j) # ou effectif_mots('ltdme80j.txt') si le fichier est dans le même répertoire que le notebook.
# -
# **Solution améliorée (en éliminant certains caractères indésirables)**
# + jupyter={"source_hidden": true}
def effectif_mots(chemin_fichier):
#1. lisons le fichier pour récupérer son contenu
with open(chemin_fichier, "r") as fichier:
contenu = fichier.read()
#2. Nettoyons ce contenu pour mieux récupérer les mots
contenu = contenu.lower() #normalisons: en minuscule
# Éliminons les caractères indésirables avec str.translate()
# -> voir https://docs.python.org/fr/3/library/stdtypes.html#str.translate
# ex: "abccba".translate({"a": "b", "b": "c", "c": "d"}) renvoie "bcddcb"
# On peut réaliser une association «caractère à caractère» avec:
# asso = str.maketrans(ch1, ch2)
# -> chaque caractère de ch1 est associé au caractère de même position dans ch2 et donc
# ex: "abccba".translate(str.maketrans("abc", "bcd")) renvoie encore "bcddcb"
table = str.maketrans(",;.:!?<>()=", " "*11)
contenu = contenu.translate(table) # ou translate({",": "", ";": "", ...})
mots = contenu.split()
#3. mots est une liste et on parcourt une liste comme une chaîne
# donc, on peut réutiliser la fonction précédente...
return occurences(mots)
import os
# Attention, le chemin dépend de l'emplacement de ce notebook et du fichier
# 'ltdme80j': il faudra probablement adapter...
chem_ltdme80j = os.path.join('..', '03_OS_et_shell', 'ltdme80j.txt')
effectif_mots(chem_ltdme80j)
# -
# ## Exercice 3 - distance touches
# On peut voir un clavier comme un tableau à deux dimensions dans lequel chaque case contient un caractère. Ainsi, la partie principale d'un clavier AZERTY peut être vue comme le tableau suivant:
AZERTY = [ ['a', 'z', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'],
['q', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm'],
['<', 'w', 'x', 'c', 'v', 'b', 'n', ',', ';', ':'] ]
# L'objectif est d'écrire une fonction `distance_touches` calculant la distance entre les touches de deux caractères sur un clavier.
#
# 1. Écrire une fonction `inverse_clavier(clavier)` prenant en paramètre un tableau à deux dimensions représentant une disposition de clavier et renvoyant un dictionnaire dont les clés sont les caractères et les valeurs des coordonnées de la touche correspondante (par ex: `'a': (0, 0)` et `'f': (1, 3)`).
# + jupyter={"source_hidden": true}
def inverse_clavier(clavier):
# clavier est supposé être une liste de listes comme dans AZERTY.
d = {} # accu.
# Nous allons lire le clavier ligne par ligne PUIS, pour chaque ligne, touche par touche
n_clavier = len(clavier)
for i in range(n_clavier):
touches = clavier[i] # une ligne de touches
n = len(touches) # nb de touches
for j in range(n):
touche = touches[j]
# la position de la touche est ligne n°i, colonne n°j donc:
d[touche] = (i, j)
return d
inverse_clavier(AZERTY)
# -
# <a href="http://pythontutor.com/visualize.html#code=AZERTY_SIMPLE%20%3D%20%5B%20%5B'a',%20'z'%5D,%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5B'q',%20's'%5D,%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5B'%3C',%20'w'%5D%20%5D%0A%0Adef%20inverse_clavier%28clavier%29%3A%0A%20%20%20%20d%20%3D%20%7B%7D%20%23%20accu.%0A%20%20%20%20n_clavier%20%3D%20len%28clavier%29%0A%20%20%20%20for%20i%20in%20range%28n_clavier%29%3A%0A%20%20%20%20%20%20%20%20touches%20%3D%20clavier%5Bi%5D%0A%20%20%20%20%20%20%20%20n%20%3D%20len%28touches%29%0A%20%20%20%20%20%20%20%20for%20j%20in%20range%28n%29%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20touche%20%3D%20touches%5Bj%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20d%5Btouche%5D%20%3D%20%28i,%20j%29%0A%20%20%20%20return%20d%0A%0Ainverse_clavier%28AZERTY_SIMPLE%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false">Voir avec python tutor</a>
# 2. Ré-utiliser la fonction précédente pour écrire une fonction `distance_touches(car1, car2, clavier)` qui donne la distance entre les touches correspondant à `car1` et `car2` pour le clavier fourni. Comme distance, on prendra la somme des écarts horizontaux et verticaux entre les touches; par exemple:
# + jupyter={"source_hidden": true}
def distance_touches(car1, car2, clavier):
touche_pos = inverse_clavier(clavier)
i1, j1 = touche_pos[car1] # car c'est un tuple...
i2, j2 = touche_pos[car2]
# rappel: la fonction valeur absolue - abs - élimine le signe «-» éventuel.
return abs(i2 - i1) + abs(j2 - j1)
# -
assert distance_touches('s', 'g', AZERTY) == 3
assert distance_touches('c', 'y', AZERTY) == 4
assert distance_touches(',', ',', AZERTY) == 0
| 00_bases_python/13_exercices_dict.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="bOChJSNXtC9g"
# # Introduction to Python
# + [markdown] colab_type="text" id="OLIxEDq6VhvZ"
# In this lesson we will learn the basics of the Python programming language (version 3). We won't learn everything about Python but enough to do some basic machine learning.
#
# <img src="figures/python.png" width=350>
#
#
#
# + [markdown] colab_type="text" id="VoMq0eFRvugb"
# # Variables
# + [markdown] colab_type="text" id="qWro5T5qTJJL"
# Variables are objects in Python that can hold anything with numbers or text. Let's look at how to create some variables.
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="0-dXQiLlTIgz" outputId="38d1f8a5-b067-416b-b042-38a373624a8b"
# Numerical example
## changed X = 7
x = 7
print (x)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="5Ym0owFxTkjo" outputId="72c2781a-4435-4c21-b15a-4c070d47bd86"
# Text example
## changed x = good bye
x = "good bye"
print (x)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="1a4ZhMV1T1-0" outputId="0817e041-5f79-46d8-84cc-ee4aaea0eba2"
# Variables can be used with each other
#Change b = 3
a = 1
b = 3
c = a + b
print (c)
# + [markdown] colab_type="text" id="nbKV4aTdUC1_"
# Variables can come in lots of different types. Even within numerical variables, you can have integers (int), floats (float), etc. All text based variables are of type string (str). We can see what type a variable is by printing its type.
# + colab={"base_uri": "https://localhost:8080/", "height": 153} colab_type="code" id="c3NJmfO4Uc6V" outputId="04b91fa4-51af-48f4-e9ac-591b5bf3e714"
# int variable
## changed x = 8
x = 8
print (x)
print (type(x))
# float variable
## Changed float variable x = 7.5
x = 7.5
print (x)
print (type(x))
# text variable
## changed text variable x = "12"
x = "12"
print (x)
print (type(x))
# boolean variable
x = True
print (x)
print (type(x))
# + [markdown] colab_type="text" id="6HPtavfdU8Ut"
# It's good practice to know what types your variables are. When you want to use numerical operations on them, they need to be compatible.
# + colab={"base_uri": "https://localhost:8080/", "height": 51} colab_type="code" id="8pr1-i7IVD-h" outputId="c2bce48d-b69f-4aab-95c1-9e588f67a6c3"
# int variables
## Changed a = 8
a = 8
b = 3
print (a + b)
# string variables
a = "8"
b = "3"
print (a + b)
# + [markdown] colab_type="text" id="q4R_UF6PVw4V"
# # Lists
# + [markdown] colab_type="text" id="LvGsQBj4VjMl"
# Lists are objects in Python that can hold a ordered sequence of numbers **and** text.
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="9iPESkq9VvlX" outputId="67dfbe9f-d4cb-4a62-a812-7c5c8a01c2fa"
# Creating a list
## Changed first item in list to 4
list_x = [4, "hello", 1]
print (list_x)
# + [markdown] colab_type="text" id="0xC6WvuwbGDg"
#
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="7lbajc-zV515" outputId="4345bbe0-0f0c-4f84-bcf2-a76130899f34"
# Adding to a list
## Changed 7 to 9
list_x.append(9)
print (list_x)
# + colab={"base_uri": "https://localhost:8080/", "height": 102} colab_type="code" id="W0xpIryJWCN9" outputId="a7676615-aff1-402f-d41f-81d004728f94"
# Accessing items at specific location in a list
print ("list_x[0]: ", list_x[0])
print ("list_x[1]: ", list_x[1])
print ("list_x[2]: ", list_x[2])
print ("list_x[-1]: ", list_x[-1]) # the last item
print ("list_x[-2]: ", list_x[-2]) # the second to last item
# + colab={"base_uri": "https://localhost:8080/", "height": 85} colab_type="code" id="VSu_HNrnc1WK" outputId="3c40cce2-9599-41aa-b01c-7c6f39329212"
# Slicing
print ("list_x[:]: ", list_x[:])
print ("list_x[2:]: ", list_x[2:])
print ("list_x[1:3]: ", list_x[1:3])
print ("list_x[:-1]: ", list_x[:-1])
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="dImY-hVzWxB4" outputId="8394f232-aa11-4dbd-8580-70adb5adc807"
# Length of a list
len(list_x)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="3-reXDniW_sm" outputId="382d1a40-ad1a-49f7-f70f-2c2a02ffd88d"
# Replacing items in a list
list_x[1] = "hi"
print (list_x)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="X8T5I3bjXJ0S" outputId="1ede1c5c-c6ea-452f-b13d-ff9efd3d53b0"
# Combining lists
### changed world to globe
list_y = [2.4, "globe"]
list_z = list_x + list_y
print (list_z)
# + [markdown] colab_type="text" id="ddpIO6LLVzh0"
# # Tuples
# + [markdown] colab_type="text" id="CAZblq7oXY3s"
# Tuples are also objects in Python that can hold data but you cannot replace their values (for this reason, tuples are called immutable, whereas lists are known as mutable).
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="G95lu8xWXY90" outputId="c23250e5-534a-48e6-ed52-f034859f73c2"
# Creating a tuple
##changed hello to hola
tuple_x = (3.0, "hola")
print (tuple_x)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="kq23Bej1acAP" outputId="34edfbff-dbc0-4385-a118-7f1bcc49e84f"
# Adding values to a tuple
### changed 5.6 to 6.5
tuple_x = tuple_x + (6.5,)
print (tuple_x)
# + colab={"base_uri": "https://localhost:8080/", "height": 164} colab_type="code" id="vyTmOc6BXkge" outputId="dadeac9a-4bb4-43a3-ff40-e8ca6a05ba2c"
# Trying to change a tuples value (you can't, this should produce an error.)
tuple_x[1] = "world"
# + [markdown] colab_type="text" id="UdlJHkwZV3Mz"
# # Dictionaries
# + [markdown] colab_type="text" id="azp3AoxYXS26"
# Dictionaries are Python objects that hold key-value pairs. In the example dictionary below, the keys are the "name" and "eye_color" variables. They each have a value associated with them. A dictionary cannot have two of the same keys.
# + colab={"base_uri": "https://localhost:8080/", "height": 68} colab_type="code" id="pXhNLbzpXXSk" outputId="e4bb80e5-4e7b-4cbb-daa6-77490ab25145"
# Creating a dictionary
### Changed name to "Byers"
dog = {"name": "Byers",
"eye_color": "brown"}
print (dog)
print (dog["name"])
print (dog["eye_color"])
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="1HXtX8vQYjXa" outputId="ad8d1a0f-d134-4c87-99c1-0f77140f2de0"
# Changing the value for a key
### Changed eye color value to blue
dog["eye_color"] = "blue"
print (dog)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="qn33iB0MY5dT" outputId="bd89033e-e307-4739-8c1d-f957c32385b5"
# Adding new key-value pairs
## Changed dog age value
dog["age"] = 3
print (dog)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="g9EYmzMKa9YV" outputId="4b9218b9-2f4d-4287-932a-caba430713aa"
# Length of a dictionary
print (len(dog))
# + [markdown] colab_type="text" id="B-DInx_Xo2vJ"
# # If statements
# + [markdown] colab_type="text" id="ZG_ICGRGo4tY"
# You can use `if` statements to conditionally do something.
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="uob9lQuKo4Pg" outputId="21d40476-ea6a-4149-f744-0119d0894d77"
# If statement
### Changed x =4 to x = 6
x = 6
if x < 1:
score = "low"
elif x <= 4:
score = "medium"
else:
score = "high"
print (score)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="vwsQaZqIpfJ3" outputId="1f190875-b910-4e54-a58a-d4230b7c8169"
# If statment with a boolean
### Changed print statement
x = True
if x:
print ("it didn't work")
# + [markdown] colab_type="text" id="sJ7NPGEKV6Ik"
# # Loops
# + [markdown] colab_type="text" id="YRVxhVCkn0vc"
# In Python, you can use `for` loop to iterate over the elements of a sequence such as a list or tuple, or use `while` loop to do something repeatedly as long as a condition holds.
# + colab={"base_uri": "https://localhost:8080/", "height": 68} colab_type="code" id="OB5PtyqAn8mj" outputId="b4595670-99d4-473e-b299-bf8cf47f1d81"
# For loop
## changed to range(4)
x = 1
for i in range(4): # goes from i=0 to i=3
x += 1 # same as x = x + 1
print ("i={0}, x={1}".format(i, x)) # printing with multiple variables
# + colab={"base_uri": "https://localhost:8080/", "height": 68} colab_type="code" id="6XyhCrFeoGj4" outputId="2427ae1f-85f7-4888-f47f-8de1992a84c3"
# Loop through items in a list
## Added 3 to in list
x = 1
for i in [0, 1, 2, 3]:
x += 1
print ("i={0}, x={1}".format(i, x))
# + colab={"base_uri": "https://localhost:8080/", "height": 68} colab_type="code" id="5Tf2x4okp3fH" outputId="1ac41665-2f35-4c7d-e9f5-22614d3ba35c"
# While loop
## Changed value of x to 5
x = 5
while x > 0:
x -= 1 # same as x = x - 1
print (x)
# + [markdown] colab_type="text" id="gJw-EDO9WBL_"
# # Functions
# + [markdown] colab_type="text" id="hDIOUdWCqBwa"
# Functions are a way to modularize reusable pieces of code.
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="iin1ZXmMqA0y" outputId="3bfae4a7-482b-4d43-8350-f8bb5e8a35ac"
# Create a function
## changed to add_three
def add_three(x):
x += 3
return x
# Use the function
score = 0
score = add_three(x=score)
print (score)
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="DC6x3DMrqlE3" outputId="8965bfab-3e20-41ae-9fc1-f22a7d4f3333"
# Function with multiple inputs
## Changed variable to city, state, location name
def location_name(city_name, state_name):
location_name = city_name + " " + state_name
return joined_name
# Use the function
city_name = "Denver"
state_name = "Colorado"
location_name = join_name(city_name=city_name, state_name=state_name)
print (location_name)
# + [markdown] colab_type="text" id="lBLa1n54WEd2"
# # Classes
# + [markdown] colab_type="text" id="mGua8QnArAZh"
# Classes are a fundamental piece of object oriented programming in Python.
# + colab={} colab_type="code" id="DXmPwI1frAAd"
# Creating the class
class Pets(object):
# Initialize the class
def __init__(self, species, color, name):
self.species = species
self.color = color
self.name = name
# For printing
def __str__(self):
return "{0} {1} named {2}.".format(self.color, self.species, self.name)
# Example function
def change_name(self, new_name):
self.name = new_name
# + colab={"base_uri": "https://localhost:8080/", "height": 51} colab_type="code" id="ezQq_Fhhrqrv" outputId="bf159745-99b1-4e33-af4d-f63924a1fe74"
# Creating an instance of a class
## changed dog color and name
my_dog = Pets(species="dog", color="black", name="Byers",)
print (my_dog)
print (my_dog.name)
# + colab={"base_uri": "https://localhost:8080/", "height": 51} colab_type="code" id="qTinlRj1szc5" outputId="80939a31-0242-4465-95ff-da0e5caaa67c"
# Using a class's function
### Changed new_name variable to Odell
my_dog.change_name(new_name="Odell")
print (my_dog)
print (my_dog.name)
# + [markdown] colab_type="text" id="kiWtd0aJtNtY"
# # Additional resources
# + [markdown] colab_type="text" id="cfLF4ktmtSC3"
# This was a very quick look at Python and we'll be learning more in future lessons. If you want to learn more right now before diving into machine learning, check out this free course: [Free Python Course](https://www.codecademy.com/learn/learn-python-3)
| jdbakker42.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="inOFqYL_O_4y" colab_type="text"
# ## CIFAR10 - zbiór danych
# + [markdown] id="IVa0qXJVPKDg" colab_type="text"
# Jest 10 klas do rozpoznania.
# + id="7wD7olXCO-x9" colab_type="code" colab={}
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras.utils import to_categorical # żeby odpowiednio przekształcić y_train
import numpy as np
np.random.seed(0)
import matplotlib.pyplot as plt
# %matplotlib inline
# + [markdown] id="H0VSG8rkeq7V" colab_type="text"
# Wczytanie danych
# + id="PGsONonnend4" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="f3501843-508a-4ffb-e393-76df896c2456" executionInfo={"status": "ok", "timestamp": 1582842572226, "user_tz": -60, "elapsed": 837, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00941150960329998400"}}
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
X_train.shape, X_test.shape
# + [markdown] id="XnstPFUGrUaj" colab_type="text"
# Wizualizacja danych
# + id="gN4xfL-SrXSZ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 729} outputId="55166e78-1712-4f7c-bc02-1983f64ff066" executionInfo={"status": "ok", "timestamp": 1582842578029, "user_tz": -60, "elapsed": 3866, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00941150960329998400"}}
fig = plt.figure(figsize=(10,10))
for idx in range(25):
plt.subplot(5,5,idx+1)
plt.imshow(X_train[idx], cmap='gray', interpolation='none')
plt.title("Class {}".format(y_train[idx]))
plt.tight_layout()
# + [markdown] id="EAPP2POzsHmw" colab_type="text"
# Przygotowujemy dane: dodajemy ilosc kanałów
# + id="K4ViQ4x7sGhT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="e731a338-951a-4c1e-c35c-59117a8b60ab" executionInfo={"status": "ok", "timestamp": 1582842581144, "user_tz": -60, "elapsed": 625, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00941150960329998400"}}
img_rows, img_cols = X_train.shape[1], X_train.shape[2]
num_channels = 3
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, num_channels)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, num_channels)
input_shape = (img_rows, img_cols, num_channels)
X_train.shape, X_test.shape
# + [markdown] id="UUlUmQ8ktHnA" colab_type="text"
# Normalizujemy ( 0-1 )
# + id="5beBpo49tKBx" colab_type="code" colab={}
if np.max(X_train) > 1 : X_train = X_train / 255
if np.max(X_test) > 1 : X_test = X_test / 255
# + id="V17j4SG0tZfS" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="fcaf0bcf-5c03-4434-dcfc-f13cbdee3b3f" executionInfo={"status": "ok", "timestamp": 1582842587364, "user_tz": -60, "elapsed": 620, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00941150960329998400"}}
X_test.max(), X_train.max()
# + id="JxnpmmVItlsY" colab_type="code" colab={}
if len(y_train.shape) == 2:
y_train = y_train.reshape(-1) # żeby miał 1 a nie 2 wymiary
y_test = y_test.reshape(-1)
if len(y_train.shape) == 1:
num_classes = len(set(y_train))
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
# + id="OvdJNStAubuq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="8eed0b1a-a1d2-4dbd-cfb8-2d2eb1d3fc09" executionInfo={"status": "ok", "timestamp": 1582842591378, "user_tz": -60, "elapsed": 589, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00941150960329998400"}}
y_train.shape, y_test.shape, num_classes
# + [markdown] id="RHoM1jSMv46Y" colab_type="text"
# Budujemy model
# + id="uD2zkhp8ujW3" colab_type="code" colab={}
model = Sequential([
Conv2D(32, kernel_size= (3,3), activation='relu', input_shape=input_shape ),
Conv2D(32, kernel_size= (3,3), activation='relu'),
MaxPool2D(pool_size=(2,2)),
Dropout(0.25),
Conv2D(64, kernel_size=(3,3), activation='relu'),
Conv2D(64, kernel_size=(3,3), activation='relu'),
MaxPool2D(pool_size=(2,2)),
Dropout(0.25),
Conv2D(128, kernel_size=(3,3), activation='relu'),
MaxPool2D(pool_size=(2,2)),
Dropout(0.25),
Flatten(), # bridge between conv layers and full connected layers
Dense(1024, activation='relu'),
Dropout(0.5),
Dense(num_classes, activation='softmax')
])
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# + id="Tocte8pcxJxa" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 655} outputId="0b60662d-9b80-4ecb-de8c-cd060561f3ec" executionInfo={"status": "ok", "timestamp": 1582842595568, "user_tz": -60, "elapsed": 561, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00941150960329998400"}}
model.summary()
# + [markdown] id="eI3c4fWFv-XY" colab_type="text"
# Trenujemy model
# + id="vWCasoKwv3Yu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 118} outputId="d64bfebd-8952-4f80-8e18-5eee9d463634" executionInfo={"status": "ok", "timestamp": 1582843162924, "user_tz": -60, "elapsed": 353079, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00941150960329998400"}}
model.fit(X_train, y_train,
batch_size=128, epochs=2, verbose=2,
validation_data= (X_test, y_test))
# + id="swgSlGPWxmXA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 50} outputId="a2e1b506-1c58-47e9-80ad-327427c5bfb2" executionInfo={"status": "ok", "timestamp": 1582843202972, "user_tz": -60, "elapsed": 10475, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00941150960329998400"}}
model.evaluate(X_test, y_test)
# + id="_3yjfgxW20fp" colab_type="code" colab={}
# !git add Data_Workshop_Challenges/Week_One/challenge_day5.ipynb
# !git commit -m "Editing day5 from Data Challenge"
# !git push -u origin master
| Data_Workshop_Challenges/Week_Two/challenge_day4.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] _cell_guid="ce8ccc67-32d3-482b-ad92-5617db0801ef" _uuid="01f8a495e4a0ae005a7868045f2b4cf584d501d3"
# Natural Language Generation is a very important area to be explored in our time. It forms the basis of how a bot would communicate with - not like how literates write books but like how we talk. In this Kernel, I'd like to show you a very simple but powerful Python module that does a similar exercise in (literally) a couple of lines of code.
#
# **Module: Markovify**
#
# The Py module we use here is [`markovify`](https://github.com/jsvine/markovify).
#
# **Descrption of Markovify: **
#
# Markovify is a simple, extensible Markov chain generator. Right now, its main use is for building Markov models of large corpora of text, and generating random sentences from that. But, in theory, it could be used for other applications.
#
# **About the Dataset:**
# This includes the entire corpus of articles published by the ABC website in the given time range. With a volume of 200 articles per day and a good focus on international news, we can be fairly certain that every event of significance has been captured here. This dataset can be downloaded from [Kaggle Datasets](https://www.kaggle.com/therohk/million-headlines/data).
# + [markdown] _uuid="20078f4a4dbcf91fa5b78849209462c9cc7c56b6"
# ### Little About Markov Chain
#
# Markov chains, named after <NAME>, are mathematical systems that hop from one "state" (a situation or set of values) to another. For example, if you made a Markov chain model of a baby's behavior, you might include "playing," "eating", "sleeping," and "crying" as states, which together with other behaviors could form a 'state space': a list of all possible states. In addition, on top of the state space, a Markov chain tells you the probabilitiy of hopping, or "transitioning," from one state to any other state---e.g., the chance that a baby currently playing will fall asleep in the next five minutes without crying first. Read more about how Markov Chain works in this [interactive article](http://setosa.io/ev/markov-chains/) by <NAME>
#
# 
# + [markdown] _cell_guid="540d8642-a5b4-46f3-9335-fc6727d3471e" _uuid="aad8efd1ab078196f640d95034320b4ed8023969"
# ### Loading Required Packages
# + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5"
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import markovify #Markov Chain Generator
# Any results you write to the current directory are saved as output.
# + [markdown] _cell_guid="06688541-f694-4f09-8f25-1cf818327905" _uuid="6014086f033e0ad3a2366c53a7ebd6dec74e356e"
# ### Reading Input Text File
# + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a"
inp = pd.read_csv('../input/abcnews-date-text.csv')
inp.head(3)
# + [markdown] _cell_guid="ff6660b1-7ef4-42ee-81c6-776585d03fe8" _uuid="aad261f6bf0ffbadfca57c17757b2867efcffad0"
# ### Building the text model with Markov Chain
# + _cell_guid="e0b8be2a-deea-4562-9457-011b2549b698" _uuid="5de10b5f2b0ff8c9cc7453c376e7a6902e2bef39"
text_model = markovify.NewlineText(inp.headline_text, state_size = 2)
# + [markdown] _cell_guid="21f34609-4ef3-4070-b4d6-c98c75ef6a66" _uuid="e58a4f4661bf26c6f2ee3c3d1f48a15a5c1139b7"
# ### Time for some fun with Autogenerated Headlines
# + _cell_guid="ff82cb0f-e384-45a1-bfe7-9447f4b23300" _uuid="5a9b93fca0d29a6841371d1634eb802bbd489255"
# Print five randomly-generated sentences
for i in range(5):
print(text_model.make_sentence())
# + [markdown] _cell_guid="03c93fae-556e-4e1f-81e5-872da3d58bd6" _uuid="5a7ad18c0529412744fb7972f2f9da3c03e18432"
# Now, this text could become input for a Twitter Bot, Slack Bot or even a Parody Blog. And that's the point.
| headlines_generator.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
# ---
# TODO: replace all str_tokens_sw with raw_news
import pandas as pd
import numpy as np
import seaborn as sns
import os
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer
from __future__ import division
import seaborn as sns
import matplotlib.pyplot as plt
# %matplotlib inline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler, RobustScaler
labels = pd.read_csv('stocknews//labels.csv', header=None)
# http://stackoverflow.com/questions/28382735/python-pandas-does-not-read-the-first-row-of-csv-file
#
# `pd.read_csv` was cutting off the first row of labels.
#
# `header=None` prevents that from happening.
# Confirm size of labels to make sure data loaded correctly
labels.shape
news = pd.read_csv('stocknews/Combined_News_DJIA.csv', dtype=str, keep_default_na=False)
raw_news = news.iloc[:,2:]
from nltk.sentiment.vader import SentimentIntensityAnalyzer
sid = SentimentIntensityAnalyzer()
"""
Showed differences between raw_news with puncuation vs tokenized news
"""
#for k in range(len(raw_news.ix[4])):
# print sid.polarity_scores(raw_news.ix[k, 2])['compound'] - sid.polarity_scores(str_tokens_sw.ix[k,2])['compound']
def compound_sentiment(element):
return sid.polarity_scores(element)['compound']
sentiment_raw = raw_news.applymap(compound_sentiment)
raw_all_sent = []
for j in range(len(sentiment_raw.index)):
for k in range(len(sentiment_raw.columns)):
raw_all_sent.append(sentiment_raw.ix[j,k])
len(raw_all_sent)
sum(1 for k in raw_all_sent if k == 0.0)
# #### Still a lot of 0's in sentiment ####
sns.distplot(raw_all_sent)
EMA = pd.Series.ewm(sentiment_raw.ix[2], com=12).mean()
EMA
# ### Set up Pandas series to get median, mean, exponentially weighted mean
median_sent = pd.Series(index=sentiment_raw.index)
mean_sent = pd.Series(index=sentiment_raw.index)
exp_mean = pd.Series(index=sentiment_raw.index)
sum_5 = pd.Series(index=sentiment_raw.index)
weighted_5 = pd.Series(index=sentiment_raw.index)
for k in range(len(sentiment_raw.index)):
median_sent[k] = sentiment_raw.iloc[k].median()
for k in range(len(sentiment_raw.index)):
mean_sent[k] = sentiment_raw.iloc[k].mean()
a = sentiment_raw.ix[2][::-1]
for k in range(len(sentiment_raw.index)):
exp_mean[k] = pd.stats.moments.ewma(sentiment_raw.ix[k], span=25).mean()
sum(sentiment_raw.iloc[4,:5])
sentiment_raw.iloc[4]
sum_sent = pd.Series(index=sentiment_raw.index)
for k in range(len(sentiment_raw.index)):
sum_sent[k] = sentiment_raw.iloc[k].sum()
for k in range(len(sentiment_raw.index)):
sum_5[k] = sum(sentiment_raw.iloc[k,:5])
sum(1 for k in sum_sent if k > 0)
sum(1 for k in exp_mean if k > 0 )
w = np.array([5,4,3,2,1])
for k in range(len(sentiment_raw.index)):
weighted_5[k] = np.dot(pd.Series([j for j in sentiment_raw.iloc[k] if j != 0][0:5]), w)
weighted_5.head()
features = pd.concat([mean_sent, median_sent, exp_mean, sum_5, weighted_5], axis=1)
mean_sent.head(2)
median_sent.head(2)
exp_mean.head(2)
features.columns = ['Mean Sentiment', 'Median Sentiment', 'Exponential Weighted Sentiment', 'Sum Top 5 Sentiment', 'Top 5 Weighted Sentiment']
features.info()
features.describe()
sns.heatmap(features.corr())
# ## Split data into train and test sets
train_text = features[0:1493] # train features
test_text = features[1493:] # test features
train_labels = labels[0:1493].values # train labels
test_labels = labels[1493:].values; # test labels
# Use Robust Scaler to rescale data
rs = RobustScaler()
train_text_scaled = rs.fit_transform(train_text)
test_text_scaled = rs.transform(test_text)
# ### Passive Aggressive Classifier
# +
# Set up GridSearch
param_grid = {'loss' : ['hinge', 'squared_hinge'],
'C': [10**x for x in np.linspace(-8, 4, 13)]}
# -
from sklearn.linear_model import PassiveAggressiveClassifier
classifier = PassiveAggressiveClassifier(fit_intercept=True,
random_state=0,
n_iter=8)
clf_grid = GridSearchCV(estimator=classifier, param_grid=param_grid, n_jobs=-1, scoring='roc_auc')
clf_grid.fit(train_text_scaled, train_labels.ravel())
clf_grid.best_estimator_
clf_grid.best_params_
clf_grid.best_score_
y_true, y_pred = test_labels.ravel(), clf_grid.predict(test_text_scaled)
from sklearn.metrics import classification_report
classification_report(y_true, y_pred)
# ### SGD Classifier
from sklearn.linear_model import SGDClassifier
classifier = SGDClassifier(loss='squared_loss', n_iter=25)
classifier.fit(train_text, train_labels.ravel())
classifier.score(test_text, test_labels.ravel())
# ### Logisitc Regression
from sklearn.linear_model import LogisticRegression
logr = LogisticRegression()
logr.fit(train_text, train_labels.ravel())
logr.score(test_text, test_labels.ravel())
# ### Ridge Classifier
from sklearn.linear_model import RidgeClassifier
clf = RidgeClassifier()
clf.fit(train_text, train_labels.ravel())
clf.score(test_text, test_labels.ravel())
# ### Gassian NB
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
gnb.fit(train_text, train_labels.ravel())
gnb.score(test_text, test_labels.ravel())
# ### Support Vector Classifier
from sklearn.svm import SVC
supportvc = SVC()
supportvc.fit(train_text, train_labels.ravel())
supportvc.score(test_text, test_labels.ravel())
# ### Random Forests
from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier()
rfc.fit(train_text, train_labels.ravel())
rfc.score(test_text, test_labels.ravel())
# ### Adaboost
from sklearn.ensemble import AdaBoostClassifier
abc = AdaBoostClassifier()
abc.fit(train_text, train_labels.ravel())
abc.score(test_text, test_labels.ravel())
| VADER_Sentiment_Analysis-Punctuation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: HiC
# language: python
# name: hic_tls
# ---
# # Make the master table
# +
import os
import sys
import pandas as pd
import subprocess as sp
import glob
os.chdir('/mnt/BioHome/jreyna/jreyna/projects/dchallenge/')
hic_python='/mnt/BioHome/jreyna/software/anaconda3/envs/hic_tls/bin/python'
# default values for the command line
# sys.argv = [0] * 8
# sys.argv[1] = 'results/main/2021_Nikhil_eQTL/Results/Colocalization/T1D_34012112_Gaulton/'
# sys.argv[1] += 'BLUEPRINT_eQTL_Monocyte/FINAL_Summary_Coloc_Gene_SNP_Pairs.bed'
# sys.argv[2] = 'results/refs/ensembl/gencode.v19.annotation.bed'
# sys.argv[3] = 'results/main/2021_Nikhil_eQTL/Data/FitHiChIP_Loops/CM/FitHiChIP_L/FitHiChIP.interactions_FitHiC_Q0.01.bed'
# sys.argv[4] = 'results/refs/spp/SPP_D-Challenge_networks.xlsx'
# sys.argv[5] = 'results/refs/hg19/hg19.chrom.sizes'
# sys.argv[6] = 'results/main/2021_Nikhil_eQTL/Data/eqtl_sqtl_summ_stats/BLUEPRINT_eQTL/Monocyte.txt.gz'
# sys.argv[7] = 'results/main/loop_analysis/washU/'
# # parsing the commandline arguments
# coloc_fn = sys.argv[1]
# genes_fn = sys.argv[2]
# loop_fn = sys.argv[3]
# spp_fn = sys.argv[4]
# gs_fn = sys.argv[5]
# eqtl_fn = sys.argv[6]
# outdir = sys.argv[7]
# # setting the output file names
# os.makedirs(outdir, exist_ok=True)
# +
# # %load ./scripts/loop_analysis/Annotation_SNPs_with_Surround_Genes_Loops.sh
# #!/usr/bin/env python
# In[1]:
# Commandline Specification
# Input
# ----------------------------------------------
# 1) colocalization file x
# 2) gencode gene annotation file in bed format x
# 3) loop data x
# 4) spp network data x
# 5) reference chrom sizes x
# Output
# ----------------------------------------------
# 1) snp-gene loop summary file
# 2) snp-gene pairs longrange file with index
# 3) snp-gene loops longrange file with index
# default values for the command line
#sys.argv = [0] * 7
#sys.argv[1] = 'results/main/2021_Nikhil_eQTL/Results/Colocalization/T1D_34012112_Gaulton/'
#sys.argv[1] += 'BLUEPRINT_eQTL_Monocyte/FINAL_Summary_Coloc_Gene_SNP_Pairs.bed'
#sys.argv[2] = 'results/refs/ensembl/gencode.v19.annotation.bed'
#sys.argv[3] = 'results/main/2021_Nikhil_eQTL/Data/FitHiChIP_Loops/CM/FitHiChIP_L/FitHiChIP.interactions_FitHiC_Q0.01.bed'
#sys.argv[4] = 'results/refs/spp/SPP_D-Challenge_networks.xlsx'
#sys.argv[5] = 'results/refs/hg19/hg19.chrom.sizes'
#sys.argv[6] = 'results/main/loop_analysis/washU/'
script = "scripts/loop_analysis/Annotate_Coloc_SNPs_with_Nearby_Genes_Loops.py"
gs = "results/refs/hg19/hg19.chrom.sizes"
gencode = "results/refs/ensembl/gencode.v19.annotation.bed"
spp = "results/refs/spp/SPP_D-Challenge_networks.xlsx"
# template file names for colocalization, hichip, eqtl and outdir
coloc_tmp = "results/main/2021_Nikhil_eQTL/Results/Colocalization/{gwas}/{eqtl}_{cline}/FINAL_Summary_Coloc_Gene_SNP_Pairs.bed"
fithichip_tmp = "results/main/2021_Nikhil_eQTL/Data/FitHiChIP_Loops/{cline}/FitHiChIP_S/FitHiChIP.interactions_FitHiC_Q0.01.bed"
eqtl_tmp = "results/main/2021_Nikhil_eQTL/Data/eqtl_sqtl_summ_stats/{eqtl}/{cline}.txt.gz"
outdir_tmp = "results/main/loop_analysis/Coloc_Approach/{gwas}/{dice_cline}/{eqtl_study}/{eqtl_cline}/"
# getting a list of DICE clines with HiChIP data
fithichip_clines = glob.glob("results/main/2021_Nikhil_eQTL/Data/FitHiChIP_Loops/*")
fithichip_clines = [x.split('/')[-1] for x in fithichip_clines]
# eqtl mapper
eqtl_mapper = pd.read_table('results/main/2021_Nikhil_eQTL/Data/eqtl_sqtl_summ_stats/eqtl.cline.mapper.study.tsv')
eqtl_mapper.sort_values(['will_analyze', 'study', 'dice_shortname'], ascending=[False, True, True], inplace=True)
eqtl_mapper[['study', 'dice_shortname', 'will_analyze', 'eqtl_file']]
eqtl_mapper = eqtl_mapper.loc[eqtl_mapper['will_analyze'] == 'Yes']
eqtl_mapper = eqtl_mapper.loc[eqtl_mapper.dice_shortname.isin(fithichip_clines)]
eqtl_clines = eqtl_mapper['eqtl_file'].str.split('/')
eqtl_clines = [x[-1].split('.')[0] for x in eqtl_clines]
eqtl_mapper['eqtl_cline'] = eqtl_clines
eqtl_mapper = eqtl_mapper[['study', 'dice_shortname', 'eqtl_cline', 'eqtl_file']]
# -
eqtl_mapper.head()
# +
# get gwas runs
gwas_runs = [os.path.basename(x) for x in glob.glob('results/main/2021_Nikhil_eQTL/Data/T1D_GWAS/*')]
gwas_runs = gwas_runs[2:3]
# get eqtl runs
eqtl_runs = [x for x in glob.glob('results/main/2021_Nikhil_eQTL/Data/eqtl_sqtl_summ_stats/*/*')]
eqtl_runs = [x for x in eqtl_runs if x != 'README' and 'eQTL' in x]
# -
eqtl_mapper.head()
qscripts_dir = 'results/main/loop_analysis/Coloc_Approach/T1D_34012112_Gaulton/qjobs/'
os.makedirs(qscripts_dir, exist_ok=True)
for gwas in gwas_runs:
for i, sr in eqtl_mapper.iterrows():
coloc = coloc_tmp.format(gwas=gwas, eqtl=sr.study, cline=sr.eqtl_cline)
fithichip = fithichip_tmp.format(cline=sr.dice_shortname)
outdir = outdir_tmp.format(gwas=gwas,
dice_cline=sr.dice_shortname,
eqtl_cline=sr.eqtl_cline,
eqtl_study=sr.study)
cmd = "{} {} {} {} {} {} {} {} {}".format(hic_python, script, coloc, gencode,
fithichip, spp, gs, sr.eqtl_file, outdir)
if not os.path.exists(outdir):
# script_fn = '{}_{}_{}_{}.qscript'.format(gwas, sr.dice_shortname, sr.eqtl_cline, sr.study)
# script_fn = os.path.join(qscripts_dir, script_fn)
# with open(script_fn, 'w') as fw:
# fw.write(cmd)
job = sp.Popen(cmd, shell=True, stderr=sp.PIPE, stdout=sp.PIPE)
out, err = job.communicate()
print('Now running: {}'.format(cmd))
print(out.decode())
print(err.decode())
print('Results can now be found at: {}'.format(outdir))
else:
msg = 'Previously ran {}'.format(outdir)
print(msg)
print()
| scripts/loop_analysis/Annotate_Coloc_SNPs_with_Nearby_Genes_Loops.BashGO.py.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
# ---
# # Answers: The Basics
#
# Provided here are answers to the practice questions at the end of "The Basics".
# ## Variables
# **Variables Q1**.
# actual values stored will differ
var_float = 9.29
var_str = 'cogs18'
var_bool = False
var_tuple = (1,2,3)
var_dict = {'a':1}
# **Variables Q2**.
scenario_A = 'tuple'
scenario_B = 'list'
scenario_C = 'dictionary'
scenario_D = 'dictionary'
# ## Operators
# **Operators Q1**.
var_even = (var_high + var_low) % var_mid
var_odd = (var_mid ** var_low) // var_high
# **Operators Q2**.
# +
# specific values will differ
my_age = 31
pres_age = 78
true_compar = my_age < pres_age
false_compar = pres_age == my_age
# -
# **Operators Q3**.
yes_member = current_holiday in spring_holidays
no_member = current_holiday not in spring_holidays
# **Operators Q4**.
# actual operations will differ
var_odd = (9 + 2 - 1) % 3
var_even = 25 / 5 * 2 // 1
var_operator = var_odd ** var_even + 5
# **Operators Q5**.
# actual operations will differ
true_var = (var_low < var_mid) or (var_high >= var_mid)
false_var = (var_mid != var_low) and (var_high < var_mid)
# **Operators Q6**.
# actual variable creation will differ
comp_a = 7 > 6 and 6 < 7
comp_b = 3 <= 3 or 4 <= 3
comp_c = 3 == 3 and not 3 != 3
**Operators Q7**.
# actual operations will differ
memb_a = 'love' in my_string
memb_b = 'Exercises' not in my_list
# ## Conditionals
# **Conditionals Q1**.
# +
comparison_name = 'Shannon'
### BEGIN SOLUTION
# my_name will differ based on person writing code
my_name = 'Shannon'
if len(my_name) < len(comparison_name):
output = 'shorter'
elif len(my_name) > len(comparison_name):
output = 'longer'
elif len(my_name) == len(comparison_name):
output = 'same length'
else:
print('something has gone awry')
# -
# ## Topics Synthesis
# **Synthesis Q1**.
# actual values stored will differ
var_cat = 'cogs' + '18'
var_sum = 9 + 29
# **Synthesis Q2**.
# actual values stored will differ
var_int = 10
var_float = 1.0
var_combined = var_int + var_float
# **Synthesis Q3**.
# actual variable creation will differ
var_a = 7.3
var_b = 6 == 6 and 3 <= 4
var_c = (6 + 3) * 4
# **Synthesis Q4**.
# actual values stored will differ
var_a = 'abcd'
var_b = 6.0
var_c = (1,2,3)
| _build/jupyter_execute/content/0X-answers/02-answers.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: conda_python3
# language: python
# name: conda_python3
# ---
# %matplotlib inline
import matplotlib.pyplot as plt
# +
plt.plot([1,2,3,4], [1,3,9,16])
plt.title('this is a title')
plt.xlabel('x label')
plt.ylabel('h label')
plt.show()
# -
import pandas
# +
df=pandas.read_excel('s3://wei-ia241-jd/house_price.xls')
df.sort_values(by=['built_in']).plot(x='built_in', y='price')
# -
avg_price_per_year=df.groupby('built_in').mean()['price']
avg_price_per_year.plot()
df['price'].hist()
avg_price_per_year=df.groupby('house_type').mean()['price']
avg_price_per_year[:]
avg_price_per_year.plot.bar()
count_per_type = df['house_type'].value_counts()
count_per_type=[:]
count_per_type.plot.pie()
df[:10]
df.plot.scatter(x='area',y='price',c='built_in')
| lec13.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda root]
# language: python
# name: conda-root-py
# ---
# # Drawing samples
# ### Curvilinear trapezoidal distribution
#
# To sample from CTrap(a, b, d), make two draws $r_1$ and $r_2$ independently from the standard rectangular distribution $R(0, 1)$ and form
# $$ a_s = (a − d) + 2dr_1 \qquad b_s = (a+b)-a_s , $$
# and
# $$ \xi = a_s + (b_s − a_s)r_2 . $$
#
# In this way $a_s$ is a draw from the rectangular distribution with limits $a \pm d$. $b_s$ is then formed to ensure that the midpoint of $a_s$ and $b_s$ is the prescribed value $x = (a + b)/2$.
#
#
# ### Task
#
# A certificate states that a voltage X lies in the interval 10.0 V ± 0.1 V. No other information is available concerning X, except that it is believed that the magnitude of the interval endpoints is the result of rounding correctly some numerical value. On this basis, that numerical value lies between 0.05 V and 0.15 V, since the numerical value of every point in the interval (0.05, 0.15) rounded to one significant decimal digit is 0.1. The location of the interval can therefore be regarded as fixed, whereas its width is inexact. The best estimate of X is x = 10.0 V.
#
# Based on a = 9.9 V, b = 10.1 V and d = 0.05 V, sample from the PDF and calculate the best estimate and the associated uncertainty.
#
#
# %pylab inline
# +
a = 9.9
b = 10.1
d = 0.05
MCruns = 1000000
r1 = random.rand(MCruns)
r2 = random.rand(MCruns)
a_s = (a-d) + 2*d*r1
b_s = (a+b) - a_s
xi = a_s + (b_s-a_s)*r2
hist(xi, bins = MCruns//1000, edgecolor="none");
x = xi.mean()
ux = xi.std()
print("estimate = %g\tuncertainty = %g"%(x, ux))
axvline(x-ux,color="k");
axvline(x+ux,color="k");
# -
| .ipynb_checkpoints/Drawing samples-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
# ---
# # Build the parent sample of large (LSLGA) galaxies.
#
# The purpose of this notebook is to build the parent sample of galaxies in the Legacy Surveys Galaxy Atlas (LSGA).
#
# The input file is
# * \$LSLGA_DIR/sample/hyperleda-d25min10-18may13.fits
#
# and the final output files are:
# * \$LSLGA_DIR/sample/LSLGA-VERSION.fits -- parent sample of large galaxies
# * \$LSLGA_DIR/sample/LSLGA-VERSION.kd.fits -- like the preceding catalog but with a pre-built KD tree
# * \$LSLGA_DIR/sample/LSLGA-VERSION-DRSUFFIX.fits -- large galaxies in the specified data release footprint
#
# where *VERSION* is specified in *LSLGA.io.parent_version* and *DRSUFFIX* is specified below.
# ### Imports and other preliminaries.
import os, sys
import time
from contextlib import redirect_stdout
import numpy as np
import numpy.ma as ma
import LSLGA.io
import LSLGA.match
from legacypipe.survey import LegacySurveyData
import multiprocessing
nproc = multiprocessing.cpu_count() // 2
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style='ticks', font_scale=1.5, palette='Set2')
# %matplotlib inline
drsuffix = 'dr6-dr7'
# #### Some choices.
rebuild_parent = False
rebuild_dr_sample = True
# ### Build the parent sample.
#
# The parent sample is defined as the set of galaxies in the full Hyperleda catalog with a finite magnitude estimate. (Visually investigating the objects without magnitude estimates reveals that the overwhelming majority are spurious.)
#
# There is also an option here to apply minimum and maximum angular diameter cuts, but in detail we do not apply any.
#
# In addition, to flag galaxies near bright stars; a particularly nice example (that we do not want to throw out!) is [IC 2204](http://legacysurvey.org/viewer?ra=115.3331&dec=34.2240&zoom=12&layer=mzls+bass-dr6), a beautiful r=13.4 disk galaxy at a redshift of z=0.0155 with an angular diameter of approximately 1.1 arcmin.
#
# Finally, we flag galaxies within the (current) DESI footprint.
def build_parent(mindiameter=10/60, maxdiameter=1e4):
"""Build the parent catalog.
"""
import desimodel.io
import desimodel.footprint
from astrometry.libkd.spherematch import tree_build_radec, tree_search_radec
# Read the Hyperleda catalog.
leda = LSLGA.io.read_hyperleda(verbose=True)
magcut = np.isfinite( leda['mag'] )
leda = leda[magcut]
print(' Removed {}/{} ({:.2f}%) objects with no magnitude estimate.'.format(
np.sum(~magcut), len(leda), 100*np.sum(~magcut)/len(leda)))
# Flag galaxies in the DESI footprint.
tiles = desimodel.io.load_tiles(onlydesi=True)
indesi = desimodel.footprint.is_point_in_desi(tiles, ma.getdata(leda['ra']),
ma.getdata(leda['dec']))
print(' Identified {} ({}) objects inside (outside) the DESI footprint.'.format(
np.sum(indesi), np.sum(~indesi)))
diamcut = (leda['d25'] >= mindiameter) * (leda['d25'] <= maxdiameter)
print(' Removed {}/{} ({:.2f}%) objects with D(25) < {:.3f} and D(25) > {:.3f} arcmin.'.format(
np.sum(~diamcut), len(leda), 100*np.sum(~diamcut)/len(leda), mindiameter, maxdiameter))
# Reject objects classified as "g"
# objnotg = np.hstack([np.char.strip(obj) != 'g' for obj in leda['objtype']])
# print(' Removed {} objects with objtype == g'.format(np.sum(~objnotg)), flush=True)
keep = np.where( diamcut )[0]
#keep = np.where( indesi * diamcut )[0]
parent = leda[keep]
parent['in_desi'] = indesi.astype(bool)
# Flag galaxies near bright stars.
tycho = LSLGA.io.read_tycho(verbose=True)
kdparent = tree_build_radec(parent['ra'], parent['dec'])
nearstar = np.zeros( len(parent), dtype=bool)
for star in tycho:
I = tree_search_radec(kdparent, star['ra'], star['dec'], star['radius'])
if len(I) > 0:
nearstar[I] = True
print(' Found {}/{} ({:.2f}%) galaxies near a Tycho-2 star.'.format(
np.sum(nearstar), len(leda), 100*np.sum(nearstar)/len(leda)))
parent['near_brightstar'] = nearstar.astype(bool)
parentfile = LSLGA.io.get_parentfile()
kdparentfile = LSLGA.io.get_parentfile(kd=True)
print('Writing {} objects to {}'.format(len(parent), parentfile))
parent.write(parentfile, overwrite=True)
print()
print('Writing {}'.format(kdparentfile))
cmd = 'startree -i {} -o {} -T -P -k -n largegals'.format(parentfile, kdparentfile)
print(cmd)
_ = os.system(cmd)
if rebuild_parent:
# %time build_parent()
parent, kdparent = LSLGA.io.read_parent(verbose=True), LSLGA.io.read_parent(kd=True, verbose=True)
parent
# #### Some sanity QA.
def qa_mag_d25():
fig, ax = plt.subplots(figsize=(7, 5))
ax.hexbin(parent['mag'], np.log10(parent['d25']), extent=(0, 25, -1, 3),
mincnt=1, cmap='viridis')
ax.axhline(y=np.log10(10 / 60), ls='-', lw=2, color='k', alpha=0.8)
ax.set_xlabel('B mag')
ax.set_ylabel(r'$\log_{10}\, D_{25}$ (arcmin)')
def qa_radec_parent():
indesi = parent['in_desi']
outdesi = ~indesi
nearstar = parent['near_brightstar']
fig, ax = plt.subplots()
ax.scatter(parent['ra'][outdesi], parent['dec'][outdesi], s=5, label='Outside DESI')
ax.scatter(parent['ra'][indesi], parent['dec'][indesi], s=5, label='In DESI')
ax.scatter(parent['ra'][nearstar], parent['dec'][nearstar],
s=1, color='k', label='Near Bright Star')
#ax.scatter(sample['ra'][idr7], sample['dec'][idr7], s=10, label='In DR7')
ax.set_xlabel('RA')
ax.set_ylabel('Dec')
ax.set_xlim(360, 0)
ax.set_ylim(-90, 120)
ax.legend(loc='upper left', fontsize=10, frameon=True, ncol=3)
qa_radec_parent()
qa_mag_d25()
# +
# This fails because of a matplotlib, basemap collision.
#from LSLGA.qa import qa_binned_radec
#qa_binned_radec(parent)
# -
# ### Find the sample of galaxies in the DR6/DR7 footprint.
survey_dr6 = LegacySurveyData(survey_dir='/global/cscratch1/sd/dstn/dr6plus')
survey_dr7 = LegacySurveyData(survey_dir='/global/cscratch1/sd/desiproc/dr7')
def _build_drsample_one(args):
"""Wrapper function for the multiprocessing."""
return build_drsample_one(*args)
def build_drsample_one(onegal, verbose=False):
"""Wrapper function to find overlapping grz CCDs for a single galaxy.
"""
diam = 1.0 * onegal['d25'] # [arcmin]
wcs = LSLGA.match.simple_wcs(onegal, diam)
ccds = survey_dr7.ccds_touching_wcs(wcs, ccdrad=None)
if ccds is not None:
dr = 'dr7'
survey = survey_dr7
else:
ccds = survey_dr6.ccds_touching_wcs(wcs, ccdrad=None)
if ccds is not None:
dr = 'dr6'
survey = survey_dr6
else:
return [None, None]
if ccds is not None:
if 'g' in ccds.filter and 'r' in ccds.filter and 'z' in ccds.filter:
nccd = len(ccds)
ccds.galaxy_npix = np.zeros(nccd).astype('int') # number of pixels in cutout
ccds.galaxy_fracsatur = np.zeros(nccd).astype('f4')
ccds.galaxy_fracinterp = np.zeros(nccd).astype('f4')
onegal['dr'] = dr.upper()
if diam > 1.0:
ccds = LSLGA.match.get_masked_pixels(ccds, survey, wcs)
if verbose:
print('Galaxy {}: {} CCDs, RA = {:.5f}, Dec = {:.5f}, Diameter={:.4f} arcmin'.format(
onegal['galaxy'], len(ccds), onegal['ra'], onegal['dec'], diam))
sys.stdout.flush()
return [onegal, ccds]
return [None, None]
def build_drsample(cat, use_nproc=nproc):
"""Build the full sample of galaxies with grz coverage in DR6+DR7.
"""
from astropy.table import vstack, Column
from astrometry.util.fits import merge_tables
cat.add_column(Column(name='dr', length=len(cat), dtype='S3'))
sampleargs = list()
for gg in cat:
sampleargs.append( (gg, True) ) # the Boolean here refers to verbose
if use_nproc > 1:
p = multiprocessing.Pool(nproc)
result = p.map(_build_drsample_one, sampleargs)
p.close()
else:
result = list()
for args in sampleargs:
result.append(_build_drsample_one(args))
# Remove non-matching objects and write out the sample
rr = list(zip(*result))
outcat = vstack(list(filter(None, rr[0])))
outccds = merge_tables(list(filter(None, rr[1])))
print('Found {}/{} objects in the DR6/DR7 footprint.'.format(len(outcat), len(cat)))
return outcat, outccds
# +
#rr = build_sample_one(parent[4264])
#rr = build_sample_one(parent[321089], verbose=True) # NGC2146, DR6
#drsample, drccds = build_drsample(parent[321089:322099])
# -
if rebuild_dr_sample:
drsamplelogfile = os.path.join(LSLGA.io.sample_dir(), 'build-sample-{}.log'.format(drsuffix))
print('Building the sample.')
print('Logging to {}'.format(drsamplelogfile))
t0 = time.time()
with open(drsamplelogfile, 'w') as log:
with redirect_stdout(log):
drsample, drccds = build_drsample(parent)
print('Found {}/ {} galaxies in the LS footprint.'.format(len(drsample), len(parent)))
print('Total time = {:.3f} minutes.'.format( (time.time() - t0) / 60 ) )
# +
#drsample
# -
stop
# #### Cross-reference the group catalog to the parent sample and then write out.
# +
sample = parentcat[np.where( np.in1d( parentcat['groupid'], groupsample['groupid']) )[0]]
print('Writing {}'.format(samplefile))
sample.write(samplefile, overwrite=True)
print('Writing {}'.format(groupsamplefile))
groupsample.write(groupsamplefile, overwrite=True)
# -
# #### Some sanity QA
def qa_radec_dr(parent, sample):
idr5 = sample['dr'] == 'dr5'
idr6 = sample['dr'] == 'dr6'
idr7 = sample['dr'] == 'dr7'
fig, ax = plt.subplots()
ax.scatter(parent['ra'], parent['dec'], alpha=0.5, s=5, label='Parent Catalog')
ax.scatter(sample['ra'][idr5], sample['dec'][idr5], s=10, label='In DR5')
ax.scatter(sample['ra'][idr6], sample['dec'][idr6], s=10, label='In DR6')
#ax.scatter(sample['ra'][idr7], sample['dec'][idr7], s=10, label='In DR7')
ax.set_xlabel('RA')
ax.set_ylabel('Dec')
ax.legend(loc='upper left', fontsize=10, frameon=True)#, ncol=3)
qa_radec_dr(groupcat, groupsample)
stop
leda[leda['d25'] > 0.5]
# ### Get viewer cutouts of a subset of the groups.
sample = astropy.table.Table.read(samplefile)
groupsample = astropy.table.Table.read(groupsamplefile)
ww = ['g' in oo for oo in sample['objtype']]
sample[ww]
jpgdir = os.path.join(LSLGAdir, 'cutouts', 'jpg')
if not os.path.isdir(jpgdir):
os.mkdir(jpgdir)
def get_groupname(group):
return 'group{:08d}-n{:03d}'.format(group['groupid'], group['nmembers'])
def get_layer(group):
if group['dr'] == 'dr6':
layer = 'mzls+bass-dr6'
elif group['dr'] == 'dr5':
layer = 'decals-dr5'
elif group['dr'] == 'dr7':
layer = 'decals-dr5'
return layer
def _get_cutouts_one(args):
"""Wrapper function for the multiprocessing."""
return get_cutouts_one(*args)
def get_cutouts_one(group, clobber=False):
"""Get viewer cutouts for a single galaxy."""
layer = get_layer(group)
groupname = get_groupname(group)
diam = group_diameter(group) # [arcmin]
size = np.ceil(diam * 60 / PIXSCALE).astype('int') # [pixels]
imageurl = '{}/?ra={:.8f}&dec={:.8f}&pixscale={:.3f}&size={:g}&layer={}'.format(
cutouturl, group['ra'], group['dec'], PIXSCALE, size, layer)
jpgfile = os.path.join(jpgdir, '{}.jpg'.format(groupname))
cmd = 'wget --continue -O {:s} "{:s}"' .format(jpgfile, imageurl)
if os.path.isfile(jpgfile) and not clobber:
print('File {} exists...skipping.'.format(jpgfile))
else:
if os.path.isfile(jpgfile):
os.remove(jpgfile)
print(cmd)
os.system(cmd)
#sys.stdout.flush()
# Get the fraction of masked pixels
#im = np.asarray( Image.open(jpgfile) )
#area = np.product(im.shape[:2])
#fracmasked = ( np.sum(im[:, :, 0] == 32) / area,
# np.sum(im[:, :, 1] == 32) / area,
# np.sum(im[:, :, 2] == 32) / area )
return #np.max(fracmasked)
def get_cutouts(groupsample, use_nproc=nproc, clobber=False):
"""Get viewer cutouts of the whole sample."""
cutoutargs = list()
for gg in groupsample:
cutoutargs.append( (gg, clobber) )
if use_nproc > 1:
p = multiprocessing.Pool(nproc)
p.map(_get_cutouts_one, cutoutargs)
p.close()
else:
for args in cutoutargs:
_get_cutouts_one(args)
return
nmin = 2
indx = groupsample['nmembers'] >= nmin
print('Getting cutouts of {} groups with >={} member(s).'.format(np.sum(indx), nmin))
#groupsample['fracmasked'][indx] = get_cutouts(groupsample[indx], clobber=True)#, use_nproc=1)
# +
#get_cutouts_one(groupsample[0], clobber=False)
# -
cutlogfile = os.path.join(LSLGAdir, 'cutouts', 'get-cutouts-{}.log'.format(drsuffix))
print('Getting viewer cutouts.')
print('Logging to {}'.format(cutlogfile))
t0 = time.time()
with open(cutlogfile, 'w') as log:
with redirect_stdout(log):
get_cutouts(groupsample[indx], clobber=False)
print('Total time = {:.3f} minutes.'.format( (time.time() - t0) / 60 ))
# #### Add labels and a scale bar.
barlen = np.round(60.0 / PIXSCALE).astype('int') # [1 arcmin in pixels]
fonttype = os.path.join(LSLGAdir, 'cutouts', 'Georgia.ttf')
def get_galaxy(group, sample, html=False):
"""List the galaxy name.
"""
these = group['groupid'] == sample['groupid']
galaxy = [gg.decode('utf-8').strip().lower() for gg in sample['galaxy'][these].data]
if html:
galaxy = ' '.join(np.sort(galaxy)).upper()
else:
galaxy = ' '.join(np.sort(galaxy))
return galaxy
def _add_labels_one(args):
"""Wrapper function for the multiprocessing."""
return add_labels_one(*args)
def add_labels_one(group, sample, clobber=False, nothumb=False):
jpgdir = os.path.join(LSLGAdir, 'cutouts', 'jpg')
pngdir = os.path.join(LSLGAdir, 'cutouts', 'png')
if not os.path.isdir(pngdir):
os.mkdir(pngdir)
groupname = get_groupname(group)
galaxy = get_galaxy(group, sample, html=True)
jpgfile = os.path.join(jpgdir, '{}.jpg'.format(groupname))
pngfile = os.path.join(pngdir, '{}.png'.format(groupname))
thumbfile = os.path.join(pngdir, 'thumb-{}.png'.format(groupname))
if os.path.isfile(jpgfile):
if os.path.isfile(pngfile) and not clobber:
print('File {} exists...skipping.'.format(pngfile))
else:
im = Image.open(jpgfile)
sz = im.size
fntsize = np.round(sz[0]/28).astype('int')
width = np.round(sz[0]/175).astype('int')
font = ImageFont.truetype(fonttype, size=fntsize)
draw = ImageDraw.Draw(im)
# Label the group--
draw.text((0+fntsize*2, 0+fntsize*2), galaxy, font=font)
# Add a scale bar--
x0, x1, yy = sz[1]-fntsize*2-barlen, sz[1]-fntsize*2, sz[0]-fntsize*2
draw.line((x0, yy, x1, yy), fill='white', width=width)
im.save(pngfile)
# Generate a thumbnail
if not nothumb:
cmd = 'convert -thumbnail 300x300 {} {}'.format(pngfile, thumbfile)
os.system(cmd)
def add_labels(groupsample, sample, clobber=False):
labelargs = list()
for group in groupsample:
labelargs.append((group, sample, clobber))
if nproc > 1:
p = multiprocessing.Pool(nproc)
res = p.map(_add_labels_one, labelargs)
p.close()
else:
for args in labelargs:
res = _add_labels_one(args)
# %time add_labels(groupsample, sample, clobber=True)
# +
#add_labels_one(groupsample[10], sample, clobber=True)
# -
# ### Finally, assemble the webpage of good and rejected gallery images.
#
# To test the webpage before release, do
#
# ```bash
# rsync -auvP $LLSLGLSLGLSLGALSLGALSLGAA/cutouts/png /global/project/projectdirs/cosmo/www/temp/ioannis/LSLGA/
# rsync -auvP /global/cscratch1/sd/ioannis/LSLGA/cutouts/*.html /global/project/projectdirs/cosmo/www/temp/ioannis/LSLGA/
# ```
# or
# ```bash
# rsync -auvP /global/cscratch1/sd/ioannis/LSLGA/cutouts/png /global/project/projectdirs/cosmo/www/temp/ioannis/LSLGA/
# rsync -auvP /global/cscratch1/sd/ioannis/LSLGA/cutouts/*.html /global/project/projectdirs/cosmo/www/temp/ioannis/LSLGA/
# ```
# and then the website can be viewed here:
# http://portal.nersc.gov/project/cosmo/temp/ioannis/LSLGA
reject = []
toss = np.zeros(len(groupsample), dtype=bool)
for ii, gg in enumerate(groupsample['groupid']):
for rej in np.atleast_1d(reject):
toss[ii] = rej in gg.lower()
if toss[ii]:
break
print('Rejecting {} groups.'.format(np.sum(toss)))
groupkeep = groupsample[~toss]
if np.sum(toss) > 0:
grouprej = groupsample[toss]
else:
grouprej = []
def html_rows(_groupkeep, sample, nperrow=4):
# Not all objects may have been analyzed.
these = [os.path.isfile(os.path.join(LSLGAdir, 'cutouts', 'png', '{}.png'.format(
get_groupname(gg)))) for gg in _groupkeep]
groupkeep = _groupkeep[these]
nrow = np.ceil(len(groupkeep) / nperrow).astype('int')
groupsplit = list()
for ii in range(nrow):
i1 = nperrow*ii
i2 = nperrow*(ii+1)
if i2 > len(groupkeep):
i2 = len(groupkeep)
groupsplit.append(groupkeep[i1:i2])
print('Splitting the sample into {} rows with {} mosaics per row.'.format(nrow, nperrow))
html.write('<table class="ls-gallery">\n')
html.write('<tbody>\n')
for grouprow in groupsplit:
html.write('<tr>\n')
for group in grouprow:
groupname = get_groupname(group)
galaxy = get_galaxy(group, sample, html=True)
pngfile = os.path.join('cutouts', 'png', '{}.png'.format(groupname))
thumbfile = os.path.join('cutouts', 'png', 'thumb-{}.png'.format(groupname))
img = 'src="{}" alt="{}"'.format(thumbfile, galaxy)
#img = 'class="ls-gallery" src="{}" alt="{}"'.format(thumbfile, nicename)
html.write('<td><a href="{}"><img {}></a></td>\n'.format(pngfile, img))
html.write('</tr>\n')
html.write('<tr>\n')
for group in grouprow:
groupname = get_groupname(group)
galaxy = '{}: {}'.format(groupname.upper(), get_galaxy(group, sample, html=True))
layer = get_layer(group)
href = '{}/?layer={}&ra={:.8f}&dec={:.8f}&zoom=12'.format(viewerurl, layer, group['ra'], group['dec'])
html.write('<td><a href="{}" target="_blank">{}</a></td>\n'.format(href, galaxy))
html.write('</tr>\n')
html.write('</tbody>\n')
html.write('</table>\n')
with open(htmlfile, 'w') as html:
html.write('<html><head>\n')
html.write('<style type="text/css">\n')
html.write('table.ls-gallery {width: 90%;}\n')
#html.write('img.ls-gallery {display: block;}\n')
#html.write('td.ls-gallery {width: 100%; height: auto}\n')
#html.write('td.ls-gallery {width: 100%; word-wrap: break-word;}\n')
html.write('p.ls-gallery {width: 80%;}\n')
html.write('</style>\n')
html.write('</head><body>\n')
html.write('<h1>Legacy Surveys Large Galaxy Atlas</h1>\n')
html.write("""<p class="ls-gallery">Each thumbnail links to a larger image while the galaxy
name below each thumbnail links to the <a href="http://legacysurvey.org/viewer">Sky Viewer</a>.
For reference, the horizontal white bar in the lower-right corner of each image represents
one arcminute.</p>\n""")
#html.write('<h2>Large Galaxy Sample</h2>\n')
html_rows(groupkeep, sample)
html.write('</body></html>\n')
if len(grouprej) > 0:
with open(htmlfile_reject, 'w') as html:
html.write('<html><head>\n')
html.write('<style type="text/css">\n')
html.write('img.ls-gallery {display: block;}\n')
html.write('td.ls-gallery {width: 20%; word-wrap: break-word;}\n')
html.write('</style>\n')
html.write('</head><body>\n')
html.write('<h1>Large Galaxies - Rejected</h1>\n')
html_rows(grouprej, sample)
html.write('</body></html>\n')
stop
# +
#ww = np.where(['NGC' in gg for gg in parent['galaxy']])[0]
#[print(gg.decode('utf-8'), rr, dd) for (gg, rr, dd) in zip(parent['galaxy'][ww].data, parent['ra'][ww].data, parent['dec'][ww].data)]
#print(ww[4])
#parent[ww]
| doc/build-lslga-parent.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
import pandas as pd
import geopandas
import libpysal
import momepy
import scipy
from dask.distributed import Client, LocalCluster, as_completed
# -
workers = 8
client = Client(LocalCluster(n_workers=workers, threads_per_worker=1))
client
cross_chunk = pd.read_parquet('../../urbangrammar_samba/spatial_signatures/cross-chunk_indices.pq')
def generate_w(chunk_id):
# load cells of a chunk
cells = geopandas.read_parquet(f"../../urbangrammar_samba/spatial_signatures/morphometrics/cells/cells_{chunk_id}.pq")
# add neighbouring cells from other chunks
cross_chunk_cells = []
for chunk, inds in cross_chunk.loc[chunk_id].indices.iteritems():
add_cells = geopandas.read_parquet(f"../../urbangrammar_samba/spatial_signatures/morphometrics/cells/cells_{chunk}.pq").iloc[inds]
cross_chunk_cells.append(add_cells)
df = cells.append(pd.concat(cross_chunk_cells, ignore_index=True), ignore_index=True)
w = libpysal.weights.Queen.from_dataframe(df, geom_col='tessellation')
w3 = momepy.sw_high(k=3, weights=w)
scipy.sparse.save_npz(f"../../urbangrammar_samba/spatial_signatures/weights/w_{chunk_id}.npz", w.sparse)
scipy.sparse.save_npz(f"../../urbangrammar_samba/spatial_signatures/weights/w3_{chunk_id}.npz", w3.sparse)
return f"Chunk {chunk_id} processed sucessfully."
# %%time
inputs = iter(range(103))
futures = [client.submit(generate_w, next(inputs)) for i in range(workers)]
ac = as_completed(futures)
for finished_future in ac:
# submit new future
try:
new_future = client.submit(generate_w, next(inputs))
ac.add(new_future)
except StopIteration:
pass
print(finished_future.result())
client.close()
| docs/_sources/measuring/_generate_w.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 pandas.plotting import register_matplotlib_converters
import pandas as pd
import matplotlib.pylab as plt
from matplotlib.pylab import rcParams
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.arima_model import ARIMA
from sklearn.metrics import mean_squared_error
# +
# figure parameters
rcParams['figure.figsize'] = 12, 6
# read data
dateparse = lambda dates: pd.datetime.strptime(dates, '%Y-%m')
data = pd.read_csv('./data/AirPassengers.csv', parse_dates=['Month'], index_col='Month',date_parser=dateparse)
print(data.head())
ts = data['Passengers']
# +
# decompose time series (optional)
decomposition = seasonal_decompose(ts, two_sided=False)
trend = decomposition.trend
seasonal = decomposition.seasonal
residual = decomposition.resid
residual.dropna(inplace=True)
register_matplotlib_converters()
plt.subplot(411)
plt.plot(ts, label='原始')
plt.legend(loc='best')
plt.subplot(412)
plt.plot(trend, label='趋势')
plt.legend(loc='best')
plt.subplot(413)
plt.plot(seasonal,label='季节')
plt.legend(loc='best')
plt.subplot(414)
plt.plot(residual, label='残差')
plt.legend(loc='best')
plt.tight_layout()
print(ts.tail())
print(trend.tail())
print(seasonal.tail())
print(residual.tail())
# -
# create training and test set
size = int(len(residual) * 0.8)
train, test = residual[0:size], residual[size:len(residual)]
plt.plot(train.index, train, color='blue', label='Training set')
plt.plot(test.index, test, color='green', label='Testing set')
plt.legend()
plt.title('Ground truth training and testing set')
plt.show()
# assess quality of ARIMA models
# 对于测试集进行迭代单步预测
def compare_ARIMA_modes_testing(order):
history = [x for x in train]
predictions_f = list()
predictions_p = list()
for t in range(len(test)):
model = ARIMA(history, order=order)
model_fit = model.fit(disp=-1)
yhat_f = model_fit.forecast()[0][0]
yhat_p = model_fit.predict(start=len(history), end=len(history))[0]
predictions_f.append(yhat_f)
predictions_p.append(yhat_p)
history.append(test[t])
#mean_squared_error即为“误差”的平方的期望值
error_f = mean_squared_error(test, predictions_f)
error_p = mean_squared_error(test, predictions_p)
print('MSE forecast:\t\t\t{:1.4f}'.format(error_f))
print('MSE predict:\t\t\t{:1.4f}'.format(error_p))
return {'Predictions forecast': pd.Series(predictions_f,index=test.index),
'Predictions predict': pd.Series(predictions_p,index=test.index),
'MSE forecast': error_f,
'MSE predict': error_p}
ar_testing = compare_ARIMA_modes_testing((1, 0, 0))
ma_testing = compare_ARIMA_modes_testing((0, 1, 0))
ig_testing = compare_ARIMA_modes_testing((0, 0, 1))
arma_testing = compare_ARIMA_modes_testing((1, 1, 0))
igma_testing = compare_ARIMA_modes_testing((0, 1, 1))
arig_testing = compare_ARIMA_modes_testing((1, 0, 1))
arima_testing = compare_ARIMA_modes_testing((1, 1, 1))
# forecast and predict are identical for AR
plt.plot(test, label='Ground Truth')
plt.plot(ar_testing['Predictions forecast'], color='red', label='.forecast()')
plt.plot(ar_testing['Predictions predict'], color='green', label='.predict()')
plt.legend(loc='best')
plt.title('AR')
plt.show(block=False)
# forecast and predict are different for ARMA
plt.plot(test, label='Ground Truth')
plt.plot(arma_testing['Predictions forecast'], color='red', label='.forecast()')
plt.plot(arma_testing['Predictions predict'], color='green', label='.predict()')
plt.legend()
plt.title('ARMA')
plt.show()
# forecast and predict are different for ARIMA
plt.plot(test, label='Ground Truth')
plt.plot(arima_testing['Predictions forecast'], color='red', label='.forecast()')
plt.plot(arima_testing['Predictions predict'], color='green', label='.predict()')
plt.legend()
plt.title('ARIMA')
plt.show()
# compare forecasting results of ARIMA models
# for iterative forecasting
def compare_ARIMA_modes(order):
history_f = [x for x in train]
history_p = [x for x in train]
predictions_f = list()
predictions_p = list()
for t in range(len(test)):
model_f = ARIMA(history_f, order=order)
model_p = ARIMA(history_p, order=order)
model_fit_f = model_f.fit(disp=-1)
model_fit_p = model_p.fit(disp=-1)
yhat_f = model_fit_f.forecast()[0][0]
yhat_p = model_fit_p.predict(start=len(history_p), end=len(history_p))[0]
predictions_f.append(yhat_f)
predictions_p.append(yhat_p)
history_f.append(yhat_f)
history_f.append(yhat_p)
error_f = mean_squared_error(test, predictions_f)
error_p = mean_squared_error(test, predictions_p)
print('MSE forecast:\t\t\t{:1.4f}'.format(error_f))
print('MSE predict:\t\t\t{:1.4f}'.format(error_p))
return {'Predictions forecast': pd.Series(predictions_f,index=test.index),
'Predictions predict': pd.Series(predictions_p,index=test.index),
'MSE forecast': error_f,
'MSE predict': error_p}
ar = compare_ARIMA_modes((1, 0, 0))
ma = compare_ARIMA_modes((0, 1, 0))
ig = compare_ARIMA_modes((0, 0, 1))
arma = compare_ARIMA_modes((1, 1, 0))
igma = compare_ARIMA_modes((0, 1, 1))
arig = compare_ARIMA_modes((1, 0, 1))
arima = compare_ARIMA_modes((1, 1, 1))
# forecast and predict are different for AR
plt.plot(test, label='Ground Truth')
plt.plot(ar['Predictions forecast'], color='red', label='.forecast()')
plt.plot(ar['Predictions predict'], color='green', label='.predict()')
plt.legend()
plt.title('AR')
plt.show()
# forecast and predict are different for ARMA
plt.plot(test, label='Ground Truth')
plt.plot(arma['Predictions forecast'], color='red', label='.forecast()')
plt.plot(arma['Predictions predict'], color='green', label='.predict()')
plt.legend()
plt.title('ARMA')
plt.show()
# forecast and predict are different for ARIMA
plt.plot(test, label='Ground Truth')
plt.plot(arima['Predictions forecast'], color='red', label='.forecast()')
plt.plot(arima['Predictions predict'], color='green', label='.predict()')
plt.legend()
plt.title('ARIMA')
plt.show()
# compare forecasting results of ARIMA models
# using the step parameter
def compare_ARIMA_modes_steps(order):
history = [x for x in train]
model = ARIMA(history, order=order)
model_fit = model.fit(disp=-1)
predictions_f_ms = model_fit.forecast(steps=len(test))[0]
predictions_p_ms = model_fit.predict(start=len(history), end=len(history)+len(test)-1)
error_f_ms = mean_squared_error(test, predictions_f_ms)
error_p_ms = mean_squared_error(test, predictions_p_ms)
print('MSE forecast:\t\t\t{:1.4f}'.format(error_f_ms))
print('MSE predict:\t\t\t{:1.4f}'.format(error_p_ms))
return {'Predictions forecast': pd.Series(predictions_f_ms,index=test.index),
'Predictions predict': pd.Series(predictions_p_ms,index=test.index),
'MSE forecast': error_f_ms,
'MSE predict': error_p_ms}
ar_steps = compare_ARIMA_modes_steps((1, 0, 0))
ma_steps = compare_ARIMA_modes_steps((0, 1, 0))
ig_steps = compare_ARIMA_modes_steps((0, 0, 1))
arma_steps = compare_ARIMA_modes_steps((1, 1, 0))
igma_steps = compare_ARIMA_modes_steps((0, 1, 1))
arig_steps = compare_ARIMA_modes_steps((1, 0, 1))
arima_steps = compare_ARIMA_modes_steps((1, 1, 1))
# forecast and predict are identical for AR
plt.plot(test, label='Ground Truth')
plt.plot(ar_steps['Predictions forecast'], color='red', label='.forecast(steps)')
plt.plot(ar_steps['Predictions predict'], color='green', label='.predict(steps)')
plt.legend()
plt.title('AR')
plt.show()
# forecast and predict are different for ARMA
plt.plot(test, label='Ground Truth')
plt.plot(arma_steps['Predictions forecast'], color='red', label='.forecast(steps)')
plt.plot(arma_steps['Predictions predict'], color='green', label='.predict(steps)')
plt.legend()
plt.title('ARMA')
plt.show()
| statsmodels_arima_evaluation.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
# ---
class Node :
def __init__(self, item) :
self.val = item
self.next = None
# +
class LinkedList :
def __init__(self, item) :
self.head = Node(item)
def add(self, item) :
cur = self.head
while cur.next is not None :
cur = cur.next
cur.next = Node(item)
def remove(self, item) :
if self.head.val == item
self.head = self.head.next
else :
while cur.next is not None :
if cur.val == item :
self.removeItem(item)
return
cur = cur.next
print("item does not exist in linke list")
def removeItem(self, item) :
cur = self.head
while cur.next is not None :
if cur.next.val = item :
nextnode = cur.next.next
cur.next = nextnode
break
def reverse(self) :
prev = None
cur = self.head
while cur is not None :
next = cur.next
cur.next = prev
prev = cur
cur = next
self.head = prev
def printlist(def) :
cur = self.head
while cur is not None :
print(cur.val)
cur = cur.next
# -
ll = LinkedList(3)
ll.head.val == 3
ll.add(4)
ll.head.next.val
| data structure/LinkedList.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'prepare/mesolitica-tpu.json'
b2_application_key_id = os.environ['b2_application_key_id']
b2_application_key = os.environ['b2_application_key']
# -
from google.cloud import storage
client = storage.Client()
bucket = client.bucket('mesolitica-tpu-general')
best = '1020200'
directory = 't5-tiny-knowledge-graph'
# !rm -rf output out {directory}
# !mkdir {directory}
# +
model = best
blob = bucket.blob(f'{directory}/model.ckpt-{model}.data-00000-of-00002')
blob.download_to_filename(f'{directory}/model.ckpt-{model}.data-00000-of-00002')
blob = bucket.blob(f'{directory}/model.ckpt-{model}.data-00001-of-00002')
blob.download_to_filename(f'{directory}/model.ckpt-{model}.data-00001-of-00002')
blob = bucket.blob(f'{directory}/model.ckpt-{model}.index')
blob.download_to_filename(f'{directory}/model.ckpt-{model}.index')
blob = bucket.blob(f'{directory}/model.ckpt-{model}.meta')
blob.download_to_filename(f'{directory}/model.ckpt-{model}.meta')
blob = bucket.blob(f'{directory}/checkpoint')
blob.download_to_filename(f'{directory}/checkpoint')
blob = bucket.blob(f'{directory}/operative_config.gin')
blob.download_to_filename(f'{directory}/operative_config.gin')
# -
with open(f'{directory}/checkpoint', 'w') as fopen:
fopen.write(f'model_checkpoint_path: "model.ckpt-{model}"')
from b2sdk.v1 import *
info = InMemoryAccountInfo()
b2_api = B2Api(info)
application_key_id = b2_application_key_id
application_key = b2_application_key
b2_api.authorize_account("production", application_key_id, application_key)
file_info = {'how': 'good-file'}
b2_bucket = b2_api.get_bucket_by_name('malaya-model')
tar = 't5-tiny-knowledge-graph-2021-07-31.tar.gz'
os.system(f'tar -czvf {tar} {directory}')
outPutname = f'finetuned/{tar}'
b2_bucket.upload_local_file(
local_file=tar,
file_name=outPutname,
file_infos=file_info,
)
os.system(f'rm {tar}')
import tensorflow as tf
import tensorflow_datasets as tfds
import t5
model = t5.models.MtfModel(
model_dir=directory,
tpu=None,
tpu_topology=None,
model_parallelism=1,
batch_size=1,
sequence_length={"inputs": 256, "targets": 256},
learning_rate_schedule=0.003,
save_checkpoints_steps=5000,
keep_checkpoint_max=3,
iterations_per_loop=100,
mesh_shape="model:1,batch:1",
mesh_devices=["cpu:0"]
)
# !rm -rf output/*
# +
import gin
from t5.data import sentencepiece_vocabulary
DEFAULT_SPM_PATH = 'prepare/sp10m.cased.ms-en.model'
DEFAULT_EXTRA_IDS = 100
model_dir = directory
def get_default_vocabulary():
return sentencepiece_vocabulary.SentencePieceVocabulary(
DEFAULT_SPM_PATH, DEFAULT_EXTRA_IDS)
with gin.unlock_config():
gin.parse_config_file(t5.models.mtf_model._operative_config_path(model_dir))
gin.bind_parameter("Bitransformer.decode.beam_size", 1)
gin.bind_parameter("Bitransformer.decode.temperature", 0)
gin.bind_parameter("utils.get_variable_dtype.slice_dtype", "float32")
gin.bind_parameter(
"utils.get_variable_dtype.activation_dtype", "float32")
vocabulary = t5.data.SentencePieceVocabulary(DEFAULT_SPM_PATH)
estimator = model.estimator(vocabulary, disable_tpu=True)
# +
import os
checkpoint_step = t5.models.mtf_model._get_latest_checkpoint_from_dir(model_dir)
model_ckpt = "model.ckpt-" + str(checkpoint_step)
checkpoint_path = os.path.join(model_dir, model_ckpt)
checkpoint_step, model_ckpt, checkpoint_path
# +
from mesh_tensorflow.transformer import dataset as transformer_dataset
def serving_input_fn():
inputs = tf.placeholder(
dtype=tf.string,
shape=[None],
name="inputs")
batch_size = tf.shape(inputs)[0]
padded_inputs = tf.pad(inputs, [(0, tf.mod(-tf.size(inputs), batch_size))])
dataset = tf.data.Dataset.from_tensor_slices(padded_inputs)
dataset = dataset.map(lambda x: {"inputs": x})
dataset = transformer_dataset.encode_all_features(dataset, vocabulary)
dataset = transformer_dataset.pack_or_pad(
dataset=dataset,
length=model._sequence_length,
pack=False,
feature_keys=["inputs"]
)
dataset = dataset.batch(tf.cast(batch_size, tf.int64))
features = tf.data.experimental.get_single_element(dataset)
return tf.estimator.export.ServingInputReceiver(
features=features, receiver_tensors=inputs)
out = estimator.export_saved_model('output', serving_input_fn, checkpoint_path=checkpoint_path)
# -
config = tf.ConfigProto()
config.allow_soft_placement = True
sess = tf.Session(config = config)
meta_graph_def = tf.saved_model.loader.load(
sess,
[tf.saved_model.tag_constants.SERVING],
out)
saver = tf.train.Saver(tf.trainable_variables())
saver.save(sess, 'tiny-knowledge-graph/model.ckpt')
strings = [
n.name
for n in tf.get_default_graph().as_graph_def().node
if ('encoder' in n.op
or 'decoder' in n.name
or 'shared' in n.name
or 'inputs' in n.name
or 'output' in n.name
or 'SentenceTokenizer' in n.name
or 'self/Softmax' in n.name)
and 'adam' not in n.name
and 'Assign' not in n.name
]
def freeze_graph(model_dir, output_node_names):
if not tf.gfile.Exists(model_dir):
raise AssertionError(
"Export directory doesn't exists. Please specify an export "
'directory: %s' % model_dir
)
checkpoint = tf.train.get_checkpoint_state(model_dir)
input_checkpoint = checkpoint.model_checkpoint_path
absolute_model_dir = '/'.join(input_checkpoint.split('/')[:-1])
output_graph = absolute_model_dir + '/frozen_model.pb'
clear_devices = True
with tf.Session(graph = tf.Graph()) as sess:
saver = tf.train.import_meta_graph(
input_checkpoint + '.meta', clear_devices = clear_devices
)
saver.restore(sess, input_checkpoint)
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess,
tf.get_default_graph().as_graph_def(),
output_node_names,
)
with tf.gfile.GFile(output_graph, 'wb') as f:
f.write(output_graph_def.SerializeToString())
print('%d ops in the final graph.' % len(output_graph_def.node))
freeze_graph('tiny-knowledge-graph', strings)
# +
import struct
unknown = b'\xff\xff\xff\xff'
def load_graph(frozen_graph_filename):
with tf.gfile.GFile(frozen_graph_filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
for node in graph_def.node:
if node.op == 'RefSwitch':
node.op = 'Switch'
for index in xrange(len(node.input)):
if 'moving_' in node.input[index]:
node.input[index] = node.input[index] + '/read'
elif node.op == 'AssignSub':
node.op = 'Sub'
if 'use_locking' in node.attr: del node.attr['use_locking']
elif node.op == 'AssignAdd':
node.op = 'Add'
if 'use_locking' in node.attr: del node.attr['use_locking']
elif node.op == 'Assign':
node.op = 'Identity'
if 'use_locking' in node.attr: del node.attr['use_locking']
if 'validate_shape' in node.attr: del node.attr['validate_shape']
if len(node.input) == 2:
node.input[0] = node.input[1]
del node.input[1]
if 'Reshape/shape' in node.name or 'Reshape_1/shape' in node.name:
b = node.attr['value'].tensor.tensor_content
arr_int = [int.from_bytes(b[i:i + 4], 'little') for i in range(0, len(b), 4)]
if len(arr_int):
arr_byte = [unknown] + [struct.pack('<i', i) for i in arr_int[1:]]
arr_byte = b''.join(arr_byte)
node.attr['value'].tensor.tensor_content = arr_byte
if len(node.attr['value'].tensor.int_val):
node.attr['value'].tensor.int_val[0] = -1
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def)
return graph
# -
g = load_graph('tiny-knowledge-graph/frozen_model.pb')
i = g.get_tensor_by_name('import/inputs:0')
o = g.get_tensor_by_name('import/SelectV2_3:0')
i, o
test_sess = tf.Session(graph = g)
# +
# %%time
o_ = test_sess.run(o, feed_dict = {i: [
"grafik pengetahuan: Yang Berhormat Dato' <NAME> bin <NAME> ialah ahli politik Malaysia dan merupakan bekas Perdana Menteri Malaysia ke-6, yang mana beliau menjawat jawatan dari 3 April 2009 hingga 9 Mei 2018. Beliau juga pernah berkhidmat sebagai bekas Menteri Kewangan dan merupakan Ahli Parlimen Pekan, Pahang. Beliau merupakan anak lelaki sulung kepada bekas Perdana Menteri Malaysia yang kedua, Tun <NAME> Dato' Hussein. Di peringkat akar umbi politik, beliau merupakan Presiden UMNO yang ke-7.",
'grafik pengetahuan: Speaker Dewan Rakyat <NAME> menegur ahli-ahli parlimen pembangkang selepas kira-kira sejam mereka menyatakan rasa tidak puas hati pada persidangan khas parlimen hari ini.',
'grafik pengetahuan: Keuskupan Agung Katolik Rom Maracaibo terletak di barat daya Keuskupan Katolik Rom Machiques.',
]})
o_.shape
# -
import sentencepiece as spm
sp_model = spm.SentencePieceProcessor()
sp_model.Load(DEFAULT_SPM_PATH)
for k in range(len(o_)):
print(k, sp_model.DecodeIds(o_[k].tolist()))
from tensorflow.tools.graph_transforms import TransformGraph
transforms = ['add_default_attributes',
'remove_nodes(op=Identity, op=CheckNumerics)',
'fold_batch_norms',
'fold_old_batch_norms',
'quantize_weights(minimum_size=1536000)',
#'quantize_weights(fallback_min=-10240, fallback_max=10240)',
'strip_unused_nodes',
'sort_by_execution_order']
# +
pb = 'tiny-knowledge-graph/frozen_model.pb'
input_graph_def = tf.GraphDef()
with tf.gfile.FastGFile(pb, 'rb') as f:
input_graph_def.ParseFromString(f.read())
transformed_graph_def = TransformGraph(input_graph_def,
['inputs'],
['SelectV2_3'], transforms)
with tf.gfile.GFile(f'{pb}.quantized', 'wb') as f:
f.write(transformed_graph_def.SerializeToString())
# -
g = load_graph('tiny-knowledge-graph/frozen_model.pb.quantized')
i = g.get_tensor_by_name('import/inputs:0')
o = g.get_tensor_by_name('import/SelectV2_3:0')
i, o
test_sess = tf.InteractiveSession(graph = g)
file = 'tiny-knowledge-graph/frozen_model.pb.quantized'
outPutname = 'knowledge-graph-triplet/tiny-t5-quantized/model.pb'
b2_bucket.upload_local_file(
local_file=file,
file_name=outPutname,
file_infos=file_info,
)
file = 'tiny-knowledge-graph/frozen_model.pb'
outPutname = 'knowledge-graph-triplet/tiny-t5/model.pb'
b2_bucket.upload_local_file(
local_file=file,
file_name=outPutname,
file_infos=file_info,
)
| session/knowledge-graph/t5/export-tiny.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
# ---
# # Calculate 3d correlation function
#
# In this example, we calculate the 3D correlation function for an example cosmology.
import numpy as np
import pyccl as ccl
import matplotlib
import matplotlib.pyplot as plt
# %matplotlib inline
# First, we define a set of cosmological parameters with two different power spectrum calculations.
# +
# Nonlinear power spectrum with CLASS Halofit transfer function
cosmo = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, sigma8=0.80, n_s=0.96,
transfer_function='boltzmann_class', matter_power_spectrum='halofit')
# Linear power spectrum with linear BBKS transfer funtion
cosmo_lin = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, sigma8=0.80, n_s=0.96,
transfer_function='bbks', matter_power_spectrum='linear')
# -
# Next, we create an array of separations $r$, and calculate the 3D correlation function for a = 1.
a = 1.0 # Scale factor
n_r = 10000 # number of points in r
r = np.logspace(-3., 4., n_r) # distance
xi = ccl.correlation_3d(cosmo, a, r)
xi_lin = ccl.correlation_3d(cosmo_lin, a, r)
# Now we plot the 3d correlation function obtained for nonlinear power spectrum (blue line) and linear power spectrum (red line). Since this plot has a log scale, negative values are plotted as dashed lines.
# +
# Plot correlation function
plt.plot(r, xi, 'b-', label='Nonlinear Halofit')
plt.plot(r, xi_lin, 'r-', label='Linear BBKS')
plt.plot(r, -xi, 'b--') # Plot negative values as dashed lines
plt.plot(r, -xi_lin, 'r--')
plt.xscale('log')
plt.yscale('log')
plt.ylim((1e-7, 2e4))
plt.xlim((0.01, 1000))
plt.xlabel(r'$r$ $[\mathrm{Mpc}]$')
plt.ylabel(r'$\xi (r)$')
plt.legend()
plt.show()
# -
# Finally, we plot the 3d correlation function for large distances on a linear scale. Note the presence of the BAO feature at $r \approx 150$ Mpc in the nonlinear model; the linear BBKS model does not include this feature.
# +
# Plot large r region on linear scale
plt.plot(r, xi, 'b-', label='Nonlinear Halofit')
plt.plot(r, xi_lin, 'r-', label='Linear BBKS')
plt.ylim((-0.001, 0.01))
plt.xlim((50, 200))
plt.xlabel(r'$r$ $[\mathrm{Mpc}]$')
plt.ylabel(r'$\xi(r)$')
plt.legend()
plt.show()
# -
| examples/Correlation_3d.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: 'Python 3.8.10 64-bit (''venv'': venv)'
# language: python
# name: python3
# ---
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Feature Transformers").getOrCreate()
# #### Tokenizer
#
# Tokenization is the process of taking text (such as a sentence) and breaking it into individual terms (usually words). A simple Tokenizer class provides this functionality. The example below shows how to split sentences into sequences of words.
#
# RegexTokenizer allows more advanced tokenization based on regular expression (regex) matching. By default, the parameter “pattern” (regex, default: "\\s+") is used as delimiters to split the input text. Alternatively, users can set parameter “gaps” to false indicating the regex “pattern” denotes “tokens” rather than splitting gaps, and find all matching occurrences as the tokenization result.
from pyspark.ml.feature import Tokenizer, RegexTokenizer
from pyspark.sql.functions import col, udf
from pyspark.sql.types import IntegerType
# +
sentenceDataFrame = spark.createDataFrame([
(0, "Hi I heard about Spark"),
(1, "I wish Java could use case classes"),
(2, "Logistic,regression,models,are,neat")
], ["id", "sentence"])
sentenceDataFrame.show()
# +
tokenizer = Tokenizer(inputCol='sentence', outputCol='words')
regexTokenizer = RegexTokenizer(inputCol='sentence', outputCol='words', pattern='\\W')
countTokens = udf(lambda w : len(w) , IntegerType())
# -
tokenizer = tokenizer.transform(sentenceDataFrame)
tokenizer.select("sentence", 'words').withColumn('tokens',countTokens(col('words'))).show(truncate=False)
regexTokenized = regexTokenizer.transform(sentenceDataFrame)
regexTokenized.select("sentence", "words") \
.withColumn("tokens", countTokens(col("words"))).show(truncate=False)
# #### Stop Words Remover
#
# Stop words are words which should be excluded from the input, typically because the words appear frequently and don’t carry as much meaning.
from pyspark.ml.feature import StopWordsRemover
# +
sentenceData = spark.createDataFrame([
(0, ["I", "saw", "the", "red", "balloon"]),
(1, ["Mary", "had", "a", "little", "lamb"])
], ["id", "raw"])
sentenceData.show()
# -
remover = StopWordsRemover(inputCol="raw", outputCol="filtered")
remover.transform(sentenceData).show(truncate=False)
# #### n-gram
#
# An n-gram is a sequence of n tokens (typically words) for some integer n. The NGram class can be used to transform input features into n-grams.
#
# NGram takes as input a sequence of strings (e.g. the output of a Tokenizer). The parameter n is used to determine the number of terms in each n-gram. The output will consist of a sequence of n-grams where each n-gram is represented by a space-delimited string of n consecutive words. If the input sequence contains fewer than n strings, no output is produced.
from pyspark.ml.feature import NGram
# +
wordDataFrame = spark.createDataFrame([
(0, ["Hi", "I", "heard", "about", "Spark"]),
(1, ["I", "wish", "Java", "could", "use", "case", "classes"]),
(2, ["Logistic", "regression", "models", "are", "neat"])
], ["id", "words"])
wordDataFrame.show()
# +
ngram = NGram(n=2, inputCol='words', outputCol='ngrams')
ngramDataFrame = ngram.transform(wordDataFrame)
ngramDataFrame.select("ngrams").show(truncate=False)
# -
# #### Binarizer
#
# Binarization is the process of thresholding numerical features to binary (0/1) features.
# +
from pyspark.ml.feature import Binarizer
continuousDataFrame = spark.createDataFrame([
(0, 0.1),
(1, 0.8),
(2, 0.2)
], ['id', 'feature'])
continuousDataFrame.show()
# +
binarizer = Binarizer(threshold=0.5, inputCol='feature', outputCol='binarized_feature')
binarizerDataFrame = binarizer.transform(continuousDataFrame)
# -
print("Binarizer output with Threshold = %f" % binarizer.getThreshold())
binarizerDataFrame.show()
# #### PCA
#
# PCA is a statistical procedure that uses an orthogonal transformation to convert a set of observations of possibly correlated variables into a set of values of linearly uncorrelated variables called principal components. A PCA class trains a model to project vectors to a low-dimensional space using PCA. The example below shows how to project 5-dimensional feature vectors into 3-dimensional principal components.
from pyspark.ml.feature import PCA
from pyspark.ml.linalg import Vectors
# +
data = [(Vectors.sparse(5, [(1, 1.0), (3, 7.0)]),),
(Vectors.dense([2.0, 0.0, 3.0, 4.0, 5.0]),),
(Vectors.dense([4.0, 0.0, 0.0, 6.0, 7.0]),)]
df = spark.createDataFrame(data, ["features"])
df.show(truncate=False)
# -
pca = PCA(k=3, inputCol='features', outputCol='pcaFeatures')
model = pca.fit(df)
result = model.transform(df).select('pcaFeatures')
result.show(truncate=False)
# #### PolynomialExpression
#
# Polynomial expansion is the process of expanding your features into a polynomial space, which is formulated by an n-degree combination of original dimensions. A PolynomialExpansion class provides this functionality. The example below shows how to expand your features into a 3-degree polynomial space.
# +
from pyspark.ml.feature import PolynomialExpansion
from pyspark.ml.linalg import Vectors
df = spark.createDataFrame([
(Vectors.dense([2.0, 1.0]),),
(Vectors.dense([0.0, 0.0]),),
(Vectors.dense([3.0, -1.0]),)
], ["features"])
df.show(truncate=False)
# -
polyExpansion = PolynomialExpansion(degree=3, inputCol="features", outputCol="polyFeatures")
polyDF = polyExpansion.transform(df)
polyDF.show(truncate=False)
# #### Discrete Cosine Transform (DCT)
#
# The Discrete Cosine Transform transforms a length N real-valued sequence in the time domain into another length N real-valued sequence in the frequency domain.
#
# A DCT class provides this functionality, implementing the DCT-II and scaling the result by 1/√2 such that the representing matrix for the transform is unitary. No shift is applied to the transformed sequence (e.g. the 0th element of the transformed sequence is the 0th DCT coefficient and not the N/2th).
#
from pyspark.ml.feature import DCT
from pyspark.ml.linalg import Vectors
# +
df = spark.createDataFrame([
(Vectors.dense([0.0, 1.0, -2.0, 3.0]),),
(Vectors.dense([-1.0, 2.0, 4.0, -7.0]),),
(Vectors.dense([14.0, -2.0, -5.0, 1.0]),)],
["features"])
df.show()
# +
dct = DCT(inverse = False, inputCol='features', outputCol = 'featuresDCT')
dctDf = dct.transform(df)
# -
dctDf.select('featuresDCT').show(truncate=False)
# #### String Indexer
#
# StringIndexer encodes a string column of labels to a column of label indices. StringIndexer can encode multiple columns. The indices are in [0, numLabels), and four ordering options are supported: “frequencyDesc”: descending order by label frequency (most frequent label assigned 0), “frequencyAsc”: ascending order by label frequency (least frequent label assigned 0), “alphabetDesc”: descending alphabetical order, and “alphabetAsc”: ascending alphabetical order (default = “frequencyDesc”). Note that in case of equal frequency when under “frequencyDesc”/”frequencyAsc”, the strings are further sorted by alphabet.
#
# The unseen labels will be put at index numLabels if user chooses to keep them. If the input column is numeric, we cast it to string and index the string values. When downstream pipeline components such as Estimator or Transformer make use of this string-indexed label, you must set the input column of the component to this string-indexed column name. In many cases, you can set the input column with setInputCol.
#
# Assume that we have the following DataFrame with columns id and category:
#
# id | category
# ----|----------
# 0 | a
# 1 | b
# 2 | c
# 3 | a
# 4 | a
# 5 | c
#
# category is a string column with three labels: “a”, “b”, and “c”. Applying StringIndexer with category as the input column and categoryIndex as the output column, we should get the following:
#
# id | category | categoryIndex
# ----|----------|---------------
# 0 | a | 0.0
# 1 | b | 2.0
# 2 | c | 1.0
# 3 | a | 0.0
# 4 | a | 0.0
# 5 | c | 1.0
#
# “a” gets index 0 because it is the most frequent, followed by “c” with index 1 and “b” with index 2.
#
#
# +
from pyspark.ml.feature import StringIndexer
df = spark.createDataFrame(
[(0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")],
["id", "category"]
)
df.show()
# +
indexer = StringIndexer(inputCol='category', outputCol='categoryIndex')
indexed = indexer.fit(df).transform(df)
indexed.show()
# -
# #### indexToString
#
# Symmetrically to StringIndexer, IndexToString maps a column of label indices back to a column containing the original labels as strings. A common use case is to produce indices from labels with StringIndexer, train a model with those indices and retrieve the original labels from the column of predicted indices with IndexToString. However, you are free to supply your own labels.
from pyspark.ml.feature import IndexToString, StringIndexer
# +
df = spark.createDataFrame(
[(0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")],
["id", "category"]
)
df.show()
# -
indexer = StringIndexer(inputCol='category', outputCol='categoryIndex')
model = indexer.fit(df)
indexed = model.transform(df)
print("Transformed string column '%s' to indexed column '%s'"
% (indexer.getInputCol(), indexer.getOutputCol()))
indexed.show()
# +
print("StringIndexer will store labels in output column metadata\n")
converter = IndexToString(inputCol='categoryIndex', outputCol='originalCategory')
converted = converter.transform(indexed)
# +
print("Transformed indexed column '%s' back to original string column '%s' using "
"labels in metadata" % (converter.getInputCol(), converter.getOutputCol()))
converted.select("id", "categoryIndex", "originalCategory").show()
# -
# #### OneHotEncoder
#
# One-hot encoding maps a categorical feature, represented as a label index, to a binary vector with at most a single one-value indicating the presence of a specific feature value from among the set of all feature values. This encoding allows algorithms which expect continuous features, such as Logistic Regression, to use categorical features. For string type input data, it is common to encode categorical features using StringIndexer first.
# +
from pyspark.ml.feature import OneHotEncoder
df = spark.createDataFrame([
(0.0, 1.0),
(1.0, 0.0),
(2.0, 1.0),
(0.0, 2.0),
(0.0, 1.0),
(2.0, 0.0)
], ["categoryIndex1", "categoryIndex2"])
df.show()
# -
encoder = OneHotEncoder(inputCols=["categoryIndex1", "categoryIndex2"],
outputCols=["categoryVec1", "categoryVec2"])
model = encoder.fit(df)
encoded = model.transform(df)
encoded.show()
# #### Vector Indexer
#
# VectorIndexer helps index categorical features in datasets of Vectors. It can both automatically decide which features are categorical and convert original values to category indices. Specifically, it does the following:
#
# - Take an input column of type Vector and a parameter maxCategories.
# - Decide which features should be categorical based on the number of distinct values, where features with at most maxCategories are declared categorical.
# - Compute 0-based category indices for each categorical feature.
# - Index categorical features and transform original feature values to indices.
# +
from pyspark.ml.feature import VectorIndexer
data = spark.read.format('libsvm').load("sample_libsvm_data.txt")
# -
data.show(2)
indexer = VectorIndexer(inputCol='features', outputCol='indexed', maxCategories=10)
indexerModel = indexer.fit(data)
categoricalFeatures = indexerModel.categoryMaps
print("Chose %d categorical features: %s" %
(len(categoricalFeatures), ", ".join(str(k) for k in categoricalFeatures.keys())))
# Create new column "indexed" with categorical values transformed to indices
indexedData = indexerModel.transform(data)
indexedData.show(5)
# #### Interaction
#
# Interaction is a Transformer which takes vector or double-valued columns, and generates a single vector column that contains the product of all combinations of one value from each input column.
#
# Examples
#
# Assume that we have the following DataFrame with the columns “id1”, “vec1”, and “vec2”:
#
# id1|vec1 |vec2
# ---|--------------|--------------
# 1 |[1.0,2.0,3.0] |[8.0,4.0,5.0]
# 2 |[4.0,3.0,8.0] |[7.0,9.0,8.0]
# 3 |[6.0,1.0,9.0] |[2.0,3.0,6.0]
# 4 |[10.0,8.0,6.0]|[9.0,4.0,5.0]
# 5 |[9.0,2.0,7.0] |[10.0,7.0,3.0]
# 6 |[1.0,1.0,4.0] |[2.0,8.0,4.0]
#
# Applying Interaction with those input columns, then interactedCol as the output column contains:
#
# id1|vec1 |vec2 |interactedCol
# ---|--------------|--------------|------------------------------------------------------
# 1 |[1.0,2.0,3.0] |[8.0,4.0,5.0] |[8.0,4.0,5.0,16.0,8.0,10.0,24.0,12.0,15.0]
# 2 |[4.0,3.0,8.0] |[7.0,9.0,8.0] |[56.0,72.0,64.0,42.0,54.0,48.0,112.0,144.0,128.0]
# 3 |[6.0,1.0,9.0] |[2.0,3.0,6.0] |[36.0,54.0,108.0,6.0,9.0,18.0,54.0,81.0,162.0]
# 4 |[10.0,8.0,6.0]|[9.0,4.0,5.0] |[360.0,160.0,200.0,288.0,128.0,160.0,216.0,96.0,120.0]
# 5 |[9.0,2.0,7.0] |[10.0,7.0,3.0]|[450.0,315.0,135.0,100.0,70.0,30.0,350.0,245.0,105.0]
# 6 |[1.0,1.0,4.0] |[2.0,8.0,4.0] |[12.0,48.0,24.0,12.0,48.0,24.0,48.0,192.0,96.0]
# +
from pyspark.ml.feature import Interaction, VectorAssembler
df = spark.createDataFrame(
[(1, 1, 2, 3, 8, 4, 5),
(2, 4, 3, 8, 7, 9, 8),
(3, 6, 1, 9, 2, 3, 6),
(4, 10, 8, 6, 9, 4, 5),
(5, 9, 2, 7, 10, 7, 3),
(6, 1, 1, 4, 2, 8, 4)],
["id1", "id2", "id3", "id4", "id5", "id6", "id7"])
df.show(5)
# +
assembler1 = VectorAssembler(inputCols=["id2", "id3", "id4"], outputCol="vec1")
assembled1 = assembler1.transform(df)
# -
assembler2 = VectorAssembler(inputCols=["id5", "id6", "id7"], outputCol="vec2")
assembled2 = assembler2.transform(assembled1).select("id1", "vec1", "vec2")
interaction = Interaction(inputCols=["id1", "vec1", "vec2"], outputCol="interactedCol")
interacted = interaction.transform(assembled2)
interacted.show(truncate=False)
# #### Normalizer
#
# Normalizer is a Transformer which transforms a dataset of Vector rows, normalizing each Vector to have unit norm. It takes parameter p, which specifies the p-norm used for normalization. (p=2 by default.) This normalization can help standardize your input data and improve the behavior of learning algorithms.
from pyspark.ml.feature import Normalizer
from pyspark.ml.linalg import Vectors
# +
dataFrame = spark.createDataFrame([
(0, Vectors.dense([1.0, 0.5, -1.0]),),
(1, Vectors.dense([2.0, 1.0, 1.0]),),
(2, Vectors.dense([4.0, 10.0, 2.0]),)
], ["id", "features"])
dataFrame.show()
# +
# Normalize each vector using $L^1$ norm.
normalizer = Normalizer(inputCol='features', outputCol='normFeatures', p=1.0)
l1NormData = normalizer.transform(dataFrame)
print("Normalized using L^1 norm")
l1NormData.show()
# -
# Normalize each Vector using $L^\infty$ norm.
lInfNormData = normalizer.transform(dataFrame, {normalizer.p: float("inf")})
print("Normalized using L^inf norm")
lInfNormData.show()
# #### SQLTransformer
#
# SQLTransformer implements the transformations which are defined by SQL statement. Currently, we only support SQL syntax like "SELECT ... FROM __THIS__ ..." where "__THIS__" represents the underlying table of the input dataset. The select clause specifies the fields, constants, and expressions to display in the output, and can be any select clause that Spark SQL supports. Users can also use Spark SQL built-in function and UDFs to operate on these selected columns. For example, SQLTransformer supports statements like:
#
# SELECT a, a + b AS a_b FROM __THIS__
#
# SELECT a, SQRT(b) AS b_sqrt FROM __THIS__ where a > 5
#
# SELECT a, b, SUM(c) AS c_sum FROM __THIS__ GROUP BY a, b
#
# Example:
#
# id | v1 | v2
# ----|-----|-----
# 0 | 1.0 | 3.0
# 2 | 2.0 | 5.0
#
# This is the output of the SQLTransformer with statement "SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__":
#
# id | v1 | v2 | v3 | v4
# ----|-----|-----|-----|-----
# 0 | 1.0 | 3.0 | 4.0 | 3.0
# 2 | 2.0 | 5.0 | 7.0 |10.0
# +
from pyspark.ml.feature import SQLTransformer
df = spark.createDataFrame([
(0, 1.0, 3.0),
(2, 2.0, 5.0)
], ["id", "v1", "v2"])
df.show()
# +
sqlTrans = SQLTransformer(
statement = "select *, (v1+v2) as v3, (v1*v2) as v4 from __THIS__"
)
sqlTrans.transform(df).show()
# -
# #### VectorAssembler
#
# VectorAssembler is a transformer that combines a given list of columns into a single vector column.
#
# It is useful for combining raw features and features generated by different feature transformers into a single feature vector, in order to train ML models like logistic regression and decision trees. VectorAssembler accepts the following input column types: all numeric types, boolean type, and vector type. In each row, the values of the input columns will be concatenated into a vector in the specified order.
#
# Examples
#
# Assume that we have a DataFrame with the columns id, hour, mobile, userFeatures, and clicked:
#
# id | hour | mobile | userFeatures | clicked
# ----|------|--------|------------------|---------
# 0 | 18 | 1.0 | [0.0, 10.0, 0.5] | 1.0
#
# userFeatures is a vector column that contains three user features. We want to combine hour, mobile, and userFeatures into a single feature vector called features and use it to predict clicked or not. If we set VectorAssembler’s input columns to hour, mobile, and userFeatures and output column to features, after transformation we should get the following DataFrame:
#
# id | hour | mobile | userFeatures | clicked | features
# ----|------|--------|------------------|---------|-----------------------------
# 0 | 18 | 1.0 | [0.0, 10.0, 0.5] | 1.0 | [18.0, 1.0, 0.0, 10.0, 0.5]
#
#
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler
# +
dataset = spark.createDataFrame(
[(0, 18, 1.0, Vectors.dense([0.0, 10.0, 0.5]), 1.0)],
["id", "hour", "mobile", "userFeatures", "clicked"])
dataset.show()
# +
assembler = VectorAssembler(
inputCols=["hour", "mobile", "userFeatures"],
outputCol="features"
)
output = assembler.transform(dataset)
output.show()
# -
output.select("features","clicked").show(truncate=False)
# #### Imputer
#
# The Imputer estimator completes missing values in a dataset, using the mean, median or mode of the columns in which the missing values are located.
#
# The input columns should be of numeric type. Currently Imputer does not support categorical features and possibly creates incorrect values for columns containing categorical features.
#
# Imputer can impute custom values other than ‘NaN’ by .setMissingValue(custom_value). For example, .setMissingValue(0) will impute all occurrences of (0).
#
# Note all null values in the input columns are treated as missing, and so are also imputed.
#
# Examples
#
# Suppose that we have a DataFrame with the columns a and b:
# a | b
# ------------|-----------
# 1.0 | Double.NaN
# 2.0 | Double.NaN
# Double.NaN | 3.0
# 4.0 | 4.0
# 5.0 | 5.0
#
#
# In this example, Imputer will replace all occurrences of Double.NaN (the default for the missing value) with the mean (the default imputation strategy) computed from the other values in the corresponding columns.
#
# In this example, the surrogate values for columns a and b are 3.0 and 4.0 respectively. After transformation, the missing values in the output columns will be replaced by the surrogate value for the relevant column.
#
# a | b | out_a | out_b
# ------------|------------|-------|-------
# 1.0 | Double.NaN | 1.0 | 4.0
# 2.0 | Double.NaN | 2.0 | 4.0
# Double.NaN | 3.0 | 3.0 | 3.0
# 4.0 | 4.0 | 4.0 | 4.0
# 5.0 | 5.0 | 5.0 | 5.0
#
# +
from pyspark.ml.feature import Imputer
df = spark.createDataFrame([
(1.0, float("nan")),
(2.0, float("nan")),
(float("nan"), 3.0),
(4.0, 4.0),
(5.0, 5.0)
], ["a", "b"])
df.show()
# +
imputer = Imputer(inputCols=['a','b'], outputCols=['out_a','out_b'])
model = imputer.fit(df)
model.transform(df).show()
# -
| Extracting_transforming_selecting_features/featureTransformers.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 sys
import numpy
import datetime as dt
housing = pd.read_csv('kc_house_data.csv')
#Step 1: Data Clean, the data from this file is already very clean and we don't need to do anything
print(housing.columns)
# just do bedrooms, bathrooms, sqft_living, sqft_lot, floors, zipcode, waterfront, yr_built, view
numeric_data = housing
# +
#define the y data that we're looking to solve for
price = numeric_data[['price']]
#define the columns that correspond with uploaded data. These will be multiplied by weights.
numeric_data = numeric_data[['bedrooms', 'bathrooms', 'sqft_living',
'sqft_lot', 'floors', 'waterfront', 'yr_built', 'view']]
# +
from sklearn.linear_model import ElasticNet
#Splitting the data into Train and Test
from sklearn.model_selection import train_test_split
xtrain, xtest, ytrain, ytest = train_test_split(numeric_data,price,test_size=1/3, random_state=0)
# +
#use Elastic net, both lasso and ridge methods to maximize accuracy although still slightly less efficient than linear regression
import datetime as dt
before = dt.datetime.now()
reg = ElasticNet(alpha=.2, l1_ratio = 1).fit(xtrain, ytrain)
after = dt.datetime.now()
score = reg.score(xtest,ytest)
print(score)
#print(after-before)
# +
#kept linear regression model because twice as fast but less accurate
#from sklearn.linear_model import LinearRegression
#before = dt.datetime.now()
#reg = LinearRegression().fit(xtrain, ytrain)
#after = dt.datetime.now()
#score = reg.score(xtest,ytest)
#print(score)
#print(after-before)
# -
test_result = reg.predict(xtest)
weights = reg
print(weights)
# +
import pickle
#pickle results into binary file that will be loaded into backend.
filename = "lin_reg_pickle"
output = open(filename, 'wb')
pickle.dump(weights, output)
output.close()
# -
| real_estate_machine_learning_king_county.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
# ---
# ---
# <div class="alert alert-success" data-title="">
# <h2><i class="fa fa-tasks" aria-hidden="true"></i> 사이킷런을 사용한 Boston 집값 예측
# </h2>
# </div>
#
# <img src = "https://cdn10.bostonmagazine.com/wp-content/uploads/sites/2/2018/05/boston-rent.jpg" width = "700" >
#
#
# 이번 실습 시간에 다뤄볼 데이터는 보스턴 시의 주택 가격과 관련된 데이터입니다.
#
# - 주택 가격에 영향을 끼치는 여러 요소들 (X, Features)
# - 주택 가격 (Y, Target)
#
# ## 목표
#
# - 주택의 가격에 영향을 미치는 요소를 분석
# - 회귀분석
# ## 데이터 살펴보기
from sklearn.datasets import load_boston
boston = load_boston()
print(boston.DESCR)
boston.feature_names
boston.data
boston.data.shape
boston.target
boston.target.shape
# ## 변수설명
#
# 1) Target (Y) data
# * Target: 1978년 보스턴 주택 가격
#
# 2) Feature (X) data
# * CRIM: 범죄율
# * INDUS: 비소매상업지역 면적 비율
# * NOX: 일산화질소 농도
# * RM: 주택당 방 개수
# * LSTAT: 인구 중 하위 계층 비율
# * B: 인구 중 흑인 비율
# * PTRATIO: 학생/교사 비율
# * ZN: 25,000 평방피트를 초과하는 거주지역 비율
# * CHAS: 찰스강의 경계에 위치한 경우는 1, 아니면 0
# * AGE: 1940년 이전에 건축된 주택의 비율
# * RAD: 방사형 고속도로까지의 거리
# * DIS: 직업센터의 거리
# * TAX: 재산세율
#
# ---
import pandas as pd
boston_df = pd.DataFrame(boston.data,
columns=boston.feature_names,
index=range(1,len(boston.data)+1))
boston_df['PRICE'] = boston.target
boston_df.head()
boston_df.shape
# ## stats_model 을 사용하여 상관관계 확인하기
#
# Feature data
rm = boston_df[['RM']]
# Target data
y_train = boston_df[['PRICE']]
import statsmodels.api as sm
X_train = sm.add_constant(rm, has_constant = 'add')
X_train.head()
# +
# 선형 회귀 모델에 Target과 Feature를 넣기
single_model = sm.OLS(y_train, X_train)
# 모델 학습하기
fitted_model = single_model.fit() # 우리가 만든 학습된 모델
# -
# 학습의 결과를 확인해보기
fitted_model.summary()
# ## 결과 해석
#
# - R-squared가 0.484로 48%의 설명력을 갖는다.
# - P-value는 0.000으로 0.05보다 작은 유의미한 상태 (P>⎪t⎪에 해당)
# <div class="alert alert-success" data-title="">
# <h2><i class="fa fa-tasks" aria-hidden="true"></i> 단순선형회귀 모델을 통한 관계분석
# </h2>
# </div>
#
# ## X,y 설정하기
boston_df.columns
X = pd.DataFrame(boston_df['RM']) # 2차원 배열로 만들기 위해서 DF로 만듬
X.head()
y = boston_df['PRICE']
y.head()
# ## 학습 평가 데이터 나누기
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,
test_size=0.3,
random_state = 42)
# ## 모델 학습
#
# ```python
# from sklearn.linear_model import LinearRegression
# #1. model 정의
# #2. fit
# #3. predict
# ```
from sklearn.linear_model import LinearRegression
model= LinearRegression() # 저의
model.fit(X_train,y_train) # 학습!!
y_pred = model.predict(X_test) # 예측값
y_pred[0]
# ## 모델 평가
#
# ```python
# from sklearn.metrics import mean_absolute_error # 1. MAE
# from sklearn.metrics import mean_squared_error # 2. MSE
# import numpy as np # 3. RMSE
# from sklearn.metrics import r2_score # 4. R2_score
# ```
from sklearn.metrics import mean_absolute_error
mean_absolute_error(y_test, y_pred)
from sklearn.metrics import mean_squared_error, r2_score
mse = mean_squared_error(y_test,y_pred)
mse
# rmse
np.sqrt(mse)
r2 = r2_score(y_test,y_pred)
r2
# 추정된 회귀 모형의 회귀 계수 및 절편 값을 확인
# 회귀 계수는 coef_ 속성, 절편은 intercept_ 속성에 각각 값이 할당
print("회귀 계수 : ", model.coef_)
print("절편 : ",model.intercept_)
# ## 데이터 시각화
import matplotlib.pyplot as plt
x = range(4,10)
plt.title("Boston House Price")
plt.plot(X,y,'o',color = 'blue',alpha = 0.5)
plt.plot(x,model.coef_*x+model.intercept_,'--',color='red')
plt.show()
| code/Day03/Day03_03 linear regression_boston house price.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/juliowaissman/transformadores/blob/main/transformadores.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="gZmf9TidlZqP"
# 
#
# # Transformadores y modelos modernos de PLN
#
# ## Curso de Procesamiento de Lenguaje Natural
#
# ### Maestría en Ciencia de Datos
#
# ### Universidad de Sonora
#
# **<NAME>** y **<NAME>**
# + [markdown] id="veLBiSxQl8TU"
# Los *transformadores* son modelos de redes neuronales que están diseñados para manejar datos secuenciales, como el lenguaje natural. A diferencia de los RNN, los transformadores utilizan un modelo que se conoce como *mecanismo de atención* que no requiere que los datos secuenciales se procesen en orden.
#
# Por ejemplo, si los datos de entrada son una oración en lenguaje natural, el transformador no necesita procesar el principio antes del final. Debido a esta característica, el transformador permite mucha más paralelización que los RNN y, por lo tanto, reduce los tiempos de entrenamiento.
#
# Estos modelos se están utilizando muy intensivamente para abordar muchos problemas de PNL, reemplazando los modelos de redes neuronales recurrentes más antiguos, como los LSTM. Dado que estos modelos facilitan una mayor paralelización durante el entrenamiento, ha permitido el entrenamiento en conjuntos de datos más grandes de lo que era posible antes de su introducción.
#
# Una buena explicación de lo que son los transformadores, y la idea subyaciente del mecanismo de atención se puede consultar en [este artículo de Medium](https://towardsdatascience.com/transformers-141e32e69591).
# + [markdown] id="KqzX6wob2fSl"
# En esta libreta vamos a explorar el uso de la librería `transformers` de la empresa [Hugging Face](https://huggingface.co). Esta librería es un *hub* que permite cargar y aplicar diferentes modelos preentrenados de transformadores para diferentes tareas. Igualmente es posible realizar un entrenamiento fino de los modelos a casos particulares, y someter dichos modelos para que puedan ser utilizados por otros.
#
# Para instalar `transformers` es necesario contar con *TensorFlow 2.x* y/o *pyTorch*. En general la mayoría de los modelos vienen en *pyTorch*. Si lo ejecutas desde *Colab*, el entorno ya viene con ambas librerias tensoriales preinstaladas.
#
# Par algunos modelos es necesario contar con [el módulo `sentencepiece`](https://github.com/google/sentencepiece) que es un módulo desarrollado por google para tokenizar, basado solo en la estructura de unigramas (independiente del lenguaje). Viene con funciones para acelerar tokenizadores existentes.
# + id="cx46Lg6t3z5p"
# !pip install transformers
# !pip install sentencepiece
# + [markdown] id="4hPWuAbT5OAz"
# La librería viene con un comando llamado `pipeline` que permite seleccionar un modelo preentrenado y aplicarlo a una serie de tareas (si el modelo viene adaptado a la tarea). La interfase es realmente sencilla de utilizar y si tenemos un modelo preentrenado que sea suficiente es una manera fácil de utilizar modelos modernos en aplicaciones.
#
# Las tareas para las que se puede utilizar el comando `pipeline`son:
#
# - `"feature-extraction"`
# - `"sentiment-analysis"`
# - `"ner"`
# - `"question-answering"`
# - `"fill-mask"`
# - `"summarization"`
# - `"translation_xx_to_yy"`
# - `"text2text-generation"`
# - `"text-generation"`
# - `"zero-shot-classification:`
# - `"conversational"`
#
# Vamos a explorar la aplicación de alguna de ellas en esta libreta. Para mayor información del uso de `pipeline`puedes consultar [la documentación correspondiente](https://huggingface.co/transformers/task_summary.html).
# + id="0QKnECvk3m1J"
from transformers import pipeline
# Si quieres ver la documentación de pipeline solo descomenta esta linea
#help(pipeline)
# + [markdown] id="bmQ5BP4X9Vw7"
# Para usar el `pipeline` es necesario seleccionar un modelo preentrenado. En la documentación se muestra [una serie de modelos generales y sus características](https://huggingface.co/transformers/model_summary.html). Lo mejor es ir y consultar la [lista exhaustiva de modelos preentrenados](https://huggingface.co/models) de *Hugging Face*.
#
# Vamos a practicar con algunas tareas.
# + [markdown] id="VtE0VHg5-ayA"
# ## Contestando preguntas
#
# Para ejemplificar esta tarea vamos a descargar el texto de una conferencia Matutina del Presidente de México del [proyecto público de NOSTRODATA](https://github.com/NOSTRODATA/conferencias_matutinas_amlo), y nos vamos a quedar con el discurso inicial.
# + id="L2yft2WD_lZg"
import pandas as pd
import pprint
file = 'https://raw.githubusercontent.com/NOSTRODATA/conferencias_matutinas_amlo/master/2021/4-2021/abril%2014%2C%202021/mananera_14_04_2021.csv'
df = pd.read_csv(file)
ind = min(df.index[df.Participante != df.Participante[0]]) - 1
contexto = "\n".join(df.Texto[:ind])
pprint.pprint(contexto)
# + [markdown] id="kQOjj1Q__q-Z"
# Ahora vamos autilizar un modelo tipo [DistilBERT](https://arxiv.org/pdf/1910.01108.pdf) entrenado en español para responder preguntas.
# + id="I1_U6NHU_s70"
nlp = pipeline(
'question-answering',
model='mrm8488/distill-bert-base-spanish-wwm-cased-finetuned-spa-squad2-es',
tokenizer=(
'mrm8488/distill-bert-base-spanish-wwm-cased-finetuned-spa-squad2-es',
{"use_fast": False}
)
)
preguntas = [
'¿Qué compañia se constituyó?',
'¿Cual es la audiencia potencial?',
'¿Que les pidió?'
]
for pregunta in preguntas:
respuesta = nlp({'question': pregunta, 'context': contexto})
print("=" * 30)
print(f"Pregunta: {pregunta}")
print(f"Respuesta: \"{respuesta['answer']}\", con un score de {respuesta['score']}")
print("=" * 30)
# + [markdown] id="v_IbLGxTCsg5"
# **Prueba ahora con otro texto (otra mañanera, o una entrada de Wikipedia por ejemplo) y revis el resultado.**
#
# **¿Es el único modelo para responer preguntas en un contexto en español entre los modelos de Hugging Faces? Si hay otro(s) anotalos aqui mismo.**
# + [markdown] id="IpPPR8LTDHII"
# ## Haciendo resumenes de un texto
#
# ¿Y como podríamos resumir el documento que acabamos de ver? Vamos a probar un modelo llamad [mT5](https://arxiv.org/pdf/2010.11934.pdf) para hacer resumenes.
# + id="E9QKshLmDTwx"
resumidor = pipeline(
"summarization",
model="LeoCordoba/mt5-small-mlsum"
)
resumen = resumidor(contexto, min_length=5, max_length=500)
print("\n\nResumen:\n\n" + resumen[0]['summary_text'])
# + [markdown] id="yV7sceuYIgoI"
# **Prueba cambiando los parámetros que puedes modificar (`min_lenght`y `max_lenght`). Revisa el resumen de otro texto (como una descripción de un sitio turístico por ejemplo).**
#
# **¿Qué otros modelos existen para hacer resúmenes de textos en español?**
# + [markdown] id="pKOAxduUDzDx"
# ## Clasificación *zero-shot*
#
# La clasificación *zero shot* es un método semi-supervisado, en el cual a un documento se le da una serie de opciones, para la cual no estuvo previamente entrenado el sistema, pero en función del contexto (vectores de palabras de nuevo) el modelo trata de inferir las categorias más probables.
# + id="cjMyE1YnJD1K"
classificador = pipeline(
"zero-shot-classification",
model="Recognai/bert-base-spanish-wwm-cased-xnli"
)
textos = [
"El autor se perfila, a los 50 años de su muerte, como uno de los grandes de su siglo",
"Se realizó la fusión de Televisa con Univisión y se constituyó la compañía de medios en español más grande del mundo.",
"El Real Madrid de nuevo se encuentra disputando la semifinal de la Copa de Campeones de la UEFA",
"La proxima semana inicia la vacunación contra COVID para el personal de educación",
"Aglomeraciones y falta de medidas se presentan en los mítines y eventos de las campañas de todos los candidatos"
]
etiquetas = ["cultura", "sociedad", "economia", "politica", "salud", "deportes"]
for texto in textos:
resultado = classificador(
texto,
candidate_labels=etiquetas,
hypothesis_template="Este texto es sobre {}."
)
print("=" * 80)
print(result['sequence'])
for label, score in zip(result['labels'], result['scores']):
print(f"\t\t{label} ({score})")
print("=" * 80)
# + [markdown] id="Ds3OH-hLKkP8"
# **Prueba cambiando categorías, el template de la hipótesis y los textos, para entender como funciona el método**
#
# **¿exiten otros modelos preentrenados para hacer clasificación *zero-shot*? Si es el caso, enuncia uno.**
# + [markdown] id="Ws_kpFsJLEHa"
# ## RuPERTa
#
# Hasta ahorita pareciera cosa mágica, pero es importante estar pendientes que no todos los modelos basados en transformadores son buenos. Algunos se han entrenado con realmente muy pocos casos y solo funcionan correctamente en casos muy estandar.
#
# Para ilustrar eso, así de como se toma un modelo que sirve para varios propósitos, pero con malos resultados, vamos autilizar el modelo *RuPERTa* que es el modelo [RoBERTa](https://arxiv.org/pdf/1907.11692.pdf) entrenado en un corpus grande en español.
#
# El modelo es muy útil y se aplica en diferentes tareas con éxito, pero en algunas apñicaciones su desempeño deja mucho que desear (sobre todo si no se utiliza un manejo del lenguaje similar al que se hace en España). Tenemos que entrenar un modelo *mexicano*.
#
# Empecemos por hacer POS-Tagging
# + id="MBNl34E-NCnS"
import torch
from transformers import AutoModelForTokenClassification, AutoTokenizer
pos2label = {
"0": "O",
"1": "ADJ",
"2": "ADP",
"3": "ADV",
"4": "AUX",
"5": "CCONJ",
"6": "DET",
"7": "INTJ",
"8": "NOUN",
"9": "NUM",
"10": "PART",
"11": "PRON",
"12": "PROPN",
"13": "PUNCT",
"14": "SCONJ",
"15": "SYM",
"16": "VERB"
}
tokenizer = AutoTokenizer.from_pretrained('mrm8488/RuPERTa-base-finetuned-pos')
model = AutoModelForTokenClassification.from_pretrained('mrm8488/RuPERTa-base-finetuned-pos')
text = (
"<NAME>, profesor de la Universidad de Sonora, " +
"nació en Cuauhtemoc, Chihuahua " +
"y está pensando en viajar a Puebla en vacaciones."
)
input_ids = torch.tensor(tokenizer.encode(text)).unsqueeze(0)
outputs = model(input_ids)
last_hidden_states = outputs[0]
for m in last_hidden_states:
for index, n in enumerate(m):
if(index > 0 and index <= len(text.split(" "))):
print(text.split(" ")[index-1] + ": " + pos2label[str(torch.argmax(n).item())])
# + [markdown] id="da3CUqlqPIv2"
# Bastante, bastante mal ¿verdad? Ahora veamos como funciona el NER:
# + id="kRQrURhGPO0R"
ner2label = {
"0": "B-LOC",
"1": "B-MISC",
"2": "B-ORG",
"3": "B-PER",
"4": "I-LOC",
"5": "I-MISC",
"6": "I-ORG",
"7": "I-PER",
"8": "O"
}
tokenizer = AutoTokenizer.from_pretrained('mrm8488/RuPERTa-base-finetuned-ner')
model = AutoModelForTokenClassification.from_pretrained('mrm8488/RuPERTa-base-finetuned-ner')
input_ids = torch.tensor(tokenizer.encode(text)).unsqueeze(0)
outputs = model(input_ids)
last_hidden_states = outputs[0]
for m in last_hidden_states:
for index, n in enumerate(m):
if(index > 0 and index <= len(text.split(" "))):
print(text.split(" ")[index-1] + ": " + ner2label[str(torch.argmax(n).item())])
# + [markdown] id="iftgA6amQXnu"
# Y para terminar de desencantarnos de RuPERTa vamos a terminar usando el modelo para llenar espacios vacios:
#
# + id="1VQOISHnQWc5"
pipeline_fill_mask = pipeline(
"fill-mask",
model='mrm8488/RuPERTa-base'
)
rellena = pipeline_fill_mask("México es un país muy <mask> en el mundo")
print("\n\n\n\nMéxico es un país muy <mask> en Latinoamérica\n")
print("=" * 30)
for caso in rellena:
print(f"{caso['sequence']} ({caso['score']})")
print("=" * 30)
# + [markdown] id="DBazHQQBQz0_"
# **¿No hay otros modelos para llenar espacio vacío en español con resultados decentes? Revisa si hay otro y aplicalo a ver si da mejores resultados.**
#
# **¿Porqué haríamos el NER o el POS tagging con transformadores, teniendo el modelo preentrenado de SpaCy?**
# + [markdown] id="ZpRwev2CRWU8"
# ## Generación de texto
#
# La generación de texto tuvo un [hito importante con el modelo GPT-2](https://openai.com/blog/better-language-models/), tanto que el modelo *GPT-3* lo mantuvieron privado por la capacidad que tenía para generar texto falso creible, y su potencial aplicación en el desarrollo de bots de noticias falsas.
#
# Para terminar con los transformadores, vamos a ver un modelo sencillo en español para generación de texto.
# + id="2xstsctWSY31"
generador = pipeline(
"text-generation",
model="datificate/gpt2-small-spanish"
)
texto_generado = generador(
"Se encontraron sapos alucinógenos en la Isla Tiburon",
max_length=100,
)
for muestra in texto_generado:
pprint.pprint(muestra['generated_text'])
# + id="QDvcCqwtVij_"
texto_generado = generador(
"¿Quén es <NAME>?",
max_length=100,
)
for muestra in texto_generado:
pprint.pprint(muestra['generated_text'])
# + [markdown] id="EvE0l0ymWPe0"
# **¿Hay otros modelos mejor entrenados en español para la generación de texto automático? Revisa diferentes modelos**
#
# **Con el modelo encontrado ¿Se podrían generar bots maliciosos para esparcir *fakes news* en tuiter?**
| transformadores.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
# ---
# # Present Value, Future Value, and Interest Rates
# ## The Time Value of Money
#
# An important concept that is the basis for most of finance is the *time value of money*: money now is worth more than money in the future. This makes sense; you would rather have \$100 now than later. But what if I owed you money and I really wanted to postpone the payment? In order to compensate you for your bias toward having money as soon as possible, I would need to pay more than I owed. Otherwise, you might not tolerate a delayed payment. This idea of an extra payment to address time concerns is called *interest*. There is also a dimension of risk as well. If you had reason to doubt my ability to repay you in the future, you might charge me more interest to compensate for this risk.
# ```{admonition} Definition
# **Interest** is payment at a particular rate for the use of money or for delaying the repayment of money. Interest is typically set at a specific rate and that rate fluctuates based on the amount of time between borrowing and repayment, the risk of default, and other factors determined by the lender.
# ```
# ## Interest
#
# Interest is at the heart of loans, fixed income securities (think bonds), and financial economics in general. We are familiar with the bank account: you give a certain amount of money to a financial institution, and they compensate you for allowing them to use your money to invest in other assets. What they pay you for keeping your money is interest, and is normally quantified as a percentage of what you deposit with them - an interest rate. Thus, for each \$1 deposited at the bank, you will receive $r$ dollars in interest, where $r$ is the interest rate quoted by the bank. Note that $r$ takes the form of a decimal value: 0.05, for instance, and not 5%.
#
# Interest can be paid out in different time intervals - usually monthly, quarterly, yearly or continuously. Also, if you earn some interest in one year, in the next year you will not only earn interest on the initial amount you deposited, but also on the amount you earned the year before. This reflects the idea of *compounding interest*. We are able to determine how much \$1 will be worth in $t$ years, when compounding $n$ times per year at an interest rate of $r$.
#
# $$\begin{aligned}
# \text{Value of 1 dollar in } t \text{ years} &= 1 \times \left(1 + \dfrac{r}{n} \right) \times \left(1 + \dfrac{r}{n} \right) \times \cdots \times \left(1 + \dfrac{r}{n} \right) \\
# &= 1 \left(1 + \dfrac{r}{n} \right)^{nt}
# \end{aligned}$$
#
# Take a look at the table below for an example of the effects of compounding.
#
# | | Bank 1: 5\% annual compounding | Bank 2: 5\% semi-annual compounding |
# |------------------------|--------------------------------|-----------------------------------------------------------|
# | January 2016 | \$100 | \$100 |
# | July 2016 | | $100 \left(1 + \dfrac{0.05}{2} \right) =$ \$102.50 |
# | January 2017 | $100 (1 + 0.05) =$ \$105 | $102.50 \left(1 + \dfrac{0.05}{2} \right) =$ \$105.0625 |
# | July 2017 | | $105.0625 \left(1 + \dfrac{0.05}{2} \right) =$ \$107.69 |
# | January 2018 | $105 (1 + 0.05) =$ \$110.25 | $107.69 \left(1 + \dfrac{0.05}{2} \right) =$ \$110.38 |
# | Total Percent Change | 10.25% | 10.38% |
#
# Notice that instead of a $5\% \cdot 2 = 10\%$ increase, you end up receiving a 10.25% or 10.38% increase depending on the rate of compounding. This is because the interest you received in the first compounding period (in bank 1’s case, a year, in bank 2’s case, half a year) is added onto your initial deposit, and this new deposit is used for calculating interest in the next period. Thus, even a small amount of money can grow quickly under interest rate compounding.
# ## Present Value, Future Value, and the Discount Factor
#
# An important related concept is the idea of present and future value (which are effectively opposites). We have already discussed future value above. A \$100 deposit at bank 1 above has a future value of \$110.25 after 2 years. Conversely, an important question frequently asked in finance is the following:
#
# > Given an amount of money in the future, what is its fair value today?
#
# In this example, what is the present value of \$110.25 at bank 1 two years in the future? Well, from the table above, \$100! This idea of present value is essential to the pricing of assets. In general, an asset's price is the present value of all expected future payments.
#
# $$\begin{aligned}
# \text{FV of 1 dollar} &= 1 \times \left(1 + \dfrac{r}{n} \right)^{nt} \\
# \text{PV of 1 dollar} &= \dfrac{1}{\left(1 + \dfrac{r}{n} \right)^{nt}}
# \end{aligned}$$
#
# We call $\dfrac{1}{(1 + \frac{r}{n})^{nt}}$ a *discount factor*. It discounts the value of \$1 from the future into today. This ties in with the time value of money. Since a dollar today is worth more than a dollar tomorrow, in order for you to be indifferent between receiving money today or tomorrow, the money you would receive tomorrow has to be discounted into the present by some amount that depends on the interest rate.
#
# $$
# \text{PV} = \text{DF} \cdot \text{FV}
# $$
#
| docs/_sources/content/09-finance/value-interest.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
# ---
#importing required libraries
import rasterio
from rasterio import plot
import matplotlib.pyplot as plt
import numpy as np
# %matplotlib inline
#opennig the study area images
band4=rasterio.open("Test Images/nir.tif")
band5=rasterio.open("Test Images/swir.tif")
#multiple band representation
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
plot.show(band4, ax=ax1, cmap='gray') #nir
plot.show(band5, ax=ax2, cmap='gray') #swir
fig.tight_layout()
#generating nir and swir objects as arrays in float64 format
nir=band4.read(1).astype('float64')
swir=band5.read(1).astype('float64')
#Normalized Burn Ratio calculation(empty cells or nodata cells are reported as 0)
nbr=np.where(
(nir+swir)==0.,
0,
(nir-swir)/(nir+swir))
#exporting the NBR image
nbr_image = rasterio.open('Outputs/nbr_image.tiff','w',driver='Gtiff',
width=band4.width,
height = band4.height,
count=1, crs=band4.crs,
transform=band4.transform,
dtype='float64')
nbr_image.write(nbr,1)
nbr_image.close()
#plotting the NBR image
nbrimg = rasterio.open('Outputs/nbr_image.tiff')
fig = plt.figure(figsize=(12,6))
plot.show(nbrimg, cmap='gray')
#raster sytem of reference
nbrimg.crs
#raster transform parameters
nbrimg.transform
#type of raster byte
nbrimg.dtypes[0]
#number of raster rows
nbrimg.height
#number of raster columns
nbrimg.width
#importing skimage library in order to show the histogram of NBR image
from skimage import io, exposure
import skimage.io
#defining a function in order to show the histogram of NBR image
def image_histogram(nbrimg):
"""
Plot image histogram
Input:
img - 2D array of uint16 type
"""
co, ce = exposure.histogram(nbr)
fig = plt.figure(figsize=(10, 7))
fig.set_facecolor('white')
plt.plot(ce[1::], co[1::])
plt.show()
image_histogram(nbrimg)
| GEO468E_nbr_v2.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: learn-env
# language: python
# name: learn-env
# ---
# # King County Dataset Linear Regression Model 8
# ### Adjustments for this model:
# Start with getting rid of 'id', 'sqft_living15', 'sqft_lot15'
# Then deal with the NaN's in 'view', 'waterfront', 'yr_renovated', and 'sqft_basement'
# Change "?" in 'sqft_basement'
# Take care of outlier in bedrooms
# Deal with the date feature
# Bin: 'view', 'grade', 'condition', 'sqft_basement', 'yr_renovated'
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
data = pd.read_csv("kc_house_data.csv")
data.head()
data.describe()
# Change "?" in 'sqft_basement' to '0';
data.sqft_basement = data.sqft_basement.replace(to_replace = '?', value = '0')
# Account for missing data in 'waterfront', 'view', 'yr_renovated';
data.waterfront.fillna(value=data.waterfront.median(), inplace = True)
data.view.fillna(value=data.view.median(), inplace = True)
data.yr_renovated.fillna(value=data.yr_renovated.median(), inplace = True)
data.sqft_basement.fillna(value=data.sqft_basement.median(), inplace = True)
# Change outlier '33' to '3' in 'bedrooms';
data.at[15856,'bedrooms'] = 3
# Change 'date' feature to float;
import datetime as dt
data['date'] = pd.to_datetime(data['date'])
data['date']= data['date'].map(dt.datetime.toordinal)
data['sqft_basement'] = data['sqft_basement'].astype(float)
data.sqft_basement.describe()
data.describe()
# +
# Create bins for 'yr_renovated' based on the values observed. 4 values will result in 3 bins
bins_A = [0, 1900, 2000, 2020]
bins_yr_renovated = pd.cut(data['yr_renovated'], bins_A)
#bins_yr_renovated = bins_yr_renovated.as_unordered()
yr_renovated_dummy = pd.get_dummies(bins_yr_renovated, prefix="yr-ren", drop_first=True)
data = data.drop(["yr_renovated"], axis=1)
data = pd.concat([data, yr_renovated_dummy], axis=1)
# +
# Create bins for 'sqft_basement' based on the values observed. 3 values will result in 2 bins
bins_B = [0, 100, 5000]
bins_sqft_basement = pd.cut(data['sqft_basement'], bins_B)
sqft_basement_dummy = pd.get_dummies(bins_sqft_basement, prefix="sqft_base", drop_first=True)
data = data.drop(["sqft_basement"], axis=1)
data = pd.concat([data, sqft_basement_dummy], axis=1)
# +
# Create bins for 'view' based on the values observed. 3 values will result in 2 bins
bins_C = [0, 2, 4]
bins_view = pd.cut(data['view'], bins_C)
view_dummy = pd.get_dummies(bins_view, prefix="new_view", drop_first=True)
data = data.drop(["view"], axis=1)
data = pd.concat([data, view_dummy], axis=1)
# +
# Create bins for 'grade' based on the values observed. 4 values will result in 3 bins
bins_D = [0, 5, 7, 13]
bins_grade = pd.cut(data['grade'], bins_D)
grade_dummy = pd.get_dummies(bins_grade, prefix="new_grade", drop_first=True)
data = data.drop(["grade"], axis=1)
data = pd.concat([data, grade_dummy], axis=1)
# +
# Create bins for 'condition' based on the values observed. 3 values will result in 2 bins
bins_E = [1, 3, 5]
bins_condition = pd.cut(data['condition'], bins_E)
condition_dummy = pd.get_dummies(bins_condition, prefix="new_condition", drop_first=True)
data = data.drop(["condition"], axis=1)
data = pd.concat([data, condition_dummy], axis=1)
# -
# Drop 'id' since it has no value;
# Drop "sqft_above", "sqft_lot15", "sqft_living15" due to multicolinearity;
X = data.drop(["id","sqft_above", "sqft_lot15", "sqft_living15"], axis=1)
y = pd.DataFrame(data, columns = ['price'])
# Perform a train-test split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y)
# A brief preview of our train test split
print(len(X_train), len(X_test), len(y_train), len(y_test))
# Apply your model to the train set
from sklearn.linear_model import LinearRegression
linreg = LinearRegression()
linreg.fit(X_train, y_train)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
# +
# Calculate predictions on training and test sets
y_hat_train = linreg.predict(X_train)
y_hat_test = linreg.predict(X_test)
# Calculate training and test residuals
train_residuals = y_hat_train - y_train
test_residuals = y_hat_test - y_test
# +
#Calculate the Mean Squared Error (MSE)
from sklearn.metrics import mean_squared_error
train_mse = mean_squared_error(y_train, y_hat_train)
test_mse = mean_squared_error(y_test, y_hat_test)
print('Train Mean Squarred Error:', train_mse)
print('Test Mean Squarred Error:', test_mse)
# -
#Evaluate the effect of train-test split
import random
random.seed(8)
train_err = []
test_err = []
t_sizes = list(range(5,100,5))
for t_size in t_sizes:
temp_train_err = []
temp_test_err = []
for i in range(100):
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=t_size/100)
linreg.fit(X_train, y_train)
y_hat_train = linreg.predict(X_train)
y_hat_test = linreg.predict(X_test)
temp_train_err.append(mean_squared_error(y_train, y_hat_train))
temp_test_err.append(mean_squared_error(y_test, y_hat_test))
train_err.append(np.mean(temp_train_err))
test_err.append(np.mean(temp_test_err))
plt.scatter(t_sizes, train_err, label='Training Error')
plt.scatter(t_sizes, test_err, label='Testing Error')
plt.legend()
# +
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import cross_val_score
cv_5_results = np.mean(cross_val_score(linreg, X, y, cv=5, scoring='neg_mean_squared_error'))
cv_5_results
# +
import statsmodels.api as sm
from statsmodels.formula.api import ols
formula = "price ~ date+bedrooms+bathrooms+sqft_living+sqft_lot+floors+yr_renovated_dummy+view_dummy+sqft_basement_dummy+grade_dummy+waterfront+yr_built+zipcode+lat+long"
model = ols(formula= formula, data=data).fit()
model.summary()
# -
# ## Results
# ###### R-squared: 0.661. The more I do the worst it gets!
| Model_Attempts/Eighth_Try_Model.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.6 - AzureML
# language: python
# name: python3-azureml
# ---
# # モデルの不公平性を検出して軽減する
#
# 機械学習モデルには意図しないバイアスが組み込まれていることがあり、*公平性* の問題につながる可能性があります。たとえば、糖尿病の可能性を予測するモデルは、一部の年齢層ではうまく機能しても、他の年齢層ではうまく機能しないかもしれません。そのため、一部の患者が不必要な検査を受けたり、糖尿病の診断を確定する検査を受けられなかったりする可能性があります。
#
# このノートブックでは、**Fairlearn** パッケージを使用してモデルを分析し、年齢に基づいて患者の異なるサブセットの予測パフォーマンスの格差を探ります。
#
# > **注**: Fairlearn パッケージとの統合は、現在プレビュー中です。予期しないエラーが発生する場合があります。
#
# ## 重要 - 公平性への配慮
#
# > このノートブックは、Fairlearn パッケージと Azure Machine Learning との統合を探索するための実践的な演習として設計されています。しかし、組織やデータ サイエンス チームがツールを使用する前に、公平性に関して議論しなければならない考慮事項は非常に多くあります。公平性は、単にモデルを分析するツールを実行するだけにとどまらない、複雑な *社会技術的* 課題です。
# >
# > Microsoft Research は 1 行のコードが記述される前に行われる必要がある重要な議論の出発点となる [公平性チェックリスト](https://www.microsoft.com/en-us/research/publication/co-designing-checklists-to-understand-organizational-challenges-and-opportunities-around-fairness-in-ai/) を共同開発しました。
#
# ## 必要な SDK をインストールする
#
# Azure Machine Learning で Fairlearn パッケージを使用するには、Azure Machine Learning と Fairlearn Python パッケージが必要なので、次のセルを実行して **azureml-contrib-fairness** パッケージがインストールされていることを確認します。
# !pip show azureml-contrib-fairness
# また、**fairlearn** パッケージ自体と **raiwidgets** パッケージ(Fairlearn がダッシュボードを視覚化するために使用する)も必要となります。インストールするには次のセルを実行します。
# !pip install --upgrade fairlearn==0.6.2 raiwidgets
# ## モデルをトレーニングする
#
# まず、糖尿病の可能性を予測するための分類モデルをトレーニングします。データを特徴およびラベルのトレーニング セットとテスト セットに分割するだけでなく、公平性を比較するデータの部分母集団を定義するために使用される *センシティブ* 特徴を抽出します。この例では、**Age** 列を使用して、50歳を超える患者と50歳以下の患者という二つのカテゴリを定義します。
# +
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# 糖尿病データセットを読み込む
print("Loading Data...")
data = pd.read_csv('data/diabetes.csv')
# 特徴とラベルを分離する
features = ['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']
X, y = data[features].values, data['Diabetic'].values
# センシティブ特徴を入手する
S = data[['Age']].astype(int)
# 年齢層を表すために値を変更する
S['Age'] = np.where(S.Age > 50, 'Over 50', '50 or younger')
# データをトレーニング セットとテスト セットに分割する
X_train, X_test, y_train, y_test, S_train, S_test = train_test_split(X, y, S, test_size=0.20, random_state=0, stratify=y)
# 分類モデルをトレーニングする
print("Training model...")
diabetes_model = DecisionTreeClassifier().fit(X_train, y_train)
print("Model trained.")
# -
# モデルのトレーニングが完了したので、Fairlearn パッケージを使用して、さまざまなセンシティブ特徴値に対する動作を比較できます。この例では、以下のことを行います。
#
# - fairlearn **selection_rate** 関数を使用して、母集団全体の選択率 (正の予測の割合) を返します。
# - **scikit-learn** メトリック関数を使用して、全体的な精度、再現率、適合率のメトリックを計算します。
# - **MetricFrame** を使用して、**Age** のセンシティブ特徴の各年齢層の選択率、精度、再現率および適合率を計算します。パフォーマンス値の計算には、**fairlearn** と **scikit-learn** のメトリック関数を組み合わせて使用することに注意してください。
# +
from fairlearn.metrics import selection_rate, MetricFrame
from sklearn.metrics import accuracy_score, recall_score, precision_score
# 伏せられたテスト データの予測を取得する
y_hat = diabetes_model.predict(X_test)
# 全体的なメトリックを取得する
print("Overall Metrics:")
# Fairlearn から選択率を取得する
overall_selection_rate = selection_rate(y_test, y_hat) # Get selection rate from fairlearn
print("\tSelection Rate:", overall_selection_rate)
# scikit-learn から標準的なメトリックを取得する
overall_accuracy = accuracy_score(y_test, y_hat)
print("\tAccuracy:", overall_accuracy)
overall_recall = recall_score(y_test, y_hat)
print("\tRecall:", overall_recall)
overall_precision = precision_score(y_test, y_hat)
print("\tPrecision:", overall_precision)
# Fairlearn からセンシティブ グループのメトリックを取得する
print('\nMetrics by Group:')
metrics = {'selection_rate': selection_rate,
'accuracy': accuracy_score,
'recall': recall_score,
'precision': precision_score}
group_metrics = MetricFrame(metrics,
y_test, y_hat,
sensitive_features=S_test['Age'])
print(group_metrics.by_group)
# -
# これらのメトリックから、高齢患者の大部分が糖尿病であると予測されることがわかるはずです。*精度* は 2 つのグループでほぼ同じですが、*精度* と *再現率* を詳しく調べると、各年齢層でのモデルの予測精度に多少の格差があることがわかります。
#
# このシナリオでは、*再現率* を検討します。このメトリックは、モデルによって正しく識別された陽性症例の割合を示します。つまり、実際に糖尿病にかかっているすべての患者のうち、モデルに検出された人数です。このモデルは、若年患者よりも高齢患者の方がこの点で優れた結果を示しました。
#
# 多くの場合、メトリックを視覚的に比較する方が簡単です。これを行うには、Fairlearn 公平性ダッシュボードを使用します。
#
# 1. 下のセルを実行して、前に作成したモデルからダッシュボードを生成します。
# 2. ウィジェットが表示されたら、**はじめに** リンクを使用して視覚化の設定を開始します。
# 3. 比較するセンシティブ特徴を選択します (この例では、次の 1 つだけです: **年齢**)。
# 4. 比較するモデル パフォーマンス メトリックを選択します (この場合は二項分類モデルであるため、オプションは *精度*、*均衡の取れた精度*、*適合率*、*再現率* です)。**再現率** から始めます。
# 5. 表示する公平性比較のタイプを選択します。**人口統計学的パリティの違い**から始めましょう。
# 6. ダッシュボードの視覚化を表示します。次の内容が表示されます。
# - **パフォーマンスの格差** - *予測不足* (偽陰性) や *予測過剰* (偽陽性) などの部分母集団と比較した、選択したパフォーマンス メトリック。
# - **予測の格差** - 部分母集団あたりの陽性症例数の比較。
# 7. 構成を編集して、異なるパフォーマンスと公平性メトリックに基づく予測を比較します。
# +
from raiwidgets import FairnessDashboard
# Fairlearn の公平性ダッシュボードでこのモデルを表示し、表示される差異を確認する
FairnessDashboard(sensitive_features=S_test,
y_true=y_test,
y_pred={"diabetes_model": diabetes_model.predict(X_test)})
# -
# その結果、50 歳以上の患者の方が若年患者よりも選択率がはるかに高くなっています。しかし、実際には年齢は糖尿病の正真正銘の要因なので、高齢患者の方が陽性症例が多くなることが予想されます。
#
# モデルのパフォーマンスを *精度* (つまり、モデルが正しく予測される割合) に基づいて判断すると、どちらの部分母集団に対してもほぼ同等に機能するように思われます。しかし、*適合率* と *再現率* のメトリックに基づくと、このモデルは 50 歳以上の患者でより良いパフォーマンスを示す傾向があります。
#
# モデルをトレーニングするときに **年齢** 特徴を除外するとどうなるか見てみましょう。
# +
# 特徴とラベルを分離する
ageless = features.copy()
ageless.remove('Age')
X2, y2 = data[ageless].values, data['Diabetic'].values
# データをトレーニング セットとテスト セットに分割する
X_train2, X_test2, y_train2, y_test2, S_train2, S_test2 = train_test_split(X2, y2, S, test_size=0.20, random_state=0, stratify=y2)
# 分類モデルをトレーニングする
print("Training model...")
ageless_model = DecisionTreeClassifier().fit(X_train2, y_train2)
print("Model trained.")
# Fairlearn の公平性ダッシュボードでこのモデルを表示し、表示される差異を確認する
FairnessDashboard(sensitive_features=S_test2,
y_true=y_test2,
y_pred={"ageless_diabetes_model": ageless_model.predict(X_test2)})
# -
# ダッシュボードのモデルを探索します。
#
# *再現率* を見直す際には、このモデルが高齢患者の陽性症例を有意に過小評価しているため、格差は減少していますが、全体的な再現率も減少していることに注意します。**年齢** はトレーニングで使用された特徴ではありませんでしたが、このモデルは高齢患者と若年患者を予測する際に若干の格差を示しています。
#
# このシナリオでは、**年齢** を削除するだけで、*再現率* の格差はわずかに減少しますが、*適合率* と *精度* の格差が大きくなります。これは、機械学習モデルに公平性を適用する際の重要な問題の 1 つを強調しています。特定のコンテキストにおいて *公平性* が何を意味するのかを明確にし、そのために最適化する必要があります。
#
# ## モデルを登録し、ダッシュボード データをワークスペースにアップロードします。
#
# このノートブックでモデルをトレーニングし、ダッシュボードをローカルで確認しました。しかし、Azure Machine Learning ワークスペースにモデルを登録し、ダッシュボード データを記録する実験を作成すると、公平性分析を追跡して共有できるので便利かもしれません。
#
# まずは元のモデル (特徴として **年齢** が含まれていました) を登録してみましょう。
#
# > **注**: Azure サブスクリプションでまだ認証済みのセッションを確立していない場合は、リンクをクリックして認証コードを入力し、Azure にサインインして認証するよう指示されます。
# +
from azureml.core import Workspace, Experiment, Model
import joblib
import os
# 保存された構成ファイルから Azure ML ワークスペースを読み込む
ws = Workspace.from_config()
print('Ready to work with', ws.name)
# トレーニング済みモデルを保存する
model_file = 'diabetes_model.pkl'
joblib.dump(value=diabetes_model, filename=model_file)
# モデルを登録する
print('Registering model...')
registered_model = Model.register(model_path=model_file,
model_name='diabetes_classifier',
workspace=ws)
model_id= registered_model.id
print('Model registered.', model_id)
# -
# これで、FairLearn パッケージを使用して 1 つ以上のモデルの二項分類グループ メトリック セットを作成し、Azure Machine Learning 実験を使用してメトリックをアップロードできるようになりました。
#
# > **注**: これには時間がかかる場合があり、警告メッセージが表示される場合もあります(無視する)。実験が完了すると、ダッシュボード データがダウンロードされて表示され、正常にアップロードされたことを確認できます。
# +
from fairlearn.metrics._group_metric_set import _create_group_metric_set
from azureml.contrib.fairness import upload_dashboard_dictionary, download_dashboard_by_upload_id
# 公平性を評価するモデルの辞書を作成する
sf = { 'Age': S_test.Age}
ys_pred = { model_id:diabetes_model.predict(X_test) }
dash_dict = _create_group_metric_set(y_true=y_test,
predictions=ys_pred,
sensitive_features=sf,
prediction_type='binary_classification')
exp = Experiment(ws, 'mslearn-diabetes-fairness')
print(exp)
run = exp.start_logging()
# Azure Machine Learning にダッシュボードをアップロードする
try:
dashboard_title = "Fairness insights of Diabetes Classifier"
upload_id = upload_dashboard_dictionary(run,
dash_dict,
dashboard_name=dashboard_title)
print("\nUploaded to id: {0}\n".format(upload_id))
# To test the dashboard, you can download it
downloaded_dict = download_dashboard_by_upload_id(run, upload_id)
print(downloaded_dict)
finally:
run.complete()
# -
# 上記のコードは、正常に完了したことを確認するためだけに、実験で生成されたメトリックをダウンロードしました。メトリックを実験にアップロードすることの本当の利点は、Azure Machine Learning Studio で FairLearn ダッシュボードを表示できるようになったことです。
#
# 下のセルを実行して実験の詳細を確認し、ウィジェットの **View Run details** (実行の詳細を表示する) リンクをクリックして Azure Machine Learning Studio での実行を確認します。次に、実験実行の **公平性** タブを表示してアップロードしたメトリックに割り当てられた公平性 ID のダッシュボードを表示します。ダッシュボードは、このノートブックで以前表示したウィジェットと同じように動作します。
# +
from azureml.widgets import RunDetails
RunDetails(run).show()
# -
# Azure Machine Learning Studio の **モデル** ページでモデルを選択し、**公平性** タブを見ることで、公平性ダッシュボードを見つけることもできます。これにより、組織はトレーニングおよび登録するモデルの公平性分析のログを保持できます。
# ## モデルの不公正性を軽減する
#
# これでモデルの公平性を分析できたので、FairLearn パッケージでサポートされている *軽減* 技術のいずれかを使用して、予測パフォーマンスと公平性のバランスを取るモデルを見つけることができます。
#
# この演習では、**GridSearch** 機能を使用します。この機能は、データセット内のセンシティブ特徴 (この場合、年齢層) の予測パフォーマンスの格差を最小限に抑えるために、複数のモデルをトレーニングします。**EqualizedOdds** パリティ制約を適用してモデルを最適化します。これは、センシティブ特徴グループごとに、モデルが同じような真陽性率と偽陽性率を示すようにするものです。
#
# > *実行に時間がかかる場合があります*
# +
from fairlearn.reductions import GridSearch, EqualizedOdds
import joblib
import os
print('Finding mitigated models...')
# 複数のモデルをトレーニングする
sweep = GridSearch(DecisionTreeClassifier(),
constraints=EqualizedOdds(),
grid_size=20)
sweep.fit(X_train, y_train, sensitive_features=S_train.Age)
models = sweep.predictors_
# モデルを保存し、そこから予測を取得する(加えて、比較用に元の純粋なもの)
model_dir = 'mitigated_models'
os.makedirs(model_dir, exist_ok=True)
model_name = 'diabetes_unmitigated'
print(model_name)
joblib.dump(value=diabetes_model, filename=os.path.join(model_dir, '{0}.pkl'.format(model_name)))
predictions = {model_name: diabetes_model.predict(X_test)}
i = 0
for model in models:
i += 1
model_name = 'diabetes_mitigated_{0}'.format(i)
print(model_name)
joblib.dump(value=model, filename=os.path.join(model_dir, '{0}.pkl'.format(model_name)))
predictions[model_name] = model.predict(X_test)
# -
# これで FairLearn ダッシュボードを使用して、軽減されたモデルを比較できるようになりました。
#
# 次のセルを実行し、ウィザードを使用して **再現率**.別の **年齢** を視覚化します。
FairnessDashboard(sensitive_features=S_test,
y_true=y_test,
y_pred=predictions)
# モデルは散布図に示されています。モデルを比較するには、予測の格差 (つまり選択率) または選択したパフォーマンス メトリックの格差 (この場合、*再現率*) を測定します。このシナリオでは、選択率の格差が予想されます (糖尿病では年齢*が*要因であることがわかっているので、年齢層が高いほど陽性症例が多くなります)。ここで注目したいのは、予測パフォーマンスの格差です。そこで、**再現率の不均衡** を測定するオプションを選択します。
#
# グラフは、X 軸に全体的な *再現率* メトリック、Y 軸に再現率の格差を持つモデルのクラスターを示しています。したがって、理想的なモデル (再現率が高く、格差が小さい) は、プロットの右下にあります。特定のニーズに適した予測パフォーマンスと公平性のバランスを選択し、適切なモデルを選択してその詳細を確認できます。
#
# 強調すべき重要な点は、モデルに公平性の軽減を適用することは、全体的な予測パフォーマンスとセンシティブ特徴グループ間の格差との間のトレードオフであるということです。一般的には、モデルが母集団のすべてのセグメントに対して公平に予測することを保証するために、全体的な予測パフォーマンスを犠牲にする必要があります。
#
# > **注**: *適合率* メトリックを表示すると、予測されるサンプルがないために適合率が 0.0 に設定されているという警告が表示される場合があります。これは無視してかまいません。
#
# ## Azure Machine Learning に軽減ダッシュボード メトリックをアップロードする
#
# 前述のように、軽減の実験を追跡することもできます。これを行うには、次を実行します。
#
# 1. GridSearch プロセスで検出されたモデルを登録します。
# 2. モデルのパフォーマンスおよび格差メトリックを計算します。
# 3. Azure Machine Learning の実験にメトリックをアップロードします。
# +
# モデルを登録する
registered_model_predictions = dict()
for model_name, prediction_data in predictions.items():
model_file = os.path.join(model_dir, model_name + ".pkl")
registered_model = Model.register(model_path=model_file,
model_name=model_name,
workspace=ws)
registered_model_predictions[registered_model.id] = prediction_data
# すべてのモデルの年齢特徴に基づいて、二項分類用のグループ メトリック セットを作成する
sf = { 'Age': S_test.Age}
dash_dict = _create_group_metric_set(y_true=y_test,
predictions=registered_model_predictions,
sensitive_features=sf,
prediction_type='binary_classification')
exp = Experiment(ws, "mslearn-diabetes-fairness")
print(exp)
run = exp.start_logging()
RunDetails(run).show()
# Azure Machine Learning にダッシュボードをアップロードする
try:
dashboard_title = "Fairness Comparison of Diabetes Models"
upload_id = upload_dashboard_dictionary(run,
dash_dict,
dashboard_name=dashboard_title)
print("\nUploaded to id: {0}\n".format(upload_id))
finally:
run.complete()
# -
# > **注**: 予測されるサンプルがないために適合率が 0.0 に設定されているという警告が表示される場合があります。これは無視してかまいません。
#
#
# 実験が終了したら、ウィジェットの **View Run details** (実行の詳細を表示する) リンクをクリックして Azure Machine Learning Studio(ウィジェットを表示するには、最初の出力を超えてスクロールする必要がある場合があります)での実行を確認し、**公平性** タブの FairLearn ダッシュボードを表示します。
| 15 - Detect Unfairness.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %matplotlib inline
from pylab import *
import cv2
rcParams['figure.figsize'] = 10, 10
from dataset import load_image
import torch
from utils import variable
from generate_masks import get_model
from torchvision.transforms import ToTensor, Normalize, Compose
img_transform = Compose([
ToTensor(),
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
def mask_overlay(image, mask, color=(0, 255, 0)):
"""
Helper function to visualize mask on the top of the car
"""
mask = np.dstack((mask, mask, mask)) * np.array(color)
mask = mask.astype(np.uint8)
weighted_sum = cv2.addWeighted(mask, 0.5, image, 0.5, 0.)
img = image.copy()
ind = mask[:, :, 1] > 0
img[ind] = weighted_sum[ind]
return img
model_path = 'data/models/UNet11/model_0.pt'
model = get_model(model_path, model_type='UNet11')
img_file_name = 'data/train/angyodysplasia/images/1099.jpg'
gt_file_name = 'data/train/angyodysplasia/masks/1099_a.jpg'
img = load_image(img_file_name)
gt = cv2.imread(gt_file_name, 0) > 0
# +
title("Left: image, right: image + ground truth mask", fontsize=20)
imshow(np.hstack([img, mask_overlay(img, gt)]))
# -
img_transform = Compose([
ToTensor(),
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
input_img = torch.unsqueeze(variable(img_transform(img), volatile=True), dim=0)
mask = model(input_img)
mask_array = mask.data[0].cpu().numpy()[0]
title('Predicted mask', fontsize=20)
imshow(mask_array > 0)
title('Prediction', fontsize=20)
imshow(mask_overlay(img, (mask_array > 0).astype(np.uint8)))
| Demo.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Saving and loading the data in .npz format
# The .npz file format is a zipped archive of files named after the variables they contain. The archive is not compressed and each file in the archive contains one variable in .npy format
# use __np.savez(filename, args)__ to save the data
# +
import numpy as np
import matplotlib.pylab as plt
# %matplotlib inline
data = np.loadtxt(fname='../data/inflammation-01.csv', delimiter=',')
# -
filename = 'datainfo.npz'
np.savez(filename, data=data, mean_daily=np.mean(data,0))
# use __np.load()__ to load it :
patient = np.load(filename)
# to check the keys in the loaded data
list(patient)
patient['mean_daily']
# We can plot this data using matplotlib.pyplot.plt:
plt.plot(patient['mean_daily'])
# [Previous: K-means clustering](k_means.ipynb)<br>[Next: Fancy indexing](fancy_indexing.ipynb)
| Day_1_Scientific_Python/numpys/savez.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# + [markdown] tags=[]
# # Assess jawiki and time-dependency
# (uncollapse for detailed code)
# + [markdown] tags=[]
# ## Import and Clean
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Import libraries and data
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### libraries
# +
import pandas as pd, numpy as np, matplotlib.pyplot as plt, statsmodels.api as sm
import os, datetime
from datetime import datetime as dt
from zoneinfo import ZoneInfo
from dateutil.tz import gettz
from dateutil.parser import isoparse
from sklearn.preprocessing import StandardScaler
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### get schema details
# + tags=[]
schema_df = pd.read_csv('../data/external/mediawiki_history_schema.tsv', delimiter='\t')
mw_hist_colnames = list(schema_df.col_name)[:-1]
# -
schema_df
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### pick columns to import
# -
usecols = ['event_entity', 'event_timestamp', 'event_user_is_bot_by_historical', 'revision_id']
# **Selection of columns:**
# - Only picked the necessary columns to:
# - Drop bot edits (event_user_is_bot_by_historical)
# - Select only "revision-type" edits (event_entity)
# - Keep a meaningful index (revision_id)
# - Timestamp (event_timestamp)
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### import data
# -
print(dt.now())
df = pd.read_csv('../data/raw/jawiki/dumps_unzipped/2021-12.jawiki.2021.tsv',
delimiter='\t', names=mw_hist_colnames, header=None, usecols=usecols
) # ,nrows=1000000
print(dt.now())
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Clean
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ##### remove bot records
# -
df = df[df.event_user_is_bot_by_historical.isna()]
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ##### keep only 'revision' edits
# -
df = df[df.event_entity.isin(['revision'])]
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ##### set index as revision_id
# -
df = df.set_index('revision_id')
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ##### convert to Japanese timezone
# + tags=[]
df['t_ja'] = df.event_timestamp.map(isoparse).dt.tz_localize('UTC').dt.tz_convert('Asia/Tokyo')
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ## Count and Plot by day, day of week
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Count edits by day, day of week
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### turn weekdays into dummy variables, add to df
# -
weekdays_dict = {0:'Mon',1:'Tue',2:'Wed',3:'Thu',4:'Fri',5:'Sat',6:'Sun'}
weekdays_str = df.t_ja.dt.weekday.map(weekdays_dict)
df = df.join(pd.get_dummies(weekdays_str))
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### count by day
# -
df['ymd'] = df.t_ja.dt.date
day_data = df.groupby('ymd').sum().sort_index()
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### count by day of week
# -
day_data['each_day'] = (
day_data[['Mon','Tue','Wed','Thu','Fri','Sat','Sun']]
.sum(axis=1)
)
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### remove partial-days at the beginning and end of dataset
# -
day_data = day_data.iloc[1:-1]
# +
# day_data.to_csv('../data/interim/ja_day_data.csv')
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Plot edits by day, day of week
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### plot edits by day
# -
day_data['each_day'].plot()
plt.xticks(rotation=90)
plt.title('Daily jawiki non-bot revision-type edit counts over 2021.')
plt.xlabel('\n\n'
'No obvious long-term trend in 2021.\n'
'Seasonal trends are very modest.')
plt.ylabel('Daily edit count')
plt.ylim(0,)
plt.show()
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### plot edits by weekday
# -
fig = plt.figure(figsize=(9,6))
ax = plt.gca()
(day_data
[['Mon','Tue','Wed','Thu','Fri','Sat','Sun']]
.replace(0, np.nan)
.boxplot(ax=ax)
)
ax.set_title('Daily jawiki non-bot edit counts by day of week')
ax.set_xlabel('\n\n'
'Edit count is quite stable.\n'
'Day-of-week accounts for much day-to-day variation.')
ax.set_ylabel('Daily edit count')
ax.set_ylim(0,)
plt.show()
weekday_edit_counts_boxplot_fig = fig
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Count Edits by Hour, Weekday
# -
df['hour'] = df.t_ja.dt.hour
total_days = (df.ymd.max() - df.ymd.min()).days
hour_data = (
df.groupby('hour')
.sum()
.sort_index()
[['Mon','Tue','Wed','Thu','Fri','Sat','Sun']]
.divide(total_days/7)
)
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Plot edits by Hour, Weekday
# -
hour_data.plot()
plt.title('Hourly jawiki non-bot revision-type edits, by weekday')
plt.xlabel('Hour of day\n'
'\n'
'Consistently low traffic from 2am-6am suggests\n'
'that jawiki editors are mostly located in Japan.')
plt.ylabel('Average hourly edit count')
plt.ylim(0,)
plt.show()
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ## Count and Plot with holidays
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Import holidays and merge
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### import holidays data
# -
# all_holidays includes observed-holidays, weekend holidays, and weekday holidays
all_holidays = pd.read_csv(
'../data/external/Japan_holidays.tsv',
delimiter='\t', usecols = ['Date', 'Name', 'Type'])
all_holidays['Date'] = (
all_holidays.Date
.apply(lambda x: pd.to_datetime(x, format='%d %b'))
.apply(lambda x: x.replace(year = 2021))
)
all_holidays['Weekday'] = all_holidays.Date.dt.weekday.map(weekdays_dict)
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### prep holidays
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ##### Select only weekday-holidays
# -
holidays = all_holidays[all_holidays.Type == 'National holiday']
holidays = holidays[['Date', 'Name', 'Type']]
holidays = holidays.rename(columns={'Name':'holiday_name'})
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ##### Remove time portion of datatype
# -
holidays['index'] = holidays.Date.dt.date
holidays = holidays.set_index('index', drop=True)
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### prep main df to integrate with holidays
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ##### Add column with time portion of datetime removed
# -
df['Date'] = df.t_ja.dt.date
# + [markdown] tags=[]
# ##### Merge holidays into full time series
# -
df = df.merge(
holidays.loc[:, 'holiday_name'],
how='left', left_on='Date', right_index=True)
# Get holiday dummy variable
df['holiday'] = df.holiday_name.notnull()
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### check merged dates / holidays dataframe
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ##### Confirm no nulls in dataset (other than the columns that use nulls on purpose)
# -
df[df.columns.difference(['holiday_name', 'event_user_is_bot_by_historical'])].isnull().any().any()
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ##### Count the holidays in the dataset
# -
num_holidays = df[['Date', 'holiday']].loc[df.holiday == True].drop_duplicates().count()[0]
num_holidays
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### Get hourly edit-counts averaged over holidays only
# -
hour_data_holidays = (
df.loc[df.holiday]
.groupby('hour')
.sum()
.loc[:,'holiday']
.sort_index()
.divide(num_holidays)
.rename('National Holidays on Weekdays')
)
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Plot edits on holidays
# -
fig = plt.figure(figsize=(9,6))
ax = fig.gca()
hour_data.plot(ax=ax, alpha=.4)
hour_data_holidays.plot(ax=ax, linewidth=3) # new untested edit
ax.set_title('Hourly jawiki non-bot revision-type edits:\n'
'highlighting "National Holidays on Weekdays"')
ax.set_xlabel('Hour of day\n'
'\n'
'On holidays daytimes, editors behave like on Saturdays.')
ax.set_label('Average hourly edit count')
ax.set_ylim(0,)
ax.legend()
plt.show()
hourly_with_holidays_fig = fig
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ## Regress to check correlation with lagged edits
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Prep data for regression
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### add holiday onehots into day_data
# -
days_holidays = (
day_data
.join(holidays.holiday_name)
.assign(holiday=lambda x: x.holiday_name.notnull().astype(int))
.drop(columns='holiday_name')
)
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### Turn weekday counts into onehots
# -
days_holidays[['Mon','Tue','Wed','Thu','Fri','Sat','Sun']] = (
days_holidays[['Mon','Tue','Wed','Thu','Fri','Sat','Sun']]
.astype(bool).astype(int)
)
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### get a column for 1-day-lagged revision count
# -
days_holidays.rename(columns={'each_day':'revisions'}, inplace=True)
days_holidays['lag_revisions'] = days_holidays.revisions.shift(-1)
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Prep regression variables
# -
ss = StandardScaler()
# +
# Partition days_holidays into X and y for regression
y = days_holidays['revisions']
X = days_holidays.loc[:, days_holidays.columns.difference(['revisions'])]
X_columns = X.columns
# Drop the last observation (observation incomplete because of lag)
X = X.iloc[:-1]
y = y.iloc[:-1]
# +
# Normalize lagged revisions
X['lag_revisions'] = ss.fit_transform(X.lag_revisions.to_frame())
# Append a constant term
X = sm.add_constant(X)
# Drop Monday (because collinear with constant)
X = X.drop('Mon', axis=1)
# Reorder columns
X = X[['lag_revisions','holiday','Tue','Wed','Thu','Fri','Sat','Sun','const']]
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ### Regress in statsmodels
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### regress
# -
mdl = sm.OLS(y, X)
rslt = mdl.fit()
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### concise summary of regression results
# -
y.mean()
pd.DataFrame({'var':X.columns,'coeff':rslt.params.round(1), 'stderr':rslt.bse.round(1)})
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# #### full summary of regression results
# -
rslt.summary()
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# ## Discussion
# -
# - Mean daily revisions are 15,000 human edits per day.
# - Edit counts are highly cyclic on weekly and hourly scales, with R² of .68 from the regression.
# - Holidays and weekends have a significant effect, Saturdays < holidays ≤ Sundays.
# - Lagged revisions are highly significant.
# - But, magnitude of the correlation with lag_revisions (controlling for day of week and holiday) is low at 500 edits/day, only 3% of the average edits per day.
# + [markdown] jp-MarkdownHeadingCollapsed=true tags=[]
# # TL;DR
# + [markdown] tags=[]
# ## Hours, Weekdays, and Holidays
# -
# - [Jawiki](https://ja.wikipedia.org/wiki/%E3%83%A1%E3%82%A4%E3%83%B3%E3%83%9A%E3%83%BC%E3%82%B8) mean daily revisions are 15,000 human edits per day.
# - Edit counts are highly cyclic on weekly and hourly scales, with R² of .68 from the regression.
# - Holidays and weekends have a significant effect, Saturdays < holidays ≤ Sundays.
# - Lagged revisions are highly significant (p<.001).
# - But, magnitude of the correlation with lag_revisions (controlling for day of week and holiday) is 500 edits/day, only 3% of the average edits per day.
# - Some of this effect of next-day correlation (AR-1) may be due to annual seasonality that is not observed in this preliminary one-year dataset.
hourly_with_holidays_fig
weekday_edit_counts_boxplot_fig
| notebooks/1.03-sfb-assess-jawiki-and-time-dependency.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
# ---
# # AWS Lambda event['body'] Inspection
# I was getting a DataFrame constructor error. I updated the AWS Lambda function to pickle the `event` object and upload it to S3. This workbook inspects the object and helped identify the steps required to convert the event['body'] object into a pandas.DataFrame.
#
# ## Resolution
# The default `dataframe.to_json` method that was initially used is difficult to parse. I added the `orient='split'` argument, which yielded a more user-friendly format. One strange feature is that `json.loads` needs to be called twice in order to convert the string object into a json object.
# +
import boto3
import pickle
import os
session = boto3.Session(aws_access_key_id=os.getenv('AWS_ADMIN_ACCESS'),
aws_secret_access_key=os.getenv('AWS_ADMIN_SECRET'))
s3 = session.client('s3')
bucket = 'gwilson253awsprojects'
key = 'neptune/event_body.pkl'
obj = s3.get_object(Bucket=bucket, Key=key)
event_body = pickle.loads(obj['Body'].read())
event_body
# -
from json import loads
j = loads(loads(event_body))
j['columns']
from pandas import DataFrame
DataFrame(data=j['data'], columns=j['columns'], index=j['index'])
| jupyter_lab/event_body_dev.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 imageai.Detection import ObjectDetection
import os
import cv2
execution_path = os.getcwd()
cap=cv2.VideoCapture(0)
ret,photo=cap.read()
cv2.imwrite("image.jpg",photo)
cv2.imshow("clcik",photo)
cv2.waitKey()
cv2.destroyAllWindows()
cap.release()
detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))
for eachObject in detections:
print(eachObject["name"] , " : " , eachObject["percentage_probability"] )
# -
execution_path
# +
import numpy as np
import cv2
from matplotlib import pyplot as plt
cap=cv2.VideoCapture(0)
ret,img=cap.read()
#cv2.imwrite("image.jpg",photo)
cv2.imshow("clcik",img)
cv2.waitKey()
cv2.destroyAllWindows()
cap.release()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# detect corners with the goodFeaturesToTrack function.
corners = cv2.goodFeaturesToTrack(gray, 27, 0.01, 10)
corners = np.int0(corners)
# we iterate through each corner,
# making a circle at each point that we think is a corner.
for i in corners:
x, y = i.ravel()
cv2.circle(img, (x, y), 3, 255, -1)
plt.imshow(img), plt.show()
# -
| Object Detect.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 warnings
warnings.filterwarnings('ignore')
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader, Dataset
import torchvision
from torchvision import transforms
from torchsummary import summary
from albumentations import (
ToFloat,
CLAHE,
RandomRotate90,
Transpose,
ShiftScaleRotate,
Blur,
OpticalDistortion,
GridDistortion,
HueSaturationValue,
IAAAdditiveGaussianNoise,
GaussNoise,
MotionBlur,
MedianBlur,
IAAPiecewiseAffine,
IAASharpen,
IAAEmboss,
RandomContrast,
RandomBrightness,
Flip,
OneOf,
Compose
)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pylab import rcParams
import numbers
from sklearn.model_selection import train_test_split
from PIL import Image
import math
from tqdm import tqdm
# +
model_file_root = '../../models/Kannada-MNIST/'
data_root = '../../data/raw/Kannada-MNIST/'
model_file_ext = '.pt'
RANDOM_STATE = 42
torch.manual_seed(RANDOM_STATE)
torch.set_num_threads(4)
np.random.seed(RANDOM_STATE)
rcParams['figure.figsize'] = 16, 16
# -
# ## 1. transform & dataload
class RandomRotation:
def __init__(self, degrees, resample=False, expand=False, center=None):
if isinstance(degrees, numbers.Number):
if degrees < 0:
raise ValueError("If degrees is a single number, it must be positive.")
self.degrees = (-degrees, degrees)
else:
if len(degrees) != 2:
raise ValueError("If degrees is a sequence, it must be of len 2.")
self.degrees = degrees
self.resample = resample
self.expand = expand
self.center = center
@staticmethod
def get_params(degrees):
angle = np.random.uniform(degrees[0], degrees[1])
return angle
def __call__(self, img):
def rotate(img, angle, resample=False, expand=False, center=None):
return img.rotate(angle, resample, expand, center)
angle = self.get_params(self.degrees)
return rotate(img, angle, self.resample, self.expand, self.center)
class RandomShift(object):
def __init__(self, shift):
self.shift = shift
@staticmethod
def get_params(shift):
hshift, vshift = np.random.uniform(-shift, shift, size=2)
return hshift, vshift
def __call__(self, img):
hshift, vshift = self.get_params(self.shift)
return img.transform(img.size, Image.AFFINE, (1,0,hshift,0,1,vshift), resample=Image.BICUBIC, fill=1)
# +
class Kannada_MNIST_data(Dataset):
def __init__(self, df, aug=False):
self.aug = aug
n_pixels = 28 * 28
# if "id" in df.columns:
# print("drop")
# df.drop(["id"], axis=1)
if "label" not in df.columns:
# test data
self.X = df.iloc[:,1:].values.reshape((-1,28,28)).astype(np.uint8)[:,:,:,None]
self.y = None
else:
# training data
self.X = df.iloc[:,1:].values.reshape((-1,28,28)).astype(np.uint8)[:,:,:,None]
self.y = torch.from_numpy(df.iloc[:,0].values)
if self.y is not None and self.aug:
self.transform = transforms.Compose([
transforms.ToPILImage(),
RandomRotation(degrees=10),
RandomShift(3),
transforms.ToTensor(),
transforms.Normalize(mean=(0.5,), std=(0.5,))
])
else:
self.transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=(0.5,), std=(0.5,))
])
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
if self.y is not None:
return self.transform(self.X[idx]), self.y[idx]
else:
return self.transform(self.X[idx])
# +
# %%time
full_train_df = pd.read_csv(data_root+'train.csv')
test_df = pd.read_csv(data_root+'test.csv')
train_df, valid_df = train_test_split(full_train_df, test_size=0.2, random_state=RANDOM_STATE, shuffle=True)
# +
batch_size = 64
train_dataset = Kannada_MNIST_data(train_df, aug=True)
valid_dataset = Kannada_MNIST_data(valid_df)
test_dataset = Kannada_MNIST_data(test_df)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=2)
valid_loader = torch.utils.data.DataLoader(dataset=valid_dataset, batch_size=batch_size, shuffle=True, num_workers=2)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False, num_workers=2)
# -
def show_batch(loader, lb=True):
batcher = iter(loader)
if lb:
images, labels = batcher.next()
else:
images = batcher.next()
grid = torchvision.utils.make_grid(images)
plt.imshow(grid.numpy().transpose((1, 2, 0)))
plt.axis('off')
if lb:
plt.title(labels.numpy());
plt.show()
show_batch(train_loader)
show_batch(valid_loader)
show_batch(test_loader, lb=False)
train_loader, valid_loader, test_loader
def train(model, train_loader):
batch_loss = 0.0
batch_corrects = 0.0
model.train()
for inputs, labels in train_loader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
preds = torch.max(outputs, 1)[1]
batch_loss += loss.item()
batch_corrects += torch.sum(preds == labels.data)
return batch_loss/len(train_loader), batch_corrects.float()/len(train_dataset)
def evaluate(model, valid_loader):
loss = 0.0
corrects = 0.0
model.eval()
with torch.no_grad():
for inputs, labels in valid_loader:
inputs, labels = Variable(inputs), Variable(labels)
outputs = model(inputs)
loss += F.cross_entropy(outputs, labels, reduction='mean').item()
pred = outputs.data.max(1, keepdim=True)[1]
corrects += pred.eq(labels.data.view_as(pred)).cpu().sum()
return loss/len(valid_loader), corrects.float()/len(valid_dataset)
# ## 1. Test pipeline
class SimpleConvNet(nn.Module):
def __init__(self):
super(SimpleConvNet, self).__init__()
self.conv_layers = nn.Sequential(
nn.Conv2d(1, 20, 5, 1),
nn.ReLU(),
nn.AvgPool2d(2, stride=2),
nn.Conv2d(20, 50, 5, 1),
nn.BatchNorm2d(50),
nn.ReLU(),
nn.AvgPool2d(2, stride=2)
)
self.full_conn_layers = nn.Sequential(
nn.Linear(4*4*50, 500),
nn.ReLU(),
nn.Linear(500, 10)
)
def forward(self, x):
x = self.conv_layers(x)
x = x.view(x.size(0), -1)
x = self.full_conn_layers(x)
return x
model = SimpleConvNet()
epochs = 20
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr = 0.01)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer,
factor=0.3,
mode="max",
verbose=True,
patience=1,
threshold=1e-3
)
# +
# %%time
epoch_loss_history = []
epoch_corrects_history = []
val_loss_history = []
val_corrects_history = []
for epoch in range(epochs):
epoch_loss, epoch_corrects = train(model, train_loader)
val_loss, val_corrects = evaluate(model, valid_loader)
epoch_loss_history.append(epoch_loss)
epoch_corrects_history.append(epoch_corrects)
val_loss_history.append(val_loss)
val_corrects_history.append(val_corrects)
print('epoch:', (epoch+1))
print('training loss: {:.4f}, training acc {:.4f} '.format(epoch_loss, epoch_corrects.item()))
print('validation loss: {:.4f}, validation acc {:.4f} '.format(val_loss, val_corrects.item()))
scheduler.step(val_corrects)
# -
plt.plot(epoch_loss_history, label='training loss')
plt.plot(val_loss_history, label='validation loss')
plt.legend()
plt.plot(epoch_corrects_history, label='training accuracy')
plt.plot(val_corrects_history, label='validation accuracy')
plt.legend()
path = f"{model_file_root}SimpleNetNet{model_file_ext}"
torch.save(model.state_dict(), path)
# ## 2. CNN
class Conv2Class2Net(nn.Module):
def __init__(self):
super(Conv2Class2Net, self).__init__()
self.cnn_layers = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Dropout(0.2),
nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Dropout(0.2)
)
self.fc_layers = nn.Sequential(
nn.Linear(64 * 7 * 7, 512),
nn.BatchNorm1d(512),
nn.LeakyReLU(inplace=True),
nn.Dropout(0.3),
nn.Linear(512, 256),
nn.BatchNorm1d(256),
nn.LeakyReLU(inplace=True),
nn.Dropout(0.3),
nn.Linear(256, 10)
)
for m in self.cnn_layers.children():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
for m in self.fc_layers.children():
if isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight)
elif isinstance(m, nn.BatchNorm1d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def forward(self, x):
out = self.cnn_layers(x)
out = out.view(out.size(0), -1)
out = self.fc_layers(out)
return out
model = Conv2Class2Net()
epochs = 20
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr = 0.01)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer,
factor=0.3,
mode="max",
verbose=True,
patience=1,
threshold=1e-3
)
# +
# %%time
epoch_loss_history = []
epoch_corrects_history = []
val_loss_history = []
val_corrects_history = []
for epoch in range(epochs):
epoch_loss, epoch_corrects = train(model, train_loader)
val_loss, val_corrects = evaluate(model, valid_loader)
epoch_loss_history.append(epoch_loss)
epoch_corrects_history.append(epoch_corrects)
val_loss_history.append(val_loss)
val_corrects_history.append(val_corrects)
print('epoch:', (epoch+1))
print('training loss: {:.4f}, training acc {:.4f} '.format(epoch_loss, epoch_corrects.item()))
print('validation loss: {:.4f}, validation acc {:.4f} '.format(val_loss, val_corrects.item()))
scheduler.step(val_corrects)
path = f"{model_file_root}Conv2Class2Net_{epoch+1}{model_file_ext}"
torch.save(model.state_dict(), path)
# -
plt.plot(epoch_loss_history, label='training loss')
plt.plot(val_loss_history, label='validation loss')
plt.legend()
plt.plot(epoch_corrects_history, label='training accuracy')
plt.plot(val_corrects_history, label='validation accuracy')
plt.legend()
# ## Predict
path = model_file_root+'SimpleNetNet'+model_file_ext
model = SimpleConvNet()
model.load_state_dict(torch.load(path))
model.eval()
def prediciton(model, data_loader):
model.eval()
test_pred = torch.LongTensor()
for i, data in enumerate(data_loader):
data = Variable(data, volatile=True)
output = model(data)
pred = output.data.max(1, keepdim=True)[1]
test_pred = torch.cat((test_pred, pred), dim=0)
return test_pred
# %%time
test_pred = prediciton(model, test_loader)
out_df = pd.DataFrame(np.c_[np.arange(1, len(test_dataset)+1)[:,None], test_pred.numpy()], columns=['ImageId', 'Label'])
out_df.head()
out_df.to_csv('submission.csv', index=False)
| notebooks/Kannada-MNIST/mnist_cnn.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda root]
# language: python
# name: conda-root-py
# ---
# # Traffic Sign Classification with Keras
#
# Keras exists to make coding deep neural networks simpler. To demonstrate just how easy it is, you’re going to use Keras to build a convolutional neural network in a few dozen lines of code.
#
# You’ll be connecting the concepts from the previous lessons to the methods that Keras provides.
# ## Dataset
#
# The network you'll build with Keras is similar to the example that you can find in Keras’s GitHub repository that builds out a [convolutional neural network for MNIST](https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py).
#
# However, instead of using the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset, you're going to use the [German Traffic Sign Recognition Benchmark](http://benchmark.ini.rub.de/?section=gtsrb&subsection=news) dataset that you've used previously.
#
# You can download pickle files with sanitized traffic sign data here.
# ## Overview
#
# Here are the steps you'll take to build the network:
#
# 1. First load the data.
# 2. Build a feedforward neural network to classify traffic signs.
# 3. Build a convolutional neural network to classify traffic signs.
#
# Keep an eye on the network’s accuracy over time. Once the accuracy reaches the 98% range, you can be confident that you’ve built and trained an effective model.
# ## Load the Data
#
# Start by importing the data from the pickle file.
# +
# TODO: Implement load the data here.
# Load pickled data
import pickle
import csv
import os
# TODO: fill this in based on where you saved the training and testing data
training_file = '../../traffic-signs/traffic-signs-data/train.p'
testing_file = '../../traffic-signs/traffic-signs-data/test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_test, y_test = test['features'], test['labels']
# Make dictionary of sign names from CSV file
with open('../../traffic-signs/signnames.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
next(reader, None) # skip the headers
sign_names = dict((int(n),label) for n, label in reader)
cls_numbers, cls_names = zip(*sign_names.items())
n_classes = len(set(y_train))
flat_img_size = 32*32*3
# STOP: Do not change the tests below. Your implementation should pass these tests.
assert(X_train.shape[0] == y_train.shape[0]), "The number of images is not equal to the number of labels."
assert(X_train.shape[1:] == (32,32,3)), "The dimensions of the images are not 32 x 32 x 3."
# -
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm_notebook
from zipfile import ZipFile
import time
from datetime import timedelta
import math
import tensorflow as tf
# ## Normalize the data
#
# Now that you've loaded the training data, normalize the input so that it has a mean of 0 and a range between -0.5 and 0.5.
# +
# TODO: Implement data normalization here.
def normalize_color(image_data):
"""
Normalize the image data with Min-Max scaling to a range of [0.1, 0.9]
:param image_data: The image data to be normalized
:return: Normalized image data
"""
a = -0.5
b = +0.5
Xmin = 0.0
Xmax = 255.0
norm_img = np.empty_like(image_data, dtype=np.float32)
norm_img = a + (image_data - Xmin)*(b-a)/(Xmax - Xmin)
return norm_img
X_train = normalize_color(X_train)
X_test = normalize_color(X_test)
# STOP: Do not change the tests below. Your implementation should pass these tests.
assert(round(np.mean(X_train)) == 0), "The mean of the input data is: %f" % np.mean(X_train)
assert(np.min(X_train) == -0.5 and np.max(X_train) == 0.5), "The range of the input data is: %.1f to %.1f" % (np.min(X_train), np.max(X_train))
# -
# ## Build a Two-Layer Feedfoward Network
#
# The code you've written so far is for data processing, not specific to Keras. Here you're going to build Keras-specific code.
#
# Build a two-layer feedforward neural network, with 128 neurons in the fully-connected hidden layer.
#
# To get started, review the Keras documentation about [models](https://keras.io/models/sequential/) and [layers](https://keras.io/layers/core/).
#
# The Keras example of a [Multi-Layer Perceptron](https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py) network is similar to what you need to do here. Use that as a guide, but keep in mind that there are a number of differences.
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.optimizers import Adam
from keras.utils import np_utils
# +
# TODO: Build a two-layer feedforward neural network with Keras here.
model = Sequential()
model.add(Dense(128, input_shape=(flat_img_size,), name='hidden1'))
model.add(Activation('relu'))
model.add(Dense(43, name='output'))
model.add(Activation('softmax'))
# STOP: Do not change the tests below. Your implementation should pass these tests.
assert(model.get_layer(name="hidden1").input_shape == (None, 32*32*3)), "The input shape is: %s" % model.get_layer(name="hidden1").input_shape
assert(model.get_layer(name="output").output_shape == (None, 43)), "The output shape is: %s" % model.get_layer(name="output").output_shape
# -
# ## Train the Network
# Compile and train the network for 2 epochs. [Use the `adam` optimizer, with `categorical_crossentropy` loss.](https://keras.io/models/sequential/)
#
# Hint 1: In order to use categorical cross entropy, you will need to [one-hot encode the labels](https://github.com/fchollet/keras/blob/master/keras/utils/np_utils.py).
#
# Hint 2: In order to pass the input images to the fully-connected hidden layer, you will need to [reshape the input](https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py).
#
# Hint 3: Keras's `.fit()` method returns a `History.history` object, which the tests below use. Save that to a variable named `history`.
# +
# One-Hot encode the labels
Y_train = np_utils.to_categorical(y_train, n_classes)
Y_test = np_utils.to_categorical(y_test, n_classes)
# Reshape input for MLP
X_train_mlp = X_train.reshape(-1, flat_img_size)
X_test_mlp = X_test.reshape(-1, flat_img_size)
# +
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(X_train_mlp, Y_train, batch_size=128, nb_epoch=10,
validation_data=(X_test_mlp, Y_test), verbose=1)
# STOP: Do not change the tests below. Your implementation should pass these tests.
assert(history.history['acc'][0] > 0.5), "The training accuracy was: %.3f" % history.history['acc'][0]
# -
# ## Validate the Network
# Split the training data into a training and validation set.
#
# Measure the [validation accuracy](https://keras.io/models/sequential/) of the network after two training epochs.
#
# Hint: [Use the `train_test_split()` method](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) from scikit-learn.
# +
# Get randomized datasets for training and validation
X_train, X_val, Y_train, Y_val = train_test_split(
X_train,
Y_train,
test_size=0.25,
random_state=0xdeadbeef)
X_val_mlp = X_val.reshape(-1, flat_img_size)
print('Training features and labels randomized and split.')
# STOP: Do not change the tests below. Your implementation should pass these tests.
assert(round(X_train.shape[0] / float(X_val.shape[0])) == 3), "The training set is %.3f times larger than the validation set." % (X_train.shape[0] / float(X_val.shape[0]))
assert(history.history['val_acc'][0] > 0.6), "The validation accuracy is: %.3f" % history.history['val_acc'][0]
# -
loss, acc = model.evaluate(X_val.reshape(-1, flat_img_size), Y_val, verbose=1)
print('\nValidation accuracy : {0:>6.2%}'.format(acc))
# **Validation Accuracy**: 95.92%
# ## Congratulations
# You've built a feedforward neural network in Keras!
#
# Don't stop here! Next, you'll add a convolutional layer to drive.py.
# ## Convolutions
# Build a new network, similar to your existing network. Before the hidden layer, add a 3x3 [convolutional layer](https://keras.io/layers/convolutional/#convolution2d) with 32 filters and valid padding.
#
# Then compile and train the network.
#
# Hint 1: The Keras example of a [convolutional neural network](https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py) for MNIST would be a good example to review.
#
# Hint 2: Now that the first layer of the network is a convolutional layer, you no longer need to reshape the input images before passing them to the network. You might need to reload your training data to recover the original shape.
#
# Hint 3: Add a [`Flatten()` layer](https://keras.io/layers/core/#flatten) between the convolutional layer and the fully-connected hidden layer.
from keras.layers import Convolution2D, MaxPooling2D, Dropout, Flatten
# +
# TODO: Re-construct the network and add a convolutional layer before the first fully-connected layer.
model = Sequential()
model.add(Convolution2D(16, 5, 5, border_mode='same', input_shape=(32, 32, 3)))
model.add(Activation('relu'))
model.add(Flatten())
model.add(Dense(128, input_shape=(flat_img_size,), name='hidden1'))
model.add(Activation('relu'))
model.add(Dense(43, name='output'))
model.add(Activation('softmax'))
# TODO: Compile and train the model.
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, Y_train, batch_size=128, nb_epoch=10,
validation_data=(X_val, Y_val), verbose=1)
# STOP: Do not change the tests below. Your implementation should pass these tests.
assert(history.history['val_acc'][0] > 0.9), "The validation accuracy is: %.3f" % history.history['val_acc'][0]
# -
# **Validation Accuracy**: 96.98%
# ## Pooling
# Re-construct your network and add a 2x2 [pooling layer](https://keras.io/layers/pooling/#maxpooling2d) immediately following your convolutional layer.
#
# Then compile and train the network.
# +
# TODO: Re-construct the network and add a pooling layer after the convolutional layer.
model = Sequential()
model.add(Convolution2D(16, 5, 5, border_mode='same', input_shape=(32, 32, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(128, input_shape=(flat_img_size,), name='hidden1'))
model.add(Activation('relu'))
model.add(Dense(43, name='output'))
model.add(Activation('softmax'))
# TODO: Compile and train the model.
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, Y_train, batch_size=128, nb_epoch=10,
validation_data=(X_val, Y_val), verbose=1)
# STOP: Do not change the tests below. Your implementation should pass these tests.
## Fixed bug
assert(history.history['val_acc'][-1] > 0.9), "The validation accuracy is: %.3f" % history.history['val_acc'][0]
# -
# **Validation Accuracy**: 97.36%
# ## Dropout
# Re-construct your network and add [dropout](https://keras.io/layers/core/#dropout) after the pooling layer. Set the dropout rate to 50%.
# +
# TODO: Re-construct the network and add dropout after the pooling layer.
model = Sequential()
model.add(Convolution2D(16, 5, 5, border_mode='same', input_shape=(32, 32, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(128, input_shape=(flat_img_size,), name='hidden1'))
model.add(Activation('relu'))
model.add(Dense(43, name='output'))
model.add(Activation('softmax'))
# TODO: Compile and train the model.
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, Y_train, batch_size=128, nb_epoch=10,
validation_data=(X_val, Y_val), verbose=1)
# STOP: Do not change the tests below. Your implementation should pass these tests.
assert(history.history['val_acc'][-1] > 0.9), "The validation accuracy is: %.3f" % history.history['val_acc'][0]
# -
# **Validation Accuracy**: 97.75%
# ## Optimization
# Congratulations! You've built a neural network with convolutions, pooling, dropout, and fully-connected layers, all in just a few lines of code.
#
# Have fun with the model and see how well you can do! Add more layers, or regularization, or different padding, or batches, or more training epochs.
#
# What is the best validation accuracy you can achieve?
# +
pool_size = (2,2)
model = Sequential()
model.add(Convolution2D(16, 5, 5, border_mode='same', input_shape=(32, 32, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.5))
model.add(Convolution2D(128, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(256, input_shape=(flat_img_size,), name='hidden1'))
model.add(Activation('relu'))
model.add(Dense(43, name='output'))
model.add(Activation('softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# -
history = model.fit(X_train, Y_train, batch_size=128, nb_epoch=50,
validation_data=(X_val, Y_val), verbose=1)
# **Best Validation Accuracy:** 99.65%
# ## Testing
# Once you've picked out your best model, it's time to test it.
#
# Load up the test data and use the [`evaluate()` method](https://keras.io/models/model/#evaluate) to see how well it does.
#
# Hint 1: After you load your test data, don't forget to normalize the input and one-hot encode the output, so it matches the training data.
#
# Hint 2: The `evaluate()` method should return an array of numbers. Use the `metrics_names()` method to get the labels.
# +
# with open('./test.p', mode='rb') as f:
# test = pickle.load(f)
# X_test = test['features']
# y_test = test['labels']
# X_test = X_test.astype('float32')
# X_test /= 255
# X_test -= 0.5
# Y_test = np_utils.to_categorical(y_test, 43)
model.evaluate(X_test, Y_test)
# +
model.save('test-acc-9716-epoch50.h5')
from keras.models import load_model
model2 = load_model('test-acc-9716-epoch50.h5')
# model2.evaluate(X_test, Y_test)
model2.summary()
# -
# **Test Accuracy:** 97.15%
# ## Summary
# Keras is a great tool to use if you want to quickly build a neural network and evaluate performance.
| labs/keras/traffic-sign-classification-with-keras.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 glob
video_files=glob.glob("input_video/*.mp4")
video_files
# +
import os
def convert_and_split(filename,extension):
command=f"ffmpeg -i input_video/{filename}.{extension} -ac 2 -f wav wav/{filename}.wav -y"
print(command)
result=os.system(command)
print(result)
filenames=[]
for i in video_files:
print(i)
filepath= i
filename=filepath.split("/")[1].split(".")[0]
extension=filepath.split("/")[1].split(".")[1]
filenames.append(f"{filename}.{extension}")
print(filename,extension)
convert_and_split(filename,extension)
# +
import speech_recognition as sr
def speech_to_text(f):
# Initialize recognizer class (for recognizing the speech)
r = sr.Recognizer()
# Reading Audio file as source
# listening the audio file and store in audio_text variable
with sr.AudioFile(f) as source:
audio_text = r.listen(source)
# recoginize_() method will throw a request error if the API is unreachable, hence using exception handling
try:
# using google speech recognition
text = r.recognize_google(audio_text)
print('Converting audio transcripts into text ...')
# print(text)
return text
except:
print('Sorry.. run again...')
return ""
# -
audio_files=glob.glob("wav/*.wav")
audio_files
transcribed_audio=[]
for f in audio_files:
print(f)
text=speech_to_text(f)
transcribed_audio.append(text)
print(transcribed_audio)
from collections import Counter
frequency=[]
for i in transcribed_audio:
l=i.split(" ")
counts = Counter(l)
words_frequency=counts.most_common(1000)
frequency.append(words_frequency)
print(frequency)
filenames.sort()
filenames
# +
import cv2
from progress.bar import Bar
from deepface import DeepFace
frames_analysis=[]
for i in filenames:
print(i)
age=[]
dominant_race=[]
dominant_emotion=[]
gender=[]
cap=cv2.VideoCapture(f"input_video/{i}")
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
bar = Bar('Processing Frames', max=length)
for i in range(0, 20):
ret, frame = cap.read()
cv2.imwrite("frame/1.jpg",frame)
obj = DeepFace.analyze(img_path = "frame/1.jpg", actions = ['age', 'gender', 'race', 'emotion'],enforce_detection=False)
age.append(obj["age"])
dominant_race.append(obj["dominant_race"])
dominant_emotion.append(obj["dominant_emotion"])
gender.append(obj["gender"])
print(obj["age"]," years old ",obj["dominant_race"]," ",obj["dominant_emotion"]," ", obj["gender"])
bar.next()
bar.finish()
d={"age":age,"dominant_race":dominant_race,"dominant_emotion":dominant_emotion,"gender":gender}
frames_analysis.append(d)
# +
import pandas as pd
# intialise data of lists.
data = {'filename':filenames,
'transcribed_audio':transcribed_audio,
'word_frequency':frequency,
'frames_analysis':frames_analysis
}
# Create DataFrame
df = pd.DataFrame(data)
# Print the output.
df
# -
df.to_csv("result.csv",index=False)
| combined.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/w8mr/ing-ml-challenge/blob/master/challenge.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="XZz-4ozU3GHG" colab_type="text"
# # ING Machine learning challenge week 6 Income data
# + [markdown] colab_type="text" id="_JgSgxmM1NGx"
# ## Setup kaggle, token and datasets
#
# Upgrade Kaggle
# + colab_type="code" id="OppyMnCuWjzJ" outputId="694bb96d-3bf2-4d1f-df18-09ec79ed8844" colab={"base_uri": "https://localhost:8080/", "height": 360}
# !pip install kaggle --upgrade
# !kaggle --version
# + [markdown] colab_type="text" id="hMY4CFezjcG-"
# Upload kaggle token
#
# + colab_type="code" id="0HtGf0HEXEa5" outputId="bfead5a3-4000-42b6-cf01-cf3ffedd3a15" colab={"resources": {"http://localhost:8080/nbextensions/google.colab/files.js": {"data": "<KEY> "ok": true, "headers": [["content-type", "application/javascript"]], "status": 200, "status_text": ""}}, "base_uri": "https://localhost:8080/", "height": 88}
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print(f'User uploaded file "{fn}" with length {len(uploaded[fn])} bytes')
# Then move kaggle.json into the folder where the API expects to find it.
# !mkdir -p ~/.kaggle/ && mv kaggle.json ~/.kaggle/ && chmod 600 ~/.kaggle/kaggle.json
# + [markdown] colab_type="text" id="dNke00r6ig3h"
# Download and unzip the dataset
# + colab_type="code" id="Aojvqv8Gaf8I" outputId="f2d8cc87-b85a-41b6-8d10-ec1066b91c50" colab={"base_uri": "https://localhost:8080/", "height": 306}
# !kaggle competitions download -c ml-challenge-week6
# !unzip -o census-income.data.zip
# !unzip -o census-income.test.zip
# + colab_type="code" id="wxs-KvIA5vhI" outputId="606265ee-00c9-450f-d4b6-7190f72a83b5" colab={"base_uri": "https://localhost:8080/", "height": 1000}
import pandas as pd
import numpy as np
# Column names found at https://www2.1010data.com/documentationcenter/beta/Tutorials/MachineLearningExamples/CensusIncomeDataSet.html manually adjusted
header_list = ["age", "class of worker", "industry code", "occupation code",
#"adjusted gross income",
"education", "wage per hour",
"enrolled in edu inst last wk", "marital status", "major industry code",
"major occupation code", "mace", "hispanic Origin", "sex",
"member of a labor union", "reason for unemployment",
"full or part time employment stat", "capital gains", "capital losses",
"divdends from stocks",
#"federal income tax liability",
"tax filer status",
"region of previous residence", "state of previous residence",
"detailed household and family stat", "detailed household summary in household",
"instance weight", "migration code-change in msa", "migration code-change in reg",
"migration code-move within reg", "live in this house 1 year ago",
"migration prev res in sunbelt", "num persons worked for employer",
"family members under 18",
#"total person earnings",
"country of birth father",
"country of birth mother", "country of birth self", "citizenship",
"total person income", "own business or self employed", "veterans benefits", "weeks worked in the year", "year of survey", "taxable income amount"]
train_df = pd.read_csv('census-income.data', header=None, names=header_list, na_values=[" Not in universe", " Not in universe or children", " Not in universe under 1 year old", " ?"])
train_df.info()
train_df.head()
# + [markdown] id="VKFV1pzCEdNk" colab_type="text"
# ## Inspect data
#
# + id="1uP79_Gn5CkT" colab_type="code" colab={}
train_df = train_df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
# + id="eTYgNgKnzIF5" colab_type="code" colab={}
smallest_group = 20
industry_occupation_count = train_df.groupby(by=['industry code','occupation code'])['age'].apply(lambda x: (x.name[0]*100+x.name[1], x.name[0]*100+x.name[1] if x.count() > smallest_group else x.name[0]*100))
industry_occupation_dict = {tup[0]: tup[1] for tup in industry_occupation_count.values}
train_df['industry_occupation'] = (train_df['industry code']*100+train_df['occupation code']).apply(lambda x: industry_occupation_dict[x])
# + id="KoX9Vd7_HLtJ" colab_type="code" outputId="73763ddb-2fd5-47ee-fb08-be88c294fcdb" colab={"base_uri": "https://localhost:8080/", "height": 1000}
for column in train_df.columns:
print("Column {}: \nValues{}\n".format(column, train_df[column].unique()))
# + [markdown] id="VnJgzIb25DXI" colab_type="text"
# Strip whitespace
# + id="9qGXKcojNnfb" colab_type="code" outputId="3fc7b704-fc90-475d-d606-f02297d91a9c" colab={"base_uri": "https://localhost:8080/", "height": 347}
def part_above_50k(column):
return {tup[0]: tup[1][tup[1]=='50000+.'].count()/tup[1].count() for tup in train_df.groupby(by=[column])['taxable income amount']}
io_above50k = part_above_50k('mace')
import matplotlib.pyplot as plt
pd.DataFrame(io_above50k.values()).plot.bar()
plt.show()
#train_df['industry_occupation_'] = train_df['industry_occupation'].apply(io_above50k.get)
#train_df
io_above50k
# + id="iICB4F8mFroY" colab_type="code" outputId="fdf79015-511e-443d-ad05-7c6b5d01f1ba" colab={"base_uri": "https://localhost:8080/", "height": 85}
train_df['class of worker'].unique()
# + id="4AWeweqF2CSC" colab_type="code" outputId="2ddb084a-2b24-4230-98df-5873884d612e" colab={"base_uri": "https://localhost:8080/", "height": 1000}
test_df = pd.read_csv('census-income.test', header=None, names=header_list[:-1])
test_df.info()
test_df.head()
# + [markdown] colab_type="text" id="L_86P4tv4K2h"
# ## Making a submission
# + colab_type="code" id="gCme0MVW7DiD" colab={}
import numpy as np
submission_df = pd.read_csv('sampleSubmission.csv')
submission_df['income class'] = np.random.randint(0, 2, submission_df.shape[0])
submission_df['income class'].head()
# + colab_type="code" id="R4cUd6VT94VJ" colab={}
submission_df.to_csv('submission.csv')
# + [markdown] colab_type="text" id="fVYsZv1SBzGQ"
# ```
# usage: kaggle competitions submit [-h] -f FILE_NAME -m MESSAGE [-q]
# [competition]
#
# required arguments:
# -f FILE_NAME, --file FILE_NAME
# File for upload (full path)
# -m MESSAGE, --message MESSAGE
# Message describing this submission
#
# optional arguments:
# -h, --help show this help message and exit
# competition Competition URL suffix (use "kaggle competitions list" to show options)
# If empty, the default competition will be used (use "kaggle config set competition")"
# -q, --quiet Suppress printing information about the upload/download progress
# ```
# + colab_type="code" id="ajUqJKv24Qqu" colab={}
# !kaggle competitions submit -c ml-challenge-week6 -f submission.csv -m "Test"
# + [markdown] colab_type="text" id="CgdvQI_qCDGY"
# ## List competition submissions
# + [markdown] colab_type="text" id="DI606jnHCfPS"
# ```
# usage: kaggle competitions submissions [-h] [-v] [-q] [competition]
#
# optional arguments:
# -h, --help show this help message and exit
# competition Competition URL suffix (use "kaggle competitions list" to show options)
# If empty, the default competition will be used (use "kaggle config set competition")"
# -v, --csv Print results in CSV format (if not set print in table format)
# -q, --quiet Suppress printing information about the upload/download progress
# ```
# + colab_type="code" id="ujdSqDtCCRAF" colab={}
# !kaggle competitions submissions ml-challenge-week6
# + [markdown] colab_type="text" id="h0pLaPQZCjE0"
# ## Get competition leaderboard
# + [markdown] colab_type="text" id="clfm4GWoCocy"
# ```
# usage: kaggle competitions leaderboard [-h] [-s] [-d] [-p PATH] [-v] [-q]
# [competition]
#
# optional arguments:
# -h, --help show this help message and exit
# competition Competition URL suffix (use "kaggle competitions list" to show options)
# If empty, the default competition will be used (use "kaggle config set competition")"
# -s, --show Show the top of the leaderboard
# -d, --download Download entire leaderboard
# -p PATH, --path PATH Folder where file(s) will be downloaded, defaults to current working directory
# -v, --csv Print results in CSV format (if not set print in table format)
# -q, --quiet Suppress printing information about the upload/download progress
# ```
# + colab_type="code" id="zAH0lJOGCtHC" outputId="f673a552-e90d-4a7c-8ae5-c8b30f78c538" colab={"base_uri": "https://localhost:8080/", "height": 136}
# !kaggle competitions leaderboard ml-challenge-week6 -s
# + [markdown] colab_type="text" id="SxdB6P_ulkfa" toc-hr-collapsed=false
# ## Uploading a Colab notebook to Kaggle Kernels
# + [markdown] colab_type="text" id="o-NDs2dImDG0"
# ### Downloading a notebook from Colab
#
# To download from Colab, use **File** | **Download .ipynb**
# + [markdown] colab_type="text" id="zUMAuin2mbbW"
# ### Then upload the notebook to your Colab runtime
# + colab_type="code" id="qox_MozfmF2Y" colab={}
uploaded = files.upload()
notebook_path = list(uploaded.keys())[0]
# + colab_type="code" id="7BT_rPcuoMsd" colab={}
# !mkdir -p export
# !mv "$notebook_path" export/
# + [markdown] colab_type="text" id="Kgr50t9CFNTY"
# ### Initialize metadata file for a kernel
#
# ```
# usage: kaggle kernels init [-h] [-p FOLDER]
#
# optional arguments:
# -h, --help show this help message and exit
# -p FOLDER, --path FOLDER
# Folder for upload, containing data files and a special kernel-metadata.json file
# (https://github.com/Kaggle/kaggle-api/wiki/Kernel-Metadata).
# Defaults to current working directory
# ```
# + colab_type="code" id="J1gMt15SFRQh" colab={}
# !kaggle kernels init -p export
# + colab_type="code" id="Ls0Umf85q9UE" colab={}
import re
your_kaggle_username = 'Your kaggle username'
notebook_title = 'New Kernel'
new_kernel_slug = re.sub(r'[^a-z0-9]+', '-', notebook_title.lower())
notebook_path = 'export'
metadata_file = 'export/kernel-metadata.json'
# + colab_type="code" id="hcPAUJknG1kj" colab={}
import json
with open(metadata_file) as json_file:
metadata = json.load(json_file)
metadata['code_file'] = notebook_path
metadata['kernel_type'] = 'notebook'
metadata['language'] = 'python'
metadata['id'] = f'{your_kaggle_username}/{new_kernel_slug}'
metadata['title'] = notebook_title
with open(metadata_file, 'w') as outfile:
json.dump(metadata, outfile, indent=4)
# + colab_type="code" id="PyX-cbzIoj-V" colab={}
# !cat export/kernel-metadata.json
# + [markdown] colab_type="text" id="_PK5ql93DS1y"
# ```
# usage: kaggle kernels push [-h] -p FOLDER
#
# optional arguments:
# -h, --help show this help message and exit
# -p FOLDER, --path FOLDER
# Folder for upload, containing data files and a special kernel-metadata.json file
# (https://github.com/Kaggle/kaggle-api/wiki/Kernel-Metadata).
# Defaults to current working directory
# ```
# + colab_type="code" id="VDP5xJPklqYk" colab={}
# !kaggle kernels push -p export
| challenge.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
gapminder = pd.read_csv('../data/gapminder.tsv', delimiter='\t')
gapminder.head()
gapminder.groupby('year')['lifeExp'].mean()
y1952 = gapminder.loc[gapminder['year'] == 1952, :]
l = [1, 2, 3, 4, 5]
l[:]
y1952['lifeExp'].mean()
gapminder.groupby('year')['lifeExp'].describe()
import numpy as np
gapminder.groupby('continent')['lifeExp'].agg(np.mean)
gapminder.groupby('continent')['lifeExp'].aggregate(np.std)
def my_mean(values):
n = len(values)
s = np.sum(values)
return s / n
gapminder.groupby('continent')['lifeExp'].aggregate(my_mean)
gapminder.groupby('continent')['lifeExp'].aggregate([
np.count_nonzero,
np.mean,
np.std
])
gapminder.groupby('continent')['lifeExp'].aggregate({
'ncount': np.count_nonzero,
'mean': np.mean,
'std': np.std
})
gapminder.groupby('continent')['lifeExp'].aggregate([
np.count_nonzero,
np.mean,
np.std]).\
rename(columns = {'count_nonzero': 'count',
'mean': 'avg',
'std': 'std_dev'}).\
reset_index()
|
| 02-lesson/07-groupby.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="ChjuaQjm_iBf"
# ##### Copyright 2020 The TensorFlow Authors.
# + cellView="form" id="uWqCArLO_kez"
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# + [markdown] id="ikhIvrku-i-L"
# # Deep & Cross Network (DCN)
#
# <table class="tfo-notebook-buttons" align="left">
# <td>
# <a target="_blank" href="https://www.tensorflow.org/recommenders/examples/dcn"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
# </td>
# <td>
# <a target="_blank" href="https://colab.research.google.com/github/tensorflow/recommenders/blob/main/docs/examples/dcn.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
# </td>
# <td>
# <a target="_blank" href="https://github.com/tensorflow/recommenders/blob/main/docs/examples/dcn.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
# </td>
# <td>
# <a href="https://storage.googleapis.com/tensorflow_docs/recommenders/docs/examples/dcn.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
# </td>
# </table>
# + [markdown] id="Q-rOX95bAye4"
# This tutorial demonstrates how to use Deep & Cross Network (DCN) to effectively learn feature crosses.
#
# ##Background
#
# **What are feature crosses and why are they important?** Imagine that we are building a recommender system to sell a blender to customers. Then, a customer's past purchase history such as `purchased_bananas` and `purchased_cooking_books`, or geographic features, are single features. If one has purchased both bananas **and** cooking books, then this customer will more likely click on the recommended blender. The combination of `purchased_bananas` and `purchased_cooking_books` is referred to as a **feature cross**, which provides additional interaction information beyond the individual features.
# <div>
# <center>
# <img src="http://drive.google.com/uc?export=view&id=1e8pYZHM1ZSwqBLYVkKDoGg0_2t2UPc2y" width="600"/>
# </center>
# </div>
#
#
#
#
# **What are the challenges in learning feature crosses?** In Web-scale applications, data are mostly categorical, leading to large and sparse feature space. Identifying effective feature crosses in this setting often requires
# manual feature engineering or exhaustive search. Traditional feed-forward multilayer perceptron (MLP) models are universal function approximators; however, they cannot efficiently approximate even 2nd or 3rd-order feature crosses [[1](https://arxiv.org/pdf/2008.13535.pdf), [2](https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/18fa88ad519f25dc4860567e19ab00beff3f01cb.pdf)].
#
# **What is Deep & Cross Network (DCN)?** DCN was designed to learn explicit and bounded-degree cross features more effectively. It starts with an input layer (typically an embedding layer), followed by a *cross network* containing multiple cross layers that models explicit feature interactions, and then combines
# with a *deep network* that models implicit feature interactions.
#
#
# * Cross Network. This is the core of DCN. It explicitly applies feature crossing at each layer, and the highest
# polynomial degree increases with layer depth. The following figure shows the $(i+1)$-th cross layer.
# <div class="fig figcenter fighighlight">
# <center>
# <img src="http://drive.google.com/uc?export=view&id=1QvIDptMxixFNp6P4bBqMN4AYAhAIAYQZ" width="50%" style="display:block">
# </center>
# </div>
# * Deep Network. It is a traditional feedforward multilayer perceptron (MLP).
#
# The deep network and cross network are then combined to form DCN [[1](https://arxiv.org/pdf/2008.13535.pdf)]. Commonly, we could stack a deep network on top of the cross network (stacked structure); we could also place them in parallel (parallel structure).
#
#
# <div class="fig figcenter fighighlight">
# <center>
# <img src="http://drive.google.com/uc?export=view&id=1WtDUCV6b-eetUnWVCAmcPh8mJFut5EUd" hspace="40" width="30%" style="margin: 0px 100px 0px 0px;">
# <img src="http://drive.google.com/uc?export=view&id=1xo_twKb847hasfss7JxF0UtFX_rEb4nt" width="20%">
# </center>
# </div>
# + [markdown] id="6OlIGoADAhZg"
# In the following, we will first show the advantage of DCN with a toy example, and then we will walk you through some common ways to utilize DCN using the MovieLen-1M dataset.
# + [markdown] id="Az-y_3qxH3gA"
# Let's first install and import the necessary packages for this colab.
#
# + id="PjfZWVEWAmxS"
# !pip install -q tensorflow-recommenders
# !pip install -q --upgrade tensorflow-datasets
# + id="DqsyLA0UHeCl"
import pprint
# %matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_recommenders as tfrs
# + [markdown] id="tHCgOeoHBGbb"
# ## Toy Example
# To illustrate the benefits of DCN, let's work through a simple example. Suppose we have a dataset where we're trying to model the likelihood of a customer clicking on a blender Ad, with its features and label described as follows.
#
# | Features / Label | Description | Value Type / Range |
# | ------------- |-------------| -----|
# | $x_1$ = country | the country this customer lives in | Int in [0, 199] |
# | $x_2$ = bananas | # bananas the customer has purchased |Int in [0, 23] |
# | $x_3$ = cookbooks | # cooking books the customer has purchased |Int in [0, 5] |
# | $y$ | the likelihood of clicking on a blender Ad | -- |
#
# Then, we let the data follow the following underlying distribution:
# $$y = f(x_1, x_2, x_3) = 0.1x_1 + 0.4x_2+0.7x_3 + 0.1x_1x_2+3.1x_2x_3+0.1x_3^2$$
#
# where the likelihood $y$ depends linearly both on features $x_i$'s, but also on multiplicative interactions between the $x_i$'s. In our case, we would say that the likelihood of purchasing a blender ($y$) depends not just on buying bananas ($x_2$) or cookbooks ($x_3$), but also on buying bananas and cookbooks *together* ($x_2x_3$).
# + [markdown] id="HO6d-0zoHrz8"
# We can generate the data for this as follows:
#
# + [markdown] id="-fi2ya4P_hab"
# ### Synthetic data generation
#
# We first define $f(x_1, x_2, x_3)$ as described above.
# + id="9rT3f6C3GX0u"
def get_mixer_data(data_size=100_000, random_seed=42):
# We need to fix the random seed
# to make colab runs repeatable.
rng = np.random.RandomState(random_seed)
country = rng.randint(200, size=[data_size, 1]) / 200.
bananas = rng.randint(24, size=[data_size, 1]) / 24.
cookbooks = rng.randint(6, size=[data_size, 1]) / 6.
x = np.concatenate([country, bananas, cookbooks], axis=1)
# # Create 1st-order terms.
y = 0.1 * country + 0.4 * bananas + 0.7 * cookbooks
# Create 2nd-order cross terms.
y += 0.1 * country * bananas + 3.1 * bananas * cookbooks + (
0.1 * cookbooks * cookbooks)
return x, y
# + [markdown] id="JXtUSs9E3uRG"
# Let's generate the data that follows the distribution, and split the data into 90% for training and 10% for testing.
# + id="vrQWVYajgmNV"
x, y = get_mixer_data()
num_train = 90000
train_x = x[:num_train]
train_y = y[:num_train]
eval_x = x[num_train:]
eval_y = y[num_train:]
# + [markdown] id="MszQC-KJLhVK"
# ### Model construction
#
# We're going to try out both cross network and deep network to illustrate the advantage a cross network can bring to recommenders. As the data we just created only contains 2nd-order feature interactions, it would be sufficient to illustrate with a single-layered cross network. If we wanted to model higher-order feature interactions, we could stack multiple cross layers and use a multi-layered cross network. The two models we will be building are:
# 1. Cross Network with only one cross layer;
# 2. Deep Network with wider and deeper ReLU layers.
#
# We first build a unified model class whose loss is the mean squared error.
# + id="bwgAH2FTR4Fe"
class Model(tfrs.Model):
def __init__(self, model):
super().__init__()
self._model = model
self._logit_layer = tf.keras.layers.Dense(1)
self.task = tfrs.tasks.Ranking(
loss=tf.keras.losses.MeanSquaredError(),
metrics=[
tf.keras.metrics.RootMeanSquaredError("RMSE")
]
)
def call(self, x):
x = self._model(x)
return self._logit_layer(x)
def compute_loss(self, features, training=False):
x, labels = features
scores = self(x)
return self.task(
labels=labels,
predictions=scores,
)
# + [markdown] id="QAKBq2QxOdM0"
# Then, we specify the cross network (with 1 cross layer of size 3) and the ReLU-based DNN (with layer sizes [512, 256, 128]):
# + id="EwBwSHz_N3pW"
crossnet = Model(tfrs.layers.dcn.Cross())
deepnet = Model(
tf.keras.Sequential([
tf.keras.layers.Dense(512, activation="relu"),
tf.keras.layers.Dense(256, activation="relu"),
tf.keras.layers.Dense(128, activation="relu")
])
)
# + [markdown] id="2EtaI5lh4X0B"
# ### Model training
# Now that we have the data and models ready, we are going to train the models. We first shuffle and batch the data to prepare for model training.
#
# + id="X6gD-NTF4eoj"
train_data = tf.data.Dataset.from_tensor_slices((train_x, train_y)).batch(1000)
eval_data = tf.data.Dataset.from_tensor_slices((eval_x, eval_y)).batch(1000)
# + [markdown] id="JYm5bmmgPVZu"
# Then, we define the number of epochs as well as the learning rate.
# + id="nFhrC7fV6szW"
epochs = 100
learning_rate = 0.4
# + [markdown] id="zbRiVPJtPz-1"
# Alright, everything is ready now and let's compile and train the models. You could set `verbose=True` if you want to see how the model progresses.
# + id="F8ZXXbmKuB8p"
crossnet.compile(optimizer=tf.keras.optimizers.Adagrad(learning_rate))
crossnet.fit(train_data, epochs=epochs, verbose=False)
# + id="Tzg3KLKW2sdA"
deepnet.compile(optimizer=tf.keras.optimizers.Adagrad(learning_rate))
deepnet.fit(train_data, epochs=epochs, verbose=False)
# + [markdown] id="xxWfaY6H7Bmp"
# ### Model evaluation
# We verify the model performance on the evaluation dataset and report the Root Mean Squared Error (RMSE, the lower the better).
# + id="l4PM-goX6FoD"
crossnet_result = crossnet.evaluate(eval_data, return_dict=True, verbose=False)
print(f"CrossNet(1 layer) RMSE is {crossnet_result['RMSE']:.4f} "
f"using {crossnet.count_params()} parameters.")
deepnet_result = deepnet.evaluate(eval_data, return_dict=True, verbose=False)
print(f"DeepNet(large) RMSE is {deepnet_result['RMSE']:.4f} "
f"using {deepnet.count_params()} parameters.")
# + [markdown] id="6_Ig-Gnm7-JD"
# We see that the cross network achieved **magnitudes lower RMSE** than a ReLU-based DNN, with **magnitudes fewer parameters**. This has suggested the efficieny of a cross network in learning feaure crosses.
# + [markdown] id="XsCsY1-Us-_e"
# ### Model understanding
# We already know what feature crosses are important in our data, it would be fun to check whether our model has indeed learned the important feature cross. This can be done by visualizing the learned weight matrix in DCN. The weight $W_{ij}$ represents the learned importance of interaction between feature $x_i$ and $x_j$.
# + id="N8dga2Qck5IV"
mat = crossnet._model._dense.kernel
features = ["country", "purchased_bananas", "purchased_cookbooks"]
plt.figure(figsize=(9,9))
im = plt.matshow(np.abs(mat.numpy()), cmap=plt.cm.Blues)
ax = plt.gca()
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
cax.tick_params(labelsize=10)
_ = ax.set_xticklabels([''] + features, rotation=45, fontsize=10)
_ = ax.set_yticklabels([''] + features, fontsize=10)
# + [markdown] id="bQHVZTu03qvi"
# Darker colours represent stronger learned interactions - in this case, it's clear that the model learned that purchasing babanas and cookbooks together is important.
#
# If you are interested in trying out more complicated synthetic data, feel free to check out [this paper](https://arxiv.org/pdf/2008.13535.pdf).
# + [markdown] id="0wU4FcpfHCZM"
# ## Movielens 1M example
# We now examine the effectiveness of DCN on a real-world dataset: Movielens 1M [[3](https://grouplens.org/datasets/movielens)]. Movielens 1M is a popular dataset for recommendation research. It predicts users' movie ratings given user-related features and movie-related features. We use this dataset to demonstrate some common ways to utilize DCN.
# + [markdown] id="8Rvlem07wfwH"
# ### Data processing
#
# The data processing procedure follows a similar procedure as the [basic ranking tutorial](https://www.tensorflow.org/recommenders/examples/basic_ranking).
# + id="7Y_n3EPosR4A"
ratings = tfds.load("movie_lens/100k-ratings", split="train")
ratings = ratings.map(lambda x: {
"movie_id": x["movie_id"],
"user_id": x["user_id"],
"user_rating": x["user_rating"],
"user_gender": int(x["user_gender"]),
"user_zip_code": x["user_zip_code"],
"user_occupation_text": x["user_occupation_text"],
"bucketized_user_age": int(x["bucketized_user_age"]),
})
# + [markdown] id="2Yb3KxrgSHiF"
# Next, we randomly split the data into 80% for training and 20% for testing.
#
# + id="a5-l91jR_zEo"
tf.random.set_seed(42)
shuffled = ratings.shuffle(100_000, seed=42, reshuffle_each_iteration=False)
train = shuffled.take(80_000)
test = shuffled.skip(80_000).take(20_000)
# + [markdown] id="MRHGa9mESMVz"
# Then, we create vocabulary for each feature.
# + id="l9qhEcHq_VfI"
feature_names = ["movie_id", "user_id", "user_gender", "user_zip_code",
"user_occupation_text", "bucketized_user_age"]
vocabularies = {}
for feature_name in feature_names:
vocab = ratings.batch(1_000_000).map(lambda x: x[feature_name])
vocabularies[feature_name] = np.unique(np.concatenate(list(vocab)))
# + [markdown] id="Eti8kNkPSORk"
# ### Model construction
#
# The model architecture we will be building starts with an embedding layer, which is fed into a cross network followed by a deep network. The embedding dimension is set to 32 for all the features. You could also use different embedding sizes for different features.
# + id="6lrDcBjiwnHU"
class DCN(tfrs.Model):
def __init__(self, use_cross_layer, deep_layer_sizes, projection_dim=None):
super().__init__()
self.embedding_dimension = 32
str_features = ["movie_id", "user_id", "user_zip_code",
"user_occupation_text"]
int_features = ["user_gender", "bucketized_user_age"]
self._all_features = str_features + int_features
self._embeddings = {}
# Compute embeddings for string features.
for feature_name in str_features:
vocabulary = vocabularies[feature_name]
self._embeddings[feature_name] = tf.keras.Sequential(
[tf.keras.layers.StringLookup(
vocabulary=vocabulary, mask_token=None),
tf.keras.layers.Embedding(len(vocabulary) + 1,
self.embedding_dimension)
])
# Compute embeddings for int features.
for feature_name in int_features:
vocabulary = vocabularies[feature_name]
self._embeddings[feature_name] = tf.keras.Sequential(
[tf.keras.layers.IntegerLookup(
vocabulary=vocabulary, mask_value=None),
tf.keras.layers.Embedding(len(vocabulary) + 1,
self.embedding_dimension)
])
if use_cross_layer:
self._cross_layer = tfrs.layers.dcn.Cross(
projection_dim=projection_dim,
kernel_initializer="glorot_uniform")
else:
self._cross_layer = None
self._deep_layers = [tf.keras.layers.Dense(layer_size, activation="relu")
for layer_size in deep_layer_sizes]
self._logit_layer = tf.keras.layers.Dense(1)
self.task = tfrs.tasks.Ranking(
loss=tf.keras.losses.MeanSquaredError(),
metrics=[tf.keras.metrics.RootMeanSquaredError("RMSE")]
)
def call(self, features):
# Concatenate embeddings
embeddings = []
for feature_name in self._all_features:
embedding_fn = self._embeddings[feature_name]
embeddings.append(embedding_fn(features[feature_name]))
x = tf.concat(embeddings, axis=1)
# Build Cross Network
if self._cross_layer is not None:
x = self._cross_layer(x)
# Build Deep Network
for deep_layer in self._deep_layers:
x = deep_layer(x)
return self._logit_layer(x)
def compute_loss(self, features, training=False):
labels = features.pop("user_rating")
scores = self(features)
return self.task(
labels=labels,
predictions=scores,
)
# + [markdown] id="jDiRfzwVW9LH"
# ### Model training
# We shuffle, batch and cache the training and test data.
#
# + id="qeFjmfUbgzcS"
cached_train = train.shuffle(100_000).batch(8192).cache()
cached_test = test.batch(4096).cache()
# + [markdown] id="5adSI3yOt2VQ"
# Let's define a function that runs a model multiple times and returns the model's RMSE mean and standard deviation out of multiple runs.
# + id="gTDk3GloquHO"
def run_models(use_cross_layer, deep_layer_sizes, projection_dim=None, num_runs=5):
models = []
rmses = []
for i in range(num_runs):
model = DCN(use_cross_layer=use_cross_layer,
deep_layer_sizes=deep_layer_sizes,
projection_dim=projection_dim)
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate))
models.append(model)
model.fit(cached_train, epochs=epochs, verbose=False)
metrics = model.evaluate(cached_test, return_dict=True)
rmses.append(metrics["RMSE"])
mean, stdv = np.average(rmses), np.std(rmses)
return {"model": models, "mean": mean, "stdv": stdv}
# + [markdown] id="ZRHjQ8g2h2-k"
# We set some hyper-parameters for the models. Note that these hyper-parameters are set globally for all the models for demonstration purpose. If you want to obtain the best performance for each model, or conduct a fair comparison among models, then we'd suggest you to fine-tune the hyper-parameters. Remember that the model architecture and optimization schemes are intertwined.
# + id="Zy3kWb5Dh0E7"
epochs = 8
learning_rate = 0.01
# + [markdown] id="Nz3ftiQLXdC0"
# **DCN (stacked).** We first train a DCN model with a stacked structure, that is, the inputs are fed to a cross network followed by a deep network.
# <div>
# <center>
# <img src="http://drive.google.com/uc?export=view&id=1X8qoMtIYKJz4yBYifvfw4QpAwrjr70e_" width="140"/>
# </center>
# </div>
#
# + id="hiuYPJWhgw3J"
dcn_result = run_models(use_cross_layer=True,
deep_layer_sizes=[192, 192])
# + [markdown] id="ZwTn_UpDX_iO"
# **Low-rank DCN.** To reduce the training and serving cost, we leverage low-rank techniques to approximate the DCN weight matrices. The rank is passed in through argument `projection_dim`; a smaller `projection_dim` results in a lower cost. Note that `projection_dim` needs to be smaller than (input size)/2 to reduce the cost. In practice, we've observed using low-rank DCN with rank (input size)/4 consistently preserved the accuracy of a full-rank DCN.
#
# <div>
# <center>
# <img src="http://drive.google.com/uc?export=view&id=1ZZfUTNdxjGAaAuwNrweKkLJ1PGxMmiCm" width="400"/>
# </center>
# </div>
#
# + id="NYxbHI7ZNJX7"
dcn_lr_result = run_models(use_cross_layer=True,
projection_dim=20,
deep_layer_sizes=[192, 192])
# + [markdown] id="5O5AoNOdaQ80"
# **DNN.** We train a same-sized DNN model as a reference.
# + id="iBPpwD4cGtXF"
dnn_result = run_models(use_cross_layer=False,
deep_layer_sizes=[192, 192, 192])
# + [markdown] id="cBY0ljpl3_k5"
# We evaluate the model on test data and report the mean and standard deviation out of 5 runs.
# + id="a1yj3pp0glEL"
print("DCN RMSE mean: {:.4f}, stdv: {:.4f}".format(
dcn_result["mean"], dcn_result["stdv"]))
print("DCN (low-rank) RMSE mean: {:.4f}, stdv: {:.4f}".format(
dcn_lr_result["mean"], dcn_lr_result["stdv"]))
print("DNN RMSE mean: {:.4f}, stdv: {:.4f}".format(
dnn_result["mean"], dnn_result["stdv"]))
# + [markdown] id="K076UbT1nnq3"
# We see that DCN achieved better performance than a same-sized DNN with ReLU layers. Moreover, the low-rank DCN was able to reduce parameters while maintaining the accuracy.
# + [markdown] id="eSF0gNLGX1Za"
# **More on DCN.** Besides what've been demonstrated above, there are more creative yet practically useful ways to utilize DCN [[1](https://arxiv.org/pdf/2008.13535.pdf)].
#
# * *DCN with a parallel structure*. The inputs are fed in parallel to a cross network and a deep network.
#
# * *Concatenating cross layers.* The inputs are fed in parallel to multiple cross layers to capture complementary feature crosses.
#
# <div class="fig figcenter fighighlight">
# <center>
# <img src="http://drive.google.com/uc?export=view&id=11RpNuj9s0OgSav9TUuGA7v7PuFLL6nVR" hspace=40 width="600" style="display:block;">
# <div class="figcaption">
# <b>Left</b>: DCN with a parallel structure; <b>Right</b>: Concatenating cross layers.
# </div>
# </center>
# </div>
# + [markdown] id="GEi9PtCEdyma"
# ### Model understanding
#
# The weight matrix $W$ in DCN reveals what feature crosses the model has learned to be important. Recall that in the previous toy example, the importance of interactions between the $i$-th and $j$-th features is captured by the ($i, j$)-th element of $W$.
#
# What's a bit different here is that the feature embeddings are of size 32 instead of size 1. Hence, the importance will be characterized by the $(i, j)$-th block
# $W_{i,j}$ which is of dimension 32 by 32.
# In the following, we visualize the Frobenius norm [[4](https://en.wikipedia.org/wiki/Matrix_norm)] $||W_{i,j}||_F$ of each block, and a larger norm would suggest higher importance (assuming the features' embeddings are of similar scales).
#
# Besides block norm, we could also visualize the entire matrix, or the mean/median/max value of each block.
# + id="47ibaEBJxOoe"
model = dcn_result["model"][0]
mat = model._cross_layer._dense.kernel
features = model._all_features
block_norm = np.ones([len(features), len(features)])
dim = model.embedding_dimension
# Compute the norms of the blocks.
for i in range(len(features)):
for j in range(len(features)):
block = mat[i * dim:(i + 1) * dim,
j * dim:(j + 1) * dim]
block_norm[i,j] = np.linalg.norm(block, ord="fro")
plt.figure(figsize=(9,9))
im = plt.matshow(block_norm, cmap=plt.cm.Blues)
ax = plt.gca()
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
cax.tick_params(labelsize=10)
_ = ax.set_xticklabels([""] + features, rotation=45, ha="left", fontsize=10)
_ = ax.set_yticklabels([""] + features, fontsize=10)
# + [markdown] id="pQH-moYd6ZKC"
# That's all for this colab! We hope that you have enjoyed learning some basics of DCN and common ways to utilize it. If you are interested in learning more, you could check out two relevant papers: [DCN-v1-paper](https://arxiv.org/pdf/1708.05123.pdf), [DCN-v2-paper](https://arxiv.org/pdf/2008.13535.pdf).
# + [markdown] id="FfAGbq2es2Yn"
# ---
#
#
# ##References
# [DCN V2: Improved Deep & Cross Network and Practical Lessons for Web-scale Learning to Rank Systems](https://arxiv.org/pdf/2008.13535.pdf). \
# *<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. (2020)*
#
#
# [Deep & Cross Network for Ad Click Predictions](https://arxiv.org/pdf/1708.05123.pdf). \
# *<NAME>, <NAME>, <NAME>, <NAME>. (AdKDD 2017)*
| docs/examples/dcn.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: TensorFlow
# language: python
# name: tensorflow_2
# ---
# <p style="border: 1px solid #e7692c; border-left: 15px solid #e7692c; padding: 10px; text-align:justify;">
# <strong style="color: #e7692c">Tip.</strong> <a style="color: #000000;" href="https://nbviewer.jupyter.org/github/PacktPublishing/Hands-On-Computer-Vision-with-TensorFlow-2/blob/master/Chapter02/ch2_nb1_mnist_keras.ipynb" title="View with Jupyter Online">Click here to view this notebook on <code>nbviewer.jupyter.org</code></a>.
# <br/>These notebooks are better read there, as Github default viewer ignores some of the formatting and interactive content.
# </p>
# <table style="font-size: 1em; padding: 0; margin: 0;">
# <tr style="vertical-align: top; padding: 0; margin: 0;background-color: #ffffff">
# <td style="vertical-align: top; padding: 0; margin: 0; padding-right: 15px;">
# <p style="background: #363636; color:#ffffff; text-align:justify; padding: 10px 25px;">
# <strong style="font-size: 1.0em;"><span style="font-size: 1.2em;"><span style="color: #e7692c;">Hands-on</span> Computer Vision with TensorFlow 2</span><br/>by <em><NAME></em> & <em><NAME></em> (Packt Pub.)</strong><br/><br/>
# <strong>> Chapter 2: TensorFlow Basics and Training a Model</strong><br/>
# </p>
#
# <h1 style="width: 100%; text-align: left; padding: 0px 25px;"><small style="color: #e7692c;">Notebook 1:</small><br/>A simple computer vision model using Keras</h1>
# <br/>
# <p style="border-left: 15px solid #363636; text-align:justify; padding: 0 10px;">
# In the second chapter of the book, we introduced the Keras API and how to build a simple model.
# <br/>In this first notebook, we will therefore detail the related code snippets and results from the book.
# </p>
# <br/>
# <p style="border-left: 15px solid #e7692c; padding: 0 10px; text-align:justify;">
# <strong style="color: #e7692c;">Tip.</strong> The notebooks shared on this git repository illustrate some notions from the book "<em><strong>Hands-on Computer Vision with TensorFlow 2</strong></em>" written by <NAME> and <NAME>, published by Packt. If you enjoyed the insights shared here, <a href="https://www.amazon.com/Hands-Computer-Vision-TensorFlow-processing/dp/1788830644" title="Learn more about the book!"><strong>please consider acquiring the book!</strong></a>
# <br/><br/>
# The book provides further guidance for those eager to learn about computer vision and to harness the power of TensorFlow 2 and Keras to build efficient recognition systems for object detection, segmentation, video processing, smartphone applications, and more.</p>
# </td>
# <td style="vertical-align: top; padding: 0; margin: 0; width: 280px;">
# <a href="https://www.amazon.com/Hands-Computer-Vision-TensorFlow-processing/dp/1788830644" title="Learn more about the book!" target="_blank">
# <img src="../banner_images/book_cover.png" width=280>
# </a>
# <p style="background: #e7692c; color:#ffffff; padding: 10px; text-align:justify;"><strong>Leverage deep learning to create powerful image processing apps with TensorFlow 2 and Keras. <br/></strong>Get the book for more insights!</p>
# <ul style="height: 32px; white-space: nowrap; text-align: center; margin: 0px; padding: 0px; padding-top: 10px;">
# <li style="display: block;height: 100%;float: left;vertical-align: middle;margin: 0 25px 10px;padding: 0px;">
# <a href="https://www.amazon.com/Hands-Computer-Vision-TensorFlow-processing/dp/1788830644" title="Get the book on Amazon (paperback or Kindle version)!" target="_blank">
# <img style="vertical-align: middle; max-width: 72px; max-height: 32px;" src="../banner_images/logo_amazon.png" width="75px">
# </a>
# </li>
# <li style="display: inline-block;height: 100%;vertical-align: middle;float: right;margin: -5px 25px 10px;padding: 0px;">
# <a href="https://www.packtpub.com/application-development/hands-computer-vision-tensorflow-2" title="Get your Packt book (paperback, PDF, ePUB, or MOBI version)!" target="_blank">
# <img style="vertical-align: middle; max-width: 72px; max-height: 32px;" src="../banner_images/logo_packt.png" width="75px">
# </a>
# </li>
# </ul>
# </td>
# </tr>
# </table>
# + tags=[]
import tensorflow as tf
# -
# ## Input data
# + jupyter={"outputs_hidden": true}
num_classes = 10
img_rows, img_cols = 28, 28
num_channels = 1
input_shape = (img_rows, img_cols, num_channels)
(x_train, y_train),(x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# -
# ## Building a simple model
# + jupyter={"outputs_hidden": true}
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(num_classes, activation='softmax'))
# -
# ## Launch training
model.compile(optimizer='sgd',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
callbacks = [tf.keras.callbacks.TensorBoard('./keras')]
model.fit(x_train, y_train, epochs=25, verbose=1, validation_data=(x_test, y_test), callbacks=callbacks)
# ## Running with an estimator
estimator = tf.keras.estimator.model_to_estimator(model, model_dir='./estimator_dir')
# +
BATCH_SIZE = 32
def train_input_fn():
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_dataset = train_dataset.batch(BATCH_SIZE).repeat()
return train_dataset
estimator.train(train_input_fn, steps=len(x_train)//BATCH_SIZE)
| Chapter02/ch2_nb1_mnist_keras.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="RGjTwSdybsSv" colab_type="text"
# # 1.1 Intro
# + id="87yNlcnabmyK" colab_type="code" colab={}
## Intro ai comandi bash linux
# + id="JXLVWgvlcYXv" colab_type="code" outputId="2f185a56-66b6-4f77-90d2-5e6dea65601f" executionInfo={"status": "ok", "timestamp": 1585471984076, "user_tz": -120, "elapsed": 7062, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 51}
# !pwd # per printare il percorso su cui ci troviamo
# !ls # per printare la lista delle cartelle che vediamo nell'attuale posizione
# + id="QNarqGZndVcM" colab_type="code" outputId="5a295c08-4076-46ef-d96d-fb4396686bd5" executionInfo={"status": "ok", "timestamp": 1585471470387, "user_tz": -120, "elapsed": 518, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
# cd sample_data
# + id="P7v6XADScph5" colab_type="code" colab={}
# per spostarci a destra dentro le sottocartelle... cd .. per spostarci a sinistra cioè tornare alla cartella superiore
# + id="a7JnltYMc30p" colab_type="code" outputId="79aaecd2-347f-46ca-98c0-5435a61c182f" executionInfo={"status": "ok", "timestamp": 1585471474166, "user_tz": -120, "elapsed": 585, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
# cd ..
# + id="JLQxQm4jdoZq" colab_type="code" outputId="47283731-d98d-4480-b287-bf80edf36ca6" executionInfo={"status": "ok", "timestamp": 1585473412446, "user_tz": -120, "elapsed": 1156, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 137}
from IPython.display import Image
Image('dog1.jpg',width=200,height=120)
#Image(url='https://cdn.mos.cms.futurecdn.net/QjuZKXnkLQgsYsL98uhL9X-1024-80.jpg',width=800,height=450)
# + id="XaEFc1k4fI-Q" colab_type="code" outputId="1d163358-30b9-4876-b275-4f31a9d92d28" executionInfo={"status": "ok", "timestamp": 1585472888592, "user_tz": -120, "elapsed": 2750, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
# !ls
# + id="kKXRxvVmh6lo" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="69388933-77fe-494d-9ca7-f36595914095" executionInfo={"status": "ok", "timestamp": 1585583140650, "user_tz": -120, "elapsed": 4161, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}}
# !pip list
# + [markdown] id="QxapIRfpv9nw" colab_type="text"
# ### Oggetti python
# + id="wfiv3f-zlqld" colab_type="code" colab={}
# [], {},() : LIST -- DICTIONARY -- TUPLE
# + id="a5opcKmU2iMm" colab_type="code" colab={}
## LIST ##
# + id="GULxPChblqis" colab_type="code" outputId="98e1b13e-2829-470f-9096-64b9d898c566" executionInfo={"status": "ok", "timestamp": 1585477994215, "user_tz": -120, "elapsed": 647, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista = [0,1,-2,3]
lista
# + id="UbXc5DR-maA5" colab_type="code" outputId="379cf557-bce4-4461-fac1-cd0f01e67a19" executionInfo={"status": "ok", "timestamp": 1585477933268, "user_tz": -120, "elapsed": 898, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista = [0,1,-2,3,'hello',1.0] # int, string,float
lista
# + id="XRg3XubJmZ-h" colab_type="code" outputId="41d41f37-4251-4b0f-ae3f-0ef06ff2d241" executionInfo={"status": "ok", "timestamp": 1585476775240, "user_tz": -120, "elapsed": 768, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
type(lista)
# + id="2HIBtOc0mZ7i" colab_type="code" outputId="1a578c59-438d-41e8-82e2-5cca9cd1251a" executionInfo={"status": "ok", "timestamp": 1585476905513, "user_tz": -120, "elapsed": 1366, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
# generate fast list:
lista1 = [2]*10
lista1
# + id="GcFFa41EyeLg" colab_type="code" outputId="182de3b5-5467-4452-f4b0-a3f6f3c6f3b3" executionInfo={"status": "ok", "timestamp": 1585477668322, "user_tz": -120, "elapsed": 1045, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista2 = [3]*5
lista2
# + id="d1FoHPFByeJF" colab_type="code" outputId="2c075cfb-92b8-4685-f903-7457d914ce7e" executionInfo={"status": "ok", "timestamp": 1585477681210, "user_tz": -120, "elapsed": 770, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista2.append(2)
lista2
# + id="iVFy4e7r1d3g" colab_type="code" outputId="00647450-12d4-4e30-c479-e6bb7926727c" executionInfo={"status": "ok", "timestamp": 1585477728121, "user_tz": -120, "elapsed": 741, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
#count element inside a list
len(lista2)
# + id="QoPYjWF31wkd" colab_type="code" outputId="50865475-cda8-40f1-e65b-3998f0a25bb1" executionInfo={"status": "ok", "timestamp": 1585484032926, "user_tz": -120, "elapsed": 752, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista = [1,2,3,4,5]
lista
# + id="1dPJwRv8zBur" colab_type="code" colab={}
#select an element of a list
lista[5] # give an ERROR ## list index 0
# + id="tM_1tReBzBq8" colab_type="code" outputId="86fae917-939c-4461-9a53-abb5ac15882f" executionInfo={"status": "ok", "timestamp": 1585484035120, "user_tz": -120, "elapsed": 529, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista[0]
#lista[1]
lista[4]
# + id="aameQygbzBoc" colab_type="code" outputId="be49b4be-654f-403b-868b-798a09b05213" executionInfo={"status": "ok", "timestamp": 1585484037779, "user_tz": -120, "elapsed": 722, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista[-1]
# + id="hpZZzGhJNiWS" colab_type="code" outputId="2fae42d9-857a-4a86-8fef-ff298abaa66d" executionInfo={"status": "ok", "timestamp": 1585484051819, "user_tz": -120, "elapsed": 778, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista[-2] ## testare anche con -3 -4 -5
# + id="C4NHcQdlL0II" colab_type="code" colab={}
primi = [2,3,5,7,11,13,17,19,23,29,31]
# + id="TjUycphYL0Er" colab_type="code" outputId="eb2720cf-9849-4416-c7ee-673359ca77ae" executionInfo={"status": "ok", "timestamp": 1585483753139, "user_tz": -120, "elapsed": 745, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
primi[0:] # tutti
#primi[0:] # escluso il primo
# + id="BzdXK686zBmE" colab_type="code" outputId="18006546-1cfc-496d-b9e9-41db83839d35" executionInfo={"status": "ok", "timestamp": 1585483792497, "user_tz": -120, "elapsed": 813, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
selection = primi[0:1] #solo il primo
selection
# + id="lXLqhWbyMwYb" colab_type="code" outputId="55e81692-efb4-4f7c-d340-d98987c79e53" executionInfo={"status": "ok", "timestamp": 1585483849486, "user_tz": -120, "elapsed": 824, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 204}
for pippo in primi:
print(pippo)
# + id="wbvJElblMwWc" colab_type="code" outputId="1680c2cb-4f6f-4ff7-b30c-db9dd90dc227" executionInfo={"status": "ok", "timestamp": 1585483986736, "user_tz": -120, "elapsed": 933, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 867}
lista_numerica = list(range(300,400,2)) ## solo numeri pari
lista_numerica
# + id="zTMNfhK6MwTW" colab_type="code" colab={}
# + id="0liKB8bpMwRP" colab_type="code" colab={}
# + id="mqhAWP2KMwNG" colab_type="code" colab={}
# + id="BepRaRm0zBjh" colab_type="code" colab={}
## DICTIONARY ##
# + id="0cPaQvOJ2rGE" colab_type="code" outputId="e1373f25-7d4c-4058-b77f-591d4f27c325" executionInfo={"status": "ok", "timestamp": 1585478152631, "user_tz": -120, "elapsed": 809, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
dizionario = {'key':'value'}
dizionario
# + id="yunAU-Bs2sH1" colab_type="code" outputId="180615a5-a914-448d-b46f-84e5f389a6b4" executionInfo={"status": "ok", "timestamp": 1585478207023, "user_tz": -120, "elapsed": 798, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
d = {'one':1,'two':2}
d
# + id="LKOfmyOV2sEj" colab_type="code" outputId="0b972dd1-0cbc-416a-94c6-395c0c694425" executionInfo={"status": "ok", "timestamp": 1585478238393, "user_tz": -120, "elapsed": 1653, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
e = {1:133,2:246}
e
# + id="hBMUtncQ30-0" colab_type="code" outputId="816bfb11-167d-4028-c981-ccfc9f98a47e" executionInfo={"status": "ok", "timestamp": 1585478393326, "user_tz": -120, "elapsed": 1197, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
f = {'one':1,2:2,3:'three'}
f.values()
# + id="Ab3_47V42sCT" colab_type="code" outputId="164e4517-2e49-4ce7-cf7e-52b7c1ffa33f" executionInfo={"status": "ok", "timestamp": 1585478302861, "user_tz": -120, "elapsed": 946, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
d.keys()
# + id="qthv7iEr2r_s" colab_type="code" outputId="ba5ad522-9083-4ecc-a22b-8d13cfd7b749" executionInfo={"status": "ok", "timestamp": 1585478304109, "user_tz": -120, "elapsed": 725, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
d.values()
# + id="FC7D9pw72rCn" colab_type="code" colab={}
### TUPLE #### (immutable)
# + id="q_bwwRHN2q_1" colab_type="code" colab={}
tup1 = (1,2,3)
tup2 = (1,4,9)
# + id="D-RgmKRn2q9y" colab_type="code" outputId="7a95b01f-2712-4a5b-e1f5-169f7db7944f" executionInfo={"status": "ok", "timestamp": 1585478511290, "user_tz": -120, "elapsed": 888, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
tup1
# + id="wYRFHQ4A2q7F" colab_type="code" outputId="daf3a677-b8c5-4793-d6ae-e37c795f40f7" executionInfo={"status": "ok", "timestamp": 1585478515806, "user_tz": -120, "elapsed": 1555, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
tup2
# + id="6RZZN63KzBg1" colab_type="code" outputId="f634dcf1-a956-4bc9-b792-8df3db805a68" executionInfo={"status": "ok", "timestamp": 1585478557403, "user_tz": -120, "elapsed": 1026, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
type(tup1)
# + id="LHlBb_Hc4qmE" colab_type="code" colab={}
### convert tuple to list
# + id="JpDo-FVx4qjH" colab_type="code" outputId="f0f70bf7-17b8-4c37-ac68-eeb2412348f9" executionInfo={"status": "ok", "timestamp": 1585478601249, "user_tz": -120, "elapsed": 1284, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista = [tup1,tup2]
lista
# + id="TXio2iRf4qgq" colab_type="code" outputId="4b805297-743a-4314-8a55-7d15a48f9ee8" executionInfo={"status": "ok", "timestamp": 1585478612479, "user_tz": -120, "elapsed": 740, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista[1] # perchè index 0
# + id="564KSXX34qd6" colab_type="code" outputId="2b84bb36-6e9d-49bf-ea91-aa311e8ef91f" executionInfo={"status": "ok", "timestamp": 1585478670402, "user_tz": -120, "elapsed": 1425, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista[0][1] #2
# + id="pmKyDlU14qa4" colab_type="code" outputId="ab0e5c34-f18b-477d-b27d-fd026f8ce3a6" executionInfo={"status": "ok", "timestamp": 1585478696945, "user_tz": -120, "elapsed": 766, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
lista[1][1] #4
# + id="CVGAEL8e5NQK" colab_type="code" colab={}
# + [markdown] id="HjGEN2qnoZyl" colab_type="text"
# #### Array
# + id="my-NpVa3pkdV" colab_type="code" colab={}
import numpy as np
# + [markdown] id="CX1QdDmkxL3v" colab_type="text"
# **Arrays can contain any type of element value (primitive types or objects), but you can't store different types in a single array. You can have an array of integers or an array of strings or an array of arrays**
# + id="V_8jx-OFpeA5" colab_type="code" outputId="7352703d-2750-48fc-ec2d-4eb8b2f57136" executionInfo={"status": "ok", "timestamp": 1585476605835, "user_tz": -120, "elapsed": 757, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
country = np.array(['USA', 'Japan', 'UK', 'Celestopoli', 'India', 'China'])
print(country)
# + id="_tylBJB1mZ2i" colab_type="code" colab={}
x = np.array([2,3,1,0])
# + id="XeZEjJ7irSEC" colab_type="code" outputId="4bdcef7b-7a0f-4032-df81-eb9aded37e25" executionInfo={"status": "ok", "timestamp": 1585476532105, "user_tz": -120, "elapsed": 1545, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
x.shape
# + id="J7gegxVUrbfD" colab_type="code" outputId="a59635de-e64b-48ae-b24c-aceb1dab93b5" executionInfo={"status": "ok", "timestamp": 1585476516233, "user_tz": -120, "elapsed": 1777, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
y = np.array([[2,3,1,0],[1,1,1,1]])
y.shape
# + id="o-sohUYirbaY" colab_type="code" colab={}
# + id="rWsFhi8FmZ0Z" colab_type="code" outputId="8a8f2214-f294-4401-ec2e-014a281d05be" executionInfo={"status": "ok", "timestamp": 1585476516234, "user_tz": -120, "elapsed": 1637, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 51}
np.zeros((2, 3))
# + id="KH_hQyXIr3Iq" colab_type="code" outputId="6026d941-1549-4e8b-e7e1-6b36d9eb6113" executionInfo={"status": "ok", "timestamp": 1585476953230, "user_tz": -120, "elapsed": 1147, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 51}
k =np.ones((2, 3))
k
# + id="T8q23YMisBhH" colab_type="code" outputId="2bebd27c-9400-425f-e1a6-68723f2f7f63" executionInfo={"status": "ok", "timestamp": 1585476956110, "user_tz": -120, "elapsed": 725, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
k.shape
# + id="fN96FKjCyn57" colab_type="code" outputId="bf82815b-8a0a-459d-c2ee-a5ed2452e407" executionInfo={"status": "ok", "timestamp": 1585477031989, "user_tz": -120, "elapsed": 780, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 51}
print(k*5)
#print(k+1)
# + id="VbNJlYREy3Ix" colab_type="code" outputId="117fe841-d535-4427-b1b7-e6e935db5200" executionInfo={"status": "ok", "timestamp": 1585477032498, "user_tz": -120, "elapsed": 673, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 51}
k
# + id="JBV9sqVHmZx2" colab_type="code" outputId="86ae7e59-f978-41ba-fe54-4f77ed9af9d7" executionInfo={"status": "ok", "timestamp": 1585476516238, "user_tz": -120, "elapsed": 1408, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
np.arange(10)
# + id="vUN7G4PNmkVi" colab_type="code" outputId="d524f3b6-7950-4b4e-b844-cd92844994d5" executionInfo={"status": "ok", "timestamp": 1585476516239, "user_tz": -120, "elapsed": 1339, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
np.arange(2, 10, dtype=float) # default strp=1
# + id="lZHAY55AmmLD" colab_type="code" outputId="a9d30643-b30b-4050-ca89-539ad0dbb780" executionInfo={"status": "ok", "timestamp": 1585476516240, "user_tz": -120, "elapsed": 1264, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
np.arange(2, 3, 0.1)
# + id="UtdgGSqvmmIK" colab_type="code" outputId="213cd1b2-c58f-4d92-dde9-e48074eacf8a" executionInfo={"status": "ok", "timestamp": 1585476516241, "user_tz": -120, "elapsed": 1190, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
np.linspace(1., 4., 6)
# + id="Z1sl3B7cmoKI" colab_type="code" colab={}
# + id="vfvlU21Qm0lc" colab_type="code" colab={}
x = np.array([3, 6, 9, 12])
# + id="KstdGHUzm3hA" colab_type="code" outputId="e5162f3d-11d3-4507-fc91-a56c245e0544" executionInfo={"status": "ok", "timestamp": 1585476516243, "user_tz": -120, "elapsed": 993, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
x/3.0
x
# + id="rFhbwv_rm0iM" colab_type="code" outputId="b0f95d59-b643-4fe8-8b53-d9298e74c38f" executionInfo={"status": "ok", "timestamp": 1585476516243, "user_tz": -120, "elapsed": 914, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
print(x)
# + id="KPvz0smpm6TJ" colab_type="code" outputId="57c09321-20eb-409d-f2d1-dca297da79c8" executionInfo={"status": "ok", "timestamp": 1585474658528, "user_tz": -120, "elapsed": 2039, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
type(x)
# + id="kC7AKOpSm8Xv" colab_type="code" colab={}
# + id="SgnjYi9sqoTP" colab_type="code" colab={}
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[9, 8, 7], [6, 5, 4]])
# + id="UXFPyrmjqoP3" colab_type="code" outputId="1a59c433-6bb2-4f14-8df1-c32a9b1939e2" executionInfo={"status": "ok", "timestamp": 1585474901240, "user_tz": -120, "elapsed": 1027, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 85}
c = np.concatenate((a, b))
c
# + id="hqKpA93qqoNX" colab_type="code" outputId="a8b31f21-d6ad-42e7-859e-992dd8a1772c" executionInfo={"status": "ok", "timestamp": 1585475018125, "user_tz": -120, "elapsed": 695, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
c.shape
# + id="lCQ7urJDqoK8" colab_type="code" outputId="59199a7e-c0c8-4047-821a-a5abe6c11506" executionInfo={"status": "ok", "timestamp": 1585476686134, "user_tz": -120, "elapsed": 932, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 51}
np.ones((2, 2), dtype=bool)
# + id="xpzWMD3BqoF9" colab_type="code" outputId="1cb4563e-a429-4e66-ddcb-8a288f041cb0" executionInfo={"status": "ok", "timestamp": 1585476732812, "user_tz": -120, "elapsed": 1364, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 51}
z = np.array([[1, 0, 1], [0, 0, 0]],dtype=bool)
z
# + id="8YTjpJAE1Y99" colab_type="code" outputId="f7b08d6b-c7a3-4d89-c029-f02910e7abf8" executionInfo={"status": "ok", "timestamp": 1585494550814, "user_tz": -120, "elapsed": 557, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
## Conversion to an array:
import numpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
my_list = np.asarray(my_list)
#type(my_list)
my_list
# + id="J4YpAyCm1Y6d" colab_type="code" outputId="4928b108-4e45-4dfa-c662-d8cbabb40ca0" executionInfo={"status": "ok", "timestamp": 1585494572979, "user_tz": -120, "elapsed": 671, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
my_tuple = ([8, 4, 6], [1, 2, 3])
type(my_tuple)
# + id="eAJ7Octx1YxH" colab_type="code" colab={}
my_tuple = np.asarray(my_tuple)
# + [markdown] id="AzZsbhaJogI7" colab_type="text"
# #### List vs Tuple
# + id="DQyB_hucm8VI" colab_type="code" colab={}
####### List vs Array
y = [3, 6, 9, 12]
y/3
##Give the error
# + id="ZaeOwp-Uo17S" colab_type="code" outputId="381541c5-f275-4be0-bfe2-900b848843c7" executionInfo={"status": "ok", "timestamp": 1585474658530, "user_tz": -120, "elapsed": 1851, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
# Sorting a list
numbers = [1, 3, 4, 2]
numbers
# + id="645DpGhbo14N" colab_type="code" outputId="0cb840df-18b6-4e86-f29b-355d3afcfc93" executionInfo={"status": "ok", "timestamp": 1585474658531, "user_tz": -120, "elapsed": 1792, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
numbers.sort()
print(numbers)
# + id="wq2oDQEGpLXf" colab_type="code" colab={}
# + id="EF41mi5Hm8S8" colab_type="code" outputId="13267e69-1ede-4c11-f745-9e85f7c19f6f" executionInfo={"status": "ok", "timestamp": 1585474658532, "user_tz": -120, "elapsed": 1692, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
## String list
a = ["mela", "banana", "arancia"]
a
# + id="Y8kVT1TbnRts" colab_type="code" outputId="79a0e7cd-5c69-4fff-d082-7313aa450074" executionInfo={"status": "ok", "timestamp": 1585474658532, "user_tz": -120, "elapsed": 1635, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
a[0] = "fragola"
a
# + id="teE0_lGlm8Qu" colab_type="code" outputId="4adc1b7f-9217-4860-a7dc-38d76413c332" executionInfo={"status": "ok", "timestamp": 1585474658533, "user_tz": -120, "elapsed": 1557, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
type(a)
# + id="RrRktnsXm8Oo" colab_type="code" outputId="8aef470b-3f18-45bf-b5bc-0b9eb9345421" executionInfo={"status": "ok", "timestamp": 1585474658533, "user_tz": -120, "elapsed": 1488, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
a = ("mela", "banana", "arancia")
a
# + id="PUHnOvnjm8MS" colab_type="code" outputId="c65dba7d-6f8d-49ce-c4a8-98afcb0733fd" executionInfo={"status": "ok", "timestamp": 1585474658534, "user_tz": -120, "elapsed": 1424, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
type(a)
# + id="Nu1pSqnZm8J8" colab_type="code" colab={}
a[0] = "fragola"
## Give the error
# + [markdown] id="ubOqz1GesYHg" colab_type="text"
# #### List recap
# + id="v8ldxFYsm8Hn" colab_type="code" colab={}
a = []
a.append("Hello")
# + id="1NToWTU5skSi" colab_type="code" outputId="ccc86f92-7f82-4de2-f1af-1bd18c3c8065" executionInfo={"status": "ok", "timestamp": 1585494803828, "user_tz": -120, "elapsed": 485, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
a
# + id="sDJZSOY5m8E5" colab_type="code" outputId="7947e26f-ba36-4d3d-c341-0820caa64d80" executionInfo={"status": "ok", "timestamp": 1585494804728, "user_tz": -120, "elapsed": 501, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
a.append("FAV's")
a.append("smart")
a.append("students")
print("The length of this list is: ", len(a))
# + id="SyvFIeC6m8AQ" colab_type="code" outputId="54f66a49-205a-4ff9-c8f6-1b27f4a4fdf1" executionInfo={"status": "ok", "timestamp": 1585494805617, "user_tz": -120, "elapsed": 556, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
type(a)
# + id="ngN3y4K9m79l" colab_type="code" outputId="df1696e3-8e87-4f69-e16a-c952e68ebb24" executionInfo={"status": "ok", "timestamp": 1585494806446, "user_tz": -120, "elapsed": 566, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
a # or print(a)
# + id="jfWmd3qusXUB" colab_type="code" outputId="e2c76240-5409-4f9e-b228-ce35f60c9161" executionInfo={"status": "ok", "timestamp": 1585494807161, "user_tz": -120, "elapsed": 392, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
# remove one element from list
a.remove(a[0]) #remove first element 'Hello'
a
# + [markdown] id="0M7HjWWss5cU" colab_type="text"
# # Matplotlib
# + id="R39h5lins7E1" colab_type="code" colab={}
# %matplotlib inline
# to avoid avery time to write plot.show() -- if you use this code into a .py file, please remove %matplotlib inline
plt.show() at the end of all your plotting commands to have the figure pop up in another window.
# + id="-1buC76ntPD8" colab_type="code" colab={}
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import normal,rand
# + id="o6fLCFt_uCOM" colab_type="code" colab={}
# rand by default, float number [0,1]
# + id="-DkslqxmtVzx" colab_type="code" outputId="90aa7ba3-f412-4965-f1af-94ed59aa91d7" executionInfo={"status": "ok", "timestamp": 1585475613308, "user_tz": -120, "elapsed": 1066, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
a = rand(100)
b = rand(100)
type(a)
# + id="pvKCXMMRtgQX" colab_type="code" outputId="6768bc9a-ec4a-4019-87df-434eb5ce921c" executionInfo={"status": "ok", "timestamp": 1585475710826, "user_tz": -120, "elapsed": 834, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 315}
plt.figure(figsize=(15,5))
plt.scatter(a,b)
#plt.show()
# + id="vm84CyBytWpQ" colab_type="code" outputId="178e47dd-5c50-49e6-c910-ec74f6e937a8" executionInfo={"status": "ok", "timestamp": 1585475909526, "user_tz": -120, "elapsed": 1355, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 265}
a = rand(1000)
b = rand(1000)
plt.scatter(a,b);
#plt.show()
# + id="MEFpkPIctY-T" colab_type="code" outputId="6c67d620-44f9-4dd3-c218-83564df05bbe" executionInfo={"status": "ok", "timestamp": 1585480329380, "user_tz": -120, "elapsed": 824, "user": {"displayName": "T3Lab Vision", "photoUrl": "", "userId": "14779383426442114373"}} colab={"base_uri": "https://localhost:8080/", "height": 34}
print('')
# + id="-kW7cytq_moS" colab_type="code" colab={}
# + id="rbbGI8ih_eTy" colab_type="code" colab={}
| courses/01_Intro/1.1_Intro.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"
# # Working with RNNs
#
# **Authors:** <NAME>, <NAME><br>
# **Date created:** 2019/07/08<br>
# **Last modified:** 2020/04/14<br>
# **Description:** Complete guide to using & customizing RNN layers.
# + [markdown] colab_type="text"
# ## Introduction
#
# Recurrent neural networks (RNN) are a class of neural networks that is powerful for
# modeling sequence data such as time series or natural language.
#
# Schematically, a RNN layer uses a `for` loop to iterate over the timesteps of a
# sequence, while maintaining an internal state that encodes information about the
# timesteps it has seen so far.
#
# The Keras RNN API is designed with a focus on:
#
# - **Ease of use**: the built-in `keras.layers.RNN`, `keras.layers.LSTM`,
# `keras.layers.GRU` layers enable you to quickly build recurrent models without
# having to make difficult configuration choices.
#
# - **Ease of customization**: You can also define your own RNN cell layer (the inner
# part of the `for` loop) with custom behavior, and use it with the generic
# `keras.layers.RNN` layer (the `for` loop itself). This allows you to quickly
# prototype different research ideas in a flexible way with minimal code.
# + [markdown] colab_type="text"
# ## Setup
# + colab_type="code"
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# + [markdown] colab_type="text"
# ## Built-in RNN layers: a simple example
# + [markdown] colab_type="text"
# There are three built-in RNN layers in Keras:
#
# 1. `keras.layers.SimpleRNN`, a fully-connected RNN where the output from previous
# timestep is to be fed to next timestep.
#
# 2. `keras.layers.GRU`, first proposed in
# [Cho et al., 2014](https://arxiv.org/abs/1406.1078).
#
# 3. `keras.layers.LSTM`, first proposed in
# [Hochreiter & Schmidhuber, 1997](https://www.bioinf.jku.at/publications/older/2604.pdf).
#
# In early 2015, Keras had the first reusable open-source Python implementations of LSTM
# and GRU.
#
# Here is a simple example of a `Sequential` model that processes sequences of integers,
# embeds each integer into a 64-dimensional vector, then processes the sequence of
# vectors using a `LSTM` layer.
# + colab_type="code"
model = keras.Sequential()
# Add an Embedding layer expecting input vocab of size 1000, and
# output embedding dimension of size 64.
model.add(layers.Embedding(input_dim=1000, output_dim=64))
# Add a LSTM layer with 128 internal units.
model.add(layers.LSTM(128))
# Add a Dense layer with 10 units.
model.add(layers.Dense(10))
model.summary()
# + [markdown] colab_type="text"
# Built-in RNNs support a number of useful features:
#
# - Recurrent dropout, via the `dropout` and `recurrent_dropout` arguments
# - Ability to process an input sequence in reverse, via the `go_backwards` argument
# - Loop unrolling (which can lead to a large speedup when processing short sequences on
# CPU), via the `unroll` argument
# - ...and more.
#
# For more information, see the
# [RNN API documentation](https://keras.io/api/layers/recurrent_layers/).
# + [markdown] colab_type="text"
# ## Outputs and states
#
# By default, the output of a RNN layer contains a single vector per sample. This vector
# is the RNN cell output corresponding to the last timestep, containing information
# about the entire input sequence. The shape of this output is `(batch_size, units)`
# where `units` corresponds to the `units` argument passed to the layer's constructor.
#
# A RNN layer can also return the entire sequence of outputs for each sample (one vector
# per timestep per sample), if you set `return_sequences=True`. The shape of this output
# is `(batch_size, timesteps, units)`.
# + colab_type="code"
model = keras.Sequential()
model.add(layers.Embedding(input_dim=1000, output_dim=64))
# The output of GRU will be a 3D tensor of shape (batch_size, timesteps, 256)
model.add(layers.GRU(256, return_sequences=True))
# The output of SimpleRNN will be a 2D tensor of shape (batch_size, 128)
model.add(layers.SimpleRNN(128))
model.add(layers.Dense(10))
model.summary()
# + [markdown] colab_type="text"
# In addition, a RNN layer can return its final internal state(s). The returned states
# can be used to resume the RNN execution later, or
# [to initialize another RNN](https://arxiv.org/abs/1409.3215).
# This setting is commonly used in the
# encoder-decoder sequence-to-sequence model, where the encoder final state is used as
# the initial state of the decoder.
#
# To configure a RNN layer to return its internal state, set the `return_state` parameter
# to `True` when creating the layer. Note that `LSTM` has 2 state tensors, but `GRU`
# only has one.
#
# To configure the initial state of the layer, just call the layer with additional
# keyword argument `initial_state`.
# Note that the shape of the state needs to match the unit size of the layer, like in the
# example below.
# + colab_type="code"
encoder_vocab = 1000
decoder_vocab = 2000
encoder_input = layers.Input(shape=(None,))
encoder_embedded = layers.Embedding(input_dim=encoder_vocab, output_dim=64)(
encoder_input
)
# Return states in addition to output
output, state_h, state_c = layers.LSTM(64, return_state=True, name="encoder")(
encoder_embedded
)
encoder_state = [state_h, state_c]
decoder_input = layers.Input(shape=(None,))
decoder_embedded = layers.Embedding(input_dim=decoder_vocab, output_dim=64)(
decoder_input
)
# Pass the 2 states to a new LSTM layer, as initial state
decoder_output = layers.LSTM(64, name="decoder")(
decoder_embedded, initial_state=encoder_state
)
output = layers.Dense(10)(decoder_output)
model = keras.Model([encoder_input, decoder_input], output)
model.summary()
# + [markdown] colab_type="text"
# ## RNN layers and RNN cells
#
# In addition to the built-in RNN layers, the RNN API also provides cell-level APIs.
# Unlike RNN layers, which processes whole batches of input sequences, the RNN cell only
# processes a single timestep.
#
# The cell is the inside of the `for` loop of a RNN layer. Wrapping a cell inside a
# `keras.layers.RNN` layer gives you a layer capable of processing batches of
# sequences, e.g. `RNN(LSTMCell(10))`.
#
# Mathematically, `RNN(LSTMCell(10))` produces the same result as `LSTM(10)`. In fact,
# the implementation of this layer in TF v1.x was just creating the corresponding RNN
# cell and wrapping it in a RNN layer. However using the built-in `GRU` and `LSTM`
# layers enable the use of CuDNN and you may see better performance.
#
# There are three built-in RNN cells, each of them corresponding to the matching RNN
# layer.
#
# - `keras.layers.SimpleRNNCell` corresponds to the `SimpleRNN` layer.
#
# - `keras.layers.GRUCell` corresponds to the `GRU` layer.
#
# - `keras.layers.LSTMCell` corresponds to the `LSTM` layer.
#
# The cell abstraction, together with the generic `keras.layers.RNN` class, make it
# very easy to implement custom RNN architectures for your research.
# + [markdown] colab_type="text"
# ## Cross-batch statefulness
#
# When processing very long sequences (possibly infinite), you may want to use the
# pattern of **cross-batch statefulness**.
#
# Normally, the internal state of a RNN layer is reset every time it sees a new batch
# (i.e. every sample seen by the layer is assumed to be independent of the past). The
# layer will only maintain a state while processing a given sample.
#
# If you have very long sequences though, it is useful to break them into shorter
# sequences, and to feed these shorter sequences sequentially into a RNN layer without
# resetting the layer's state. That way, the layer can retain information about the
# entirety of the sequence, even though it's only seeing one sub-sequence at a time.
#
# You can do this by setting `stateful=True` in the constructor.
#
# If you have a sequence `s = [t0, t1, ... t1546, t1547]`, you would split it into e.g.
#
# ```
# s1 = [t0, t1, ... t100]
# s2 = [t101, ... t201]
# ...
# s16 = [t1501, ... t1547]
# ```
#
# Then you would process it via:
#
# ```python
# lstm_layer = layers.LSTM(64, stateful=True)
# for s in sub_sequences:
# output = lstm_layer(s)
# ```
#
# When you want to clear the state, you can use `layer.reset_states()`.
#
#
# > Note: In this setup, sample `i` in a given batch is assumed to be the continuation of
# sample `i` in the previous batch. This means that all batches should contain the same
# number of samples (batch size). E.g. if a batch contains `[sequence_A_from_t0_to_t100,
# sequence_B_from_t0_to_t100]`, the next batch should contain
# `[sequence_A_from_t101_to_t200, sequence_B_from_t101_to_t200]`.
#
#
#
#
# Here is a complete example:
# + colab_type="code"
paragraph1 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph2 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph3 = np.random.random((20, 10, 50)).astype(np.float32)
lstm_layer = layers.LSTM(64, stateful=True)
output = lstm_layer(paragraph1)
output = lstm_layer(paragraph2)
output = lstm_layer(paragraph3)
# reset_states() will reset the cached state to the original initial_state.
# If no initial_state was provided, zero-states will be used by default.
lstm_layer.reset_states()
# + [markdown] colab_type="text"
# ### RNN State Reuse
# <a id="rnn_state_reuse"></a>
# + [markdown] colab_type="text"
# The recorded states of the RNN layer are not included in the `layer.weights()`. If you
# would like to reuse the state from a RNN layer, you can retrieve the states value by
# `layer.states` and use it as the
# initial state for a new layer via the Keras functional API like `new_layer(inputs,
# initial_state=layer.states)`, or model subclassing.
#
# Please also note that sequential model might not be used in this case since it only
# supports layers with single input and output, the extra input of initial state makes
# it impossible to use here.
# + colab_type="code"
paragraph1 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph2 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph3 = np.random.random((20, 10, 50)).astype(np.float32)
lstm_layer = layers.LSTM(64, stateful=True)
output = lstm_layer(paragraph1)
output = lstm_layer(paragraph2)
existing_state = lstm_layer.states
new_lstm_layer = layers.LSTM(64)
new_output = new_lstm_layer(paragraph3, initial_state=existing_state)
# + [markdown] colab_type="text"
# ## Bidirectional RNNs
#
# For sequences other than time series (e.g. text), it is often the case that a RNN model
# can perform better if it not only processes sequence from start to end, but also
# backwards. For example, to predict the next word in a sentence, it is often useful to
# have the context around the word, not only just the words that come before it.
#
# Keras provides an easy API for you to build such bidirectional RNNs: the
# `keras.layers.Bidirectional` wrapper.
# + colab_type="code"
model = keras.Sequential()
model.add(
layers.Bidirectional(layers.LSTM(64, return_sequences=True), input_shape=(5, 10))
)
model.add(layers.Bidirectional(layers.LSTM(32)))
model.add(layers.Dense(10))
model.summary()
# + [markdown] colab_type="text"
# Under the hood, `Bidirectional` will copy the RNN layer passed in, and flip the
# `go_backwards` field of the newly copied layer, so that it will process the inputs in
# reverse order.
#
# The output of the `Bidirectional` RNN will be, by default, the concatenation of the forward layer
# output and the backward layer output. If you need a different merging behavior, e.g.
# concatenation, change the `merge_mode` parameter in the `Bidirectional` wrapper
# constructor. For more details about `Bidirectional`, please check
# [the API docs](https://keras.io/api/layers/recurrent_layers/bidirectional/).
# + [markdown] colab_type="text"
# ## Performance optimization and CuDNN kernels
#
# In TensorFlow 2.0, the built-in LSTM and GRU layers have been updated to leverage CuDNN
# kernels by default when a GPU is available. With this change, the prior
# `keras.layers.CuDNNLSTM/CuDNNGRU` layers have been deprecated, and you can build your
# model without worrying about the hardware it will run on.
#
# Since the CuDNN kernel is built with certain assumptions, this means the layer **will
# not be able to use the CuDNN kernel if you change the defaults of the built-in LSTM or
# GRU layers**. E.g.:
#
# - Changing the `activation` function from `tanh` to something else.
# - Changing the `recurrent_activation` function from `sigmoid` to something else.
# - Using `recurrent_dropout` > 0.
# - Setting `unroll` to True, which forces LSTM/GRU to decompose the inner
# `tf.while_loop` into an unrolled `for` loop.
# - Setting `use_bias` to False.
# - Using masking when the input data is not strictly right padded (if the mask
# corresponds to strictly right padded data, CuDNN can still be used. This is the most
# common case).
#
# For the detailed list of constraints, please see the documentation for the
# [LSTM](https://keras.io/api/layers/recurrent_layers/lstm/) and
# [GRU](https://keras.io/api/layers/recurrent_layers/gru/) layers.
# + [markdown] colab_type="text"
# ### Using CuDNN kernels when available
#
# Let's build a simple LSTM model to demonstrate the performance difference.
#
# We'll use as input sequences the sequence of rows of MNIST digits (treating each row of
# pixels as a timestep), and we'll predict the digit's label.
# + colab_type="code"
batch_size = 64
# Each MNIST image batch is a tensor of shape (batch_size, 28, 28).
# Each input sequence will be of size (28, 28) (height is treated like time).
input_dim = 28
units = 64
output_size = 10 # labels are from 0 to 9
# Build the RNN model
def build_model(allow_cudnn_kernel=True):
# CuDNN is only available at the layer level, and not at the cell level.
# This means `LSTM(units)` will use the CuDNN kernel,
# while RNN(LSTMCell(units)) will run on non-CuDNN kernel.
if allow_cudnn_kernel:
# The LSTM layer with default options uses CuDNN.
lstm_layer = keras.layers.LSTM(units, input_shape=(None, input_dim))
else:
# Wrapping a LSTMCell in a RNN layer will not use CuDNN.
lstm_layer = keras.layers.RNN(
keras.layers.LSTMCell(units), input_shape=(None, input_dim)
)
model = keras.models.Sequential(
[
lstm_layer,
keras.layers.BatchNormalization(),
keras.layers.Dense(output_size),
]
)
return model
# + [markdown] colab_type="text"
# Let's load the MNIST dataset:
# + colab_type="code"
mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
sample, sample_label = x_train[0], y_train[0]
# + [markdown] colab_type="text"
# Let's create a model instance and train it.
#
# We choose `sparse_categorical_crossentropy` as the loss function for the model. The
# output of the model has shape of `[batch_size, 10]`. The target for the model is an
# integer vector, each of the integer is in the range of 0 to 9.
# + colab_type="code"
model = build_model(allow_cudnn_kernel=True)
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer="sgd",
metrics=["accuracy"],
)
model.fit(
x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1
)
# + [markdown] colab_type="text"
# Now, let's compare to a model that does not use the CuDNN kernel:
# + colab_type="code"
noncudnn_model = build_model(allow_cudnn_kernel=False)
noncudnn_model.set_weights(model.get_weights())
noncudnn_model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer="sgd",
metrics=["accuracy"],
)
noncudnn_model.fit(
x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1
)
# + [markdown] colab_type="text"
# When running on a machine with a NVIDIA GPU and CuDNN installed,
# the model built with CuDNN is much faster to train compared to the
# model that uses the regular TensorFlow kernel.
#
# The same CuDNN-enabled model can also be used to run inference in a CPU-only
# environment. The `tf.device` annotation below is just forcing the device placement.
# The model will run on CPU by default if no GPU is available.
#
# You simply don't have to worry about the hardware you're running on anymore. Isn't that
# pretty cool?
# + colab_type="code"
import matplotlib.pyplot as plt
with tf.device("CPU:0"):
cpu_model = build_model(allow_cudnn_kernel=True)
cpu_model.set_weights(model.get_weights())
result = tf.argmax(cpu_model.predict_on_batch(tf.expand_dims(sample, 0)), axis=1)
print(
"Predicted result is: %s, target result is: %s" % (result.numpy(), sample_label)
)
plt.imshow(sample, cmap=plt.get_cmap("gray"))
# + [markdown] colab_type="text"
# ## RNNs with list/dict inputs, or nested inputs
#
# Nested structures allow implementers to include more information within a single
# timestep. For example, a video frame could have audio and video input at the same
# time. The data shape in this case could be:
#
# `[batch, timestep, {"video": [height, width, channel], "audio": [frequency]}]`
#
# In another example, handwriting data could have both coordinates x and y for the
# current position of the pen, as well as pressure information. So the data
# representation could be:
#
# `[batch, timestep, {"location": [x, y], "pressure": [force]}]`
#
# The following code provides an example of how to build a custom RNN cell that accepts
# such structured inputs.
# + [markdown] colab_type="text"
# ### Define a custom cell that supports nested input/output
# + [markdown] colab_type="text"
# See [Making new Layers & Models via subclassing](/guides/making_new_layers_and_models_via_subclassing/)
# for details on writing your own layers.
# + colab_type="code"
class NestedCell(keras.layers.Layer):
def __init__(self, unit_1, unit_2, unit_3, **kwargs):
self.unit_1 = unit_1
self.unit_2 = unit_2
self.unit_3 = unit_3
self.state_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])]
self.output_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])]
super(NestedCell, self).__init__(**kwargs)
def build(self, input_shapes):
# expect input_shape to contain 2 items, [(batch, i1), (batch, i2, i3)]
i1 = input_shapes[0][1]
i2 = input_shapes[1][1]
i3 = input_shapes[1][2]
self.kernel_1 = self.add_weight(
shape=(i1, self.unit_1), initializer="uniform", name="kernel_1"
)
self.kernel_2_3 = self.add_weight(
shape=(i2, i3, self.unit_2, self.unit_3),
initializer="uniform",
name="kernel_2_3",
)
def call(self, inputs, states):
# inputs should be in [(batch, input_1), (batch, input_2, input_3)]
# state should be in shape [(batch, unit_1), (batch, unit_2, unit_3)]
input_1, input_2 = tf.nest.flatten(inputs)
s1, s2 = states
output_1 = tf.matmul(input_1, self.kernel_1)
output_2_3 = tf.einsum("bij,ijkl->bkl", input_2, self.kernel_2_3)
state_1 = s1 + output_1
state_2_3 = s2 + output_2_3
output = (output_1, output_2_3)
new_states = (state_1, state_2_3)
return output, new_states
def get_config(self):
return {"unit_1": self.unit_1, "unit_2": unit_2, "unit_3": self.unit_3}
# + [markdown] colab_type="text"
# ### Build a RNN model with nested input/output
#
# Let's build a Keras model that uses a `keras.layers.RNN` layer and the custom cell
# we just defined.
# + colab_type="code"
unit_1 = 10
unit_2 = 20
unit_3 = 30
i1 = 32
i2 = 64
i3 = 32
batch_size = 64
num_batches = 10
timestep = 50
cell = NestedCell(unit_1, unit_2, unit_3)
rnn = keras.layers.RNN(cell)
input_1 = keras.Input((None, i1))
input_2 = keras.Input((None, i2, i3))
outputs = rnn((input_1, input_2))
model = keras.models.Model([input_1, input_2], outputs)
model.compile(optimizer="adam", loss="mse", metrics=["accuracy"])
# + [markdown] colab_type="text"
# ### Train the model with randomly generated data
#
# Since there isn't a good candidate dataset for this model, we use random Numpy data for
# demonstration.
# + colab_type="code"
input_1_data = np.random.random((batch_size * num_batches, timestep, i1))
input_2_data = np.random.random((batch_size * num_batches, timestep, i2, i3))
target_1_data = np.random.random((batch_size * num_batches, unit_1))
target_2_data = np.random.random((batch_size * num_batches, unit_2, unit_3))
input_data = [input_1_data, input_2_data]
target_data = [target_1_data, target_2_data]
model.fit(input_data, target_data, batch_size=batch_size)
# + [markdown] colab_type="text"
# With the Keras `keras.layers.RNN` layer, You are only expected to define the math
# logic for individual step within the sequence, and the `keras.layers.RNN` layer
# will handle the sequence iteration for you. It's an incredibly powerful way to quickly
# prototype new kinds of RNNs (e.g. a LSTM variant).
#
# For more details, please visit the [API docs](https://keras.io/api/layers/recurrent_layers/rnn/).
| guides/ipynb/working_with_rnns.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
# ---
# +
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import time
import theano
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
'''
This script generates a sequence of numbers, then passes a portion of them 1 at a time to an LSTM
which is then trained to guess the next number. The LSTM is then tested on its ability to guess the
remaining numbers. A stateful LSTM network is used, so only the most recent time step needs to be
passed in order for the network to learn.
'''
data = [.1 , .1 , .4 , .1 , .2 ]
data = data * 300
numOfPrevSteps = 1 # We will only pass in 1 timestep at a time. The network will guess the next step from the previous step and its internal state.
batchSize = 2 # We are only tracking a single set of features through time per epoch.
featurelen = 1 # Only a single feature is being trained on. If our data was guess a list of numbers instead of 1 number each time, this would be set equal to the length of that list.
testingSize = 100 # 100 data points will be used as a test set
totalTimeSteps = len(data) # Each element in the data represents one timestep of our single feature.
print('Formatting Data')
'''
The data must be converted into a list of matrices to be fed to our network.
In this case, one matrix must be generated for item in the batch. Our batchsize
is 1, so there will only be 1 matrix in this list. The matrix consists of a list
of features. Each row has 1 column per feature. There is 1 column in the matrix
per timestep.
So the final form of the data will be a list containing a single matrix, which has
1 row per timestep, and only 1 column because we only have 1 feature.
'''
X = np.zeros([batchSize, totalTimeSteps , featurelen])
for r in range(totalTimeSteps):
X[0][r] = data[r]
print('Formatted Data ',X)
print('Building model...')
'''
This problem is very simple, so only 2 layers with 10 nodes
each are used. For more complicated data, more numerous and
larger layers will likely be required. This data is very simple and
could probably be trained off of only 1 layer. Remember to set
return_sequences=False for the last hidden layer.
'''
model = Sequential()
model.add(LSTM(10 ,return_sequences=True, batch_input_shape=(batchSize, numOfPrevSteps , featurelen), stateful=True))
model.add(Dropout(0.2))
model.add(LSTM(10 , return_sequences=False,stateful=True))
model.add(Dropout(0.2))
model.add(Dense( featurelen ))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer='rmsprop')
model.reset_states()
print('starting training')
num_epochs = 100
for e in range(num_epochs):
print('epoch - ',e+1)
for i in range(0,totalTimeSteps-testingSize):
model.train_on_batch(X[:, numOfPrevSteps*i:(i+1)*numOfPrevSteps, :], np.reshape(X[:, (i+1)*numOfPrevSteps, :], (batchSize, featurelen)) ) # Train on guessing a single element based on the previous element
model.reset_states()
print('training complete')
print('warming up on training data') # Predict on all training data in order to warm up for testing data
warmupPredictions = []
for i in range(0,totalTimeSteps-testingSize ):
pred = model.predict(X[:, numOfPrevSteps*i:(i+1)*numOfPrevSteps, :] )
warmupPredictions.append(pred)
print('testing network')
predictions = []
testStart = totalTimeSteps-testingSize -1 #We subtract one because we want the last element of the training set to be first element of the testing set
for i in range(testStart,totalTimeSteps-1):
pred = model.predict(X[:, numOfPrevSteps*i:(i+1)*numOfPrevSteps, :] )
predictions.append(pred)
targets = []
for o in range(len(predictions)):
target = X[0][o+testStart+1]
targets.append(target)
guess = predictions[o]
inputs = X[0][o + testStart ]
print('prediction ',guess,'target ',target,'inputs ',inputs)
model.reset_states()
# -
# #Problem 1
# * does the stateful method work for decoding (i.e. does the model start where it left off if sequence is not fed in all at once)
# * can we get varying length input, i.e. not just training batch size?
#Try decoding with just the one step as in training
model.reset_states()
model.predict([np.array([[[ 0.2]],[[ 0.1 ]]],[[[ 0.1]],[[ 0.4 ]]],dtype="float")] )
model.predict([np.array([[[0.1]]],dtype="float")] )
model.predict([np.array([[[0.4]]],dtype="float")] )
model.predict([np.array([[[0.1]]],dtype="float")] )
#Now try with multple inputs and see if for input lengths >2 the results are the same
model.reset_states()
model.predict([np.array([[[0.2],[0.1]]],dtype="float")] )
model.reset_states()
model.predict([np.array([[[0.2],[0.1],[0.1]]],dtype="float")] )
model.reset_states()
model.predict([np.array([[[0.2],[0.1],[0.1],[0.4]]],dtype="float")] )
model.reset_states()
model.predict([np.array([[[0.2],[0.1],[0.1],[0.4],[0.1]]],dtype="float")] )
# #Conclusion 1:
#
# * As result is the same if fed in one by one or as a sequence, we do get statefulness until the reset_states() is called.
# * As a consequence we can use varying length input in prediction.
# #Problem 2:
# * Can we access the activations/state of the hidden layers output from the network at run time?
print(model.layers)
print(len(model.layers))
layer_index = 3 #output from the 4th layer Dropout
get_activations = theano.function([model.layers[0].input], model.layers[layer_index].get_output(), allow_input_downcast=True)
model.reset_states()
get_activations([np.array([[0.2],[0.1],[0.1]],dtype="float")] )
layer_index = 5 #equiv to prediction?
get_activations = theano.function([model.layers[0].input], model.layers[layer_index].get_output(), allow_input_downcast=True)
model.reset_states()
get_activations([np.array([[0.2],[0.1],[0.1]],dtype="float")] )
# #Conclusion 2:
# * Yes we can get the internal activations of any layer during run time- though is it as fast as prediction?
# #Problem 3:
# * speed comparisons, (how much) does stateful slow things down, and is getting the hidden layer activations slower than prediction?
model.reset_states()
tic = time.clock()
print('warming up on training data') # Predict on all training data in order to warm up for testing data
warmupPredictions = []
warm_up_training = []
for i in range(0,totalTimeSteps-testingSize):
warm_up_training.append(X[:, numOfPrevSteps*i:(i+1)*numOfPrevSteps, :])
pred = model.predict(X[:, numOfPrevSteps*i:(i+1)*numOfPrevSteps, :] )
warmupPredictions.append(pred)
print(len(warmupPredictions))
print(time.clock() - tic)
model.reset_states()
tic = time.clock()
layer_index = 5 #equiv to prediction?
get_activations = theano.function([model.layers[0].input], model.layers[layer_index].get_output(), allow_input_downcast=True)
print('warming up on training data') # Predict on all training data in order to warm up for testing data
warmupPredictions2 = []
warm_up_training2 = []
for i in range(0,totalTimeSteps-testingSize):
warm_up_training2.append(X[:, numOfPrevSteps*i:(i+1)*numOfPrevSteps, :])
pred = get_activations(X[:, numOfPrevSteps*i:(i+1)*numOfPrevSteps, :] )
warmupPredictions2.append(pred)
print(len(warmupPredictions2))
print(time.clock() - tic)
for a,b,c,d in zip(warm_up_training,warm_up_training2,warmupPredictions,warmupPredictions2):
print(a,b,a==b,c,d)
#Conclusion 3:
* getting the internal states is faster than the overall prediction
# #Problem 4:
# * can we allow varying batch size in training?
# * or does this not really matter? it does in so far as we'd want to reset-states before consuming a new dialogue and the dialogues won't neccessarily be neatly divisible by the batch size
| deep_disfluency/rnn/dev/Keras_experimentation.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/yukinaga/ai_programming/blob/main/lecture_04/03_neural_network.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="j73Kthjp1iAq"
# # ニューラルネットワーク
# 複数のニューロンからなるニューラルネットワークを構築し、Irisの品種分類を行います。
#
# + [markdown] id="E7AByiMV1jOx"
# ## ● ニューラルネットワークの構築
# ニューロンを層状に並べて、入力層、中間層、出力層とします。
# 入力層は入力を受け取るのみですが、中間層には2つ、出力層には1つのニューロンを配置します。
# + id="zNwYWDe_jZeb"
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris()
iris_data = iris.data
sl_data = iris_data[:100, 0] # SetosaとVersicolor、Sepal length
sw_data = iris_data[:100, 1] # SetosaとVersicolor、Sepal width
# 平均値を0に
sl_ave = np.average(sl_data) # 平均値
sl_data -= sl_ave # 平均値を引く
sw_ave = np.average(sw_data)
sw_data -= sw_ave
# 入力をリストに格納
input_data = []
for i in range(100): # iには0から99までが入る
input_data.append([sl_data[i], sw_data[i]])
# シグモイド関数
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
# ニューロン
class Neuron:
def __init__(self): # 初期設定
self.input_sum = 0.0
self.output = 0.0
def set_input(self, inp):
self.input_sum += inp
def get_output(self):
self.output = sigmoid(self.input_sum)
return self.output
def reset(self):
self.input_sum = 0
self.output = 0
# ニューラルネットワーク
class NeuralNetwork:
def __init__(self): # 初期設定
# 重み
self.w_im = [[4.0, 4.0], [4.0, 4.0]] # 入力:2 ニューロン数:2
self.w_mo = [[1.0, -1.0]] # 入力:2 ニューロン数:1
# バイアス
self.b_m = [2.0, -2.0] # ニューロン数:2
self.b_o = [-0.5] # ニューロン数:1
# 各層の宣言
self.input_layer = [0.0, 0.0]
self.middle_layer = [Neuron(), Neuron()]
self.output_layer = [Neuron()]
def commit(self, input_data): # 実行
# 各層のリセット
self.input_layer[0] = input_data[0] # 入力層は値を受け取るのみ
self.input_layer[1] = input_data[1]
self.middle_layer[0].reset()
self.middle_layer[1].reset()
self.output_layer[0].reset()
# 入力層→中間層
self.middle_layer[0].set_input(self.input_layer[0] * self.w_im[0][0])
self.middle_layer[0].set_input(self.input_layer[1] * self.w_im[0][1])
self.middle_layer[0].set_input(self.b_m[0])
self.middle_layer[1].set_input(self.input_layer[0] * self.w_im[1][0])
self.middle_layer[1].set_input(self.input_layer[1] * self.w_im[1][1])
self.middle_layer[1].set_input(self.b_m[1])
# 中間層→出力層
self.output_layer[0].set_input(self.middle_layer[0].get_output() * self.w_mo[0][0])
self.output_layer[0].set_input(self.middle_layer[1].get_output() * self.w_mo[0][1])
self.output_layer[0].set_input(self.b_o[0])
return self.output_layer[0].get_output()
# ニューラルネットワークのインスタンス
neural_network = NeuralNetwork()
# 実行
st_predicted = [[], []] # Setosa
vc_predicted = [[], []] # Versicolor
for data in input_data:
if neural_network.commit(data) < 0.5:
st_predicted[0].append(data[0]+sl_ave)
st_predicted[1].append(data[1]+sw_ave)
else:
vc_predicted[0].append(data[0]+sl_ave)
vc_predicted[1].append(data[1]+sw_ave)
# 分類結果をグラフ表示
plt.scatter(st_predicted[0], st_predicted[1], label="Setosa")
plt.scatter(vc_predicted[0], vc_predicted[1], label="Versicolor")
plt.legend()
plt.xlabel("Sepal length (cm)")
plt.ylabel("Sepal width (cm)")
plt.title("Predicted")
plt.show()
# + id="cP99nXA-8Tfp"
# コードの練習用
| lecture_04/03_neural_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
# ---
# +
# Concurrent programming with Gevent-
# Gevent provides clean API for a variety of concurrency and network related tasks
# Importing the Gevent package
import gevent
def function1():
print('Running first line- FIRST FUNCTION')
print('----------')
gevent.sleep(0) # Skipping to second function
print('\n --')
print('Explicitly switched to Function1 again!')
def function2():
print('Running first line of- SECOND FUNCTION')
print('**********')
gevent.sleep(0) # Skip back to first one
print('\n **')
print('Explicitly back to Function2!')
def function3():
print('Running first line of- THIRD FUNCTION')
print('##########')
gevent.sleep(0) # Skip back to first one
print('\n ##')
print('Now back to Function3!')
gevent.joinall([
gevent.spawn(function1),
gevent.spawn(function2),
gevent.spawn(function3),
])
# +
# Similarly we can perform such tasks in Input-Output stream
# to take inputs of all functions first and then printing there output
# Lets take more practical example-
# Here we are taking inputs firstly from 2 functions and then giving output-
def square():
print('Taking input of- FIRST FUNCTION ')
print('----------')
x = int(input("Enter a number to SQUARE "))
gevent.sleep(0) # Skipping to second function
xy = x*x
print('Square is-', xy)
def cube():
print('Taking input of- SECOND FUNCTION ')
print('**********')
y = int(input("Enter a number to CUBE "))
gevent.sleep(0) # Skip back to first one
yx = y*y
print('Cube is-', yx)
gevent.joinall([
gevent.spawn(square),
gevent.spawn(cube),
])
# -
| Section 4/#4.1 Simple concurrent programming with gevent.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 ray
import raydp
ray.shutdown()
ray.init(address="127.0.0.1:6379")
configs={
"spark.driver.extraJavaOptions": "--add-opens=java.base/sun.nio.ch=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED",
"spark.jars.packages": "org.apache.hadoop:hadoop-aws:3.2.0,com.amazonaws:aws-java-sdk-s3:1.12.210,com.amazonaws:aws-java-sdk:1.12.210",
"spark.hadoop.fs.s3a.impl": "org.apache.hadoop.fs.s3a.S3AFileSystem",
"spark.hadoop.fs.s3a.aws.credentials.provider": "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider"
}
raydp.stop_spark()
spark = raydp.init_spark(
app_name = "example",
num_executors = 1,
executor_cores = 1,
executor_memory = "1GB",
configs = configs
)
df_from_csv = spark.read.option('delimiter', ',') \
.option('header', True) \
.csv('s3a://dsoaws/ray/datasets/data/train/part-algo-1-womens_clothing_ecommerce_reviews.csv')
# .csv('./data/train/part-algo-1-womens_clothing_ecommerce_reviews.csv')
print(df_from_csv)
df_from_csv.groupBy("sentiment").count().show()
# -
raydp.stop_spark()
| wip/ray/datasets/csv-spark.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
import pandas as pd
import six
import tensorflow as tf
import time
import os
from tqdm import tqdm
import random
import string
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.models import load_model
tf.logging.set_verbosity(tf.logging.INFO)
os.environ["CUDA_VISIBLE_DEVICES"]="0";
# %matplotlib inline
EMBEDDING_DIM = 512
SCRAPED_DATA_PATH = 'data/scraped/descriptions.pickle'
FAKE_NAMES_PATH = 'data/fake/fake_names_12949.pickle'
MODEL_WEIGHTS_PATH = 'data/models_weights/model_description_weights.h5'
# +
# Convert text to arrays of letters represented as integers
def transform(txt, pad_to=None):
# drop any non-ascii characters
output = np.asarray([ord(c) for c in txt if ord(c) < 255], dtype=np.int32)
if pad_to is not None:
output = output[:pad_to]
output = np.concatenate([
np.zeros([pad_to - len(txt)], dtype=np.int32),
output
])
return output
# How the characters will be fed into the model
def training_generator(seq_len=100, batch_size=1024):
"""A generator yields (source, target) arrays for training."""
names_raw, descs_raw = pd.read_pickle(SCRAPED_DATA_PATH)
txt = '\n'.join(descs_raw)
tf.logging.info('Input text [%d] %s', len(txt), txt[:50])
source = transform(txt)
while True:
offsets = np.random.randint(0, len(source) - seq_len, batch_size)
yield (
np.stack([source[idx:idx + seq_len] for idx in offsets]),
np.expand_dims(
np.stack([source[idx + 1:idx + seq_len + 1] for idx in offsets]),
-1),
)
# +
def lstm_model(seq_len=100, batch_size=None, stateful=True):
"""Language model: predict the next word given the current word."""
source = tf.keras.Input(
name='seed', shape=(seq_len,), batch_size=batch_size, dtype=tf.int32)
embedding = tf.keras.layers.Embedding(input_dim=256, output_dim=EMBEDDING_DIM)(source)
lstm_1 = tf.keras.layers.LSTM(EMBEDDING_DIM, stateful=stateful, return_sequences=True)(embedding)
lstm_2 = tf.keras.layers.LSTM(EMBEDDING_DIM, stateful=stateful, return_sequences=True)(lstm_1)
#drop_1 = tf.keras.layers.Dropout(0.2)
predicted_char = tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(256, activation='softmax'))(lstm_2)
model = tf.keras.Model(inputs=[source], outputs=[predicted_char])
#model = tf.keras.utils.multi_gpu_model(model, gpus=2)
model.compile(
optimizer=tf.train.RMSPropOptimizer(learning_rate=0.01),
#optimizer=tf.keras.optimizers.RMSprop(lr=0.01),
loss='sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'])
return model
tf.keras.backend.clear_session()
training_model = lstm_model(seq_len=100, batch_size=1024, stateful=False)
#training_model.load_weights('model_small_chkpt.h5', by_name=True)
checkpoint = ModelCheckpoint('data/models_weights/model_char_DESCS_chkpt.h5',
monitor='sparse_categorical_accuracy',
verbose=1,
save_best_only=True,
mode='max')
early_stopping = EarlyStopping(monitor='sparse_categorical_accuracy',
patience=5,
mode='max')
callbacks_list = [checkpoint,early_stopping]
training_model.fit_generator(
training_generator(seq_len=100, batch_size=1024),
steps_per_epoch=100,
epochs=50,
callbacks = callbacks_list
)
training_model.save_weights(MODEL_WEIGHTS_PATH, overwrite=True)
# -
training_model.summary()
# # Show sample of created wine descriptions
# +
BATCH_SIZE = 5
PREDICT_LEN = 350
EMBEDDING_DIM = 512
MODEL_WEIGHTS_PATH = 'data/models_weights/model_description_weights.h5'
# Keras requires the batch size be specified ahead of time for stateful models.
# We use a sequence length of 1, as we will be feeding in one character at a
# time and predicting the next character.
prediction_model = lstm_model(seq_len=1, batch_size=BATCH_SIZE, stateful=True)
prediction_model.load_weights(MODEL_WEIGHTS_PATH)
# We seed the model with our initial string, copied BATCH_SIZE times
seed_txt = 'This wine tastes like '
seed_txt = ''.join(random.choices(string.ascii_uppercase + string.digits, k=20))
seed = transform(seed_txt)
seed = np.repeat(np.expand_dims(seed, 0), BATCH_SIZE, axis=0)
# First, run the seed forward to prime the state of the model.
prediction_model.reset_states()
for i in range(len(seed_txt) - 1):
prediction_model.predict(seed[:, i:i + 1])
# Now we can accumulate predictions!
predictions = [seed[:, -1:]]
for i in range(PREDICT_LEN):
last_word = predictions[-1]
next_probits = prediction_model.predict(last_word)[:, 0, :]
# sample from our output distribution
next_idx = [
np.random.choice(256, p=next_probits[i])
for i in range(BATCH_SIZE)
]
predictions.append(np.asarray(next_idx, dtype=np.int32))
for i in range(BATCH_SIZE):
print('PREDICTION %d\n\n' % i)
p = [predictions[j][i] for j in range(PREDICT_LEN)]
generated = ''.join([chr(c) for c in p])
print(generated)
print()
assert len(generated) == PREDICT_LEN, 'Generated text too short'
# -
# # Create larger fake wine description list
# +
BATCH_SIZE = 1
PREDICT_LEN = 600
N_PREDICTIONS = 100
EMBEDDING_DIM = 512
MODEL_WEIGHTS_PATH = 'data/models_weights/model_description_weights.h5'
# Keras requires the batch size be specified ahead of time for stateful models.
# We use a sequence length of 1, as we will be feeding in one character at a
# time and predicting the next character.
prediction_model = lstm_model(seq_len=1, batch_size=BATCH_SIZE, stateful=True)
prediction_model.load_weights(MODEL_WEIGHTS_PATH)
predicted_names = pd.read_csv('data/fake/NAMES_v1.csv')
N_PREDICTIONS = len(predicted_names)
fake_NAME = []
fake_DESC = []
for ii in tqdm(range(N_PREDICTIONS)):
# We seed the model with our initial string, copied BATCH_SIZE times
#seed_array = np.zeros(shape=(BATCH_SIZE,))
for i in range(BATCH_SIZE):
seed_txt = predicted_names['name'][ii+i]
seed = transform(seed_txt)
#print(seed.shape)
seed = np.repeat(np.expand_dims(seed, 0), BATCH_SIZE, axis=0)
# First, run the seed forward to prime the state of the model.
prediction_model.reset_states()
for i in range(len(seed_txt) - 1):
prediction_model.predict(seed[:, i:i + 1])
# Now we can accumulate predictions!
predictions = [seed[:, -1:]]
for i in range(PREDICT_LEN):
last_word = predictions[-1]
next_probits = prediction_model.predict(last_word)[:, 0, :]
# sample from our output distribution
next_idx = [
np.random.choice(256, p=next_probits[i])
for i in range(BATCH_SIZE)
]
predictions.append(np.asarray(next_idx, dtype=np.int32))
for i in range(BATCH_SIZE):
#print('PREDICTION %d\n\n' % i)
p = [predictions[j][i] for j in range(PREDICT_LEN)]
generated = ''.join([chr(c) for c in p])
#print(generated)
#print()
gen_list = generated.split('.')[1:-1]
gen_conc = ' '.join(gen_list) + '.'
fake_NAME.append(seed_txt)
fake_DESC.append(gen_conc)
# -
pd.DataFrame({'name' : fake_NAME,
'description' : fake_DESC})\
.to_excel('data/fake/names_descriptions.xlsx', index=False,
engine='xlsxwriter')
| notebooks/4_model_descriptions_v1.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
# ---
#PID VALUES FOR GRAPH
kP = 1.5
kI = 0.005
kD = 100.6
# +
from math import sqrt
MAX_RATE = 10
TIME_STEP = 0.02 #50Hz
DEBUG = False
MAX_ACCELERATION = 3
class dot:
max_rate = MAX_RATE
Max_Acceleration = MAX_ACCELERATION
IDENTIFICATION = False
calc_error = lambda self: self.Target - self.Current
def __init__(self, Current, Target = False):
self.Current = Current
self.Previous = False
self.Target = Target
self.Error = self.Target-self.Current if Target else 0
self.Previous_Error = self.Error
self.Integral = 0
self.Velocity = 0
self.vPrev = 0
self.reachedTargetCount = 0
self.DONE = False
def action(self):
self.movement()
self.checkDone()
def checkDone(self):
if abs(self.Target - self.Current) < 0.05:
self.reachedTargetCount += 1
if self.reachedTargetCount == 10:
self.DONE = True
else:
self.reachedTargetCount = 0
def movement(self):
vDesired = constrainer(self.v_profile(self), self.max_rate)
self.Velocity = Acceleration_Constrainer(self, vDesired)
Delta = TIME_STEP*self.Velocity
self.Previous = self.Current
self.Current = Delta+self.Current
self.vPrev = self.Velocity
def __str__(self):
if self.DONE:
return self.Target
if self.IDENTIFICATION:
return self.IDENTIFICATION + str(round(self.Current, 3))
return str(round(self.Current, 3))
def __repr__(self):
return str(self.__str__())
class PID_controller:
def __init__(self, kP = 1, kI = 0, kD = 0):
self.kP = kP
self.kI = kI
self.kD = kD
def calc(self, dot):
return self.kP*dot.Proportion+self.kI*dot.Integral+self.kD*dot.Derivitive
class Frame:
def __init__(self, dots):
assert type(dots) == list, "dots should be of type list"
self.dots = dots
def addDot(self, dot):
self.dots.append(dot)
def update(self):
for dot in self.dots:
dot.action()
def PID_profile_maker(PID):
assert type(PID) == PID_controller, "PID parameter for function PID_profile_maker should be of type PID"
def v_profile(_dot):
assert type(_dot) == dot, "Dot must be a parameter to v_profile"
_dot.Error = _dot.calc_error()
_dot.Proportion = _dot.Error
_dot.Integral += _dot.Error*TIME_STEP
_dot.Derivitive = (_dot.Error-_dot.Previous_Error)/TIME_STEP
_dot.Previous_Error = _dot.Error
if(DEBUG):
print(str(_dot.Error) + ' ' + str(PID.calc(_dot)))
return PID.calc(_dot)
return v_profile
#TEST CONTROLLERS
P_C = PID_controller()
PI_C = PID_controller(1, 0.001, 0)
PID_C = PID_controller(1, 0.001, 3)
I_C = PID_controller(0, 0.1, 0)
PD_C = PID_controller(1, 0, 0.1)
D_C = PID_controller(0.001, 0 , 1)
controllers = [P_C, PI_C, PID_C, I_C, PD_C, D_C]
v_profiles = [PID_profile_maker(controller) for controller in controllers]
sgn = lambda number: 0 if number == 0 else (1 if number > 0 else -1)
constrainer = lambda number, constraint: min(number, sgn(number)*constraint, key=abs)
def Acceleration_Constrainer(_dot, vDesired, Time_Step = TIME_STEP):
if abs(vDesired - _dot.vPrev) > _dot.Max_Acceleration:
return (sgn(vDesired-_dot.vPrev)*_dot.Max_Acceleration*Time_Step)+_dot.vPrev
return vDesired
bang_bang = lambda error: sgn(error)
proportional = lambda error: error
quadratic = lambda error: sgn(error)*error**2
square_root = lambda error: sgn(error)*sqrt(abs(error))
rate_arr = [bang_bang, proportional, quadratic, square_root]
range_array = lambda start, end, step: [_ * step for _ in range(int(start*step**-1), int(end*step**-1))]
def rate_test():
print("-10, 10" +str([rate(error) for rate in rate_arr for error in range(-10,10)]))
print("-1, 1 s 0.1" +str([rate(error) for rate in rate_arr for error in range_array(-1, 1, 0.1)]))
def test():
dot_array = [dot(0) for _ in range(len(v_profiles))]
for d, v_prof in zip(dot_array, v_profiles):
d.v_profile = v_prof
d.Target = 500
test_frame = Frame(dot_array)
for _ in range(int(TARGET*(1/(TIME_STEP*MAX_RATE)*3))):
print(str(_)+ ': ', dot_array)
test_frame.update()
# -
def getData(v_p, startPosition, endPosition):
data_dot = dot(startPosition)
data_dot.v_profile = v_p
data_dot.Target = endPosition
data_Frame = Frame([data_dot])
dataPos = []
dataVelo = []
watchDog = 0
while(not data_dot.DONE):
dataPos.append(data_dot.Current)
dataVelo.append(data_dot.Velocity)
data_Frame.update()
watchDog += 1
if watchDog>1000000:
data_dot.DONE = True
#print(data_dot.Current)
dataPos.append(data_dot.Current)
dataVelo.append(data_dot.Velocity)
return dataPos, dataVelo
# +
import matplotlib.pyplot as plt
# %matplotlib inline
Target = 100
Data1Pos, Data1Velo = getData(PID_profile_maker(PID_controller(1.0, 0, 0)), 0, Target)
Data2Pos, Data2Velo = getData(PID_profile_maker(PID_controller(1.0, 0.0, 0.0)), 0, Target)
print(len(Data1Pos), len(Data2Pos))
plt.plot(Data1Pos, color='Red')
plt.plot(Data2Pos, color='Green')
plt.plot([Target]*max(len(Data1Pos), len(Data2Pos)), color='Black', linewidth=2, linestyle='dashed', label="target")
# -
Data3Pos, Data3Velo = getData(PID_profile_maker(PID_controller(17.0, 0, 0)), 0, Target)
plt.plot(Data3Pos, color='Red')
plt.plot([Target]*len(Data3Pos), color='Black', linewidth=2, linestyle='dashed', label="target")
Data3Pos, Data3Velo = getData(PID_profile_maker(PID_controller(18.0, 0, 0)), 0, Target)
plt.plot(Data3Pos, color='Red')
plt.plot([Target]*len(Data3Pos), color='Black', linewidth=2, linestyle='dashed', label="target")
Data3Pos, Data3Velo = getData(PID_profile_maker(PID_controller(19, 0, 0)), 0, Target)
plt.plot(Data3Pos, color='Red')
plt.plot([Target]*len(Data3Pos), color='Black', linewidth=2, linestyle='dashed', label="target")
Data3Pos, Data3Velo = getData(PID_profile_maker(PID_controller(21, 0, 0)), 0, Target)
plt.plot(Data3Pos, color='Red')
plt.plot([Target]*len(Data3Pos), color='Black', linewidth=2, linestyle='dashed', label="target")
plt.plot(Data1Velo, color='Red')
plt.plot(Data2Velo, color='Green')
plt.plot([dot.max_rate]*max(len(Data1Pos), len(Data2Pos)), color='Black', linewidth=2, linestyle='dashed', label="target")
plt.plot([-dot.max_rate]*max(len(Data1Pos), len(Data2Pos)), color='Black', linewidth=2, linestyle='dashed', label="target")
| resources/controller_simulation_with_moving_dot.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="e8fac08a-e5a2-4937-976d-04642c77e5f9" _uuid="a3d20745-3597-4070-acb9-a70c64ca447c"
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory
import os
for dirname, _, filenames in os.walk('/kaggle/working'):
for filename in filenames:
print(os.path.join(dirname, filename))
# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All"
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
# + _cell_guid="0f5e563d-1918-431c-8699-d8d6cc0a4c1e" _uuid="0407a5e0-0998-4501-a43b-0bd3d51b1da2"
# !apt install bzip2
# + _cell_guid="ad1ff951-e93f-4793-8735-131ea87266b5" _uuid="2fa2848d-0c26-4477-b6e8-1450924c428c"
# !wget http://wikipedia2vec.s3.amazonaws.com/models/zh/2018-04-20/zhwiki_20180420_300d.txt.bz2
# + _cell_guid="0f726d10-3b7b-4621-a72a-3d433b001941" _uuid="1171b104-f175-4985-b3a0-49129468c677"
# !pip install wikipedia2vec
# + _cell_guid="87fb57f0-07bb-47d3-8826-039675487e8d" _uuid="b7f24b3c-34bd-43f6-8ff7-dd8230690533"
# !bzip2 -d /kaggle/working/zhwiki_20180420_300d.txt.bz2
# + _cell_guid="737e98f8-1ddf-4067-82d1-128ff99933e4" _uuid="9062dbde-a784-4e84-8b79-39e13c2385a2"
from wikipedia2vec import Wikipedia2Vec
model_ext = Wikipedia2Vec.load_text('/kaggle/working/zhwiki_20180420_300d.txt')
# + _cell_guid="9d9fc66a-9ede-4bab-9219-c31fe0ea6f7c" _uuid="89158288-e72e-410e-a9b9-5d5601c9cb80"
def single_comment_words_construct(comment_cut_path):
comment_distinct_words = set([])
with open(comment_cut_path, "r") as f:
idx = 0
while True:
line = f.readline()
if line:
idx += 1
if idx > 0 and idx % 100000 == 0:
print("read num {} set size {}".format(idx, len(comment_distinct_words)))
for w in line.split(" "):
comment_distinct_words.add(w)
else:
break
return comment_distinct_words
# + _cell_guid="c6bc2606-66b0-4f6b-8af0-c44d8561cd58" _uuid="034e4cd3-c8af-44c6-8d42-c4135e9bcb02"
from functools import reduce
from glob import glob
import os
comment_distinct_words = reduce(lambda a, b: a.union(b) ,map(single_comment_words_construct, glob(os.path.join("/kaggle/input/douban-comment-cut-split", "*"))))
# + _cell_guid="58a5c9f9-a661-409f-9603-384cb88b4a40" _uuid="8368370c-136f-459e-a81e-a36d58a62e0c"
from gensim.models import KeyedVectors
KeyedVectors_ext = KeyedVectors(vector_size=model_ext.get_word_vector(u"中国").shape[0])
flush_size = 10000
words, vectors = [], []
def get_wrapper(word_text):
req = None
try:
req = model_ext.get_word_vector(word_text)
except:
pass
return req
for word_text in comment_distinct_words:
vec = get_wrapper(word_text)
if vec is not None:
words.append(word_text)
vectors.append(vec)
if len(words) >= flush_size:
print("flush {} into".format(len(words)))
KeyedVectors_ext.add(words, vectors)
words, vectors = [], []
KeyedVectors_ext.add(words, vectors)
len(KeyedVectors_ext.vocab), len(comment_distinct_words)
# + _cell_guid="9bea28e0-d61b-4660-9f91-40e26cca4c05" _uuid="d80b205e-b50b-4e56-bdcb-c6dad1b21973"
from gensim.models import Word2Vec
w2v_model = Word2Vec(size = KeyedVectors_ext.wv[u"中国"].shape[0], min_count=1)
w2v_model.build_vocab([list(comment_distinct_words)], update=False)
len(w2v_model.wv.vocab)
# + _cell_guid="22a8a56d-a5a4-4473-851c-5cc49bff543e" _uuid="34655db2-c31f-43e2-830c-399145fde348"
for k in KeyedVectors_ext.vocab.keys():
w2v_model.wv.syn0[w2v_model.wv.vocab[k].index] = KeyedVectors_ext.wv[k]
# + _cell_guid="42b40be0-7bcb-4b9e-bc74-735b3126d4c1" _uuid="222cdbc3-ecac-481f-a39f-18843823b81c"
def iter_one_time(w2v_model, file_path = None):
if file_path is None:
file_path = np.random.choice(glob(os.path.join("/kaggle/input/douban-comment-cut-split", "*")))
sentences = read_tiny_file_to_sentences(file_path)
w2v_model.train(sentences, epochs=5, total_examples=len(sentences))
return w2v_model
def read_tiny_file_to_sentences(tiny_file):
with open(tiny_file, "r") as f:
return list(map(lambda x: x.strip().split(" ") ,f.readlines()))
# -
run_times = int(1e6)
save_every = 3
w2v_save_path = "w2v_douban.model"
if os.path.exists(w2v_save_path):
os.remove(w2v_save_path)
for run_time in range(run_times):
w2v_model = iter_one_time(w2v_model)
if run_time > 0 and run_time % save_every == 0:
w2v_model.save(w2v_save_path)
print("save {} to {}".format(run_time ,w2v_save_path))
| .ipynb_checkpoints/fine-tune-douban-w2v-kaggle-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
# ---
from fastai import * # Quick accesss to most common functionality
from fastai.collab import * # Quick accesss to collab filtering functionality
from fastai.docs import * # Access to example data provided with fastai
# ## Collaborative filtering example
# `collab` models use data in a `DataFrame` of user, items, and ratings.
untar_movie_lens()
ML_PATH
ratings = pd.read_csv(ML_PATH/'ratings.csv')
series2cat(ratings, 'userId', 'movieId')
ratings.head()
# That's all we need to create and train a model:
learn = get_collab_learner(ratings, n_factors=50, min_score=0., max_score=5.)
learn.fit_one_cycle(4, 5e-3)
| examples/collab.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
# ---
# ### Variable & Typecast
# Can not start with number or special characters
2name_of_var = 2
x = 2
y = 3
z = x + y
print(z)
x = 'hello'
x
print(x)
x=10
type(x)
print(type(x))
num = 12
name = 'Sam'
a=100
print (a)
type(a)
# +
#Text Type: str
#Numeric Types: int, float, complex
#Sequence Types: list, tuple, range
#Mapping Type: dict
#Set Types: set, frozenset
#Boolean Type: bool
# -
x = 1.1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
# +
x = 1.0
y = 3565622255488735656222554887711711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
# +
import random
print(random.randrange(1,10))
# + jupyter={"outputs_hidden": true}
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
print(type(x))
print(type(y))
print(type(z))
print(z)
# -
a=str("Soumyadip")+"Hello"
print (a)
type(a)
print('My number is: {}, and my name is: {}'.format(num,name))
# Declare a variable and initialize it
f = 0
print(f)
print(type(f))
# re-declaring the variable works
f = 'soumyadip'
print(f)
print(type(f))
a="Soumyadip"
b = str(99)
print(a+(((b))))
#Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
p=x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
print(p)
x = "Python is "
y = "awesome"
z = x + y
print(z)
x = y = z = "Orange"
print(x)
print(y)
print(z)
x = "awesome"
print("Python is " + x)
| Variable.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: micro
# language: python
# name: micro
# ---
# +
################################################################ TO CHANGE ################################################################
# Stolen from Sneha
# FILE PATHS AND FIELDS
path_json = "../comp767_papers_sample.jsonl" #3154 papers
fields = ["title", "abstract", "authors"] # fields to include in training
# TRAINING PARAM
num_topics = 10 # truthfully we want to see 13 topics
chunksize = 2000 # how many docs are processed at a time set to 2000 as default
passes = 20 # how often the model is trained on all the docs set to 20 as default
iterations = 400 # how often do we iterate over each doc set to 400 as default
eval_every = None # Don't evaluate model perplexity, takes too much time.
################################################################ TO CHANGE ################################################################
import json #
import nltk # for preprocessing
nltk.download('wordnet')
from nltk.tokenize import RegexpTokenizer # for tokenization
from nltk.stem.wordnet import WordNetLemmatizer # for lemmatizing
from gensim.corpora import Dictionary # to construct dictionary
from gensim.models import LdaModel # to make LDA model
from pprint import pprint # print output in a readable way
from nltk.util import ngrams
import pyLDAvis.gensim
import numpy as np
with open(path_json) as fp:
papers = [json.loads(line) for line in fp.readlines()]
np.random.seed(767)
# +
def ident(z,*args):
'''dummy identity function'''
if (type(z) is not list):
return z
else:
return ' '.join(z)
def author_iden(z,*args):
return z
def add_ngrams(inpt_sentence, n=[1]):
if inpt_sentence is not None:
out=inpt_sentence
for i in n:
grams=ngrams(inpt_sentence, i)
out.extend(['_'.join(x) for x in grams])
return ' '.join(out)
return ''
def author_ngram(input_list, *args):
return [x.replace(' ', '_').lower() for x in input_list]
def destroy_param(z,*args):
return []
def preprocess_data(all_docs, min_word_len=2,
title_pp=ident,arg_title=None,
abstract_pp=ident, arg_abstract=None,
author_pp=author_iden, arg_author=None):
ret_ar=[]
tokenizer = RegexpTokenizer(r'\w+')
lemmatizer = WordNetLemmatizer()
for doc in all_docs:
#title
title= ' '.join([lemmatizer.lemmatize (x) for x in doc['title'].split(' ')])
#abstract
abstract= [lemmatizer.lemmatize (x) for x in str(doc['abstract']).split(' ')] #list
abstract = [x for x in abstract if len(x)>min_word_len]
# concatenate all strings
representation = title_pp(title,arg_title) + ' \n '+ abstract_pp(abstract,arg_abstract).lower()
# get rid of punctuation & tokenize
representation=tokenizer.tokenize(representation.lower()) + author_pp(doc['authors'],arg_author)
# take out numbers (but not numbers within words)
representation = [token for token in representation if not token.isnumeric()]
# take out words that are at least 3 characters long character
representation = [token for token in representation if len(token) > min_word_len]
# channge code here to not lemmatize ngrams
#representation = [lemmatizer.lemmatize(token) for token in representation]
representation=[x.strip('_') for x in representation]
ret_ar.append(representation)
return ret_ar
# -
# +
def hLDA(documents, layers, pp_args, ret=None, depth=0 ):
print(layers)
# start the with the base model
if len(layers) >1:
if(ret is None):
ret=dict([(i, []) for i in range(len(layers))])
full_data=preprocess_data(documents,**pp_args)
#constructs word to ID mapping
dictionary = Dictionary(full_data)
# filters out words that occur less than 20 times or are in more than 50% of docs
dictionary.filter_extremes(no_below=20, no_above=0.5)
# transform to vectorized form to put in model
corpus = [dictionary.doc2bow(doc) for doc in full_data]
# Finds how many unique tokens we've found and how many docs we have
print('Number of unique tokens: %d' % len(dictionary))
print('Number of documents: %d' % len(corpus))
# index to word dictionary
temp = dictionary[0]
id2word = dictionary.id2token
model = LdaModel(
corpus=corpus,
id2word=id2word,
chunksize=chunksize,
alpha='auto',
eta='auto',
iterations=iterations,
num_topics=layers[0],
passes=passes,
eval_every=eval_every
)
ret[depth].append((model, corpus,dictionary))
#list of list of documents in each topic
topic_sep = [[] for i in range(layers[0])]
for i in range(len(corpus)):
#find out which topic document corresponds to
doc_topic=np.argmax(model.inference(corpus[i:i+1])[0])
#append document to
topic_sep[doc_topic].append(documents[i])
# for each subtopic, we redo hLDA with new parameter
sub_models=[]
for top_docs in topic_sep:
ret=hLDA(top_docs, layers[1:] , pp_args, ret=ret, depth=depth+1)
return ret
# leaves of tree
else:
full_data=preprocess_data(documents,**pp_args)
#constructs word to ID mapping
dictionary = Dictionary(full_data)
# filters out words that occur less than 20 times or are in more than 50% of docs
dictionary.filter_extremes(no_below=20, no_above=0.5)
# transform to vectorized form to put in model
corpus = [dictionary.doc2bow(doc) for doc in full_data]
# Finds how many unique tokens we've found and how many docs we have
print('Number of unique tokens: %d' % len(dictionary))
print('Number of documents: %d' % len(corpus))
# index to word dictionary
temp = dictionary[0]
id2word = dictionary.id2token
model = LdaModel(
corpus=corpus,
id2word=id2word,
chunksize=chunksize,
alpha='auto',
eta='auto',
iterations=iterations,
num_topics=layers[0],
passes=passes,
eval_every=eval_every
)
ret[depth].append((model, corpus,dictionary))
return ret
# +
preprocess_args={'author_pp':author_ngram,
'abstract_pp':add_ngrams,
'arg_abstract':[3]}
print('Test 1')
test_1=hLDA(papers, [2,13], pp_args=preprocess_args, ret=None, depth=0 )
print('Test 2')
test_2=hLDA(papers, [13,2], pp_args=preprocess_args, ret=None, depth=0 )
print('Test 3')
test_3=hLDA(papers, [5,5], pp_args=preprocess_args, ret=None, depth=0 )
print('Test 4')
test_4=hLDA(papers, [2,10], pp_args=preprocess_args, ret=None, depth=0 )
print('Test 5')
test_5=hLDA(papers, [10,2], pp_args=preprocess_args, ret=None, depth=0 )
# -
def eval_Hmodel(hMod, label):
#hmod is dict tree output from hLDA
ret={'ave_level_coherences':[], 'ave_tree_coherence':0}
level_coherence=[]
for key in hMod.keys():
# all models and corresponding corpi at a specific depth
all_forks=hMod[key]
all_coherences=[]
#go through each fork and all corpus in each fork
sub_index=0
for mod, corps,dic in all_forks:
#find average coherence within the fork
avg_topic_coherence = sum([t[1] for t in mod.top_topics(corps)]) / mod.num_topics
all_coherences.append(avg_topic_coherence)
#viz current model
visualisation = pyLDAvis.gensim.prepare(mod, corps, dic)
param_changes= 'depth_'+str(key)+'_topic_'+str(sub_index)+"_atc_"+str(round(avg_topic_coherence,4))
full_output_path = "./hierarchical_visualization/hLDA_Visualization_" + label+ '_' + param_changes + ".html"
pyLDAvis.save_html(visualisation, full_output_path)
mod.save("./hierarchical_models/"+label+"/LDA_" + param_changes + ".model")
sub_index+=1
ave_atc=sum(all_coherences)/len(all_coherences)
ret['ave_level_coherences'].append(ave_atc)
level_coherence.append(ave_atc)
tree_aatc=sum(level_coherence)/len(level_coherence)
ret['ave_tree_coherence']=tree_aatc
return ret
eval_Hmodel(test_1, 'test1')
eval_Hmodel(test_2, 'test2')
eval_Hmodel(test_3, 'test3')
eval_Hmodel(test_4, 'test4')
eval_Hmodel(test_5, 'test5')
| heirarchichal LDA/Hierarchical LDA.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# ---
# <div class="contentcontainer med left" style="margin-left: -50px;">
# <dl class="dl-horizontal">
# <dt>Title</dt> <dd> Box Element</dd>
# <dt>Dependencies</dt> <dd>Matplotlib</dd>
# <dt>Backends</dt> <dd><a href='./Box.ipynb'>Matplotlib</a></dd> <dd><a href='../bokeh/Box.ipynb'>Bokeh</a></dd>
# </dl>
# </div>
import numpy as np
import holoviews as hv
hv.extension('matplotlib')
# A ``Box`` is an annotation that takes a center x-position, a center y-position and a size:
# %%opts Box (linewidth=5 color='red') Image (cmap='gray')
data = np.sin(np.mgrid[0:100,0:100][1]/10.0)
data[np.arange(40, 60), np.arange(20, 40)] = -1
data[np.arange(40, 50), np.arange(70, 80)] = -3
hv.Image(data) * hv.Box(-0.2, 0, 0.25 ) * hv.Box(-0, 0, (0.4,0.9) )
# In addition to these arguments, it supports an optional ``aspect ratio``:
#
# By default, the size argument results in a square such as the small square shown above. Alternatively, the size can be given as the tuple ``(width, height)`` resulting in a rectangle. If you only supply a size value, you can still specify a rectangle by specifying an optional aspect value. In addition, you can also set the orientation (in radians, rotating anticlockwise):
# %%opts Box (linewidth=5 color='purple') Image (cmap='gray')
data = np.sin(np.mgrid[0:100,0:100][1]/10.0)
data[np.arange(30, 70), np.arange(30, 70)] = -3
hv.Image(data) * hv.Box(-0, 0, 0.25, aspect=3, orientation=-np.pi/4)
# For full documentation and the available style and plot options, use ``hv.help(hv.Box).``
| examples/reference/elements/matplotlib/Box.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.utils import to_categorical
import os
import sys
sys.path.insert(0, 'G:\\My Drive\\Colab Notebooks\\MWCNN')
import models.DWT2
from tensorflow.keras.datasets import mnist
from tensorflow.keras.optimizers import Adam, SGD
# +
nb_classes = 10
batch_size = 32
epochs = 30
lr = 1e-4 # learning rate
beta_1 = 0.9 # beta 1 - for adam optimizer
beta_2 = 0.96 # beta 2 - for adam optimizer
epsilon = 1e-7 # epsilon - for adam optimizer
trainFactor = 0.8
input_shape = (28, 28, 1)
# optimizer = Adam(learning_rate=lr, beta_1=beta_1, beta_2=beta_2, epsilon=epsilon)
optimizer = SGD(lr=lr, momentum=beta_1)
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# # Remove images to get smaller dataset
# x_train = x_train[:1000, :, :]
# y_train = y_train[:1000]
# x_test = x_test[:500, :, :]
# y_test = y_test[:500]
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
x_train = x_train.astype('float32') / 255.0
x_train = np.expand_dims(x_train, axis=-1)
x_test = x_test.astype('float32') / 255.0
x_test = np.expand_dims(x_test, axis=-1)
# -
# load DWT db2 model
model = keras.Sequential()
model.add(keras.Input(shape=input_shape))
model.add(keras.layers.Conv2D(32, (3, 3), activation="relu"))
model.add(models.DWT2.DWT(name="db2"))
model.add(keras.layers.Conv2D(64, (3, 3), activation="relu"))
model.add(models.DWT2.DWT(name="haar"))
model.add(keras.layers.Conv2D(128, (3, 3), activation="relu"))
model.add(keras.layers.Dropout(0.5))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(nb_classes, activation="softmax"))
model.summary()
model.compile(loss="categorical_crossentropy",
optimizer=optimizer, metrics=["accuracy"])
history = model.fit(x_train, y_train,
validation_split=1 - trainFactor,
epochs=epochs,
batch_size=batch_size,
verbose=2,
)
# +
import matplotlib.pyplot as plt
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# -
| Development/mnist_models_compare/db2_haar_model.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda root]
# language: python
# name: conda-root-py
# ---
# ## Data Processing
#
# #### The first step in our Deep Learning workflow is to process the BRATS image data. The BRATS data is stored as DICOM images, which is a medical image data format. To access the DICOM images and convert them to numpy we will use the python package `SimpleITK`, which is a popular image processing library.
# +
import SimpleITK as sitk
import os
import numpy as np
import matplotlib
import os
# %matplotlib inline
matplotlib.rcParams.update({'font.size': 24})
import matplotlib.pyplot as plt
#Code to stop notebook from hiding plots with scrolling
from IPython.display import display, Javascript
disable_js = """
IPython.OutputArea.prototype._should_scroll = function(lines) {
return false;
}
"""
def disable_scroll():
display(Javascript(disable_js))
print ("autoscrolling long output is disabled")
disable_scroll()
# -
# ### Image modalities and reading the data
#
# #### Medical imaging can make use of a number of modalities. Here will consider FLAIR-MRI images which stands for Fluid Attenuated Inversion Recovery - Magnetic Resonance Imaging. FLAIR-MRI decreases the signal from fluid in the body, allowing us to better see surrounding structures.
#
# #### We will read the data by gathering a list of file names and feeding these to SimpleITK. Each image is converted to a 3D numpy array with dimensions Width x Height x Depth
# +
data_path = '../datasets/BRATS2015_Training/HGG/'
flairs = []
segs = []
for root,dirs,files in os.walk(data_path):
for f in files:
if 'Flair' in f:
flairs.append(root+'/'+f)
if '.OT' in f:
segs.append(root+'/'+f)
flairs = sorted(flairs)
segs = sorted(segs)
# -
# ### Inspecting the data
#
# #### Before reading all the data we can try plotting it to see what it looks like. Here we look at an image and its associated ground truth segmentation. Since the images are 3D, we can select a particular cross section and visualize it. We can see how the gliomas show up as bright spots in the images.
# +
SLICE = 90
IMAGE_NUMBER = 20
print flairs[IMAGE_NUMBER]
print segs[IMAGE_NUMBER]
im1 = sitk.GetArrayFromImage(sitk.ReadImage(flairs[IMAGE_NUMBER]))
im2 = sitk.GetArrayFromImage(sitk.ReadImage(segs[IMAGE_NUMBER]))
print im1.shape
print im2.shape
plt.figure()
plt.grid('off')
plt.imshow(im1[SLICE,:,:],cmap='gray')
plt.colorbar()
plt.show()
plt.figure()
plt.grid('off')
plt.imshow(im2[SLICE,:,:])
plt.colorbar()
plt.show()
# -
# ### Processing all of the images
#
# #### Now that we know what the images look like we can start processing the entire dataset. We will extract 2D slices from all images and use them to train a 2D fully convolutional neural network.
#
# #### Since the labeled images are typically sparse (few labeled pixels) we separate the dataset into a set where the ground truth images have few labeled pixels (negative set) and a set where the ground truth images have many labeled pixels (positive set). During training we can then sample from both these sets.
#
# #### To store the data we use the HDF5 file format. HDF5 allows us to use the images to train our neural network without loading them all into memory.
#
# #### Finally we also normalize the input image pixel values to be between 0 and 1 and we crop all images to a size of 128 x 128
# +
def process_image_seg(image,segmentation,crop=128):
image = image.astype(float)
image = (image-np.amin(image))/(np.amax(image)-np.amin(image))
N,H,W = image.shape
x = image[:,H/2-crop/2:H/2+crop/2,W/2-crop/2:W/2+crop/2]
y = segmentation[:,H/2-crop/2:H/2+crop/2,W/2-crop/2:W/2+crop/2]
return x,y
def split_positive_negative(images,segmentations):
negative_index = np.where(np.sum(segmentations,axis=(1,2))<1)
positive_index = np.where(np.sum(segmentations,axis=(1,2))>=1)
X_negative = images[negative_index]
Y_negative = segmentations[negative_index]
X_positive = images[positive_index]
Y_positive = segmentations[positive_index]
return X_positive,Y_positive,X_negative,Y_negative
# -
def make_dataset(f,flairs,segs):
i_positive = 0
i_negative = 0
X_p = f.create_dataset("X_positive", (100000, CROP_DIMS,CROP_DIMS),
maxshape=(None, CROP_DIMS,CROP_DIMS))
Y_p = f.create_dataset("Y_positive", (100000, CROP_DIMS,CROP_DIMS),
maxshape=(None, CROP_DIMS,CROP_DIMS))
X_n = f.create_dataset("X_negative", (100000, CROP_DIMS,CROP_DIMS),
maxshape=(None, CROP_DIMS,CROP_DIMS))
Y_n = f.create_dataset("Y_negative", (100000, CROP_DIMS,CROP_DIMS),
maxshape=(None, CROP_DIMS,CROP_DIMS))
for flair_file,seg_file in zip(flairs,segs):
im1 = sitk.GetArrayFromImage(sitk.ReadImage(flair_file))
im2 = sitk.GetArrayFromImage(sitk.ReadImage(seg_file))
x_processed,y_processed = process_image_seg(im1,im2,CROP_DIMS)
x_positive,y_positive,x_negative,y_negative = split_positive_negative(x_processed,
y_processed)
n_positive = len(x_positive)
n_negative = len(x_negative)
X_p[i_positive:i_positive+n_positive] = x_positive
Y_p[i_positive:i_positive+n_positive] = y_positive
X_n[i_negative:i_negative+n_negative] = x_negative
Y_n[i_negative:i_negative+n_negative] = y_negative
i_positive = i_positive + n_positive
i_negative = i_negative + n_negative
X_p.resize(i_positive,axis=0)
Y_p.resize(i_positive,axis=0)
X_n.resize(i_negative,axis=0)
Y_n.resize(i_negative,axis=0)
print 'found {} positive examples and {} negative examples'.format(i_positive,i_negative)
# +
import h5py
CROP_DIMS = 128
f_train = h5py.File('brats_train.h5','w')
f_test = h5py.File('brats_test.h5','w')
make_dataset(f_train,flairs[:-20],segs[:-20])
make_dataset(f_test,flairs[-20:],segs[-20:])
f_train.close()
f_test.close()
# -
| notes-assignments/Week-5/openSAP_ml2_Week_05/week_5_unit_4_data_processing.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
# ---
# +
# Imports
from biocrnpyler import *
from genelet import *
import pylab as plt
import numpy as np
from bokeh.layouts import row
from bokeh.io import export_png
import warnings
import bokeh.io
import bokeh.plotting
# -
# ## CRN for Produce 2N w/ Broccoli Aptamer ##
# +
# Create CRN of Produce 2N
Prod2_off = Species("Prod2")
rR1 = Species("rR1")
Broccoli_Aptamer = Species("BrocApt")
dA1 = Species("dA1" )
DFHBI = Species("DFHBI")
Prod2 = Genelet(Prod2_off, transcript= Broccoli_Aptamer , activator= dA1 , inhibitor= rR1)
M_Prod2 = Mixture(name = "Produce2_test", components = [Prod2], parameter_file = "default_parameters.txt")
repr(M_Prod2)
CRN_Prod2 = M_Prod2.compile_crn()
rxn1 = Reaction([Broccoli_Aptamer,DFHBI], [ComplexSpecies([Broccoli_Aptamer, DFHBI], name = "Flu1")], k = 9.96e-2)
CRN_Prod2.add_reactions([rxn1])
# Write SBML
#CRN_Prod2.write_sbml_file('Prod2_CRN.xml')
print(CRN_Prod2)
# +
# BioSCRAPE simulation of Produce2N with No repressors
io = {"Prod2_OFF": 5000, "dA1": 5000, "rR1": 0, "BrocApt": 0, "DFHBI": 60000,
"protein_RNAseH":0, "protein_RNAP":200}
# For label convenience
x = 'Time (hours)'
y = 'Concentration (uM)'
timepoints = np.linspace(0, 28800, 1000)
R = CRN_Prod2.simulate_with_bioscrape(timepoints, initial_condition_dict = io)
timepoints = timepoints/3600
bokeh.io.output_notebook()
p = bokeh.plotting.figure(
plot_width = 400,
plot_height = 300,
x_axis_label = x,
y_axis_label = y,
)
p.circle(timepoints, R["Prod2_OFF"], legend_label = "OFF Produce 2", color = "orange")
p.circle(timepoints, R["complex_Prod2_ON"], legend_label = "ON Produce 2" , color = "red")
p.legend.click_policy="hide"
p.legend.location = "center_right"
r = bokeh.plotting.figure(
plot_width = 400,
plot_height = 300,
x_axis_label = x,
y_axis_label = y,)
r.circle(timepoints, R["complex_Flu1"], legend_label = "Fluoresence", color = "darkgreen")
r.legend.location = "bottom_right"
s = bokeh.plotting.figure(
plot_width = 400,
plot_height = 300,
x_axis_label = x,
y_axis_label = y,)
s.circle(timepoints, R["BrocApt"], legend_label = "Broc Apt", color = "green")
s.legend.click_policy="hide"
s.legend.location = "top_left"
#### Attempt to track DFHBI dye molecules ####
#### Ended with key error #####
t = bokeh.plotting.figure(
plot_width = 400,
plot_height = 300,
x_axis_label = x,
y_axis_label = y,)
t.circle(timepoints, R["DFHBI"], legend_label = "DFHBI molecules", color = "lightgreen")
t.legend.click_policy="hide"
t.legend.location = "top_right"
bokeh.io.show(row (p, s, r, t))
warnings.filterwarnings("ignore")
# -
# export_png(row (p, s, r, t), filename = "Produce2plots.png")
| Produce_2N/Produce 2N.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# # 更多关于线性回归模型的讨论
# +
import numpy as np
from sklearn import datasets
boston = datasets.load_boston()
X = boston.data
y = boston.target
X = X[y<50.0]
y = y[y<50.0]
# +
from sklearn.linear_model.base import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)
# -
lin_reg.coef_
# 把系数按从小到大排一下序
arg_sort = np.argsort(lin_reg.coef_)
arg_sort
# 看看按照影响程度从小到大排序后的各个系数对应的都是什么属性(名称)
boston.feature_names[arg_sort]
print(boston.DESCR)
| c2_linear_regression/10_More_About_Linear_Regression.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Now You Code In-Class: Boxes Of Flooring
#
# ## The Problem
#
# High's Home Improvement store has hired you to write a mobile app which will estimate the number of boxes of flooring required to cover a room.
#
# Things to note:
#
# - One box of flooring covers 24.5 square feet.
# - You should account for 10% waste in any project. This means you should buy 10% more flooring than you need.
#
# Write a python program which given the length and width measurement of a room will correctly calculate:
#
# - The area of the room in square feet
# - The project area when accounting for an additional 10% waste
# - The number of boxes of flooring required, rounded up to the nearest whole box (since we can only purchase complete boxes).
#
# Example:
#
# ```
# *** Flooring Calculator ***
# Project Name: Mud Room
# Length of room (ft): 3
# Width of room (ft): 6
#
# Calculations....
# Project: Mud Room
# Room Area: ==> 18.0 square ft
# Project Area: 18.0 square ft + 1.8 (10% waste) ==> 19.8 square ft
# Number of boxes at 24.5 square ft: ==> 1
# ```
#
# NOTES:
#
# - Display the output to 1 decimal place.
# - Round up your boxes of flooring to the nearest whole box.
#
# ## Problem Solving Approach: Understanding the Problem By Example
#
# Before you can write code for a solution, you need to ensure you have a very good understanding of the problem. One approach to get a better understanding of the problem is to work through the examples yourself. If you can do the steps yourself, its rather trivial to explain the steps to a computer.
#
#
# ### Example 1
#
# Inputs:
#
# - Length: 5
# - Width: 4
#
# Outputs:
#
# - Room Area: PROMPT 1
# - Project Area: PROMPT 2
# - Number of Boxes: PROMPT 3
# - Boxes Rounded Up to Nearest Whole Number: PROMPT 4
#
#
# ### Example 1
#
# Inputs:
#
# - Length: 7
# - Width: 7
#
# Outputs:
#
# - Room Area: PROMPT 5
# - Project Area: PROMPT 6
# - Number of Boxes: PROMPT 7
# - Boxes Rounded Up to Nearest Whole Number: PROMPT 8
#
# With a good understanding of the problem, we can move on to the problem analysis.
#
#
# ## Part 1: Problem Analysis
#
# Inputs:
#
# - PROMPT 9
#
# Outputs:
#
# - PROMPT 10
#
# Algorithm (Steps in Program):
#
# ```
# PROMPT 11
# ```
#
#
# ### Can you perform each step in Code?
#
# Now review your algorithm. Can you translate each step of the algorithm into a line of code trivially? That which we cannot do, we will need to look up. Problem solving is often a bunch of little problems!
#
# - How do I Display the output to 1 decimal place.
# - Round up your boxes of flooring to the nearest whole box. (How do I round a float up to the next whole number in python?)
# PROMPT 12: Write code here
# ### Making it better !
#
# In reality, each brand of flooring will have different square footage per box. Some brands have 24.5 sqft per box, while others will have a different number.
#
# Copy and paste the code below so you have an additional copy. Re-Write the program so that 24.5 is a variable.
# PROMPT 13
#
# Then re-write the program to ask for the square footage of the box as input.
# PROMPT 14
#
# Code again
# run this code to turn in your work!
from coursetools.submission import Submission
Submission().submit_now()
| content/lessons/02-Variables/SmallGroup-Variables.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# ---
# <div class="contentcontainer med left" style="margin-left: -50px;">
# <dl class="dl-horizontal">
# <dt>Title</dt> <dd> Polygons Element</dd>
# <dt>Dependencies</dt> <dd>Bokeh</dd>
# <dt>Backends</dt> <dd><a href='./Polygons.ipynb'>Bokeh</a></dd> <dd><a href='../matplotlib/Polygons.ipynb'>Matplotlib</a></dd>
# </dl>
# </div>
import numpy as np
import holoviews as hv
hv.extension('bokeh')
# A ``Polygons`` object is similar to a ``Contours`` object except that each supplied path is closed and filled. Just like ``Contours``, an optional ``level`` value may be supplied; the Polygons will then be colored according to the supplied ``cmap``. Non-finite values such as ``np.NaN`` or ``np.inf`` will default to the supplied ``facecolor``.
#
# Polygons with values can be used to build heatmaps with arbitrary shapes.
# %%opts Polygons (cmap='hot' line_color='black' line_width=2)
np.random.seed(35)
hv.Polygons([np.random.rand(4,2)], level=0.5) *\
hv.Polygons([np.random.rand(4,2)], level=1.0) *\
hv.Polygons([np.random.rand(4,2)], level=1.5) *\
hv.Polygons([np.random.rand(4,2)], level=2.0)
# ``Polygons`` without a value are useful as annotation, but also allow us to draw arbitrary shapes.
# +
def rectangle(x=0, y=0, width=1, height=1):
return np.array([(x,y), (x+width, y), (x+width, y+height), (x, y+height)])
(hv.Polygons([rectangle(width=2), rectangle(x=6, width=2)]).opts(style={'fill_color': '#a50d0d'})
* hv.Polygons([rectangle(x=2, height=2), rectangle(x=5, height=2)]).opts(style={'fill_color': '#ffcc00'})
* hv.Polygons([rectangle(x=3, height=2, width=2)]).opts(style={'fill_color': 'cyan'}))
| examples/reference/elements/bokeh/Polygons.ipynb |