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 2
# language: python
# name: python2
# ---
# ### Hello World using Flask
# %pwd
import os
hello_world_script_file = os.path.join(os.path.pardir,'src','models','hello_world_api.py')
# *Note: I'm using IP 0.0.0.0 because I'm hosting in Docker*
# +
# %%writefile $hello_world_script_file
from flask import Flask, request
app = Flask(__name__)
@app.route('/api', methods=['POST'])
def say_hello():
data = request.get_json(force=True)
name = data['name']
return "hello {0}".format(name)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=10001, debug=True)
# -
import json
import requests
url = 'http://127.0.0.1:10001/api'
# create json formatted string
data = json.dumps({'name' : 'bruce'})
r = requests.post(url, data)
print r.text
# ### Machine Leaning API using Flask
# #### Building API
machine_learning_api_script_file = os.path.join(os.path.pardir,'src','models','machine_leaning_api.py')
# +
# %%writefile $machine_learning_api_script_file
from flask import Flask, request
import pandas as pd
import numpy as np
import json
import pickle
import os
app = Flask(__name__)
#load model and scaler files
model_path = os.path.join(os.path.pardir, os.path.pardir,'models')
model_filepath = os.path.join(model_path, 'lr_model.pkl')
scaler_filepath = os.path.join(model_path, 'lr_scaler.pkl')
scaler = pickle.load(open(scaler_filepath))
model = pickle.load(open(model_filepath))
#columns
columns = [ u'Age', u'Fare', u'FamilySize', \
u'IsMother', u'IsMale', u'Deck_A', u'Deck_B', u'Deck_C', u'Deck_D', \
u'Deck_E', u'Deck_F', u'Deck_G', u'Deck_Z', u'Pclass_1', u'Pclass_2', \
u'Pclass_3', u'Title_Lady', u'Title_Master', u'Title_Miss', u'Title_Mr', \
u'Title_Mrs', u'Title_Officer', u'Title_Sir', u'Fare_Bin_very_low', \
u'Fare_Bin_low', u'Fare_Bin_high', u'Fare_Bin_very_high', u'Embarked_C', \
u'Embarked_Q', u'Embarked_S', u'AgeState_Adult', u'AgeState_Child']
@app.route('/api', methods=['POST'])
def make_prediction():
# read json object and covert to json string
data = json.dumps(request.get_json(force=True))
# create pandas dataframe using json string
df = pd.read_json(data)
# extract passengerIds
passenger_ids = df['PassengerId'].ravel()
# actual survived values
actuals = df['Survived'].ravel()
# extract required columns based and convert to matrix
X = df[columns].as_matrix().astype('float')
# transform the input
X_scaled = scaler.transform(X)
# made predictions
predictions = model.predict(X_scaled)
# create response dataframe
df_response = pd.DataFrame({'PassengerId' : passenger_ids, 'Predicted' : predictions, \
'Actual' : actuals})
# return json
return df_response.to_json()
if __name__ == '__main__':
# host flask app at port 10001
app.run(host='0.0.0.0', port=10001, debug=True)
# -
# #### Invoking API using Requests
import os
import pandas as pd
import numpy as np
processed_data_path = os.path.join(os.path.pardir,'data', 'processed')
train_file_path = os.path.join(processed_data_path, 'train.csv')
train_df = pd.read_csv(train_file_path)
survived_passengers = train_df[train_df['Survived'] == 1][:5]
survived_passengers
import requests
def make_api_request(data):
# url for api
url = 'http://127.0.0.1:10001/api'
r = requests.post(url,data)
# return
return r.json()
make_api_request(survived_passengers.to_json())
# compare results
result = make_api_request(train_df.to_json())
df_result = pd.read_json(json.dumps(result))
df_result.head()
# accuracy level
np.mean(df_result.Actual == df_result.Predicted)
|
notebooks/4.0-ak-building-machine-learning-api.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/lmoroney/dlaicourse/blob/master/Course%202%20-%20Part%204%20-%20Lesson%202%20-%20Notebook%20(Cats%20v%20Dogs%20Augmentation).ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] colab_type="text" id="rX8mhOLljYeM"
# ##### Copyright 2019 The TensorFlow Authors.
# + cellView="form" colab_type="code" id="BZSlp3DAjdYf" colab={}
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# + [markdown] colab_type="text" id="gGxCD4mGHHjG"
# Let's start with a model that's very effective at learning Cats v Dogs.
#
# It's similar to the previous models that you have used, but I have updated the layers definition. Note that there are now 4 convolutional layers with 32, 64, 128 and 128 convolutions respectively.
#
# Also, this will train for 100 epochs, because I want to plot the graph of loss and accuracy.
# + id="MJPyDEzOqrKB" colab_type="code" colab={}
# !wget --no-check-certificate \
# https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip \
# -O /tmp/cats_and_dogs_filtered.zip
import os
import zipfile
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
local_zip = '/tmp/cats_and_dogs_filtered.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('/tmp')
zip_ref.close()
base_dir = '/tmp/cats_and_dogs_filtered'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
# Directory with our training cat pictures
train_cats_dir = os.path.join(train_dir, 'cats')
# Directory with our training dog pictures
train_dogs_dir = os.path.join(train_dir, 'dogs')
# Directory with our validation cat pictures
validation_cats_dir = os.path.join(validation_dir, 'cats')
# Directory with our validation dog pictures
validation_dogs_dir = os.path.join(validation_dir, 'dogs')
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy',
optimizer=RMSprop(lr=1e-4),
metrics=['acc'])
# All images will be rescaled by 1./255
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
# Flow training images in batches of 20 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
train_dir, # This is the source directory for training images
target_size=(150, 150), # All images will be resized to 150x150
batch_size=20,
# Since we use binary_crossentropy loss, we need binary labels
class_mode='binary')
# Flow validation images in batches of 20 using test_datagen generator
validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary')
history = model.fit_generator(
train_generator,
steps_per_epoch=100, # 2000 images = batch_size * steps
epochs=100,
validation_data=validation_generator,
validation_steps=50, # 1000 images = batch_size * steps
verbose=2)
# + id="GZWPcmKWO303" colab_type="code" outputId="9dc14530-e7af-4e53-d7c1-71051a60b154" colab={"height": 561}
import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'bo', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training Loss')
plt.plot(epochs, val_loss, 'b', label='Validation Loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
# + [markdown] id="zb81GvNov-Tg" colab_type="text"
# The Training Accuracy is close to 100%, and the validation accuracy is in the 70%-80% range. This is a great example of overfitting -- which in short means that it can do very well with images it has seen before, but not so well with images it hasn't. Let's see if we can do better to avoid overfitting -- and one simple method is to augment the images a bit. If you think about it, most pictures of a cat are very similar -- the ears are at the top, then the eyes, then the mouth etc. Things like the distance between the eyes and ears will always be quite similar too.
#
# What if we tweak with the images to change this up a bit -- rotate the image, squash it, etc. That's what image augementation is all about. And there's an API that makes it easy...
#
# Now take a look at the ImageGenerator. There are properties on it that you can use to augment the image.
#
# ```
# # Updated to do image augmentation
# train_datagen = ImageDataGenerator(
# rotation_range=40,
# width_shift_range=0.2,
# height_shift_range=0.2,
# shear_range=0.2,
# zoom_range=0.2,
# horizontal_flip=True,
# fill_mode='nearest')
# ```
# These are just a few of the options available (for more, see the Keras documentation. Let's quickly go over what we just wrote:
#
# * rotation_range is a value in degrees (0–180), a range within which to randomly rotate pictures.
# * width_shift and height_shift are ranges (as a fraction of total width or height) within which to randomly translate pictures vertically or horizontally.
# * shear_range is for randomly applying shearing transformations.
# * zoom_range is for randomly zooming inside pictures.
# * horizontal_flip is for randomly flipping half of the images horizontally. This is relevant when there are no assumptions of horizontal assymmetry (e.g. real-world pictures).
# * fill_mode is the strategy used for filling in newly created pixels, which can appear after a rotation or a width/height shift.
#
#
# Here's some code where we've added Image Augmentation. Run it to see the impact.
#
# + id="UK7_Fflgv8YC" colab_type="code" colab={}
# !wget --no-check-certificate \
# https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip \
# -O /tmp/cats_and_dogs_filtered.zip
import os
import zipfile
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
local_zip = '/tmp/cats_and_dogs_filtered.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('/tmp')
zip_ref.close()
base_dir = '/tmp/cats_and_dogs_filtered'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
# Directory with our training cat pictures
train_cats_dir = os.path.join(train_dir, 'cats')
# Directory with our training dog pictures
train_dogs_dir = os.path.join(train_dir, 'dogs')
# Directory with our validation cat pictures
validation_cats_dir = os.path.join(validation_dir, 'cats')
# Directory with our validation dog pictures
validation_dogs_dir = os.path.join(validation_dir, 'dogs')
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy',
optimizer=RMSprop(lr=1e-4),
metrics=['acc'])
# This code has changed. Now instead of the ImageGenerator just rescaling
# the image, we also rotate and do other operations
# Updated to do image augmentation
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
test_datagen = ImageDataGenerator(rescale=1./255)
# Flow training images in batches of 20 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
train_dir, # This is the source directory for training images
target_size=(150, 150), # All images will be resized to 150x150
batch_size=20,
# Since we use binary_crossentropy loss, we need binary labels
class_mode='binary')
# Flow validation images in batches of 20 using test_datagen generator
validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary')
history = model.fit_generator(
train_generator,
steps_per_epoch=100, # 2000 images = batch_size * steps
epochs=100,
validation_data=validation_generator,
validation_steps=50, # 1000 images = batch_size * steps
verbose=2)
# + id="bnyRnwopT5aW" colab_type="code" outputId="8cdd3e7b-43f0-44de-ad69-30f08e1c5d4d" colab={"height": 561}
import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'bo', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training Loss')
plt.plot(epochs, val_loss, 'b', label='Validation Loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
# + id="TmYgnrcobqw1" colab_type="code" outputId="556cc15b-fe3d-40c0-a5e7-33c787ce1031" colab={"height": 3731}
# !wget --no-check-certificate \
# https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip \
# -O /tmp/cats_and_dogs_filtered.zip
import os
import zipfile
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
local_zip = '/tmp/cats_and_dogs_filtered.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('/tmp')
zip_ref.close()
base_dir = '/tmp/cats_and_dogs_filtered'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
# Directory with our training cat pictures
train_cats_dir = os.path.join(train_dir, 'cats')
# Directory with our training dog pictures
train_dogs_dir = os.path.join(train_dir, 'dogs')
# Directory with our validation cat pictures
validation_cats_dir = os.path.join(validation_dir, 'cats')
# Directory with our validation dog pictures
validation_dogs_dir = os.path.join(validation_dir, 'dogs')
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy',
optimizer=RMSprop(lr=1e-4),
metrics=['acc'])
# This code has changed. Now instead of the ImageGenerator just rescaling
# the image, we also rotate and do other operations
# Updated to do image augmentation
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
test_datagen = ImageDataGenerator(rescale=1./255)
# Flow training images in batches of 20 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
train_dir, # This is the source directory for training images
target_size=(150, 150), # All images will be resized to 150x150
batch_size=20,
# Since we use binary_crossentropy loss, we need binary labels
class_mode='binary')
# Flow validation images in batches of 20 using test_datagen generator
validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary')
history = model.fit_generator(
train_generator,
steps_per_epoch=100, # 2000 images = batch_size * steps
epochs=100,
validation_data=validation_generator,
validation_steps=50, # 1000 images = batch_size * steps
verbose=2)
# + id="I3yFv2Jpb2Dl" colab_type="code" outputId="fc13860a-d65f-4836-ad41-79b8c45588eb" colab={"height": 561}
import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'bo', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training Loss')
plt.plot(epochs, val_loss, 'b', label='Validation Loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
|
Tensorflow/Course 2 - Part 4 - Lesson 2 - Notebook (Cats v Dogs Augmentation).ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# !git clone https://github.com/omriallouche/text_classification_from_zero_to_hero.git --depth 1
import os
os.chdir('text_classification_from_zero_to_hero/notebooks')
# +
import sys, os
from pathlib import Path
def locate(fname):
"""Search file in google drive"""
if os.path.exists(fname):
return fname
try:
return next(filter(lambda p: str(p).endswith(fname),
Path("/content/drive/My Drive/nlpday_content").glob('**/*.*')))
except StopIteration:
raise FileNotFoundError(fname)
if 'google.colab' in sys.modules:
from google.colab import drive
drive.mount('/content/drive/')
__dir__ = "/content/drive/My Drive/nlpday_content/zero2hero/"
sys.path.append(__dir__ + 'src')
# -
# # Training our own Word Vectors
# It's very easy to train our own word vectors based on our custom task. This can lead to an increase in performance if our domain is different from that used for training common word vectors (usually Wikipedia).
#
# We will train word vectors using the Gensim package:
# +
# # !pip install gensim
# -
import pandas as pd
df = pd.read_csv('../data/train.csv')
import gensim
w2v = gensim.models.Word2Vec([s.split() for s in df['text'].values],
iter=500,
sg=1,
min_count=1,
size=50,
window=3,
workers=7)
w2v.init_sims(replace=True) # frees memory of word vectors but prevents further training
def evaluate_words(words_to_check = ['love', 'hate']):
for word in words_to_check:
print(word, ' -> ')
try:
print('\n'.join(['\t{} ({:.2f}), '.format(tup[0], tup[1]) for tup in w2v.wv.similar_by_word(word, topn=5)]))
except:
pass
print()
evaluate_words(words_to_check=['gun', 'inning', 'win', 'arab', 'problem'])
|
notebooks/2a_optional_train_word_embeddings.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Qiskit v0.31.0 (ipykernel)
# language: python
# name: python3
# ---
# + [markdown] slideshow={"slide_type": "slide"}
# ## IBM Quantum Challenge Fall 2021
# # Challenge 1: Optimizing your portfolio with quantum computers
#
# <div class="alert alert-block alert-info">
#
# We recommend that you switch to **light** workspace theme under the Account menu in the upper right corner for optimal experience.
# -
# ## Introduction: What is portfolio optimization?
# Portfolio optimization is a crucial process for anyone who wants to maximize returns from their investments.
# Investments are usually a collection of so-called assets (stock, credits, bonds, derivatives, calls, puts, etc..) and this collection of assets is called a **portfolio**.
# <center><img src="resources/ex1-01.png" width="270"></center>
# The goal of portfolio optimization is to minimize risks (financial loss) and maximize returns (financial gain). But this process is not as simple as it may seem. Gaining high returns with little risk is indeed too good to be true. Risks and returns usually have a trade-off relationship which makes optmizing your portfolio a little more complicated. As Dr. <NAME> states in his Moderbn Portfolio Theory he created in 1952, "risk is an inherrent part of higher reward."
# **Modern Portfolio Theory (MPT)** <br>
# An investment theory based on the idea that investors are risk-averse, meaning that when given two portfolios that offer the same expected return they will prefer the less risky one. Investors can construct portfolios to maximize expected return based on a given level of market risk, emphasizing that risk is an inherent part of higher reward. It is one of the most important and influential economic theories dealing with finance and investment. Dr. <NAME> created the modern portfolio theory (MPT) in 1952 and won the Nobel Prize in Economic Sciences in 1990 for it. <br><br>
# **Reference:** [<b>Modern Portfolio Theory<i>](https://en.wikipedia.org/wiki/Modern_portfolio_theory)
# ## Challenge
#
# <div class="alert alert-block alert-success">
#
# **Goal**
#
# Portfolio optimization is a crucial process for anyone who wants to maximize returns from their investments. In this first challenge, you will learn some of the basic theory behind portfolio optimization and how to formulate the problem so it can be solved by quantum computers. During the process, you will learn about Qiskit's Finance application class and methods to solve the problem efficiently.
#
# 1. **Challenge 1a**: Learn how to use the PortfolioOptimization() method in Qiskit's Finance module to convert the portfolio optimization into a quadratic program.
#
# 2. **Challenge 1b**: Implement VQE to solve a four-stock portfolio optimization problem based on the instance created in challenge 1a.
#
#
# 3. **Challenge 1c**: Solve the same problem using QAOA with three budgets and double weights for any of the assets in your portfolio.
#
# </div>
# <div class="alert alert-block alert-info">
#
# Before you begin, we recommend watching the [**Qiskit Finance Demo Session with Julien Gacon**](https://youtu.be/UtMVoGXlz04?t=2022) and check out the corresponding [**demo notebook**](https://github.com/qiskit-community/qiskit-application-modules-demo-sessions/tree/main/qiskit-finance) to learn about Qiskit's Finance module and its appications in portfolio optimization.
#
# </div>
# + [markdown] slideshow={"slide_type": "slide"}
# ## 1. Finding the efficient frontier
# The Modern portfolio theory (MPT) serves as a general framework to determine an ideal portfolio for investors. The MPT is also referred to as mean-variance portfolio theory because it assumes that any investor will choose the optimal portfolio from the set of portfolios that
# - Maximizes expected return for a given level of risk; and
# - Minimizes risks for a given level of expected returns.
#
# The figure below shows the minimum variance frontier of modern portfolio theory where the horizontal axis shows the risk and the vertical axis shows expected return.
#
# <center><img src="resources/ex1-02.png" width="600"></center>
#
# Consider a situation where you have two stocks to choose from: A and B. You can invest your entire wealth in one of these two stocks. Or you can invest 10% in A and 90% in B, or 20% in A and 80% in B, or 70% in A and 30% in B, etc ... There is a huge number of possible combinations and this is a simple case when considering two stocks. Imagine the different combinations you have to consider when you have thousands of stocks.
#
# The minimum variance frontier shows the minimum variance that can be achieved for a given level of expected return. To construct a minimum-variance frontier of a portfolio:
#
# - Use historical data to estimate the mean, variance of each individual stock in the portfolio, and the correlation of each pair of stocks.
# - Use a computer program to find out the weights of all stocks that minimize the portfolio variance for each pre-specified expected return.
# - Calculate the expected returns and variances for all the minimum variance portfolios determined in step 2 and then graph the two variables.
#
# Investors will never want to hold a portfolio below the minimum variance point. They will always get higher returns along the positively sloped part of the minimum-variance frontier. And the positively sloped part of the minimum-variance frontier is called the **efficient frontier**.
#
# The **efficient frontier** is where the optimal portfolios are. And it helps narrow down the different portfolios from which the investor may choose.
#
# + [markdown] slideshow={"slide_type": "slide"}
# ## 2. Goal Of Our Exercise
# The goal of this exercise is to find the efficent frontier for an inherent risk using a quantum approach. We will use Qiskit's Finance application modules to convert our portfolio optimization problem into a quadratic program so we can then use variational quantum algorithms such as VQE and QAOA to solve our optimization problem. Let's first start by looking at the actual problem we have at hand.
# + [markdown] slideshow={"slide_type": "fragment"}
# ## 3. Four-Stock Portfolio Optimization Problem
#
# Let us consider a portfolio optimization problem where you have a total of four assets (e.g. STOCK0, STOCK1, STOCK2, STOCK3) to choose from. Your goal is to find out a combination of two assets that will minimize the tradeoff between risk and return which is the same as finding the efficient frontier for the given risk.
# + [markdown] slideshow={"slide_type": "slide"}
# ## 4. Formulation
#
# How can we formulate this problem?<br>
# The function which describes the efficient frontier can be formulated into a quadratic program with linear constraints as shown below. <br>
# The terms that are marked in red are associated with risks and the terms in blue are associated with returns.
# You can see that our goal is to minimize the tradeoff between risk and return. In general, the function we want to optimize is called an objective function. <br> <br>
#
# <div align="center"> <font size=5em >$\min_{x \in \{0, 1\}^n}: $</font> <font color='red', size=5em >$q x^n\Sigma x$</font> - <font color='blue', size=5em>$\mu^n x$</font> </div>
#
# <div align="center"> <font size=5em >$subject$</font> <font size=5em >$to: 1^n x = B$</font> </div>
#
#
# - <font size=4em >$x$</font> indicates asset allocation.
# - <font size=4em >$Σ$</font> (sigma) is a covariance matrix.
# A covariance matrix is a useful math concept that is widely applied in financial engineering. It is a statistical measure of how two asset prices are varying with respect to each other. When the covariance between two stocks is high, it means that one stock experiences heavy price movements and is volatile if the price of the other stock changes.
# - <font size=4em >$q$</font> is called a risk factor (risk tolerance), which is an evaluation of an individual's willingness or ability to take risks. For example, when you use the automated financial advising services, the so-called robo-advising, you will usually see different risk tolerance levels. This q value is the same as such and takes a value between 0 and 1.
# - <font size=4em >$𝝁$</font> (mu) is the expected return and is something we obviously want to maximize.
# - <font size=4em >$n$</font> is the number of different assets we can choose from
# - <font size=4em >$B$</font> stands for Budget.
# And budget in this context means the number of assets we can allocate in our portfolio.
#
#
#
# #### Goal:
# Our goal is to find the **x** value. The x value here indicates which asset to pick (𝑥[𝑖]=1) and which not to pick (𝑥[𝑖]=0).
#
#
# #### Assumptions:
# We assume the following simplifications:
# - all assets have the same price (normalized to 1),
# - the full budget $B$ has to be spent, i.e. one has to select exactly $B$ assets.
# - the equality constraint $1^n x = B$ is mapped to a penalty term $(1^n x - B)^2$ which is scaled by a parameter and subtracted from the objective function.
#
# + [markdown] slideshow={"slide_type": "slide"}
# ## Step 1. Import necessary libraries
# + slideshow={"slide_type": "fragment"}
#Let us begin by importing necessary libraries.
from qiskit import Aer
from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import *
from qiskit.circuit.library import TwoLocal
from qiskit.utils import QuantumInstance
from qiskit.utils import algorithm_globals
from qiskit_finance import QiskitFinanceError
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import *
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.applications import OptimizationApplication
from qiskit_optimization.converters import QuadraticProgramToQubo
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
import datetime
import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
warnings.simplefilter("ignore", SymPyDeprecationWarning)
# + [markdown] slideshow={"slide_type": "slide"}
# ## Step 2. Generate time series data (Financial Data)
# Let's first generate a random time series financial data for a total number of stocks n=4. We use RandomDataProvider for this. We are going back in time and retrieve financial data from November 5, 1955 to October 26, 1985.
# + slideshow={"slide_type": "fragment"}
# Set parameters for assets and risk factor
num_assets = 4 # set number of assets to 4
q = 0.5 # set risk factor to 0.5
budget = 2 # set budget as defined in the problem
seed = 132 #set random seed
# Generate time series data
stocks = [("STOCK%s" % i) for i in range(num_assets)]
data = RandomDataProvider(tickers=stocks,
start=datetime.datetime(1955,11,5),
end=datetime.datetime(1985,10,26),
seed=seed)
data.run()
# + slideshow={"slide_type": "slide"}
# Let's plot our finanical data
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.xlabel('days')
plt.ylabel('stock value')
plt.show()
# + [markdown] slideshow={"slide_type": "slide"}
# <div id='problem'></div>
# <div class="alert alert-block alert-danger">
#
# **WARNING** Please do not change the start/end dates that are given to the RandomDataProvider in this challenge. Otherwise, your answers will not be graded properly.
# </div>
# + [markdown] slideshow={"slide_type": "slide"}
# ## Step 3. Quadratic Program Formulation
#
# Let's generate the expected return first and then the covariance matrix which are both needed to create our portfolio.
# + [markdown] slideshow={"slide_type": "fragment"}
# ### Expected Return μ
# Expected return of a portfolio is the anticipated amount of returns that a portfolio may generate, making it the mean (average) of the portfolio's possible return distribution.
# For example, let's say stock A, B and C each weighted 50%, 20% and 30% respectively in the portfolio. If the expected return for each stock was 15%, 6% and 9% respectively, the expected return of the portfolio would be:
#
#
# <div align="center"> μ = (50% x 15%) + (20% x 6%) + (30% x 9%) = 11.4% </div>
#
# For the problem data we generated earlier, we can calculate the expected return over the 30 years period from 1955 to 1985 by using the following `get_period_return_mean_vector()` method which is provided by Qiskit's RandomDataProvider.
# + slideshow={"slide_type": "fragment"}
#Let's calculate the expected return for our problem data
mu = data.get_period_return_mean_vector() # Returns a vector containing the mean value of each asset's expected return.
print(mu)
# + [markdown] slideshow={"slide_type": "slide"}
# ### Covariance Matrix Σ
# Covariance Σ is a statistical measure of how two asset's mean returns vary with respect to each other and helps us understand the amount of risk involved from an investment portfolio's perspective to make an informed decision about buying or selling stocks.
#
# If you have 'n' stocks in your porfolio, the size of the covariance matrix will be n x n.
# Let us plot the covariance marix for our 4 stock portfolio which will be a 4 x 4 matrix.
# + slideshow={"slide_type": "subslide"}
# Let's plot our covariance matrix Σ(sigma)
sigma = data.get_period_return_covariance_matrix() #Returns the covariance matrix of the four assets
print(sigma)
fig, ax = plt.subplots(1,1)
im = plt.imshow(sigma, extent=[-1,1,-1,1])
x_label_list = ['stock3', 'stock2', 'stock1', 'stock0']
y_label_list = ['stock3', 'stock2', 'stock1', 'stock0']
ax.set_xticks([-0.75,-0.25,0.25,0.75])
ax.set_yticks([0.75,0.25,-0.25,-0.75])
ax.set_xticklabels(x_label_list)
ax.set_yticklabels(y_label_list)
plt.colorbar()
plt.clim(-0.000002, 0.00001)
plt.show()
# + [markdown] slideshow={"slide_type": "subslide"}
# The left-to-right diagonal values (yellow boxes in the figure below) show the relation of a stock with 'itself'. And the off-diagonal values show the deviation of each stock's mean expected return with respect to each other. A simple way to look at a covariance matrix is:
#
# - If two stocks increase and decrease simultaneously then the covariance value will be positive.
# - If one increases while the other decreases then the covariance will be negative.
#
# <center><img src= "resources/ex1-05.png" width="370"></center>
#
# You may have heard the phrase "Don't Put All Your Eggs in One Basket." If you invest in things that always move in the same direction, there will be a risk of losing all your money at the same time. Covariance matrix is a nice measure to help investors diversify their assets to reduce such risk.
# + [markdown] slideshow={"slide_type": "slide"}
# Now that we have all the values we need to build our portfolio for optimization, we will look into Qiskit's Finance application class that will help us contruct the quadratic program for our problem.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Qiskit Finance application class
#
# In Qiskit, there is a dedicated [`PortfolioOptimization`](https://qiskit.org/documentation/finance/stubs/qiskit_finance.applications.PortfolioOptimization.html#qiskit_finance.applications.PortfolioOptimization) application to construct the quadratic program for portfolio optimizations.
#
# PortfolioOptimization class creates a porfolio instance by taking the following **five arguments** then converts the instance into a quadratic program.
#
# Arguments of the PortfolioOptimization class:
# - expected_returns
# - covariances
# - risk_factor
# - budget
# - bounds
#
# Once our portfolio instance is converted into a quadratic program, then we can use quantum variational algorithms suchs as Variational Quantum Eigensolver (VQE) or the Quantum Approximate Optimization Algorithm (QAOA) to find the optimal solution to our problem.<br>
#
# We already obtained expected_return and covariances from Step 3 and have risk factor and budget pre-defined. So, let's build our portfolio using the [`PortfolioOptimization`](https://qiskit.org/documentation/finance/stubs/qiskit_finance.applications.PortfolioOptimization.html#qiskit_finance.applications.PortfolioOptimization) class.
#
# + [markdown] slideshow={"slide_type": "slide"}
# ## Challenge 1a: Create the portfolio instance using PortfolioOptimization class
# <div id='u-definition'></div>
# <div class="alert alert-block alert-success">
#
# **Challenge 1a** <br>
# Complete the code to generate the portfolio instance using the [**PortfolioOptimization**](https://qiskit.org/documentation/finance/stubs/qiskit_finance.applications.PortfolioOptimization.html#qiskit_finance.applications.PortfolioOptimization) class. Make sure you use the **five arguments** and their values which were obtained in the previos steps and convert the instance into a quadratic program **qp**.
# </div>
#
# <div id='problem'></div>
# <div class="alert alert-block alert-info">
#
# **Note:** A binary list [1. 1. 0. 0.] indicates a portfolio consisting STOCK2 and STOCK3.
#
# </div>
# + slideshow={"slide_type": "fragment"}
##############################
# Provide your code here
portfolio = PortfolioOptimization(expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget)
qp = portfolio.to_quadratic_program()
##############################
print(qp)
# -
# If you were able to successfully generate the code, you should see a standard representation of the formulation of our qudratic program.
# Check your answer and submit using the following code
from qc_grader import grade_ex1a
grade_ex1a(qp)
# ## Minimum Eigen Optimizer
#
# Interestingly, our portfolio optimization problem can be solved as a ground state search of a Hamiltonian. You can think of a Hamiltonian as an energy function representing the total energy of a physical system we want to simulate such as a molecule or a magnet. The physical system can be further represented by a mathemetical model called an [**Ising model**](https://en.wikipedia.org/wiki/Ising_model) which gives us a framework to convert our binary variables into a so called spin up (+1) or spin down (-1) state.
#
# When it comes to applyting the optimization algorithms, the algorithms usually require problems to satisfy certain criteria to be applicable. For example, variational algorithms such as VQE and QAOA can only be applied to [**Quadratic Unconstrained Binary Optimization (QUBO)**](https://en.wikipedia.org/wiki/Quadratic_unconstrained_binary_optimization) problems, thus Qiskit provides converters to automatically map optimization problems to these different formats whenever possible.
#
# <center><img src= "resources/ex1-04.png" width="700"></center>
#
# Solving a QUBO is equivalent to finding a ground state of a Hamiltonian. And the Minimum Eigen Optimizer translates the Quadratic Program to a Hamiltonian, then calls a given Mimimum Eigensolver such as VQE or QAOA to compute the ground states and returns the optimization results for us.
#
# This approach allows us to utilize computing ground states in the context of solving optimization problems as we will demonstrate in the next step in our challenge exercise.
# ## Step 5. Solve with classical optimizer as a reference
# Lets solve the problem. First classically...
#
# We can now use the Operator we built above without regard to the specifics of how it was created. We set the algorithm for the NumPyMinimumEigensolver so we can have a classical reference. Backend is not required since this is computed classically not using quantum computation. The result is returned as a dictionary.
# +
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print(result)
# -
# The optimal value indicates your asset allocation.
# ## Challenge1b: Solution using VQE
#
# **Variational Quantum Eigensolver (VQE)** is a classical-quantum hybrid algorithm which outsources some of the processing workload to a classical computer to efficiently calculate the ground state energy (lowest energy) of a [**Hamiltonian**](https://en.wikipedia.org/wiki/Hamiltonian_(quantum_mechanics)). As we discussed earlier, we can reformulate the quadratic program as a ground state energy search to be solved by [**VQE**](https://qiskit.org/documentation/stubs/qiskit.algorithms.VQE.html) where the ground state corresponds to the optimal solution we are looking for. In this challenge exercise, you will be asked to find the optimal solution using VQE. <br>
#
#
# <div id='u-definition'></div>
# <div class="alert alert-block alert-success">
#
# **Challenge 1b** <br>
# Find the same solution by using Variational Quantum Eigensolver (VQE) to solve the problem. We will specify the optimizer and variational form to be used.
# </div>
#
# <div id='problem'></div>
# <div class="alert alert-block alert-info">
#
# **HINT:** If you are stuck, check out [**this qiskit tutorial**](https://qiskit.org/documentation/finance/tutorials/01_portfolio_optimization.html) and adapt it to our problem:
#
# </div>
#
# Below is some code to get you started.
# +
optimizer = SLSQP(maxiter=1000)
algorithm_globals.random_seed = 1234
backend = Aer.get_backend('statevector_simulator')
##############################
# Provide your code here
#cobyla = COBYLA()
#cobyla.set_options(maxiter=500)
ry = TwoLocal(num_assets, 'ry', 'cz', reps=3, entanglement='full')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
vqe = VQE(ry, optimizer=optimizer, quantum_instance=quantum_instance)
##############################
vqe_meo = MinimumEigenOptimizer(vqe) #please do not change this code
result = vqe_meo.solve(qp) #please do not change this code
print(result) #please do not change this code
# -
# Check your answer and submit using the following code
from qc_grader import grade_ex1b
grade_ex1b(vqe, qp)
# VQE should give you the same optimal results as the reference solution.
# ## Challenge 1c: Portfolio optimization for B=3, n=4 stocks
#
# In this exercise, solve the same problem where one can allocate double weights (can allocate twice the amount) for a single asset. (For example, if you allocate twice for STOCK3 one for STOCK2, then your portfolio can be represented as [2, 1, 0, 0]. If you allocate a single weight for STOCK0, STOCK1, STOCK2 then your portfolio will look like [0, 1, 1, 1]) <br>
# Furthermore, change the constraint to B=3. With this new constraint, find the optimal portfolio that minimizes the tradeoff between risk and return.
#
# <div id='u-definition'></div>
# <div class="alert alert-block alert-success">
#
# **Challenge 1c** <br>
# Complete the code to generate the portfolio instance using the PortfolioOptimization class. <br>
# Find the optimal portfolio for budget=3 where one can allocate double weights for a single asset.<br>
# Use QAOA to find your optimal solution and submit your answer.
#
# </div>
#
# <div id='problem'></div>
# <div class="alert alert-block alert-info">
#
# **HINT:** Remember that any one of STOCK0, STOCK1, STOCK2, STOCK3 can have double weights in our portfolio. How can we change our code to accommodate integer variables? <br>
# </div>
# ## Step 1: Import necessary libraries
#Step 1: Let us begin by importing necessary libraries
import qiskit
from qiskit import Aer
from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import *
from qiskit.circuit.library import TwoLocal
from qiskit.utils import QuantumInstance
from qiskit.utils import algorithm_globals
from qiskit_finance import QiskitFinanceError
from qiskit_finance.applications.optimization import *
from qiskit_finance.data_providers import *
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.applications import OptimizationApplication
from qiskit_optimization.converters import QuadraticProgramToQubo
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
import datetime
import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
warnings.simplefilter("ignore",SymPyDeprecationWarning)
# ## Step 2: Generate Time Series Data (Financial Data)
# Step 2. Generate time series data for four assets.
# Do not change start/end dates specified to generate problem data.
seed = 132
num_assets = 4
stocks = [("STOCK%s" % i) for i in range(num_assets)]
data = RandomDataProvider(tickers=stocks,
start=datetime.datetime(1955,11,5),
end=datetime.datetime(1985,10,26),
seed=seed)
data.run()
# Let's plot our finanical data (We are generating the same time series data as in the previous example.)
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.xlabel('days')
plt.ylabel('stock value')
plt.show()
# ## Step 3: Calculate expected return mu and covariance sigma
# +
# Step 3. Calculate mu and sigma for this problem
mu2 = data.get_period_return_mean_vector() #Returns a vector containing the mean value of each asset.
sigma2 = data.get_period_return_covariance_matrix() #Returns the covariance matrix associated with the assets.
print(mu2, sigma2)
# -
# ## Step 4: Set parameters and constraints based on this challenge 1c.
# +
# Step 4. Set parameters and constraints based on this challenge 1c
##############################
# Provide your code here
q2 = 0.5 #Set risk factor to 0.5
budget2 = 3 #Set budget to 3
##############################
# -
# ## Step 5: Complete code to generate the portfolio instance
# +
# Step 5. Complete code to generate the portfolio instance
##############################
# Provide your code here
portfolio2 =PortfolioOptimization(expected_returns=mu2, covariances=sigma2, risk_factor=q2, budget=budget2, bounds= [(0,2),(0,2),(0,2),(0,2)])
qp2 = portfolio2.to_quadratic_program()
##############################
# -
# ## Step 6: Let's solve the problem using QAOA
#
# **Quantum Approximate Optimization Algorithm (QAOA)** is another variational algorithm that has applications for solving combinatorial optimization problems on near-term quantum systems. This algorithm can also be used to calculate ground states of a Hamiltonian and can be easily implemented by using Qiskit's [**QAOA**](https://qiskit.org/documentation/stubs/qiskit.algorithms.QAOA.html) application. (You will get to learn about QAOA in detail in challenge 4. Let us first focus on the basic implementation of QAOA using Qiskit in this exercise.)
#
# +
# Step 6. Now let's use QAOA to solve this problem.
optimizer = SLSQP(maxiter=1000)
algorithm_globals.random_seed = 1234
backend = Aer.get_backend('statevector_simulator')
##############################
# Provide your code here
#cobyla = COBYLA()
#cobyla.set_options(maxiter=250)
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
qaoa = QAOA(optimizer=optimizer, reps=3, quantum_instance=quantum_instance)
##############################
qaoa_meo = MinimumEigenOptimizer(qaoa) #please do not change this code
result2 = qaoa_meo.solve(qp2) #please do not change this code
print(result2) #please do not change this code
# -
# Note: The QAOA execution may take up to a few minutes to complete.
# # Submit your answer
# Check your answer and submit using the following code
from qc_grader import grade_ex1c
grade_ex1c(qaoa, qp2)
# ### Further Reading:
# For those who have successfully solved the first introductory level challenge, **congratulations!** <br>
# I hope you were able to learn something about optimizing portfolios and how you can use Qiskit's Finance module to solve the example problem. <br> If you are interested in further reading, here are a few literature to explore:
# <br>
# 1. [**Quantum optimization using variational algorithms on near-term quantum devices. Moll et al. 2017**](https://arxiv.org/abs/1710.01022)<br>
# 2. [**Improving Variational Quantum Optimization using CVaR. Barkoutsos et al. 2019.**](https://arxiv.org/abs/1907.04769)<br>
# ### Good luck and have fun with the challenge!
# ## Additional information
#
# **Created by:** <NAME>
#
# **Version:** 1.0.1
|
challenge-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
# name: python3
# ---
# + id="B8vMLarc_KQH" executionInfo={"status": "ok", "timestamp": 1635761606767, "user_tz": -210, "elapsed": 5326, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "18076820241113126701"}}
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
import pymc3 as pm
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
# + [markdown] id="h9gdgHV8GU5s"
# In this exapmle, the author tries to illustrate that if the shape of your priors are approximately the same, then your posterior distribution will not change dramatically:
# + colab={"base_uri": "https://localhost:8080/", "height": 532} id="RUpR9Xae_PRE" executionInfo={"status": "ok", "timestamp": 1635763320318, "user_tz": -210, "elapsed": 49416, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s64", "userId": "18076820241113126701"}} outputId="ca0e9e07-711e-4679-f4df-2f0f5aed7d6d"
with pm.Model():
s1 = pm.Uniform('s1',0,10**7)
obs1 = pm.Poisson('obs1',mu = s1 ,observed = 4)
trace = pm.sample(20000)
with pm.Model():
s2 = pm.HalfNormal('s2',10)
obs2 = pm.Poisson('obs2',mu = s2 ,observed = 4)
trace3 = pm.sample(20000)
sns.histplot(trace['s1'], stat = 'density' , kde = 1)
sns.histplot(trace3['s2'], stat = 'density' , kde = 1, color = 'r')
plt.xlim(0,10)
plt.legend(['uni-prior','nor-prior'])
plt.show()
|
Chapter 5/Page_40.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Chicago Crime Prediction
#
# The model forecasts how many crimes are expected to be reported the next day, based on how many were reported over the previous `n` days.
# ## Imports
# +
# %%capture
# %pip install --upgrade pip
# %pip install --upgrade seaborn
# %pip install --upgrade numpy
# %pip install --upgrade pandas
# %pip install --upgrade "tensorflow<2"
# %pip install --upgrade scikit-learn
# %pip install --upgrade google-cloud-bigquery
# +
from math import sqrt
import numpy as np
import pandas as pd
from pandas.plotting import register_matplotlib_converters
import matplotlib.pyplot as plt
register_matplotlib_converters()
import seaborn as sns
from sklearn.preprocessing import RobustScaler
from sklearn.metrics import mean_squared_error
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import LSTM, Dense, Dropout
import warnings
# -
# ## Load data
# +
from google.cloud import bigquery
sql = """
SELECT count(*) as count, TIMESTAMP_TRUNC(date, DAY) as day
FROM `bigquery-public-data.chicago_crime.crime`
GROUP BY day
ORDER BY day
"""
client = bigquery.Client()
df = client.query(sql).result().to_dataframe()
df.index = df.day
df = df[['count']]
df.head()
# -
# ## Visualize data
plt.figure(figsize=(20, 6))
with warnings.catch_warnings():
warnings.simplefilter("ignore")
sns.lineplot(data=df).set_title('Daily Crime Reports')
plt.show()
# ## Preprocess data
# Split dataset into sequences of previous values and current values
# For example, given a dataset: [1, 2, 3, 4, 5] and a window size of 2:
# data_X = [[1, 2], [2, 3], [3, 4]]
# data_y = [3, 4, 5]
def create_dataset(dataset, window_size = 1):
data_X, data_y = [], []
df = pd.DataFrame(dataset)
columns = [df.shift(i) for i in reversed(range(1, window_size+1))]
data_X = pd.concat(columns, axis=1).dropna().values
data_y = df.shift(-window_size).dropna().values
return data_X, data_y
# +
# The % of data we should use for training
TRAINING_SPLIT = 0.8
# The # of observations to use to predict the next observation
WINDOW_SIZE = 7
def preprocess_data(df, window_size):
# Normalize inputs to improve learning process
scaler = RobustScaler()
# Time series: split latest data into test set
train = df.values[:int(TRAINING_SPLIT * len(df)), :]
train = scaler.fit_transform(train)
test = df.values[int(TRAINING_SPLIT * len(df)):, :]
test = scaler.transform(test)
# Create test and training sets
train_X, train_y = create_dataset(train, window_size)
test_X, test_y = create_dataset(test, window_size)
# Reshape input data
train_X = np.reshape(train_X, (train_X.shape[0], 1, train_X.shape[1]))
test_X = np.reshape(test_X, (test_X.shape[0], 1, test_X.shape[1]))
return train_X, train_y, test_X, test_y, scaler
train_X, train_y, test_X, test_y, scaler = preprocess_data(df, WINDOW_SIZE)
# -
# ## Train model
def input_fn(features, labels, shuffle, num_epochs, batch_size):
"""Generates an input function to be used for model training.
Args:
features: numpy array of features used for training or inference
labels: numpy array of labels for each example
shuffle: boolean for whether to shuffle the data or not (set True for
training, False for evaluation)
num_epochs: number of epochs to provide the data for
batch_size: batch size for training
Returns:
A tf.data.Dataset that can provide data to the Keras model for training or
evaluation
"""
if labels is None:
inputs = features
else:
inputs = (features, labels)
dataset = tf.data.Dataset.from_tensor_slices(inputs)
if shuffle:
dataset = dataset.shuffle(buffer_size=len(features))
# We call repeat after shuffling, rather than before, to prevent separate
# epochs from blending together.
dataset = dataset.repeat(num_epochs)
dataset = dataset.batch(batch_size)
return dataset
def create_keras_model(input_dim, learning_rate, window_size):
"""Creates Keras model for regression.
Args:
input_dim: How many features the input has
learning_rate: Learning rate for training
Returns:
The compiled Keras model (still needs to be trained)
"""
model = keras.Sequential([
LSTM(4, dropout = 0.2, input_shape = (input_dim, window_size)),
Dense(1)
])
model.compile(loss='mean_squared_error', optimizer=tf.train.AdamOptimizer(
learning_rate=learning_rate))
return(model)
def train_and_evaluate(batch_size, learning_rate, num_epochs, window_size):
# Dimensions
num_train_examples, input_dim, _ = train_X.shape
num_eval_examples = test_X.shape[0]
# Create the Keras Model
keras_model = create_keras_model(
input_dim=input_dim, learning_rate=learning_rate, window_size=window_size)
# Pass a numpy array by passing DataFrame.values
training_dataset = input_fn(
features=train_X,
labels=train_y,
shuffle=False,
num_epochs=num_epochs,
batch_size=batch_size)
# Pass a numpy array by passing DataFrame.values
validation_dataset = input_fn(
features=test_X,
labels=test_y,
shuffle=False,
num_epochs=num_epochs,
batch_size=num_eval_examples)
# Train model
keras_model.fit(
training_dataset,
steps_per_epoch=int(num_train_examples / batch_size),
epochs=num_epochs,
validation_data=validation_dataset,
validation_steps=1,
verbose=1,
shuffle=False,
)
return keras_model
# +
BATCH_SIZE = 256
LEARNING_RATE = 0.01
NUM_EPOCHS = 25
model = train_and_evaluate(BATCH_SIZE, LEARNING_RATE, NUM_EPOCHS, WINDOW_SIZE)
# -
# ## Evaluate model
# +
def predict(model, X, y, scaler):
y_true = scaler.inverse_transform(y)
y_pred = scaler.inverse_transform(model.predict(X))
rmse = sqrt(mean_squared_error(y_true, y_pred))
return y_pred, rmse
train_predict, _ = predict(model, train_X, train_y, scaler)
test_predict, rmse = predict(model, test_X, test_y, scaler)
model.evaluate(train_X, train_y)
print(rmse)
# -
# ## Plot predictions
# +
# Create new dataframe with similar indexes and columns to store prediction array
df_test_predict = pd.DataFrame().reindex_like(df)
# Assign test predictions to end of dataframe
df_test_predict['count'][len(train_predict) + (WINDOW_SIZE * 2):len(df)] = np.squeeze(test_predict)
# Append the test predictions to the end of the existing dataframe, while renaming the column to avoid collision
df_combined = df.join(df_test_predict.rename(index=str, columns={'count':'predicted'}))
# Plot the predicted vs actual counts
plt.figure(figsize=(20, 6))
with warnings.catch_warnings():
warnings.simplefilter("ignore")
sns.lineplot(data=df_combined).set_title('Daily Crime Reports')
plt.show()
|
courses/machine_learning/deepdive2/production_ml/labs/samples/core/ai_platform/local/Chicago Crime Research.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/jaya-shankar/education-impact/blob/master/data_extract_code/wcde.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + colab={"base_uri": "https://localhost:8080/"} id="g6PvwqBO0C5C" outputId="76d823a2-8e17-4e34-f481-119b5db5ae61"
from google.colab import drive
drive.mount('drive')
# + id="B7Lozl3AmPlU"
import pandas as pd
import numpy as np
import csv
# + id="_xuThskFJ-Va"
data = pd.read_csv("/content/drive/MyDrive/wcde_data.csv")
df = pd.DataFrame(data)
# + id="VVAaVHdg0UW_"
age = list(df.Age.unique())
for i in range(0,len(age),2):
sr = df.loc[((df['Age'] == age[i]) | (df['Age']==age[i+1])) & ((df['Year']<=2015) & (df['Year']>=1960))]
sr.to_csv('/content/drive/My Drive/wcde/wcde'+age[i][:4]+age[i+1][4:]+'.csv', encoding='utf-8', index=False)
# + id="TCzHSOk2djee"
countries = list(df.Area.unique())
# + id="Eqjkqj0p7oUa"
def init_timeline():
timeline = [i for i in range(1960,2016)]
timeline_dic={c:{t : 0 if not t%5 else np.NaN for t in timeline } for c in countries}
return timeline_dic
# + id="dxSOnYxnoLw1"
def convert_to_df():
dft = pd.DataFrame.from_dict(timeline_dic,orient='index')
dft.insert(0, "Country", countries, True)
return dft
# + id="FQ8k5G_R7lQC"
for i in range(0,len(age),2):
timeline_dic = init_timeline()
data = pd.read_csv("/content/drive/MyDrive/wcde/wcde"+age[i][:4]+age[i+1][4:]+".csv")
dfs = pd.DataFrame(data)
for j in range(len(data)):
timeline_dic[dfs.iloc[j]['Area']][dfs.iloc[j]['Year']] += dfs.iloc[j]['Years']
round(timeline_dic[dfs.iloc[j]['Area']][dfs.iloc[j]['Year']], 2)
dft = convert_to_df()
dft.to_csv('/content/drive/My Drive/wcde/modified/wcde-'+age[i][:4]+age[i+1][4:]+'.csv', encoding='utf-8', index=False)
|
data_extract_code/wcde.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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/aeropython_logo.png" alt="AeroPython" style="width: 300px;"/>
# # Clase 3b: Perfil de Yukovski
# _Aunque no te lo creas, __con lo que hemos visto hasta ahora eres capaz de hacer grandes cosas__. Vale sí, un perfil de Yukovski no es gran cosa aerodinámicamente, pero si lo hacemos en Python... Echa un vistazo a la figura ¿no está mal, no? algo así intentaremos conseguir al final de esta clase._
#
# 
#
# _Como no se trata de aprender (o reaprender) aerodinámica, te daremos las funciones matemáticas y los pasos a seguir así como la estructura del programa. Tú sólo tienes que preocuparte de programar cada bloque. Puedes leer en detalle todo lo relativo a la aerodinámica en el libro Aerodinámica básica de <NAME>., <NAME>. (Editorial Garceta)._
#
# ## 1. Importamos paquetes.
# Lo primero es lo primero, importemos los paquetes:
# Recuerda, utilizaremos arrays y pintaremos gráficas.
import numpy as np
import matplotlib.pyplot as plt
# ## 2. Parámetros del problema
# ######  <h6 align="right">__Fuente:__ _Aerodinámica básica, <NAME>., <NAME>._<div>
# La transformación de Yukovski es: $$\tau=t+\frac{a^{2}}{t}$$
#
# Los parámetros del problema son los del siguiente bloque, puedes cambiarlos más adelante:
# +
# Datos para el perfil de Yukovski
# Parámetro de la transformación de Yukovski
a = 1
# Centro de la circunferencia
landa = 0.2 # coordenada x (en valor absoluto)
delta = 0.3 # coordenada y
t0 = a * (-landa + delta * 1j) # centro: plano complejo
# Valor del radio de la circunferencia
R = a * np.sqrt((1 + landa)**2 + delta**2)
# Ángulo de ataque corriente incidente
alfa_grados = 0
alfa = np.deg2rad(alfa_grados)
#Velocidad de la corriente incidente
U = 1
# -
# ## 3. Perfil de Yukoski a partir de una circunferencia.
# ### Función transformación de Yukovski
# __Se trata de definir una función que realice la transformación de Yukovski.__ Esta función recibirá el parámetro de la transformación, $a$ y el punto del plano complejo $t$. Devolverá el valor $\tau$, punto del plano complejo en el que se transforma $t$.
def transf_yukovski(a, t):
"""Dado el punto t (complejo) y el parámetro a
a de la transformación proporciona el punto
tau (complejo) en el que se transforma t."""
tau = t + a ** 2 / t
return tau
# aeropython: preserve
#comprobamos que la función está bien programada
#puntos del eje real siguen siendo del eje real
err_message = "La transformación de Yukovski no devuelve un resultado correcto"
np.testing.assert_equal(transf_yukovski(1, 1+0j), 2+0j, err_message)
# ### Circunferencia
# Ahora queremos transformar la circunferencia de radio $R$ con centro en $t_0$ usando la función anterior:
#
# 1. __Creamos `N` puntos de la circunferencia__ de modo que __en `Xc` estén las coordenadas $x$ y en `Yc` estén las coordenadas $y$__ de los puntos que la forman. Controla el número de puntos mediante un parámetro que se llame `N_perfil`.
# $$X_c = real(t_0) + R·cos(\theta)$$
# $$Y_c = imag(t_0) + R·sin(\theta)$$
# 2. Una vez hayas obtenido los dos arrays `Xc` e `Yc`, __píntalos mediante un `scatter`__ para comprobar que todo ha ido bien.
# 3. Pinta también el __centro de la circunferencia__.
#
# Deberías obtener algo así:
#
# 
# +
# Número de puntos de la circunferencia que
# vamos a transformar para obtener el perfil
N_perfil = 100
#se barre un ángulo de 0 a 2 pi
theta = np.linspace(0, 2*np.pi, N_perfil)
#se crean las coordenadas del los puntos
#de la circunferencia
Xc = np.real(t0) + R * np.cos(theta)
Yc = np.imag(t0) + R * np.sin(theta)
#lo visualizamos
plt.figure("circunferencia", figsize=(5,5))
plt.title('Circunferencia', {'fontsize':20})
plt.scatter(Xc, Yc)
plt.scatter(np.real(t0), np.imag(t0), color='orange', marker='x', s=100)
plt.grid()
plt.show()
# +
# aeropython: preserve
# Lo visualizamos más bonito
plt.figure("circunferencia", figsize=(5,5))
plt.title('Circunferencia', {'fontsize':20})
# Esto no tienes por qué entenderlo ahora
p = plt.Polygon(list(zip(Xc, Yc)), color="#cccccc", zorder=3)
plt.gca().add_patch(p)
plt.ylim(-1.5, 2)
plt.xlim(-2, 1.5)
plt.grid()
plt.show()
# -
# ### Transformación de cirunferencia a perfil
# Ahora estamos en condiciones de __transformar estos puntos de la circunferencia (`Xc`, `Yc`) en los del perfil (`Xp`, `Yp`)__. Para esto vamos a usar nuestra función `transf_yukovski`. Recuerda que esta función recibe y da números complejos. ¿Saldrá un perfil?
# +
Puntos_perfil = transf_yukovski(a, Xc+Yc*1j)
Xp, Yp = np.real(Puntos_perfil) , np.imag(Puntos_perfil)
#lo visualizamos
plt.figure("perfil yukovski", figsize=(10,10))
plt.title('Perfil', {'fontsize':20})
plt.scatter(Xp, Yp)
plt.grid()
plt.gca().set_aspect(1)
plt.show()
# +
# aeropython: preserve
#lo visualizamos más bonito
plt.figure('perfil yukovski', figsize=(10,10))
plt.title('Perfil', {'fontsize':20})
p = plt.Polygon(list(zip(Xp, Yp)), color="#cccccc", zorder=3)
plt.gca().add_patch(p)
plt.gca().set_aspect(1)
plt.xlim(-3, 3)
plt.ylim(-0.4,1)
plt.grid()
plt.show()
# -
# ## 4. Flujo alrededor del cilindro
# Para visualizar ahora el flujo alrededor del cilindro recurrimos al __potencial complejo__ de una _corriente uniforme_ que forme un ángulo $\alpha$ con el eje $x$ _en presencia de un cilindro_ (aplicando el teorema del círculo) y se añade un torbellino con la intensidad adecuada para que se cumpla la hipótesis de Kutta en el perfil:
#
# \begin{equation}
# f(t)=U_{\infty}\text{·}\left((t-t_{0})\text{·}e^{-i\alpha}+\frac{R^{2}}{t-t_{0}}\text{·}e^{i\alpha}\right)+\frac{i\Gamma}{2\pi}\text{·}ln(t-t_{0})=\Phi+i\Psi
# \end{equation}
#
# donde $\Phi$ es el potencial de velocidades y $\Psi$ es la función de corriente.
#
# $$\Gamma = 4 \pi a U (\delta + (1+\lambda) \alpha)$$
#
# $\Gamma$ es la circulación que hay que añadir al cilindro para que al transformarlo en el perfil se cumpla la condición de Kutta.
#
# Recordando que la función de corriente toma un valor constante en las líneas de corriente, sabemos que: dibujando $\Psi=cte$ se puede visualizar el flujo.
#
# __Pintaremos estas lineas de potencial constante utilizando la función `contour()`, pero antes tendremos que crear una malla circular. Esto será lo primero que hagamos:__
#
# 1. Crea un parámetro `N_R` cuyo valor sea el número de puntos que va a tener la malla en dirección radial. Desde otro punto de vista, esta parámetro es el número de círculos concéntricos que forman la malla.
# 2. Crea dos parámetros `R_min` y `R_max` que representen el radio mínimo y máximo entre los que se extiende la malla. El radio mínimo debe de ser el radio del círculo, porque estamos calculando el aire en el exterior del perfil.
# 4. La dirección tangencial necesita un sólo parámetro `N_T`, que representa el número de puntos que la malla tendrá en esta dirección. Dicho de otro modo, cuántos puntos forman los círculos concéntricos de la malla.
# 3. Crea un array `R_` que vaya desde `R_min` hasta `R_max` y que tenga `N_R` elementos. De manera análoga, crea el array `T_`, que al representar los ángulos de los puntos que forman las circunferencias, debe ir de 0 a 2$\pi$, y tener `N_T` elementos.
# 4. Para trabajar con la malla, deberemos usar coordenadas cartesianas. Crea la malla: `XX, YY` van a ser dos matrices de `N_T · N_R` elementos. Cada elemento de estas matrices se corresponde con un punto de la malla: la matriz `XX` contiene las coordenadas X de cada punto y la matriz `YY`, las coordenadas y.
#
# La manera de generar estas matrices tiene un poco de truco, porque depende de ambos vectores.
# Para cada elemento, $x = real(t_0) + R · cos (T) $ , $y = imag(t_0) + R · sin(T)$.
#
#
# __Recuerda que:__
#
# * Los puntos sobre la circunferencia se transforman en el perfil.
# * Los puntos interiores a la circunferencia se transforman en puntos interiores al perfil.
# * Los puntos exteriores a la circunferencia se transforman en puntos exteriores al perfil. __Los puntos que nos interesan__.
# +
#se crea la malla donde se va pintar la función de corriente
# Dirección radial
N_R = 50 # Número de puntos en la dirección radial
R_min = R
R_max = 10
# Dirección tangencial
N_T = 180 # Número de puntos en la dirección tangencial
R_ = np.linspace(R_min, R_max, N_R)
T_ = np.linspace(0, 2*np.pi , N_T)
# Crear la malla:
XX = R_ * np.cos(T_).reshape((-1, 1)) + np.real(t0)
YY = R_ * np.sin(T_).reshape((-1, 1)) + np.imag(t0)
# -
#pintamos la malla para verla
plt.figure(figsize=(10,10))
plt.scatter(XX.flatten(), YY.flatten(), marker='.')
plt.show()
# __NOTA__: En versiones anteriores se utilizaba una malla rectangular. Esto generaba algunos problemas con los puntos interiores a la hora de pintar las líneas de corriente y los campos de velocidades y presiones. La idea de usar una malla circular está tomada de [este ejercicio](http://nbviewer.ipython.org/github/barbagroup/AeroPython/blob/master/lessons/06_Lesson06_Assignment.ipynb) del curso Aerodynamics-Hydrodynamics with Python de la [Prof. <NAME>](http://lorenabarba.com/).
# ### Probando a transformar la malla
# Bueno, lo que queríamos era hacer cosas alrededor de nuestro perfil, ¿no?
#
# Esto lo conseguiremos pintando la función $\Psi$ en los puntos `XX_tau, YY_tau` transformados de los `XX, YY` a través de la función `transf_yukovski`, recuerda que la transformación que tenemos recibe y da números complejos. Como antes, debes separar parte real e imaginaria. En la siguiente celda calcula y transforma `tt` (donde debe estar almacenada la malla en forma compleja) para obtener `XX_tau, YY_tau`.
#
# Probemos a visualizar como se transforman los puntos de la malla primero.
tt = XX + YY * 1j
tautau = transf_yukovski(a, tt)
XX_tau, YY_tau = np.real(tautau) , np.imag(tautau)
# Comprobamos que los puntos exteriores a la circunferencia se transforman en los puntos exteriores del perfil
#pintamos la malla para verla
plt.figure(figsize=(10,10))
plt.scatter(XX_tau.flatten(), YY_tau.flatten(), marker='.')
plt.show()
# ### Obteniendo el flujo
# 1. Crea una variable `T` que tenga el valor correspondiente a la circulación $\Gamma$.
# 2. Utilizando el array `tt`, el valor `T` y los parámetros definidos al principio (`t0, alfa, U...`) crea `f` según la fórmula de arriba (no hace falta que crees una función).
# 3. Guarda la parte imaginaria de esa función (función de corriente) en una variable `psi`.
# +
# aeropython: preserve
# Circulación que hay que añadir al cilindro para
# que se cumpla la hipótesis de Kutta en el perfil
T = 4 * np.pi * a * U * (delta + (1+landa) * alfa)
# Malla compleja
tt = XX + YY * 1j
# Potencial complejo
f = U * ( (tt - t0) * np.exp(-alfa *1j) + R**2 / (tt - t0) * np.exp(alfa * 1j) )
f += 1j * T / (2* np.pi) * np.log(tt - t0)
# Función de corriente
psi = np.imag(f)
# -
# Como la función de corriente toma un valor constante en cada línea de corriente, podemos visualizar el flujo alrededor del cilindro pintando las lineas en las que `psi` toma un valor constante. Para ello utilizaremos la función `contour()` en la malla `XX, YY`. Si no se ve nada prueba a cambiar el número de líneas y los valores máximo y mínimo de la función que se representan.
# +
#lo visualizamos
# aeropython: preserve
plt.figure('lineas de corriente', figsize=(10,10))
plt.contour(XX, YY, psi, np.linspace(-5,5,50))
plt.grid()
plt.gca().set_aspect(1)
#plt.xlim(-8, 8)
#plt.ylim(-3, 3)
plt.show()
# +
#ponemos el cilindro encima
# aeropython: preserve
plt.figure('flujo cilindro', figsize=(10,10))
plt.contour(XX, YY, psi, np.linspace(-5,5,50), colors=['blue', 'blue'])
plt.grid()
plt.gca().set_aspect(1)
p = plt.Polygon(list(zip(Xc, Yc)), color="#cccccc", zorder=3)
plt.gca().add_patch(p)
plt.show()
# -
# ## 5. Flujo alrededor del perfil
# +
plt.figure("flujo perfil", figsize=(12,12))
plt.contour(XX_tau, YY_tau, psi, np.linspace(-5,5,50))
plt.xlim(-8,8)
plt.ylim(-3,3)
plt.grid()
plt.gca().set_aspect(1)
plt.show()
# +
#Ahora ponemos el perfil encima
# aeropython: preserve
plt.figure("flujo perfil", figsize=(12,12))
plt.contour(XX_tau, YY_tau, psi, np.linspace(-5, 5, 50), colors=['blue', 'blue'])
p = plt.Polygon(list(zip(Xp, Yp)), color="#cccccc", zorder=10)
plt.gca().add_patch(p)
plt.xlim(-8,8)
plt.ylim(-3,3)
plt.grid()
plt.gca().set_aspect(1)
plt.show()
# -
# ## 6. Interact
# __Ahora es un buen momento para jugar con todos los parámetros del problema.
# ~~¡Prueba a cambiarlos y ejecuta el notebook entero!~~__
#
# __Vamos a usar un `interact`, ¿no?__
#
# Tenemos que crear una función que haga todas las tareas: reciba los argumentos y pinte para llamar a interact con ella. No tenemos más que cortar y pegar.
# aeropython: preserve
def transformacion_geometrica(a, landa, delta, N_perfil=100):
#punto del plano complejo
t0 = a * (-landa + delta * 1j)
#valor del radio de la circunferencia
R = a * np.sqrt((1 + landa)**2 + delta**2)
#se barre un ángulo de 0 a 2 pi
theta = np.linspace(0, 2*np.pi, N_perfil)
#se crean las coordenadas del los puntos
#de la circunferencia
Xc = - a * landa + R * np.cos(theta)
Yc = a * delta + R * np.sin(theta)
#se crean las coordenadas del los puntos
#del perfil
Puntos_perfil = transf_yukovski(a, Xc+Yc*1j)
Xp, Yp = np.real(Puntos_perfil) , np.imag(Puntos_perfil)
#Se pintan la cirunferencia y el perfil
fig, ax = plt.subplots(1,2)
fig.set_size_inches(15,15)
p_c = plt.Polygon(list(zip(Xc, Yc)), color="#cccccc", zorder=1)
ax[0].add_patch(p_c)
ax[0].plot(Xc,Yc)
ax[0].set_aspect(1)
ax[0].set_xlim(-3, 3)
ax[0].set_ylim(-2,2)
ax[0].grid()
p_p = plt.Polygon(list(zip(Xp, Yp)), color="#cccccc", zorder=1)
ax[1].add_patch(p_p)
ax[1].plot(Xp,Yp)
ax[1].set_aspect(1)
ax[1].set_xlim(-3, 3)
ax[1].set_ylim(-2,2)
ax[1].grid()
plt.show()
from ipywidgets import interact
# aeropython: preserve
interact(transformacion_geometrica, landa=(-1.,1, 0.01), delta=(-1.,1,0.01),
a=(0,2.,0.1), N_perfil=(4, 200) )
# aeropython: preserve
def flujo_perfil_circunferencia(landa, delta, alfa, U=1, N_malla = 100):
N_perfil=N_malla
a=1
#punto del plano complejo
t0 = a * (-landa + delta * 1j)
#valor del radio de la circunferencia
R = a * np.sqrt((1 + landa)**2 + delta**2)
#se barre un ángulo de 0 a 2 pi
theta = np.linspace(0, 2*np.pi, N_perfil)
#se crean las coordenadas del los puntos
#de la circunferencia
Xc = - a * landa + R * np.cos(theta)
Yc = a * delta + R * np.sin(theta)
#se crean las coordenadas del los puntos
#del perfil
Puntos_perfil = transf_yukovski(a, Xc+Yc*1j)
Xp, Yp = np.real(Puntos_perfil) , np.imag(Puntos_perfil)
#se crea la malla donde se va pintar la función de corriente
# Dirección radial
N_R = N_malla//2 # Número de puntos en la dirección radial
R_min = R
R_max = 10
# Dirección tangencial
N_T = N_malla # Número de puntos en la dirección tangencial
R_ = np.linspace(R_min, R_max, N_R)
T_ = np.linspace(0, 2*np.pi , N_T)
# El menos en la XX es para que el borde de ataque del perfil esté en la izquierda
XX = - (R_ * np.cos(T_).reshape((-1, 1)) - np.real(t0))
YY = R_ * np.sin(T_).reshape((-1, 1)) + np.imag(t0)
tt = XX + YY * 1j
alfa = np.deg2rad(alfa)
# Circulación que hay que añadir al cilindro para
# que se cumpla la hipótesis de Kutta en el perfil
T = 4 * np.pi * a * U * (delta + (1+landa) * alfa)
#Potencial complejo
f = U * ( (tt - t0) * np.exp(-alfa *1j) + R**2 / (tt - t0) * np.exp(alfa * 1j) )
f += 1j * T / (2* np.pi) * np.log(tt - t0)
#Función de corriente
psi = np.imag(f)
Puntos_plano_tau = transf_yukovski(a, tt)
XX_tau, YY_tau = np.real(Puntos_plano_tau) , np.imag(Puntos_plano_tau)
#Se pinta
fig, ax = plt.subplots(1,2)
#lineas de corriente
fig.set_size_inches(15,15)
ax[0].contour(XX, YY, psi, np.linspace(-10,10,50), colors = ['blue', 'blue'])
ax[0].grid()
ax[0].set_aspect(1)
p = plt.Polygon(list(zip(Xc, Yc)), color="#cccccc", zorder=10)
ax[0].add_patch(p)
ax[0].set_xlim(-5, 5)
ax[0].set_ylim(-2,2)
ax[1].contour(XX_tau, YY_tau, psi, np.linspace(-10,10,50), colors = ['blue', 'blue'])
ax[1].grid()
ax[1].set_aspect(1)
p = plt.Polygon(list(zip(Xp, Yp)), color="#cccccc", zorder=10)
ax[1].add_patch(p)
ax[1].set_xlim(-5, 5)
ax[1].set_ylim(-2,2)
plt.show()
p = interact(flujo_perfil_circunferencia, landa=(0.,1), delta=(0.,1), alfa=(0, 30), U=(0,10), N_malla = (10,150))
# ## 7. Pintemos un poco más
# Con los datos que ya hemos manejado, sin mucho más esfuerzo, podemos fácilmente pintar la velocidad y la presión del aire alrededor del perfil.
# aeropython: preserve
#Velocidad conjugada
dfdt = U * ( 1 * np.exp(-alfa * 1j) - R**2 / (tt - t0)**2 * np.exp(alfa * 1j) )
dfdt += 1j * T / (2*np.pi) * 1 / (tt - t0)
#coeficiente de presion
cp = 1 - np.abs(dfdt)**2 / U**2
# aeropython: preserve
cmap = plt.cm.RdBu
# aeropython: preserve
#Se pinta
fig, ax = plt.subplots(1,3)
#lineas de corriente
fig.set_size_inches(15,15)
ax[0].contour(XX, YY, psi, np.linspace(-10,10,50), colors = ['blue', 'blue'])
ax[0].grid()
ax[0].set_aspect(1)
p = plt.Polygon(list(zip(Xc, Yc)), color="#cccccc", zorder=10)
ax[0].add_patch(p)
#Campo de velocidades
ax[1].contourf(XX, YY, np.abs(dfdt), 200, cmap=cmap)
p = plt.Polygon(list(zip(Xc, Yc)), color="#cccccc", zorder=10)
ax[1].set_title('campo de velocidades')
ax[1].add_patch(p)
ax[1].set_aspect(1)
ax[1].grid()
#campo de presiones
ax[2].contourf(XX, YY, cp, 200, cmap=cmap)
p = plt.Polygon(list(zip(Xc, Yc)), color="#cccccc", zorder=10)
ax[2].set_title('coeficiente de presión')
ax[2].add_patch(p)
ax[2].set_aspect(1)
ax[2].grid()
plt.show()
#Se pinta
# aeropython: preserve
fig, ax = plt.subplots(1,3)
#lineas de corriente
fig.set_size_inches(15,15)
ax[0].contour(XX_tau, YY_tau, psi, np.linspace(-10,10,50), colors = ['blue', 'blue'])
ax[0].grid()
ax[0].set_aspect(1)
p = plt.Polygon(list(zip(Xp, Yp)), color="#cccccc", zorder=10)
ax[0].add_patch(p)
#Campo de velocidades
ax[1].contourf(XX_tau, YY_tau, np.abs(dfdt), 200, cmap=cmap)
p = plt.Polygon(list(zip(Xp, Yp)), color="#cccccc", zorder=10)
ax[1].set_title('campo de velocidades')
ax[1].add_patch(p)
ax[1].set_aspect(1)
ax[1].grid()
#campo de presiones
ax[2].contourf(XX_tau, YY_tau, cp, 200, cmap=cmap)
p = plt.Polygon(list(zip(Xp, Yp)), color="#cccccc", zorder=10)
ax[2].set_title('coeficiente de presión')
ax[2].add_patch(p)
ax[2].set_aspect(1)
ax[2].grid()
plt.show()
# aeropython: preserve
def cp_perfil_circunferencia(landa, delta, alfa, U=1, N_malla = 100):
N_perfil=N_malla
a=1
#punto del plano complejo
t0 = a * (-landa + delta * 1j)
#valor del radio de la circunferencia
R = a * np.sqrt((1 + landa)**2 + delta**2)
#se barre un ángulo de 0 a 2 pi
theta = np.linspace(0, 2*np.pi, N_perfil)
#se crean las coordenadas del los puntos
#de la circunferencia
Xc = - a * landa + R * np.cos(theta)
Yc = a * delta + R * np.sin(theta)
#se crean las coordenadas del los puntos
#del perfil
Puntos_perfil = transf_yukovski(a, Xc+Yc*1j)
Xp, Yp = np.real(Puntos_perfil) , np.imag(Puntos_perfil)
#se crea la malla donde se va pintar la función de corriente
# Dirección radial
N_R = N_malla//2 # Número de puntos en la dirección radial
R_min = R
R_max = 10
# Dirección tangencial
N_T = N_malla # Número de puntos en la dirección tangencial
R_ = np.linspace(R_min, R_max, N_R)
T_ = np.linspace(0, 2*np.pi, N_T)
# El menos en la XX es para que el borde de ataque del perfil esté en la izquierda
XX = - (R_ * np.cos(T_).reshape((-1, 1)) - np.real(t0))
YY = R_ * np.sin(T_).reshape((-1, 1)) + np.imag(t0)
tt = XX + YY * 1j
alfa = np.deg2rad(alfa)
# Circulación que hay que añadir al cilindro para
# que se cumpla la hipótesis de Kutta en el perfil
T = 4 * np.pi * a * U * (delta + (1+landa) * alfa)
#Velocidad conjugada
dfdt = U * ( 1 * np.exp(-alfa * 1j) - R**2 / (tt - t0)**2 * np.exp(alfa * 1j) )
dfdt = dfdt + 1j * T / (2*np.pi) * 1 / (tt - t0)
#coeficiente de presion
cp = 1 - np.abs(dfdt)**2 / U**2
Puntos_plano_tau = transf_yukovski(a, tt)
XX_tau, YY_tau = np.real(Puntos_plano_tau) , np.imag(Puntos_plano_tau)
#Se pinta
fig, ax = plt.subplots(1,2)
#coeficiente de presión
fig.set_size_inches(15,15)
ax[0].contourf(XX, YY, cp, 200, cmap=cmap)
ax[0].grid()
ax[0].set_aspect(1)
p = plt.Polygon(list(zip(Xc, Yc)), color="#cccccc", zorder=10)
ax[0].add_patch(p)
ax[0].set_xlim(-5, 5)
ax[0].set_ylim(-3,3)
ax[1].contourf(XX_tau, YY_tau, cp, 200, cmap=cmap)
ax[1].grid()
ax[1].set_aspect(1)
p = plt.Polygon(list(zip(Xp, Yp)), color="#cccccc", zorder=10)
ax[1].add_patch(p)
ax[1].set_xlim(-5, 5)
ax[1].set_ylim(-3,3)
plt.show()
interact(cp_perfil_circunferencia, landa=(0.,1), delta=(0.,1), alfa=(0, 30), U=(0,10), N_malla = (10,200))
# ---
# _En esta clase hemos reafirmado nuestros conocimientos de NumPy, matplotlib y Python, general (funciones, bucles, condicionales...) aplicándolos a un ejemplo muy aeronáutico_
# Si te ha gustado esta clase:
#
# <a href="https://twitter.com/share" class="twitter-share-button" data-url="https://github.com/AeroPython/Curso_AeroPython" data-text="Aprendiendo Python con" data-via="pybonacci" data-size="large" data-hashtags="AeroPython">Tweet</a>
# <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
#
# ---
# #### <h4 align="right">¡Síguenos en Twitter!
# ###### <a href="https://twitter.com/Pybonacci" class="twitter-follow-button" data-show-count="false">Follow @Pybonacci</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <a href="https://twitter.com/Alex__S12" class="twitter-follow-button" data-show-count="false" align="right";>Follow @Alex__S12</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <a href="https://twitter.com/newlawrence" class="twitter-follow-button" data-show-count="false" align="right";>Follow @newlawrence</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
# <a rel="license" href="http://creativecommons.org/licenses/by/4.0/deed.es"><img alt="Licencia Creative Commons" style="border-width:0" src="http://i.creativecommons.org/l/by/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Curso AeroPython</span> por <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName"><NAME> y <NAME></span> se distribuye bajo una <a rel="license" href="http://creativecommons.org/licenses/by/4.0/deed.es">Licencia Creative Commons Atribución 4.0 Internacional</a>.
# ---
# _Las siguientes celdas contienen configuración del Notebook_
#
# _Para visualizar y utlizar los enlaces a Twitter el notebook debe ejecutarse como [seguro](http://ipython.org/ipython-doc/dev/notebook/security.html)_
#
# File > Trusted Notebook
# + language="html"
# <a href="https://twitter.com/Pybonacci" class="twitter-follow-button" data-show-count="false">Follow @Pybonacci</a>
# <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
# -
# Esta celda da el estilo al notebook
from IPython.core.display import HTML
css_file = '../styles/aeropython.css'
HTML(open(css_file, "r").read())
|
notebooks_completos/090-Ejemplos-Yukovski.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
# ---
# # Supplemental Information:
#
# > **"Clonal heterogeneity influences the fate of new adaptive mutations"**
#
# > <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
#
# ## Figure 6 (+ Supp. Figs.)
#
# This IPython notebook is provided for reproduction of Figures 6, S10, S11 and S12 of the paper. It can be viewed by copying its URL to nbviewer and it can be run by opening it in binder.
# +
# Load external dependencies
from setup import *
# Load internal dependencies
import config,plot,utils
# %load_ext autoreload
# %autoreload 2
# %matplotlib inline
# -
# In this experiment, we cross individuals of the ancestral population with pre-existing variation and mutant individuals from the evolved population. All of these are diploid cells which undergo sporulation (labelled *spores*) and mating (creating *hybrids*). We evaluate phenotypes of the spore and hybrid genotypes. Phenotypic variation can then be attributed to dominance or epistatic effects.
# ## Data import
#
# ### Spores
# +
# Load data
spores_df = pd.read_csv(dir_data+'pheno/genetic-cross/pheno_genetic_cross_spores.csv.gz', encoding='utf-8', keep_default_na=False, na_values='NaN')
# Filter out blank positions and constructs
spores_df = spores_df[~(spores_df['strain'].isin(['control','']))&\
~(spores_df['genotype_long'].isin([u'fpr1Δ',u'tor1Δ']))]
# Set contaminated samples as missing (NaN)
spores_df.loc[(spores_df['contamination']=='yes'),
['abs_growth_rate','abs_doubling_time','norm_growth_rate','norm_doubling_time']] = np.nan
# Define individual and replicate
spores_df['individual'] = spores_df[['group','background','gene','tetrad','spore']].apply(tuple, axis=1)
spores_df['replicate'] = spores_df[['group','background','gene','tetrad','spore','plate','row','column']].apply(tuple, axis=1)
# # Filter out measurement replicates with >5% measurement error
# spores_df['pct'] = spores_df.groupby(['selection','environment','replicate'])['growth_rate']\
# .apply(lambda x: (x-x.mean())/float(x.mean()))
# spores_df = spores_df[abs(spores_df['pct'])<0.05]
spores_df.head() # show dataframe header to stdout
# -
# ### Hybrids
# +
# Load data
hybrids_df = pd.read_csv(dir_data+'pheno/genetic-cross/pheno_genetic_cross_hybrids.csv.gz', encoding='utf-8', keep_default_na=False, na_values='NaN')
# Combine MATa/α to create tuples
for column in ['strain','group','background','gene','genotype_short','genotype_long','amino_acids']:
hybrids_df[column] = utils.combine_columns(hybrids_df,u'%s_MATa'%column,u'%s_MATα'%column)
for column in ['auxotrophy','mating','tetrad','spore','strain','contamination']:
hybrids_df[column] = utils.combine_columns(hybrids_df,u'%s_MATa'%column,u'%s_MATα'%column,mirror=False)
# Filter out blank positions, contamination and constructs
hybrids_df = hybrids_df[~(hybrids_df['strain'].isin([('control','control'),('','')]))&\
~(hybrids_df['genotype_long'].isin([u'fpr1Δ',u'tor1Δ']))]
# Set contaminated samples as missing (NaN)
hybrids_df.loc[hybrids_df['contamination'].isin([('yes','yes'),('no','yes'),('yes','no')]),
['abs_growth_rate','abs_doubling_time','norm_growth_rate','norm_doubling_time']] = np.nan
# Fix diploid genotypes for different genes
hybrids_df.loc[(hybrids_df[u'gene_MATa']=='RNR4')&\
(hybrids_df[u'gene_MATα']=='RNR2'),'genotype_short'] =\
hybrids_df.loc[(hybrids_df[u'gene_MATa']=='RNR4')&\
(hybrids_df[u'gene_MATα']=='RNR2'),'genotype_short'].apply(lambda x: x[::-1])
hybrids_df.loc[(hybrids_df[u'gene_MATa']=='TOR1')&\
(hybrids_df[u'gene_MATα']=='FPR1'),'genotype_short'] =\
hybrids_df.loc[(hybrids_df[u'gene_MATa']=='TOR1')&\
(hybrids_df[u'gene_MATα']=='FPR1'),'genotype_short'].apply(lambda x: x[::-1])
# Define individual
hybrids_df['individual'] = hybrids_df[['group','background','gene','tetrad','spore']].apply(tuple, axis=1)
hybrids_df['replicate'] = hybrids_df[['group','background','gene','tetrad','spore','plate','row','column']].apply(tuple, axis=1)
# # Filter out measurement replicates with >5% measurement error
# hybrids_df['pct'] = hybrids_df.groupby(['selection','environment','replicate'])['growth_rate']\
# .apply(lambda x: (x-x.mean())/float(x.mean()))
# hybrids_df = hybrids_df[abs(hybrids_df['pct'])<0.05]
hybrids_df.head() # show dataframe header to stdout
# -
# ### Clones
# +
# Load data
clone_df = pd.read_csv(dir_data+'pheno/populations/pheno_populations.csv.gz', encoding='utf-8', keep_default_na=False, na_values='NaN')
# Filter out strains used for spatial control
clone_df = clone_df[(clone_df.group == 'ancestral')|\
(clone_df.group == 'evolved')]
clone_df['genotype_short'] = map(lambda x: tuple(x.strip("/").split("/")),clone_df['genotype_short'])
clone_df['genotype_long'] = map(lambda x: tuple(x.strip("/").split("/")),clone_df['genotype_long'])
clone_df['group'] = zip(clone_df.group, clone_df.group)
clone_df['background'] = zip(clone_df.background, clone_df.background)
clone_df['gene'] = zip(clone_df.gene, clone_df.gene)
clone_df.head()
# -
# ### Analysis of variance
lmm_fit = pd.read_csv(dir_data+'pheno/genetic-cross/lmm_fit.csv')
lmm_var_comp = pd.read_csv(dir_data+'pheno/genetic-cross/lmm_var_components.csv')
# We need to filter and sort the vector of spore phenotypes and matrix of hybrid phenotypes by environment.
# +
def filter_spores(S, env_evo):
# Filter by dictionary
S = S[(S['group'].isin(config.spores_bg['position'][env_evo].keys())) &
(S['genotype_short'].isin(config.spores_gt_short['position'][env_evo].keys())) &
(S['background'].isin(config.spores_cl['position'][env_evo].keys()))]
return S
def filter_hybrids(H, env_evo):
# Filter by dictionary
H = H[(H['group'].isin(config.hybrids_bg['position'][env_evo].keys())) &
(H['genotype_short'].isin(config.hybrids_gt_short['position'][env_evo].keys())) &
(H['background'].isin(config.hybrids_cl['position'][env_evo].keys()))]
return H
def sort_spores(S, env_evo):
# Apply sorting ranks to reorder rows
S.loc[:,'rank_group'] = S['group'].map(config.spores_bg['position'][env_evo])
S.loc[:,'rank_background'] = S['background'].map(config.spores_cl['position'][env_evo])
S.loc[:,'rank_gene'] = S['gene'].map(config.spores_gn['position'][env_evo])
S.loc[:,'rank_genotype'] = S['genotype_short'].map(config.spores_gt_short['position'][env_evo])
S.sort_values(['rank_group','rank_background','rank_gene','rank_genotype'],
ascending=True,inplace=True)
return S
def sort_hybrids(H, env_evo):
# Apply sorting ranks to reorder rows
H.loc[:,'rank_group'] = H['group'].map(config.hybrids_bg['position'][env_evo])
H.loc[:,'rank_background'] = H['background'].map(config.hybrids_cl['position'][env_evo])
H.loc[:,'rank_gene'] = H['gene'].map(config.hybrids_gn['position'][env_evo])
H.loc[:,'rank_genotype'] = H['genotype_short'].map(config.hybrids_gt_short['position'][env_evo])
H.sort_values(['rank_group','rank_background','rank_gene','rank_genotype'],
ascending=True,inplace=True)
return H
# -
# ## Figure 6 - Background-averaged fitness effects
from IPython.display import Image
Image(filename=dir_paper+'figures/figure6/figure6A_schematic_publication.png', retina=True)
# +
param='norm_growth_rate'
fig = plt.figure(figsize=(12, 6))
grid = gridspec.GridSpec(2, 3, width_ratios=[1.1,3,1.075], hspace=0.35, wspace=0.2)
gs = {}
gs['schematic'] = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=grid[0,0])
gs['variance'] = gridspec.GridSpecFromSubplotSpec(3, 1, height_ratios=[5,5,2], subplot_spec=grid[1,0], hspace=0.1)
gs[('HU','heatmap')] = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=grid[0,2])
gs[('HU','barplot')] = gridspec.GridSpecFromSubplotSpec(1, 24, subplot_spec=grid[0,1], wspace=0)
gs[('RM','heatmap')] = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=grid[1,2])
gs[('RM','barplot')] = gridspec.GridSpecFromSubplotSpec(1, 24, subplot_spec=grid[1,1], wspace=0)
### Schematic ###
ax = plt.subplot(gs['schematic'][:])
ax.text(-0.1, 1.125, chr(ord('A')), transform=ax.transAxes,
fontsize=9, fontweight='bold', va='center', ha='right')
ax.axis('off')
### Box plots ###
groups_sp = spores_df.groupby(['selection','environment'])
groups_hy = hybrids_df.groupby(['selection','environment'])
groups_cl = clone_df.groupby(['selection','environment'])
for (ii, (env_evo, env_test)) in enumerate([('HU','HU'),('RM','RM')]):
# Group by evolution and test environment
S = groups_sp.get_group((env_evo, env_test))
H = groups_hy.get_group((env_evo, env_test))
C = groups_cl.get_group((env_evo, env_test))
# Filter by dictionary
S = filter_spores(S, env_evo)
H = filter_hybrids(H, env_evo)
# Apply sorting ranks to reorder rows
S = sort_spores(S, env_evo)
H = sort_hybrids(H, env_evo)
### Spores barplot ###
ax1 = plt.subplot(gs[(env_evo,'barplot')][:7])
ax1.text(-0.2, 1.15, chr(3*ii + ord('B')), transform=ax1.transAxes,
fontsize=9, fontweight='bold', va='center', ha='right')
ax1.text(0, 1.15,
'Selection: %s\nMeasurement: %s' %\
(config.selection['long_label'][env_evo], config.environment['long_label'][env_test]),
transform=ax1.transAxes,
fontsize=6, va='center', ha='left')
S = S.groupby(['group','background','gene','genotype_short','tetrad','spore'], sort=False)[param]\
.agg([np.mean, np.median, np.std, 'count'])['mean']\
.unstack(level=['group','background','gene','genotype_short'])
S_ref = S.ix[:,'ancestral'].median().values[0]
S = S-S_ref
bp = S.plot(
ax=ax1, kind='box', by='group', return_type='dict',
labels=S.columns.get_level_values('group')
)
colors = [config.spores_gt_short['color'][env_evo][x] for x in S.columns.get_level_values('genotype_short')]
plot.boxplot_custom(bp, ax1, colors=colors, hatches=[' ']*10)
ax1.set_title('Spores (haploid)', fontsize=6, y=1, weight='bold')
ax1.set_xlabel('')
ax1.set_ylabel(r'Rel. growth rate, $\lambda^{btd}_{a\alpha}$', fontsize=6, labelpad=2)
### Hybrids barplot ###
ax2 = plt.subplot(gs[(env_evo,'barplot')][7:], sharey=ax1)
H = H.groupby(['group','background','gene','genotype_short','tetrad','spore'], sort=False)[param]\
.agg([np.mean, np.median, np.std, 'count'])['mean']\
.unstack(level=['group','background','gene','genotype_short'])
ix_use = pd.MultiIndex.from_tuples([[('ancestral', 'ancestral')]], names=['group'])
H_ref = H.loc[:,H.columns.get_level_values('group').isin(ix_use.get_level_values(0))].median().squeeze()
H = H-H_ref
C = C.groupby(['group','background','gene','genotype_short','isolate'], sort=False)[param]\
.agg([np.mean, np.median, np.std, 'count'])['mean']
C_ref = C[('ancestral', 'ancestral')].median()
C = C-C_ref
C = C.unstack(level=['group','background','gene','genotype_short'])
C = C.loc[:,(C.columns.get_level_values('group').isin([('evolved','evolved')])\
&~(C.columns.get_level_values('gene').isin([('','')])))]
C = C.reindex(columns=H.columns)
C = C.dropna(how='all')
bp = H.plot(
ax=ax2, kind='box', by='group', return_type='dict',
labels=H.columns.get_level_values('group')
)
colors = [config.hybrids_gt_short['color'][env_evo][x] for x in H.columns.get_level_values('genotype_short')]
plot.boxplot_custom(bp, ax2, colors=colors, hatches=[' ']*30)
for i,d in enumerate(C):
y = C[d]
x = [i+1]*len(y)
ax2.plot(x, y,
mfc=config.hybrids_gt_short['color'][env_evo][d[-1]], mec='k',
ms=3, marker="D", linestyle="None", zorder=6)
ax2.set_title('Hybrids (diploid)', fontsize=6, y=1, weight='bold')
ax2.set_xlabel('')
ax2.set_ylabel('', fontsize=6)
wt_artist = lines.Line2D((0,.75),(0,0), mec='k', mfc=config.hybrids_gt_short['color'][env_evo][('+','+')], marker='s', markersize=4, linestyle='')
het_artist = lines.Line2D((0,.75),(0,0), mec='k', mfc=config.hybrids_gt_short['color'][env_evo][('+','-')], marker='s', markersize=4, linestyle='')
hom_artist = lines.Line2D((0,.75),(0,0), mec='k', mfc=config.hybrids_gt_short['color'][env_evo][('-','-')], marker='s', markersize=4, linestyle='')
clone_artist = lines.Line2D((0,.75),(0,0), mec='k', mfc='w', marker='D', markersize=3, linestyle='')
leg = ax2.legend([wt_artist,het_artist,hom_artist,clone_artist],
['WT','het.','hom.','clone'], ncol=1,
frameon=False, loc='upper right',
borderaxespad=0, handlelength=0.75,
prop={'size':5}, labelspacing=.32)
# Grid
for ax, g in zip([ax1,ax2],[S,H]):
### horizontal ###
ax.yaxis.grid(ls="-", lw=.8, color="0.9", zorder=0)
ax.axhline(y=0., c='k', ls="--", dashes=(7, 7), lw=.8, zorder=1)
ax.set_axisbelow(True)
### vertical ###
## Background
xstart, xend, xlabels = plot.set_custom_labels(g.columns, 0)
# labels
for k, v in xlabels.iteritems():
ax.annotate('\nx\n'.join(k) if isinstance(k, tuple) else k,
xy=(v+1, 0.97), xycoords=("data", "axes fraction"),
ha='center', va='top', annotation_clip=False, fontsize=5)
# grid
xgrid=[xst+1.5 for xst in list(set(xstart.values()))]
[ax.axvline(x, lw=1.0, ls='-', color='0.9', zorder=0) for x in xgrid]
## gene
xend, xstart, xlabels = plot.set_custom_labels(g.columns, 2)
transform = transforms.blended_transform_factory(ax.transData, ax.transAxes)
for k in xlabels:
if (k!='') & (k!=('','')):
if abs(xstart[k]-xend[k])>0:
line = lines.Line2D([xstart[k]+.75,xend[k]+1.25], [-.05,-.05],
color='k', lw=1, transform=transform)
else:
line = lines.Line2D([xstart[k]+.75,xend[k]+1.25], [-.05,-.05],
color='k', lw=1, transform=transform)
ax.add_line(line)
line.set_clip_on(False)
ax.set_xticks([x+1 for x in xlabels.values()], minor=False)
di = {u'no driver': u'no\ndriver', u'/': u'',
u'\nRNR2': u'RNR2\nRNR2', u'\nRNR4': u'RNR4\nRNR4',
u'\nno driver': u'no\ndriver', u'no driver\nno driver': u'no\ndriver',
u'\nFPR1': u'FPR1\nFPR1', u'\nTOR1': u'TOR1\nTOR1'}
xlabels = ['\n'.join(k) if isinstance(k, tuple) else k for k in xlabels.keys()]
xlabels = [di[x] if x in di else x for x in xlabels]
ax.set_xticklabels(xlabels, minor=False, fontsize=5, style='italic', va='top')
ax.tick_params(axis='x', which='minor', size=0, pad=-30)
ax.tick_params(axis='x', which='major', size=0, pad=10)
ax.tick_params(axis='y', which='major', labelsize=6)
if env_evo=='HU':
ax.set_ylim(-0.25,0.75)
ax.yaxis.set_major_locator( ticker.MaxNLocator(nbins = 4) )
ax.yaxis.set_minor_locator( ticker.MaxNLocator(nbins = 4) )
elif env_evo=='RM':
ax.set_ylim(-0.5,2.0)
ax.yaxis.set_major_locator( ticker.MaxNLocator(nbins = 5) )
ax.yaxis.set_minor_locator( ticker.MaxNLocator(nbins = 5) )
### Heatmaps ###
for (ii, (env_evo, env_test)) in enumerate([('HU','HU'),('RM','RM')]):
# Group by evolution and test environment
S = groups_sp.get_group((env_evo, env_test))
H = groups_hy.get_group((env_evo, env_test))
# Apply sorting ranks to reorder rows
S = sort_spores(S, env_evo)
H = sort_hybrids(H, env_evo)
ax = plt.subplot(gs[(env_evo,'heatmap')][:])
ax.text(-0.15, 1.175, chr(3*ii + ord('C')), transform=ax.transAxes,
fontsize=9, fontweight='bold', va='center', ha='right')
ax.text(0.5, 1.175,
'Selection: %s\nMeasurement: %s' %\
(config.selection['long_label'][env_evo], config.environment['long_label'][env_test]),
transform=ax.transAxes,
fontsize=6, va='center', ha='center')
# Spores
S = S.groupby([u'mating',u'group',u'background',u'genotype_short',u'gene'],
sort=False).agg(np.mean)[param]
S_ref = S.ix[:,'ancestral'].mean()
S = S-S_ref
title = ''
xlabel= ''
ylabel= ''
xticklabels = []
yticklabels = []
vmax = max(S.min(), S.max())
vmin = -vmax
plot.heatmap_spores(
S, ax, title,
xlabel, ylabel, xticklabels, yticklabels,
cmap=plt.cm.RdBu_r, vmin=vmin, vmax=vmax, radius=0.25
)
# Hybrids
H = H.groupby([u'group_MATa',u'background_MATa',u'gene_MATa',u'genotype_short_MATa',
u'group_MATα',u'background_MATα',u'gene_MATα',u'genotype_short_MATα'],
sort=False).agg(np.mean)[param]
H = H.unstack(level=[u'group_MATα',u'background_MATα',u'gene_MATα',u'genotype_short_MATα'])
H_ref = H.loc['ancestral','ancestral'].loc['WAxNA','WAxNA'].values.squeeze()
H = H-H_ref
title = ''
xlabel= ''
ylabel= ''
xticklabels = []
yticklabels = []
vmax = max(np.nanmin(H), np.nanmax(H), key=abs)#H.values.max()
vmin = -vmax
legend_title = r'$\langle\lambda\rangle_{a\alpha}^{td}$'
plot.heatmap_hybrids(
H, ax, title,
xlabel, ylabel, xticklabels, yticklabels,
fold=False, legend_title=legend_title, cmap=plt.cm.RdBu_r,
vmin=vmin, vmax=vmax, pad=30
)
ax.xaxis.set_ticks_position('top')
ax.yaxis.set_ticks_position('left')
ax.annotate(r'$\mathbf{a}$', xy=(-0.1, 1.01), xycoords=('axes fraction', 'axes fraction'),
ha='center', va='bottom', annotation_clip=False, weight='bold', fontsize=8)
ax.annotate(r'$\mathbf{\alpha}$', xy=(-0.01, 1.1), xycoords=('axes fraction', 'axes fraction'),
ha='right', va='center', annotation_clip=False, weight='bold', fontsize=8)
## Gene
# labels
xstart, xend, xlabels = plot.set_custom_labels(H.columns, 2)
for k, v in xlabels.iteritems():
ax.annotate(k, xy=(v+0.5, 1.12), xycoords=("data", "axes fraction"),
ha='center', va='top', annotation_clip=False,
style=('italic' if k!='no driver' else 'normal'), fontsize=5)
ystart, yend, ylabels = plot.set_custom_labels(H.index, 2)
for k, v in xlabels.iteritems():
ax.annotate(k, xy=(-0.12, v+0.5), xycoords=("axes fraction", "data"),
ha='left', va='center', annotation_clip=False,
style=('italic' if k!='no driver' else 'normal'), fontsize=5, rotation=90)
## Background
xstart, xend, xlabels = plot.set_custom_labels(H.columns, 0)
ax.set_xticks([x+0.5 for x in xlabels.values()], minor=False)
ax.set_xticklabels(xlabels.keys(), minor=False, fontsize=6)
xgrid=[xst+1. for xst in list(set(xstart.values()))]
[ax.axvline(g, lw=1, ls="-", color="black") for g in xgrid]
ystart, yend, ylabels= plot.set_custom_labels(H.columns, 0)
ax.set_yticks([y+0.5 for y in ylabels.values()], minor=False)
ax.set_yticklabels(ylabels.keys(), minor=False, fontsize=6, rotation=90)
ygrid=[yst+1. for yst in list(set(ystart.values()))]
[ax.axhline(g, lw=1, ls="-", color="black") for g in ygrid]
for x in ([-1]+xstart.values()):
line = lines.Line2D([x+1,x+1], [0.,-.5], color='k', lw=1)
ax.add_line(line)
line.set_clip_on(False)
for y in ([-1]+ystart.values()):
line = lines.Line2D([0.,-.5], [y+1,y+1], color='k', lw=1)
ax.add_line(line)
line.set_clip_on(False)
ax.tick_params(axis='both', which='minor', size=0, pad=10)
ax.tick_params(axis='both', which='major', size=0, pad=18)
### Variance components ###
var_comp = lmm_var_comp.set_index(['selection','environment','type'])
var_comp = var_comp.sort_index(level=['selection','environment','type'])
var_comp = var_comp.sort_index(ascending=[False,False,True])
# Fix columns
var_comp = var_comp.rename(
columns={
'background (genotype)':'Background\n(genotype)',
'de novo (genotype)':'De novo\n(genotype)',
'time':'Time of\nsampling',
'auxotrophy':'Auxotrophy'
}
)
axes = {}
for ii, (env_evo, ge) in enumerate(var_comp.groupby(level='selection')):
if env_evo=='HU':
axes[env_evo] = plt.subplot(gs['variance'][ii])
axes[env_evo].text(-0.1, 1.35, chr(ord('D')), transform=axes[env_evo].transAxes,
fontsize=9, fontweight='bold', va='center', ha='right')
else:
axes[env_evo] = plt.subplot(gs['variance'][ii], sharex=axes['HU'])
ax = axes[env_evo]
utils.simple_axes(ax)
ge.plot(
ax=ax, kind='barh', stacked=True,
color=[config.factors['color'][x] for x in ge.columns], edgecolor='w',
align='center', legend=False, width=0.75, rasterized=True
)
bars = ax.patches
hatches = [config.factors['hatch'][x] for x in ge.index.get_level_values('type')]*len(ge)
for bar, hatch in zip(bars, hatches):
bar.set_hatch(hatch)
# x-axis
ax.set_xlabel('Variance (%)', fontsize=6, labelpad=2, visible=True)
xscale = 1e-2
xticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/xscale))
ax.xaxis.set_major_formatter(xticks)
# y-axis
ax.set_ylabel('')
ystart, yend, ylabels = plot.set_custom_labels(ge.index, 1)
ax.set_yticks(ylabels.values())
ax.set_yticklabels(ylabels.keys(), fontsize=6)
# Annotate panels and axis
ax.annotate(env_evo, xy=(1, 0.05), xycoords=('axes fraction', 'axes fraction'),
ha='right', va='bottom', fontsize=6)
ax.tick_params(axis='both', which='major', labelsize=6, size=2)
# Fix x-axis labels (missing due to boxplot styling)
axes['RM'].xaxis.set_visible(True)
plt.setp(axes['RM'].get_xticklabels(), visible=True)
leg1 = ax.legend(bbox_to_anchor=(0.5, -0.65), ncol=4,
frameon=False, loc='lower center',
borderaxespad=0, handlelength=0.75, prop={'size':6})
s_artist = patches.Rectangle((0,0), width=1, height=1,
facecolor='w', edgecolor='k')
h_artist = patches.Rectangle((0,0), width=1, height=1, hatch='///',
facecolor='w', edgecolor='k')
leg2 = axes['HU'].legend([s_artist,h_artist], ['Spores','Hybrids'],
bbox_to_anchor=(0.5, 1.2), ncol=2,
frameon=False, loc='upper center',
borderaxespad=0, handlelength=0.75, prop={'size':6})
ax.add_artist(leg1)
plot.save_figure(dir_paper+'figures/figure6/figure6')
plt.show()
# -
# **Fig. 6:** Fitness contribution of genetic background and *de novo* mutations. (**A**) To determine fitness effects of background variation and de novo mutations in hydroxyurea (*RNR2*, *RNR4*) and rapamycin (*FPR1*, *TOR1*), we isolated individuals from ancestral and evolved populations. From these diploid cells, we sporulated and selected haploid segregants of each mating type. Spores with mutations in *RNR2*, *RNR4* and *TOR1* were genotyped to test if they carry the wild-type or mutated allele. We crossed the *MAT*a and *MAT*α versions to create hybrids (48x48 in hydroxyurea and 56x56 in rapamycin). Independent segregants were used to measure biological variability of ancestral and evolved backgrounds. All panels follow this legend. (**B**, **E**) Relative growth rate, $\lambda$, measured with respect to the ancestral population for multiple combinations (background genotype, $b$; *de novo* genotype, $d$; time of sampling during the selection phase, $t$; auxotrophy, $x$) and averaged over measurement replicates. Medians and 25%/75% percentiles across groups are shown, with medians as horizontal black lines and colored by de novo genotype [wild-type +/+ (blue); heterozygote +/− (cyan); homozygote −/− (green)]. Outliers (circles) and isolated, selected clones with matching genotypes (diamonds) are highlighted. (**D**) Variance decomposition of the growth rate of spores (solid) and hybrids (hatched) that can be attributed to different components using a linear mixed model. Estimates of variance components are obtained by restricted maximum likelihood (Fig. S12 and Table S6). (**C**, **F**) Ensemble average of the growth rate of spores and hybrids . An extended version of the figure with all combinations and controls can be found in Figs. S11 and S12, respectively.
# ## Figure S10 - Background-averaged fitness effects (full matrix)
# +
param='norm_growth_rate'
fig = plt.figure(figsize=(8, 8))
grid = gridspec.GridSpec(2, 2, hspace=0.35, wspace=0.25)
gs = {}
gs[('HU','HU')] = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=grid[0,0])
gs[('HU','SC')] = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=grid[0,1])
gs[('RM','RM')] = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=grid[1,0])
gs[('RM','SC')] = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=grid[1,1])
groups_sp = spores_df.groupby(['selection','environment'])
groups_hy = hybrids_df.groupby(['selection','environment'])
groups_cl = clone_df.groupby(['selection','environment'])
for (ii, (env_evo, env_test)) in enumerate([('HU','HU'),('HU','SC'),('RM','RM'),('RM','SC')]):
# Group by evolution and test environment
S = groups_sp.get_group((env_evo, env_test))
H = groups_hy.get_group((env_evo, env_test))
C = groups_cl.get_group((env_evo, env_test))
# Apply sorting ranks to reorder rows
S = sort_spores(S, env_evo)
H = sort_hybrids(H, env_evo)
### Heatmap ###
ax = plt.subplot(gs[(env_evo, env_test)][0])
ax.text(-0.115, 1.2, chr(ii + ord('A')), transform=ax.transAxes,
fontsize=9, fontweight='bold', va='center', ha='right')
ax.text(0.5, 1.2,
'Selection: %s\nMeasurement: %s' %\
(config.selection['long_label'][env_evo], config.environment['long_label'][env_test]),
transform=ax.transAxes,
fontsize=6, va='center', ha='center')
# Spores
S = S.groupby([u'mating',u'group',u'background',u'gene',u'genotype_short',u'tetrad',u'spore'],
sort=False)[param].agg(np.median).reset_index()
S = S.set_index('mating')[param]
S_ref = np.nanmean(S)
S = S-S_ref
title = ''
xlabel= ''
ylabel= ''
xticklabels = []
yticklabels = []
vmax = max(S.min(), S.max())
vmin = -vmax
plot.heatmap_spores(
S, ax, title,
xlabel, ylabel, xticklabels, yticklabels,
cmap=plt.cm.RdBu_r, vmin=vmin, vmax=vmax, radius=0.5
)
# Hybrids
H = H.groupby([u'group_MATa',u'background_MATa',u'gene_MATa',u'genotype_short_MATa',u'tetrad_MATa',u'spore_MATa',
u'group_MATα',u'background_MATα',u'gene_MATα',u'genotype_short_MATα',u'tetrad_MATα',u'spore_MATα'],
sort=False).agg(np.median)[param]
H = H.unstack(level=[u'group_MATα',u'background_MATα',u'gene_MATα',u'genotype_short_MATα',u'tetrad_MATα',u'spore_MATα'])
H_ref = np.nanmean(H.loc['ancestral','ancestral'].loc['WAxNA','WAxNA'])
H = H-H_ref
title = ''
xlabel= ''
ylabel= ''
xticklabels = []
yticklabels = []
vmax = max(np.nanmin(H), np.nanmax(H), key=abs)
vmin = -vmax
legend_title = r'$\lambda^{btd}_{a\alpha}$'
plot.heatmap_hybrids(
H, ax, title,
xlabel, ylabel, xticklabels, yticklabels,
fold=False, legend_title=legend_title, cmap=plt.cm.RdBu_r,
vmin=vmin, vmax=vmax, pad=30
)
print 'Spores\nSelection: %s, Environment: %s, Pass: %4d, Fail: %4d' \
% (env_evo, env_test, S.notnull().values.flatten().sum(), S.isnull().values.flatten().sum())
print 'Hybrids\nSelection: %s, Environment: %s, Pass: %4d, Fail: %4d\n' \
% (env_evo, env_test, H.notnull().values.flatten().sum(), H.isnull().values.flatten().sum())
ax.xaxis.set_ticks_position('top')
ax.yaxis.set_ticks_position('left')
ax.annotate(r'$\mathbf{a}$', xy=(-0.075, 1.01), xycoords=('axes fraction', 'axes fraction'),
ha='center', va='bottom', annotation_clip=False, weight='bold', fontsize=8)
ax.annotate(r'$\mathbf{\alpha}$', xy=(-0.01, 1.075), xycoords=('axes fraction', 'axes fraction'),
ha='right', va='center', annotation_clip=False, weight='bold', fontsize=8)
## Gene + genotype
# labels and grid
xstart, xend, xlabels = plot.set_custom_labels(H.columns, slice(2, 4))
for k, v in xlabels.iteritems():
ax.annotate(k[0].replace('no driver','no\ndri.'),
xy=(v+0.5, 1.05), xycoords=("data", "axes fraction"),
ha='center', va='bottom', annotation_clip=False,
style=('italic' if k[0]!='no driver' else 'normal'), fontsize=6)
xgrid=[xst+1. for xst in list(set(xstart.values()))]
[ax.axvline(g, lw=.75, ls="--", dashes=(5, 2), color="gray") for g in xgrid]
for x in ([-1]+xstart.values()):
line = lines.Line2D([x+1,x+1], [0.,-3], color='gray', ls='-', lw=.75)
ax.add_line(line)
line.set_clip_on(False)
ystart, yend, ylabels = plot.set_custom_labels(H.index, slice(2, 4))
for k, v in ylabels.iteritems():
ax.annotate(k[0].replace('no driver','no\ndri.'),
xy=(-0.05, v+0.5), xycoords=("axes fraction", "data"),
ha='right', va='center', annotation_clip=False,
style=('italic' if k[0]!='no driver' else 'normal'), fontsize=6, rotation=90)
ygrid=[yst+1. for yst in list(set(ystart.values()))]
[ax.axhline(g, lw=.75, ls="--", dashes=(5, 2), color="gray") for g in ygrid]
for y in ([-1]+ystart.values()):
line = lines.Line2D([0.,-3], [y+1,y+1], color='gray', ls='-', lw=.75)
ax.add_line(line)
line.set_clip_on(False)
## Background
# labels and grid
xstart, xend, xlabels = plot.set_custom_labels(H.columns, 0)
for k, v in xlabels.iteritems():
ax.annotate(config.population['short_label'][k],
xy=(v+0.5, config.population['pad'][k]+1), xycoords=("data", "axes fraction"),
ha='center', va='bottom', annotation_clip=False, fontsize=6)
xgrid=[xst+1. for xst in list(set(xstart.values()))]
[ax.axvline(g, lw=.75, ls="-", color="k") for g in xgrid]
for x in ([-1]+xstart.values()):
line = lines.Line2D([x+1,x+1], [0.,-4], color='k', lw=1)
ax.add_line(line)
line.set_clip_on(False)
ystart, yend, ylabels = plot.set_custom_labels(H.index, 0)
for k, v in ylabels.iteritems():
ax.annotate(config.population['short_label'][k],
xy=(-config.population['pad'][k], v+0.5), xycoords=("axes fraction", "data"),
ha='right', va='center', annotation_clip=False, fontsize=6, rotation=90)
ygrid=[yst+1. for yst in list(set(ystart.values()))]
[ax.axhline(g, lw=.75, ls="-", color="k") for g in ygrid]
for y in ([-1]+ystart.values()):
line = lines.Line2D([0.,-4], [y+1,y+1], color='k', lw=1)
ax.add_line(line)
line.set_clip_on(False)
ax.tick_params(axis='both', which='minor', size=0, pad=2)
ax.tick_params(axis='both', which='major', size=0, pad=15)
plot.save_figure(dir_supp+'figures/supp_figure_pheno_cross/supp_figure_pheno_cross_extended')
plt.show()
# -
# **Fig. S10**: Fitness contribution of genetic background and *de novo* mutations. Given an ensemble of $n_b$ unique genetic backgrounds (${n_b\,{=}\,48}$ in hydroxyurea and ${n_b\,{=}\,56}$ in rapamycin), we constructed a matrix of size $n_b \times n_b$ where every unique haploid background is crossed against itself and all other haploid backgrounds, and the two must be of opposite mating type (*MAT*a or *MAT*α). Each matrix element is labeled by background genotype, $b$; *de novo* genotype, $d$; time, $t$; and auxotrophy, $x$. Measurements of relative growth rates of spores $\lambda^{btd}_{\{a,\alpha\}}$ and hybrids $\lambda^{btd}_{a\alpha}$ are shown, normalized with respect to the ancestral WAxNA crosses. Measurements are taken in (**A**) SC+HU 10 $\text{mg ml}^{-1}$ and (**B**) SC; (**C**) SC+RM 0.025 $\mu\text{g ml}^{-1}$ and (**D**) SC, respectively. The color scale for all matrices to the right of each panel indicates the relative fold-change with respect to the ancestral WAxNA crosses. White boxes indicate missing data due to mating inefficiency and slow growth.
# ## Figure S11- Background-averaged fitness effects (control)
# +
param='norm_growth_rate'
fig = plt.figure(figsize=(9.5, 6))
grid = gridspec.GridSpec(2, 2, width_ratios=[3,1], hspace=0.4, wspace=0.2)
gs = {}
gs[('HU','barplot')] = gridspec.GridSpecFromSubplotSpec(1, 24, subplot_spec=grid[0,0], wspace=0)
gs[('HU','heatmap')] = gridspec.GridSpecFromSubplotSpec(1, 1,subplot_spec=grid[0,1])
gs[('RM','barplot')] = gridspec.GridSpecFromSubplotSpec(1, 24, subplot_spec=grid[1,0], wspace=0)
gs[('RM','heatmap')] = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=grid[1,1])
### Box plots ###
groups_sp = spores_df.groupby(['selection','environment'])
groups_hy = hybrids_df.groupby(['selection','environment'])
groups_cl = clone_df.groupby(['selection','environment'])
for (ii, (env_evo, env_test)) in enumerate([('HU','SC'),('RM','SC')]):
# Group by evolution and test environment
S = groups_sp.get_group((env_evo, env_test))
H = groups_hy.get_group((env_evo, env_test))
C = groups_cl.get_group((env_evo, env_test))
# Filter by dictionary
S = filter_spores(S, env_evo)
H = filter_hybrids(H, env_evo)
# Apply sorting ranks to reorder rows
S = sort_spores(S, env_evo)
H = sort_hybrids(H, env_evo)
### Spores barplot ###
ax1 = plt.subplot(gs[(env_evo,'barplot')][:7])
ax1.text(-0.2, 1.15, chr(2*ii + ord('A')), transform=ax1.transAxes,
fontsize=9, fontweight='bold', va='center', ha='right')
ax1.text(0, 1.15,
'Selection: %s\nMeasurement: %s' %\
(config.selection['long_label'][env_evo], config.environment['long_label'][env_test]),
transform=ax1.transAxes,
fontsize=6, va='center', ha='left')
S = S.groupby(['group','background','gene','genotype_short','tetrad','spore'], sort=False)[param]\
.agg([np.mean, np.median, np.std, 'count'])['mean']\
.unstack(level=['group','background','gene','genotype_short'])
S_ref = S.ix[:,'ancestral'].mean().values[0]
S = S-S_ref
bp = S.plot(
ax=ax1, kind='box', by='group', return_type='dict',
labels=S.columns.get_level_values('group')
)
plot.boxplot_custom(bp, ax1,
colors=[config.spores_gt_short['color'][env_evo][x] for x in S.columns.get_level_values('genotype_short')],
hatches=[' ']*10)
ax1.set_title('Spores (haploid)', fontsize=6, weight='bold')
ax1.set_xlabel('')
ax1.set_ylabel(r'Rel. growth rate, $\lambda^{btd}_{a\alpha}$', fontsize=6, labelpad=2)
### Hybrids barplot ###
ax2 = plt.subplot(gs[(env_evo,'barplot')][7:], sharey=ax1)
H = H.groupby(['group','background','gene','genotype_short','tetrad','spore'], sort=False)[param]\
.agg([np.mean, np.median, np.std, 'count'])['mean']\
.unstack(level=['group','background','gene','genotype_short'])
ix_use = pd.MultiIndex.from_tuples([[('ancestral', 'ancestral')]], names=['group'])
H_ref = H.loc[:,H.columns.get_level_values('group').isin(ix_use.get_level_values(0))].mean().squeeze()
H = H-H_ref
C = C.groupby(['group','background','gene','genotype_short','isolate'], sort=False)[param]\
.agg([np.mean, np.median, np.std, 'count'])['mean']
C_ref = C[('ancestral', 'ancestral')].mean()
C = C-C_ref
C = C.unstack(level=['group','background','gene','genotype_short'])
C = C.loc[:,(C.columns.get_level_values('group').isin([('evolved','evolved')])\
&~(C.columns.get_level_values('gene').isin([('','')])))]
C = C.reindex(columns=H.columns)
C = C.dropna(how='all')
bp = H.plot(
ax=ax2, kind='box', by='group', return_type='dict',
labels=H.columns.get_level_values('group')
)
plot.boxplot_custom(bp, ax2,
colors=[config.hybrids_gt_short['color'][env_evo][x] for x in H.columns.get_level_values('genotype_short')],
hatches=[' ']*30)
for i,d in enumerate(C):
y = C[d]
x = [i+1]*len(y)
ax2.plot(x, y,
mfc=config.hybrids_gt_short['color'][env_evo][d[-1]], mec='k',
ms=3, marker='D', linestyle="None", zorder=6)
ax2.set_title('Hybrids (diploid)', fontsize=6, weight='bold')
ax2.set_xlabel('')
ax2.set_ylabel('', fontsize=6)
wt_artist = patches.Rectangle((0,0), width=1, height=1, color=config.hybrids_gt_short['color'][env_evo][('+','+')])
het_artist = patches.Rectangle((0,0), width=1, height=1, color=config.hybrids_gt_short['color'][env_evo][('+','-')])
hom_artist = patches.Rectangle((0,0), width=1, height=1, color=config.hybrids_gt_short['color'][env_evo][('-','-')])
wt_artist = lines.Line2D((0,.75),(0,0), mec='k', mfc=config.hybrids_gt_short['color'][env_evo][('+','+')], marker='s', markersize=4, linestyle='')
het_artist = lines.Line2D((0,.75),(0,0), mec='k', mfc=config.hybrids_gt_short['color'][env_evo][('+','-')], marker='s', markersize=4, linestyle='')
hom_artist = lines.Line2D((0,.75),(0,0), mec='k', mfc=config.hybrids_gt_short['color'][env_evo][('-','-')], marker='s', markersize=4, linestyle='')
clone_artist = lines.Line2D((0,1),(0,0), mec='k', mfc='w', marker='D', markersize=3, linestyle='')
leg = ax2.legend([wt_artist,het_artist,hom_artist,clone_artist],
['WT','het.','hom.','clone'], ncol=1,
frameon=False, loc='upper right',
borderaxespad=0, handlelength=0.75,
prop={'size':5}, labelspacing=.32)
for ax, g in zip([ax1,ax2],[S,H]):
### Horizontal ###
ax.yaxis.grid(ls="-", lw=.8, color="0.9", zorder=-1)
ax.axhline(y=0., c='k', ls="--", dashes=(7, 7), lw=.8, zorder=1)
ax.set_axisbelow(True)
### Bertical ###
## Background
xstart, xend, xlabels = plot.set_custom_labels(g.columns, 0)
# labels
for k, v in xlabels.iteritems():
ax.annotate('\nx\n'.join(k) if isinstance(k, tuple) else k,
xy=(v+1, 0.97), xycoords=("data", "axes fraction"),
ha='center', va='top', annotation_clip=False, fontsize=5)
# grid
xgrid=[xst+1.5 for xst in list(set(xstart.values()))]
[ax.axvline(x, lw=1.0, ls='-', color="0.9", zorder=0) for x in xgrid]
## Gene
xend, xstart, xlabels = plot.set_custom_labels(g.columns, 2)
transform = transforms.blended_transform_factory(ax.transData, ax.transAxes)
for k in xlabels:
if (k!='') & (k!=('','')):
if abs(xstart[k]-xend[k])>0:
line = lines.Line2D([xstart[k]+.75,xend[k]+1.25], [-.05,-.05],
color='k', lw=1, transform=transform)
else:
line = lines.Line2D([xstart[k]+.75,xend[k]+1.25], [-.05,-.05],
color='k', lw=1, transform=transform)
ax.add_line(line)
line.set_clip_on(False)
ax.set_xticks([x+1 for x in xlabels.values()], minor=False)
di = {u'no driver': u'no\ndriver', u'/': u'',
u'\nRNR2': u'RNR2\nRNR2', u'\nRNR4': u'RNR4\nRNR4',
u'\nno driver': u'no\ndriver', u'no driver\nno driver': u'no\ndriver',
u'\nFPR1': u'FPR1\nFPR1', u'\nTOR1': u'TOR1\nTOR1'}
xlabels = ['\n'.join(k) if isinstance(k, tuple) else k for k in xlabels.keys()]
xlabels = [di[x] if x in di else x for x in xlabels]
ax.set_xticklabels(xlabels, minor=False, fontsize=5, style='italic', va='top')
ax.tick_params(axis='x', which='minor', size=0, pad=-30)
ax.tick_params(axis='x', which='major', size=0, pad=10)
ax.tick_params(axis='y', which='major', labelsize=6)
if env_evo=='HU':
ax.set_ylim(-0.25,0.5)
ax.yaxis.set_major_locator( ticker.MaxNLocator(nbins = 3) )
ax.yaxis.set_minor_locator( ticker.MaxNLocator(nbins = 3) )
elif env_evo=='RM':
ax.set_ylim(-0.5,0.5)
ax.yaxis.set_major_locator( ticker.MaxNLocator(nbins = 4) )
ax.yaxis.set_minor_locator( ticker.MaxNLocator(nbins = 4) )
### Heatmaps ###
for (ii, (env_evo, env_test)) in enumerate([('HU','SC'),('RM','SC')]):
# Group by evolution and test environment
S = groups_sp.get_group((env_evo, env_test))
H = groups_hy.get_group((env_evo, env_test))
# Apply sorting ranks to reorder rows
S = sort_spores(S, env_evo)
H = sort_hybrids(H, env_evo)
ax = plt.subplot(gs[(env_evo,'heatmap')][:])
ax.text(-0.15, 1.21, chr(2*ii + ord('B')), transform=ax.transAxes,
fontsize=9, fontweight='bold', va='center', ha='right')
ax.text(0.5, 1.21,
'Selection: %s\nMeasurement: %s' %\
(config.selection['long_label'][env_evo], config.environment['long_label'][env_test]),
transform=ax.transAxes,
fontsize=6, va='center', ha='center')
# Spores
S = S.groupby([u'mating',u'group',u'background',u'genotype_short',u'gene'],
sort=False).agg(np.mean)[param]
S_ref = S.ix[:,'ancestral'].mean()
S = S-S_ref
title = ''
xlabel= ''
ylabel= ''
xticklabels = []
yticklabels = []
vmax = max(S.min(), S.max())
vmin = -vmax
plot.heatmap_spores(S, ax, title,
xlabel, ylabel, xticklabels, yticklabels,
cmap=plt.cm.RdBu_r, vmin=vmin, vmax=vmax, radius=0.25)
# Hybrids
H = H.groupby([u'group_MATa',u'background_MATa',u'gene_MATa',u'genotype_short_MATa',
u'group_MATα',u'background_MATα',u'gene_MATα',u'genotype_short_MATα'],
sort=False).agg(np.mean)[param]
H = H.unstack(level=[u'group_MATα',u'background_MATα',u'gene_MATα',u'genotype_short_MATα'])
H_ref = H.loc['ancestral','ancestral'].loc['WAxNA','WAxNA'].values.squeeze()
H = H-H_ref
title = ''
xlabel= ''
ylabel= ''
xticklabels = []
yticklabels = []
vmax = max(np.nanmin(H), np.nanmax(H), key=abs)
vmin = -vmax
legend_title = r'$\langle \lambda\rangle_{a\alpha}^{td}$'
plot.heatmap_hybrids(H, ax, title,
xlabel, ylabel, xticklabels, yticklabels,
fold=False, legend_title=legend_title, cmap=plt.cm.RdBu_r,
vmin=vmin, vmax=vmax, pad=30)
ax.xaxis.set_ticks_position('top')
ax.yaxis.set_ticks_position('left')
ax.annotate(r'$\mathbf{a}$', xy=(-0.1, 1.01), xycoords=('axes fraction', 'axes fraction'),
ha='center', va='bottom', annotation_clip=False, weight='bold', fontsize=8)
ax.annotate(r'$\mathbf{\alpha}$', xy=(-0.01, 1.1), xycoords=('axes fraction', 'axes fraction'),
ha='right', va='center', annotation_clip=False, weight='bold', fontsize=8)
## Gene
# labels
xstart, xend, xlabels = plot.set_custom_labels(H.columns, 2)
for k, v in xlabels.iteritems():
ax.annotate(k, xy=(v+0.5, 1.12), xycoords=("data", "axes fraction"),
ha='center', va='top', annotation_clip=False,
style=('italic' if k!='no driver' else 'normal'), fontsize=5)
ystart, yend, ylabels = plot.set_custom_labels(H.index, 2)
for k, v in xlabels.iteritems():
ax.annotate(k, xy=(-0.12, v+0.5), xycoords=("axes fraction", "data"),
ha='left', va='center', annotation_clip=False,
style=('italic' if k!='no driver' else 'normal'), fontsize=5, rotation=90)
## Background
# labels and grid
xstart, xend, xlabels = plot.set_custom_labels(H.columns, 0)
ax.set_xticks([x+0.5 for x in xlabels.values()], minor=False)
ax.set_xticklabels(xlabels.keys(), minor=False, fontsize=6)
xgrid=[xst+1. for xst in list(set(xstart.values()))]
[ax.axvline(g, lw=1, ls="-", color="black") for g in xgrid]
ystart, yend, ylabels= plot.set_custom_labels(H.columns, 0)
ax.set_yticks([y+0.5 for y in ylabels.values()], minor=False)
ax.set_yticklabels(ylabels.keys(), minor=False, fontsize=6, rotation=90)
ygrid=[yst+1. for yst in list(set(ystart.values()))]
[ax.axhline(g, lw=1, ls="-", color="black") for g in ygrid]
for x in ([-1]+xstart.values()):
line = lines.Line2D([x+1,x+1], [0.,-.5], color='k', lw=1)
ax.add_line(line)
line.set_clip_on(False)
for y in ([-1]+ystart.values()):
line = lines.Line2D([0.,-.5], [y+1,y+1], color='k', lw=1)
ax.add_line(line)
line.set_clip_on(False)
ax.tick_params(axis='both', which='minor', size=0, pad=10)
ax.tick_params(axis='both', which='major', size=0, pad=18)
plot.save_figure(dir_supp+'figures/supp_figure_pheno_cross/supp_figure_pheno_cross_reduced')
plt.show()
# -
# **Fig. S11:** Ensemble average of fitness effects over genetic backgrounds. (**A**, **C**) Relative growth rate, $\lambda$, measured in a control environment (SC) for cells selected in (A) hydroxyurea and (C) rapamycin. Measurements are normalized with respect to the ancestral population for multiple combinations (background genotype, $b$; *de novo* genotype, $d$; sampling time during selection, $t$; auxotrophy, $x$) and averaged over measurement replicates. Medians and 25\%/75\% percentiles across groups are shown, with medians as horizontal lines and colored by *de novo* genotype [wild-type +/+ (blue); heterozygote +/- (cyan); homozygote -/- (green)]. Outliers (circles) and isolated, selected clones with matching genotypes (diamonds) are highlighted. (**B**, **D**) Ensemble average of the growth rate of spores, $\langle \lambda^{td} \rangle^b_{\{a,\alpha\}}$, and hybrids, $\langle \lambda^{td} \rangle^b_{a\alpha}$ over genetic backgrounds. The color scale for all matrices to the right of each panel indicates the relative fold-change with respect to the ancestral WAxNA crosses.
# ## Figure S12 - Analysis of variance
# ### Linear mixed model
# +
import statsmodels.api as sm
panels = {
'HU': {
'HU':(0,0),
'SC':(1,0)
},
'RM': {
'RM':(0,1),
'SC':(1,1)
}
}
fig = plt.figure(figsize=(8, 4))
grid = gridspec.GridSpec(2, 2, hspace=0.5, wspace=0.1)
gs = {}
var_comp = lmm_var_comp.copy()
var_comp['total_variance'] = var_comp.sum(axis=1)
for ii, (s, e) in enumerate([('HU','HU'),('HU','SC'),('RM','RM'),('RM','SC')]):
gs[(s, e)] = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=grid[panels[s][e]], wspace=0.02)
for ii, ((s, e), fit_all) in enumerate(lmm_fit.groupby(['selection','environment'], sort=False)):
for jj, (t, fit_type) in enumerate(fit_all.groupby('type', sort=False)):
ax = plt.subplot(gs[(s,e)][jj])
utils.simple_axes(ax)
if jj==0:
ax.text(-0.2, 1.125, chr(ii + ord('A')), transform=ax.transAxes,
fontsize=9, fontweight='bold', va='center', ha='right')
ax.annotate('Selection: %s\nMeasurement: %s' %\
(config.selection['long_label'][s], \
config.environment['long_label'][e]),
xy=(0, 1.125), xycoords="axes fraction",
ha='left', va='center', annotation_clip=False, fontsize=6)
nobs = len(fit_type.observed_growth_rate)
y = fit_type.observed_growth_rate
yhat = fit_type.fitted_growth_rate
ymin, ymax = y.quantile([.005, .995])
yrange = ymax - ymin
# Scatter
ax.scatter(y, yhat, facecolor='gray', s=1.5, lw=0, alpha=0.75, rasterized=True)
# Fit
line_fit = sm.OLS(y, sm.add_constant(yhat, prepend=False)).fit().params
fit = lambda x: line_fit[1] + line_fit[0] * x
ax.plot(np.linspace(ymin-.1*yrange, ymax+.1*yrange, nobs),
fit(np.linspace(ymin-.1*yrange, ymax+.1*yrange, nobs)),
label=t, color='k', ls='--', dashes=(5, 2), lw=1)
# Variance explained
var_total = var_comp.groupby(['selection','environment','type']).get_group((s,e,t))['total_variance'].values[0]
ax.annotate('{}\n' r'$r^2$ = {:.2f}'.format(t.capitalize(), var_total),
xy=(.1, .9), xycoords="axes fraction",
ha='left', va='center', fontsize=6)
# x-axis
ax.set_xlim(ymin-.1*yrange, ymax+.1*yrange)
ax.xaxis.set_major_locator( ticker.MaxNLocator(nbins = 4) )
# y-axis
ax.set_ylim(ymin-.1*yrange, ymax+.1*yrange)
ax.yaxis.set_major_locator( ticker.MaxNLocator(nbins = 4) )
ax.set_aspect('equal', adjustable='box')
if jj==0:
ax.annotate(r'Rel. growth rate (observed), $\lambda$',
xy=(1.2, -0.175), xycoords="axes fraction",
ha='center', va='center', annotation_clip=False, fontsize=6)
ax.set_ylabel(r'Rel. growth rate (fitted), $\hat{\lambda}$', fontsize=6)
for ax in fig.get_axes():
ax.tick_params(axis='both', which='major', labelsize=6, size=2)
ax.tick_params(axis='both', which='minor', labelsize=6, size=0)
for loc in ['top','bottom','left','right']:
ax.spines[loc].set_linewidth(.6)
plot.save_figure(dir_supp+'figures/supp_figure_pheno_cross/supp_figure_pheno_cross_lmm')
plt.show()
# -
# **Fig. S12:** Hierarchical analysis of variance in the genetic cross using linear mixed models. We model the growth rate of spores $\lambda_{\{a,\alpha\}}^{btd}$ and hybrids $\lambda_{a\alpha}^{btd}$ as a function of background genotype $b$, *de novo* genotype $d$, sampling time during selection $t$, and auxotrophy $x$. Relative growth rates are accurately fitted by this model (Model 4). Model fits are summarised in Table S6. Measurements are taken in SC+HU 10 $\text{mg ml}^{-1}$ and SC only for populations selected in hydroxyurea (**A**, **B**); SC+RM 0.025 $\mu \text{g ml}^{-1}$ and SC only for populations selected in rapamycin (**C**, **D**). The scatter shows a set of measurements $\lambda$ ($x$-axis) against the fitted rates $\hat{\lambda}$ ($y$-axis). The total variance explained, $r^2$, is separately computed for spores and hybrids by environment.
|
src/figure6.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/Cally02/OOP---58002/blob/main/Concept_in_Python.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="rStM9ySMZT84"
# Create a Class
# + id="fh8xpG5IZYOX"
class Car:
pass
# + [markdown] id="tPsT8TxYZZW3"
# Object Methods
# + colab={"base_uri": "https://localhost:8080/"} id="ZXpBstFpZsm2" outputId="c915d116-030c-4f9c-df08-752cc8e3e380"
class Person:
def __init__(self,name, age):
self.name = name
self.age = age
def myFunction(self):
print("Hello! My name is",self.name)
print("I am",self.age, "years old")
p1 = Person("Angela",19)
p1.myFunction()
# + [markdown] id="EfQBGpBIZ2L2"
# Create an Object
# + colab={"base_uri": "https://localhost:8080/"} id="APmknDN4Z4GW" outputId="aeccb6ab-45d1-4362-9f27-23766bbd9fc9"
class Car:
def __init__(self,name, color): # all classes have function called __init__
self.name = name # attribute names of class named Car
self.color = color
def decription(self):
return "The" + self.name +"has a color" + self.color
def show(self):
print("The"+" "+self.name+" " + "has a color"+" "+self.color)
car1 = Car("Honda City","Black")
car1.show()
# + [markdown] id="J4rM40njZ9OO"
# Modify an object Property
# + colab={"base_uri": "https://localhost:8080/"} id="vKd-blmYaDJO" outputId="a7e8be18-f6b2-48a2-9603-681881cb1ada"
car1.name = "Mitsubishi"
print(car1.name)
car1.color = "Red"
print(car1.color)
# + colab={"base_uri": "https://localhost:8080/"} id="gxQRB8BkaJ9_" outputId="4ec94bce-c614-40c6-ec33-effb27bc117a"
car1.show()
# + [markdown] id="qcc4PqS9aMYI"
# Delete an Object property
# + colab={"base_uri": "https://localhost:8080/"} id="ObivNqxIafb-" outputId="0b320bd0-da0c-446e-dd13-9132410c3414"
class Car(): #Create a class named car
def __init__(self,name,color):
self.name = name #represents the instance of class named Car
self.color = color
def description(self):
return self.name, self.color
def display(self):
print ("The name and color of the car ", self.description())
obj1 = Car("Mitsubishi","blue")
obj1.display()
# + id="hzsCV1z_asFe"
del car1.color
print(car1.color)
# + id="vdKC9vONauge"
print(car1.name)
print(car1.color)
# + [markdown] id="RVzx4YtZa5_-"
# Application 1 - Write a Python program that computes for the Area and Perimeter of a Square, and create a class name Square with side as its attribute
# + colab={"base_uri": "https://localhost:8080/"} id="iH9tCMfea9dn" outputId="177cb47c-f564-41f4-974e-57e79c98c439"
#Area of a Square = s*s
#Perimeter of a Square = 4*s = s+s+s+s
class Square:
def __init__(self,side):
self.side = side
def Area(self):
return self.side*self.side
def Perimeter(self):
return 4*(self.side)
def display(self):
print("The area of a square is", self.Area())
print("The perimeter of a square is", self.Perimeter())
sq1 = Square(2)
sq1.display()
# + [markdown] id="uhUb90BKbEq9"
# Application 2 - Write a Python program that is display your student no. and fullname(Surname, First Name, MI) and create a class name OOP_58002
#
# + colab={"base_uri": "https://localhost:8080/"} id="O4WKMvyKbTjm" outputId="85bd27e0-5643-43b9-c2e2-7b5e7699a4f4"
class Person:
def __init__(self, student, number):
self.student = student
self.number = number
def myFunction(self):
print("Hello! I am", self.student)
print("and my student number is", self.number)
print("Section : OOP-58002")
p1 = Person("<NAME>.", 202111287)
p1.myFunction()
|
Concept_in_Python.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# ---
# # Mini-batch Stochastic Gradient Descent
#
# :label:`chapter_minibatch_sgd`
#
#
# In each iteration, the gradient descent uses the entire training data set to compute the gradient, so it is sometimes referred to as batch gradient descent. Stochastic gradient descent (SGD) only randomly select one example in each iteration to compute the gradient. Just like in the previous chapters, we can perform random uniform sampling for each iteration to form a mini-batch and then use this mini-batch to compute the gradient. Now, we are going to discuss mini-batch stochastic gradient descent.
#
# Set objective function $f(\boldsymbol{x}): \mathbb{R}^d \rightarrow \mathbb{R}$. The time step before the start of iteration is set to 0. The independent variable of this time step is $\boldsymbol{x}_0\in \mathbb{R}^d$ and is usually obtained by random initialization. In each subsequent time step $t>0$, mini-batch SGD uses random uniform sampling to get a mini-batch $\mathcal{B}_t$ made of example indices from the training data set. We can use sampling with replacement or sampling without replacement to get a mini-batch example. The former method allows duplicate examples in the same mini-batch, the latter does not and is more commonly used. We can use either of the two methods
#
# $$\boldsymbol{g}_t \leftarrow \nabla f_{\mathcal{B}_t}(\boldsymbol{x}_{t-1}) = \frac{1}{|\mathcal{B}|} \sum_{i \in \mathcal{B}_t}\nabla f_i(\boldsymbol{x}_{t-1})$$
#
# to compute the gradient $\boldsymbol{g}_t$ of the objective function at $\boldsymbol{x}_{t-1}$ with mini-batch $\mathcal{B}_t$ at time step $t$. Here, $|\mathcal{B}|$ is the size of the batch, which is the number of examples in the mini-batch. This is a hyper-parameter. Just like the stochastic gradient, the mini-batch SGD $\boldsymbol{g}_t$ obtained by sampling with replacement is also the unbiased estimate of the gradient $\nabla f(\boldsymbol{x}_{t-1})$. Given the learning rate $\eta_t$ (positive), the iteration of the mini-batch SGD on the independent variable is as follows:
#
# $$\boldsymbol{x}_t \leftarrow \boldsymbol{x}_{t-1} - \eta_t \boldsymbol{g}_t.$$
#
# The variance of the gradient based on random sampling cannot be reduced during the iterative process, so in practice, the learning rate of the (mini-batch) SGD can self-decay during the iteration, such as $\eta_t=\eta t^\alpha$ (usually $\alpha=-1$ or $-0.5$), $\eta_t = \eta \alpha^t$ (e.g $\alpha=0.95$), or learning rate decay once per iteration or after several iterations. As a result, the variance of the learning rate and the (mini-batch) SGD will decrease. Gradient descent always uses the true gradient of the objective function during the iteration, without the need to self-decay the learning rate.
#
#
# The cost for computing each iteration is $\mathcal{O}(|\mathcal{B}|)$. When the batch size is 1, the algorithm is an SGD; when the batch size equals the example size of the training data, the algorithm is a gradient descent. When the batch size is small, fewer examples are used in each iteration, which will result in parallel processing and reduce the RAM usage efficiency. This makes it more time consuming to compute examples of the same size than using larger batches. When the batch size increases, each mini-batch gradient may contain more redundant information. To get a better solution, we need to compute more examples for a larger batch size, such as increasing the number of epochs.
#
#
# ## Reading Data
#
# In this chapter, we will use a [data set](https://archive.ics.uci.edu/ml/datasets/Airfoil+Self-Noise) developed by NASA to test the wing noise from different aircraft to compare these optimization algorithms. We will use the first 1500 examples of the data set, 5 features, and a normalization method to preprocess the data.
# + attributes={"classes": [], "id": "", "n": "1"}
# %matplotlib inline
import d2l
from mxnet import autograd, gluon, init, np, npx
from mxnet.gluon import nn
npx.set_np()
# Save to the d2l package.
def get_data_ch10(batch_size=10, n=1500):
data = np.genfromtxt('../data/airfoil_self_noise.dat', dtype=np.float32, delimiter='\t')
data = (data - data.mean(axis=0)) / data.std(axis=0)
data_iter = d2l.load_array((data[:n, :-1], data[:n, -1]),
batch_size, is_train=True)
return data_iter, data.shape[1]-1
# -
# ## Implementation from Scratch
#
# We have already implemented the mini-batch SGD algorithm in the
# :numref:`chapter_linear_scratch`. We have made its input parameters more generic
# here, so that we can conveniently use the same input for the other optimization
# algorithms introduced later in this chapter. Specifically, we add the status
# input `states` and place the hyper-parameter in dictionary `hyperparams`. In
# addition, we will average the loss of each mini-batch example in the training
# function, so the gradient in the optimization algorithm does not need to be
# divided by the batch size.
# + attributes={"classes": [], "id": "", "n": "2"}
def sgd(params, states, hyperparams):
for p in params:
p[:] -= hyperparams['lr'] * p.grad
# -
# Next, we are going to implement a generic training function to facilitate the use of the other optimization algorithms introduced later in this chapter. It initializes a linear regression model and can then be used to train the model with the mini-batch SGD and other algorithms introduced in subsequent sections.
# + attributes={"classes": [], "id": "", "n": "3"}
# Save to the d2l package.
def train_ch10(trainer_fn, states, hyperparams, data_iter,
feature_dim, num_epochs=2):
# Initialization
w = np.random.normal(scale=0.01, size=(feature_dim, 1))
b = np.zeros(1)
w.attach_grad()
b.attach_grad()
net, loss = lambda X: d2l.linreg(X, w, b), d2l.squared_loss
# Train
animator = d2l.Animator(xlabel='epoch', ylabel='loss',
xlim=[0, num_epochs], ylim=[0.22, 0.35])
n, timer = 0, d2l.Timer()
for _ in range(num_epochs):
for X, y in data_iter:
with autograd.record():
l = loss(net(X), y).mean()
l.backward()
trainer_fn([w, b], states, hyperparams)
n += X.shape[0]
if n % 200 == 0:
timer.stop()
animator.add(n/X.shape[0]/len(data_iter),
(d2l.evaluate_loss(net, data_iter, loss),))
timer.start()
print('loss: %.3f, %.3f sec/epoch'%(animator.Y[0][-1], timer.avg()))
return timer.cumsum(), animator.Y[0]
# -
# When the batch size equals 1500 (the total number of examples), we use gradient descent for optimization. The model parameters will be iterated only once for each epoch of the gradient descent. As we can see, the downward trend of the value of the objective function (training loss) flattened out after 6 iterations.
# + attributes={"classes": [], "id": "", "n": "4"}
def train_sgd(lr, batch_size, num_epochs=2):
data_iter, feature_dim = get_data_ch10(batch_size)
return train_ch10(
sgd, None, {'lr': lr}, data_iter, feature_dim, num_epochs)
gd_res = train_sgd(1, 1500, 6)
# -
# When the batch size equals 1, we use SGD for optimization. In order to simplify the implementation, we did not self-decay the learning rate. Instead, we simply used a small constant for the learning rate in the (mini-batch) SGD experiment. In SGD, the independent variable (model parameter) is updated whenever an example is processed. Thus it is updated 1500 times in one epoch. As we can see, the decline in the value of the objective function slows down after one epoch.
#
# Although both the procedures processed 1500 examples within one epoch, SGD consumes more time than gradient descent in our experiment. This is because SGD performed more iterations on the independent variable within one epoch, and it is harder for single-example gradient computation to use parallel computing effectively.
# + attributes={"classes": [], "id": "", "n": "5"}
sgd_res = train_sgd(0.005, 1)
# -
# When the batch size equals 100, we use mini-batch SGD for optimization. The time required for one epoch is between the time needed for gradient descent and SGD to complete the same epoch.
# + attributes={"classes": [], "id": "", "n": "6"}
mini1_res = train_sgd(.4, 100)
# -
# Reduce the batch size to 10, the time for each epoch increases because the workload for each batch is less efficient to execute.
# + attributes={"classes": [], "id": "", "n": "7"}
mini2_res = train_sgd(.05, 10)
# -
# Finally, we compare the time versus loss for the preview four experiments. As can be seen, despite SGD converges faster than GD in terms of number of examples processed, it uses more time to reach the same loss than GD because that computing gradient example by example is not efficient. Mini-batch SGD is able to trade-off the convergence speed and computation efficiency. Here, a batch size 10 improves SGD, and a batch size 100 even outperforms GD.
# + attributes={"classes": [], "id": "", "n": "8"}
d2l.set_figsize([6, 3])
d2l.plot(*list(map(list, zip(gd_res, sgd_res, mini1_res, mini2_res))),
'time (sec)', 'loss', xlim=[1e-2, 10],
legend=['gd', 'sgd', 'batch size=100', 'batch size=10'])
d2l.plt.gca().set_xscale('log')
# -
# ## Concise Implementation
#
# In Gluon, we can use the `Trainer` class to call optimization algorithms. Next, we are going to implement a generic training function that uses the optimization name `trainer_name` and hyperparameter `trainer_hyperparameter` to create the instance `Trainer`.
# + attributes={"classes": [], "id": "", "n": "9"}
# Save to the d2l package.
def train_gluon_ch10(trainer_name, trainer_hyperparams,
data_iter, num_epochs=2):
# Initialization
net = nn.Sequential()
net.add(nn.Dense(1))
net.initialize(init.Normal(sigma=0.01))
trainer = gluon.Trainer(
net.collect_params(), trainer_name, trainer_hyperparams)
loss = gluon.loss.L2Loss()
animator = d2l.Animator(xlabel='epoch', ylabel='loss',
xlim=[0, num_epochs], ylim=[0.22, 0.35])
n, timer = 0, d2l.Timer()
for _ in range(num_epochs):
for X, y in data_iter:
with autograd.record():
l = loss(net(X), y)
l.backward()
trainer.step(X.shape[0])
n += X.shape[0]
if n % 200 == 0:
timer.stop()
animator.add(n/X.shape[0]/len(data_iter),
(d2l.evaluate_loss(net, data_iter, loss),))
timer.start()
print('loss: %.3f, %.3f sec/epoch'%(animator.Y[0][-1], timer.avg()))
# -
# Use Gluon to repeat the last experiment.
# + attributes={"classes": [], "id": "", "n": "10"}
data_iter, _ = get_data_ch10(10)
train_gluon_ch10('sgd', {'learning_rate': 0.05}, data_iter)
# -
# ## Summary
#
# * Mini-batch stochastic gradient uses random uniform sampling to get a mini-batch training example for gradient computation.
# * In practice, learning rates of the (mini-batch) SGD can self-decay during iteration.
# * In general, the time consumption per epoch for mini-batch stochastic gradient is between what takes for gradient descent and SGD to complete the same epoch.
#
# ## Exercises
#
# * Modify the batch size and learning rate and observe the rate of decline for the value of the objective function and the time consumed in each epoch.
# * Read the MXNet documentation and use the `Trainer` class `set_learning_rate` function to reduce the learning rate of the mini-batch SGD to 1/10 of its previous value after each epoch.
#
#
# ## Scan the QR Code to [Discuss](https://discuss.mxnet.io/t/2373)
#
# 
|
_10 optimization/minibatch-sgd.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Xarray-spatial
# ### User Guide: Pathfinding
# -----
#
# Xarray-spatial's Pathfinding provides a comprehensive tool for finding the shortest path from one point to another in a raster that can contain any level of complex boundaries or obstacles amidst an interconnected set of traversable path segments.
#
# [A* Pathfinding](#A*)
#
# -----------
#
# #### Let's use datashader to render our images...
#
# First, we'll import some basic packages and some functions from datashader for image rendering.
# +
import numpy as np
import pandas as pd
import datashader as ds
from datashader.transfer_functions import shade
from datashader.transfer_functions import stack
from datashader.transfer_functions import dynspread
from datashader.transfer_functions import set_background
from datashader.colors import Elevation
import xrspatial
# -
# To download the examples data, run the command `xrspatial examples` in your terminal. All the data will be stored in your current directory inside a folder named `xrspatial-examples`.
# ## A*
#
# A* is an informed search algorithm, or a best-first search, meaning that it is formulated in terms of weighted graphs: starting from a specific starting node of a graph, it aims to find a path to the given goal node having the smallest cost (min distance travelled, shortest time, ...).
#
# The `xrspatial.a_star_search` function calculates the shortest path in pixel space from a start location to a goal location through a given aggregate surface graph. The graph should be a line raster which contains crossable and non-crossable (a.k.a walls or barrieres) values. Note that both start and goal are in (lon, lat), or (x, y) coordinate space and must be within the graph. `xrspatial.a_star_search` provides 2 separate options, `snap_start` and `snap_goal`, which can be set to true to snap locations to the nearest valid value before beginning pathfinding. It also provides a `connectivity` option to indicate neighborhood structure. This value can be set to 4 or 8 for 4-connectivity or 8-connectivity.
# Let's generate a fake line raster and find the shortest path with A*.
#
# - First, we'll generate a line raster by setting up a pandas DataFrame specifying the line coordinates.
# - Then, we'll aggregate that into a lines raster with Canvas.line
# - Once we have that, we'll choose a start and goal point to put into the a* pathfinding function.
# - For visualization, we'll also aggregate those points and render them in an image together with the lines.
# +
from xrspatial import a_star_search
# define range of x and y
xrange = (0, 4)
yrange = (0, 4)
# create line raster
ys = [1, 1, 3, 3, 1, 1, np.nan, 1, 3, np.nan, 1, 3, np.nan, 1, 3, np.nan, 2, 2]
xs = [1, 3, 3, 1, 1, 3, np.nan, 1, 3, np.nan, 3, 1, np.nan, 2, 2, np.nan, 1, 3]
line_df = pd.DataFrame(dict(x=xs, y=ys))
W = 800
H = 600
cvs = ds.Canvas(plot_width=W, plot_height=H, x_range=xrange, y_range=yrange)
line_agg = cvs.line(line_df, x="x", y="y").astype(int)
line_shaded = dynspread(shade(line_agg, cmap=["black", "salmon"]))
# pick up 2 random locations
start = (3, 1)
goal = (1, 3)
start_df = pd.DataFrame({"x": [start[1]], "y": [start[0]]})
start_agg = cvs.points(start_df, "x", "y")
start_shaded = dynspread(shade(start_agg, cmap=["red"]), threshold=1, max_px=5)
goal_df = pd.DataFrame({"x": [goal[1]], "y": [goal[0]]})
goal_agg = cvs.points(goal_df, "x", "y")
goal_shaded = dynspread(shade(goal_agg, cmap=["lime"]), threshold=1, max_px=5)
set_background(stack(line_shaded, start_shaded, goal_shaded), "black")
# -
# We're now ready to apply `a_star_search`.
# ### Calculating the 8-connectivity shortest path:
#
# - To calculate the path, we input the line raster and the start and goal point coordinates.
# - We also set the barriers; i.e. cells that are not crossable. In our case, any cell with a value of 0 (all the black non-line cells).
# - Finally, we'll also set snap_start and snap_goal to True.
# - Note: since `a_star_search` uses 8-connectivity by default, we don't need to pass that in.
#
# The shortest path is highlighted in the rendering below.
# +
# find the path from start to goal,
# barriers are uncrossable cells. In this case, they are cells with a value of 0
path_agg_8_connectivity = a_star_search(
line_agg, start, goal, barriers=[0], snap_start=True, snap_goal=True
)
path_shaded = dynspread(shade(path_agg_8_connectivity, cmap=["green"]))
set_background(stack(line_shaded, path_shaded, start_shaded, goal_shaded), "black")
# -
# ### 4-connectivity
#
# For 4-connectivity distance, we use the same arguments as above, but set the connectivity to 4.
# +
# find the path from start to goal,
# barriers are uncrossable cells. In this case, they are cells with a value of 0
path_agg_4_connectivity = a_star_search(
line_agg, start, goal, barriers=[0], snap_start=True, snap_goal=True, connectivity=4
)
path_shaded = dynspread(shade(path_agg_4_connectivity, cmap=["green"]))
set_background(stack(line_shaded, path_shaded, start_shaded, goal_shaded), "black")
# -
#
#
#
# ### References
#
# - A* search algorithm: https://en.wikipedia.org/wiki/A*_search_algorithm
|
examples/user_guide/7_Pathfinding.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: conda_pytorch_p36
# language: python
# name: conda_pytorch_p36
# ---
# %pip install gensim
# +
import sys
sys.path.append('../')
import datasets
import log_reg
from dataproc import extract_wvs
from dataproc import get_discharge_summaries
from dataproc import concat_and_split
from dataproc import build_vocab
from dataproc import vocab_index_descriptions
from dataproc import word_embeddings
from constants import MIMIC_3_DIR, DATA_DIR
import numpy as np
import pandas as pd
from collections import Counter, defaultdict
import csv
import math
import operator
# -
# Let's do some data processing in a much better way, with a notebook.
#
# First, let's define some stuff.
Y = 'full' #use all available labels in the dataset for prediction
notes_file = '%s/NOTEEVENTS.csv' % MIMIC_3_DIR # raw note events downloaded from MIMIC-III
vocab_size = 'full' #don't limit the vocab size to a specific number
vocab_min = 3 #discard tokens appearing in fewer than this many documents
# # Data processing
# ## Combine diagnosis and procedure codes and reformat them
# The codes in MIMIC-III are given in separate files for procedures and diagnoses, and the codes are given without periods, which might lead to collisions if we naively combine them. So we have to add the periods back in the right place.
dfproc = pd.read_csv('%s/PROCEDURES_ICD.csv' % MIMIC_3_DIR)
dfdiag = pd.read_csv('%s/DIAGNOSES_ICD.csv' % MIMIC_3_DIR)
dfdiag['absolute_code'] = dfdiag.apply(lambda row: str(datasets.reformat(str(row[4]), True)), axis=1)
dfproc['absolute_code'] = dfproc.apply(lambda row: str(datasets.reformat(str(row[4]), False)), axis=1)
dfcodes = pd.concat([dfdiag, dfproc])
dfcodes.to_csv('%s/ALL_CODES.csv' % MIMIC_3_DIR, index=False,
columns=['ROW_ID', 'SUBJECT_ID', 'HADM_ID', 'SEQ_NUM', 'absolute_code'],
header=['ROW_ID', 'SUBJECT_ID', 'HADM_ID', 'SEQ_NUM', 'ICD9_CODE'])
# ## How many codes are there?
#In the full dataset (not just discharge summaries)
df = pd.read_csv('%s/ALL_CODES.csv' % MIMIC_3_DIR, dtype={"ICD9_CODE": str})
len(df['ICD9_CODE'].unique())
# ## Tokenize and preprocess raw text
# Preprocessing time!
#
# This will:
# - Select only discharge summaries and their addenda
# - remove punctuation and numeric-only tokens, removing 500 but keeping 250mg
# - lowercase all tokens
# + active=""
# pd.read_csv('../mimicdata/mimic3/DIAGNOSES_ICD.csv')
# -
pd.read_csv(notes_file).head()
#This reads all notes, selects only the discharge summaries, and tokenizes them, returning the output filename
disch_full_file = get_discharge_summaries.write_discharge_summaries(out_file="%s/disch_full.csv" % MIMIC_3_DIR)
# Let's read this in and see what kind of data we're working with
df = pd.read_csv('%s/disch_full.csv' % MIMIC_3_DIR)
df.head()
#How many admissions?
len(df['HADM_ID'].unique())
#Tokens and types
types = set()
num_tok = 0
for row in df.itertuples():
for w in row[4].split():
types.add(w)
num_tok += 1
print("Num types", len(types))
print("Num tokens", str(num_tok))
#Let's sort by SUBJECT_ID and HADM_ID to make a correspondence with the MIMIC-3 label file
df = df.sort_values(['SUBJECT_ID', 'HADM_ID'])
#Sort the label file by the same
dfl = pd.read_csv('%s/ALL_CODES.csv' % MIMIC_3_DIR)
dfl = dfl.sort_values(['SUBJECT_ID', 'HADM_ID'])
len(df['HADM_ID'].unique()), len(dfl['HADM_ID'].unique())
# ## Consolidate labels with set of discharge summaries
# Looks like there were some HADM_ID's that didn't have discharge summaries, so they weren't included with our notes
#Let's filter out these HADM_ID's
hadm_ids = set(df['HADM_ID'])
with open('%s/ALL_CODES.csv' % MIMIC_3_DIR, 'r') as lf:
with open('%s/ALL_CODES_filtered.csv' % MIMIC_3_DIR, 'w') as of:
w = csv.writer(of)
w.writerow(['SUBJECT_ID', 'HADM_ID', 'ICD9_CODE', 'ADMITTIME', 'DISCHTIME'])
r = csv.reader(lf)
#header
next(r)
for i,row in enumerate(r):
hadm_id = int(row[2])
#print(hadm_id)
#break
if hadm_id in hadm_ids:
w.writerow(row[1:3] + [row[-1], '', ''])
dfl = pd.read_csv('%s/ALL_CODES_filtered.csv' % MIMIC_3_DIR, index_col=None)
len(dfl['HADM_ID'].unique())
#we still need to sort it by HADM_ID
dfl = dfl.sort_values(['SUBJECT_ID', 'HADM_ID'])
dfl.to_csv('%s/ALL_CODES_filtered.csv' % MIMIC_3_DIR, index=False)
# ## Append labels to notes in a single file
#Now let's append each instance with all of its codes
#this is pretty non-trivial so let's use this script I wrote, which requires the notes to be written to file
sorted_file = '%s/disch_full.csv' % MIMIC_3_DIR
df.to_csv(sorted_file, index=False)
labeled = concat_and_split.concat_data('%s/ALL_CODES_filtered.csv' % MIMIC_3_DIR, sorted_file)
#name of the file we just made
print(labeled)
# Let's sanity check the combined data we just made. Do we have all hadm id's accounted for, and the same vocab stats?
dfnl = pd.read_csv(labeled)
#Tokens and types
types = set()
num_tok = 0
for row in dfnl.itertuples():
for w in row[3].split():
types.add(w)
num_tok += 1
print("num types", len(types), "num tokens", num_tok)
len(dfnl['HADM_ID'].unique())
# ## Create train/dev/test splits
fname = '%s/notes_labeled.csv' % MIMIC_3_DIR
base_name = "%s/disch" % MIMIC_3_DIR #for output
tr, dv, te = concat_and_split.split_data(fname, base_name=base_name)
# ## Build vocabulary from training data
vocab_min = 3
vname = '%s/vocab.csv' % MIMIC_3_DIR
build_vocab.build_vocab(vocab_min, tr, vname)
# ## Sort each data split by length for batching
for splt in ['train', 'dev', 'test']:
filename = '%s/disch_%s_split.csv' % (MIMIC_3_DIR, splt)
df = pd.read_csv(filename)
df['length'] = df.apply(lambda row: len(str(row['TEXT']).split()), axis=1)
df = df.sort_values(['length'])
df.to_csv('%s/%s_full.csv' % (MIMIC_3_DIR, splt), index=False)
# ## Pre-train word embeddings
# Let's train word embeddings on all words
w2v_file = word_embeddings.word_embeddings('full', '%s/disch_full.csv' % MIMIC_3_DIR, 100, 0, 5)
# + active=""
# import gensim.models.word2vec as w2v
#
#
# -
# ## Write pre-trained word embeddings with new vocab
extract_wvs.gensim_to_embeddings('%s/processed_full.w2v' % MIMIC_3_DIR, '%s/vocab.csv' % MIMIC_3_DIR, Y)
# ## Pre-process code descriptions using the vocab
vocab_index_descriptions.vocab_index_descriptions('%s/vocab.csv' % MIMIC_3_DIR,
'%s/description_vectors.vocab' % MIMIC_3_DIR)
# ## Filter each split to the top 50 diagnosis/procedure codes
Y = 50
#first calculate the top k
counts = Counter()
dfnl = pd.read_csv('%s/notes_labeled.csv' % MIMIC_3_DIR)
for row in dfnl.itertuples():
for label in str(row[4]).split(';'):
counts[label] += 1
codes_50 = sorted(counts.items(), key=operator.itemgetter(1), reverse=True)
codes_50 = [code[0] for code in codes_50[:Y]]
codes_50
with open('%s/TOP_%s_CODES.csv' % (MIMIC_3_DIR, str(Y)), 'w') as of:
w = csv.writer(of)
for code in codes_50:
w.writerow([code])
for splt in ['train', 'dev', 'test']:
print(splt)
hadm_ids = set()
with open('%s/%s_50_hadm_ids.csv' % (MIMIC_3_DIR, splt), 'r') as f:
for line in f:
hadm_ids.add(line.rstrip())
with open('%s/notes_labeled.csv' % MIMIC_3_DIR, 'r') as f:
with open('%s/%s_%s.csv' % (MIMIC_3_DIR, splt, str(Y)), 'w') as of:
r = csv.reader(f)
w = csv.writer(of)
#header
w.writerow(next(r))
i = 0
for row in r:
hadm_id = row[1]
if hadm_id not in hadm_ids:
continue
codes = set(str(row[3]).split(';'))
filtered_codes = codes.intersection(set(codes_50))
if len(filtered_codes) > 0:
w.writerow(row[:3] + [';'.join(filtered_codes)])
i += 1
for splt in ['train', 'dev', 'test']:
filename = '%s/%s_%s.csv' % (MIMIC_3_DIR, splt, str(Y))
df = pd.read_csv(filename)
df['length'] = df.apply(lambda row: len(str(row['TEXT']).split()), axis=1)
df = df.sort_values(['length'])
df.to_csv('%s/%s_%s.csv' % (MIMIC_3_DIR, splt, str(Y)), index=False)
|
notebooks/dataproc_mimic_III.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# + [markdown] id="df8f1bba"
# # **Prediction using Supervised ML**
# Predicting percentage of a student who studies 9.5 hours.
# + id="9749c5a8"
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
# + id="6bbe0478"
def build_model(my_learning_rate):
"""Create and compile a simple linear regression model."""
# Most simple tf.keras models are sequential.
# A sequential model contains one or more layers.
model = tf.keras.models.Sequential()
# Describe the topography of the model.
# The topography of a simple linear regression model
# is a single node in a single layer.
model.add(tf.keras.layers.Dense(units=1,
input_shape=(1,)))
# Compile the model topography into code that
# TensorFlow can efficiently execute. Configure
# training to minimize the model's mean squared error.
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=my_learning_rate),
loss="mean_squared_error",
metrics=[tf.keras.metrics.RootMeanSquaredError()])
return model
def train_model(model, feature, label, epochs, batch_size):
"""Train the model by feeding it data."""
# Feed the feature values and the label values to the
# model. The model will train for the specified number
# of epochs, gradually learning how the feature values
# relate to the label values.
history = model.fit(x=feature,
y=label,
batch_size=batch_size,
epochs=epochs)
# Gather the trained model's weight and bias.
trained_weight = model.get_weights()[0]
trained_bias = model.get_weights()[1]
# The list of epochs is stored separately from the
# rest of history.
epochs = history.epoch
# Gather the history (a snapshot) of each epoch.
hist = pd.DataFrame(history.history)
# Specifically gather the model's root mean
#squared error at each epoch.
rmse = hist["root_mean_squared_error"]
return trained_weight, trained_bias, epochs, rmse
#print("Defined create_model and train_model")
# + id="261de9b6"
data_file=pd.read_csv(filepath_or_buffer="/content/sample_data/DataTask1.csv",sep=',')
# + colab={"base_uri": "https://localhost:8080/", "height": 833} id="83ZBM-48U17r" outputId="33c83f37-b682-4256-d489-bf51cc7f826c"
data_file
# + colab={"base_uri": "https://localhost:8080/"} id="bfzrVi2S6oG5" outputId="d8c9a9d4-2c2c-455a-c43a-b1560c5fa135"
data_file.columns
# + id="e1f613a4"
feature=data_file.loc[:,"Hours"]
# + id="20bfc7f0"
my_feature=np.array(feature)
# + id="a31cd430"
label=data_file.loc[:,"Scores"]
# + id="14b75a29"
my_label=np.array(label)
# + id="2a0bba36"
# Setting the number of epochs to a large value for the model to converge
epochs=3000
# + id="0179662a"
my_batch_size=4
# + id="db150b63"
# Learning rate is a very critical parameter as it decides the step size at each iteration while moving toward a minimum of a loss function.
learning_rate=0.001
# + id="2fb6d200"
my_model=build_model(learning_rate)
# + colab={"base_uri": "https://localhost:8080/"} id="643de1ae" outputId="5fc2523e-f941-4ddd-b50b-7ce70ee45ff2"
trained_weight,trained_bias,epochs,rmse=train_model(my_model,my_feature,my_label,epochs,my_batch_size)
# + [markdown] id="1a616786"
# ## **Model built and trained**
# + id="2ffd68b3"
def plot_the_model(trained_weight, trained_bias, feature, label):
"""Plot the trained model against the training feature and label."""
# Label the axes.
plt.xlabel("feature")
plt.ylabel("label")
# Plot the feature values vs. label values.
plt.scatter(feature, label)
# Create a red line representing the model. The red line starts
# at coordinates (x0, y0) and ends at coordinates (x1, y1).
x0 = 0
y0 = trained_bias
x1 = my_feature[-1]
y1 = trained_bias + (trained_weight * x1)
plt.plot([x0, x1], [y0, y1], c='r')
# Render the scatter plot and the red line.
plt.show()
def plot_the_loss_curve(epochs, rmse):
"""Plot the loss curve, which shows loss vs. epoch."""
plt.figure()
plt.xlabel("Epoch")
plt.ylabel("Root Mean Squared Error")
plt.plot(epochs, rmse, label="Loss")
plt.legend()
plt.ylim([rmse.min()*0.97, rmse.max()])
plt.show()
# + [markdown] id="32bf318e"
# ## **Defined the plot_the_model and plot_the_loss_curve functions.**
# + colab={"base_uri": "https://localhost:8080/", "height": 541} id="9b39ebb9" outputId="0b81cef8-e40a-4b04-b56b-1750bcecfc6d"
plot_the_model(trained_weight, trained_bias, my_feature, my_label)
plot_the_loss_curve(epochs, rmse)
# + [markdown] id="zbtGDoigOv0D"
# As we can see in the above graph, the rmse after close to 1500 epochs remains constant suggesting that the model has converged. And we get a
# good fit to our data points.
# + id="8b3eeed8"
q=np.array([9.5])
# + id="bad6e177"
ans=my_model.predict_on_batch(q)
# + colab={"base_uri": "https://localhost:8080/"} id="b7432ca9" outputId="ed51b06a-d8df-4a3d-c1e6-d06eb81eb100"
print("Prediction is:",ans)
# + id="cuH8xcE_BWhx"
# + id="9yXK2hkLRf5Q"
|
submissions/Keshav_IIEST .ipynb
|
# ---
# jupyter:
# jupytext:
# text_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="2E9PSVGar_P2"
# # Функции, распаковка аргументов
# + [markdown] colab_type="text" id="G8cvP38xsA9c"
# Функция в python - объект, принимающий аргументы и возвращающий значение. Обычно функция определяется с помощью инструкции def.
#
# Определим простейшую функцию:
# + colab={"base_uri": "https://localhost:8080/", "height": 51} colab_type="code" executionInfo={"elapsed": 921, "status": "ok", "timestamp": 1575291863858, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="LAuK2PEUsKVt" outputId="155ca390-8ab2-4138-9b31-41dfe657958f"
def add(x, y):
return x + y # Инструкция return возвращает значение.
print(add(1, 10))
print(add('abc', 'def'))
# + [markdown] colab_type="text" id="9_RoJGBas3Q5"
# Функция может не врзвращать значение. Тогда она вернет `None`.
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 1212, "status": "ok", "timestamp": 1575291853814, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="-yI4x4-EtedU" outputId="4ac3e7da-bae3-44d9-a4b6-42f527fb8678"
def func():
pass
print(func())
# + [markdown] colab_type="text" id="yBVIEOjKtnGm"
# ## Аргументы функции
#
# Функция может принимать произвольное количество аргументов или не принимать их вовсе. Также распространены функции с произвольным числом аргументов, функции с позиционными и именованными аргументами, обязательными и необязательными.
# + colab={"base_uri": "https://localhost:8080/", "height": 85} colab_type="code" executionInfo={"elapsed": 1148, "status": "ok", "timestamp": 1575633834091, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="rD-EwNEyuAW-" outputId="4e21c441-f0c7-4d0b-f875-5d822aaceab2"
# Позиционные аргументы, передаются при вызове строго в том порядке, в котором описаны
def func(a, b, c=2): # c - необязательный аргумент
return a + b + c
print(func(1, 2)) # a = 1, b = 2, c = 2 (по умолчанию)
print(func(1, 2, 3)) # a = 1, b = 2, c = 3
# Но к ним можно обратиться и по имени
print(func(a=1, b=3)) # a = 1, b = 3, c = 2
print(func(a=3, c=6)) # a = 3, c = 6, b не определен, ошибка TypeError
# -
func(b=1, a=3)
# + [markdown] colab_type="text" id="PCUL1a0jFhhm"
# При использовании позиционных аргументов вы вынуждены соблюдать их порядок, в то время как именованные аргументы можно расположить как угодно. Также они позволяют не указывать значения аргументов, у которых есть значения по умолчанию.
#
# Если мы хотим получить только именованные аргументы без захвата неограниченного количества позиционных, Python позволяет сделать это с помощью одинокой звёздочки:
# + colab={"base_uri": "https://localhost:8080/", "height": 248} colab_type="code" executionInfo={"elapsed": 1062, "status": "error", "timestamp": 1575634129382, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="NIO-KmXUB0Dn" outputId="698b7953-8467-4625-80c1-67526eaf14ce"
# Все аргументы после звездочки являются строго именованными
def foo(a, b=3, *, c, d=10):
return(a, b, c, d)
print(foo(1, 2, c=3, d=4))
print(foo(1, c=3, d=4))
# К первым двум по-прежнему можно обращаться и по имени
print(foo(a=10, b=20, c=30, d=40))
# Попытка передачи аргументов как позиционных приведет к ошибке:
print(foo(1, 2, 3, 4))
# + [markdown] colab_type="text" id="_jbrP93AuQxJ"
# Функция также может принимать переменное количество позиционных аргументов, тогда перед именем ставится `*`.
#
# `args` - это кортеж из всех переданных аргументов функции, и с переменной можно работать также, как и с кортежем.
# + colab={"base_uri": "https://localhost:8080/", "height": 68} colab_type="code" executionInfo={"elapsed": 957, "status": "ok", "timestamp": 1575293047043, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="dcQj5pLVucAZ" outputId="5f9af835-767f-41f4-c08d-90d27e916d95"
def func(*args):
return args
print(func(1, 2, 3, 'abc'))
print(func())
print(func(1))
# + [markdown] colab_type="text" id="2xlrXoh7uvKW"
# Функция может принимать и произвольное число именованных аргументов, тогда перед именем ставится `**`.
#
# В переменной `kwargs` у нас хранится словарь, с которым мы тоже можем производить операции.
# + colab={"base_uri": "https://localhost:8080/", "height": 68} colab_type="code" executionInfo={"elapsed": 1217, "status": "ok", "timestamp": 1575292272047, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="A3l4ExdcuuQ4" outputId="0ca68134-49e8-458e-c32c-62871d90f22b"
def func(**kwargs):
return kwargs
print(func(a=1, b=2, c=3))
print(func())
print(func(a='python'))
# -
func(1, 2, c=3)
# + [markdown] colab_type="text" id="iPWkI6iSzFPD"
# ## Распаковка
#
# В Python 3 также появилась возможность использовать оператор `*` для распаковки итерируемых объектов:
# + colab={"base_uri": "https://localhost:8080/", "height": 68} colab_type="code" executionInfo={"elapsed": 1068, "status": "ok", "timestamp": 1575297553302, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="Fl6DfwkcDD7P" outputId="a7bcfdb6-700f-449f-9e58-a95eed14a76e"
fruits = ['lemon', 'pear', 'watermelon', 'tomato']
first, second, *remaining = fruits
print(remaining)
first, *remaining = fruits
print(remaining)
first, *middle, last = fruits
print(middle)
# -
a, b, c, d, e = fruits
print(e)
# + [markdown] colab_type="text" id="Lgcs6x9IDUAZ"
# В Python 3.5 появились новые способы использования оператора `*`. Например, возможность сложить итерируемый объект в новый список.
#
# Допустим, у вас есть функция, которая принимает любую последовательность и возвращает список, состоящий из этой последовательности и её обратной копии, сконкатенированных вместе.
# + colab={} colab_type="code" id="ai1y4TwTD5Q1"
def palindromify(sequence):
return list(sequence) + list(reversed(sequence))
# + [markdown] colab_type="text" id="yHkTOXpXD--V"
# Здесь нам требуется несколько раз преобразовывать последовательности в списки, чтобы получить конечный результат. В Python 3.5 можно поступить по-другому:
# + colab={} colab_type="code" id="DDt9h-cAD_uf"
def palindromify(sequence):
return [*sequence, *reversed(sequence)]
# + [markdown] colab_type="text" id="c5lScjQiEExB"
# Этот вариант избавляет нас от необходимости лишний раз вызывать `list` и делает наш код более эффективным и читаемым.
#
# Такой вариант использования оператора `*` является отличной возможностью для конкатенации итерируемых объектов разных типов. Оператор `*` работает с любым итерируемым объектом, в то время как оператор `+` работает только с определёнными последовательностями, которые должны быть одного типа.
# + colab={"base_uri": "https://localhost:8080/", "height": 51} colab_type="code" executionInfo={"elapsed": 941, "status": "ok", "timestamp": 1575298166488, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="tnh8VCyAEeNz" outputId="8c891ccb-93aa-492d-ef25-0f2bb24aeaf8"
fruits = ['lemon', 'pear', 'watermelon', 'tomato']
print((*fruits[1:], fruits[0]))
uppercase_fruits = (f.upper() for f in fruits)
print({*fruits, *uppercase_fruits}) # новое множество из списка и генератора
# -
{*fruits}
{'lemon', 'pear', 'watermelon', 'tomato'}
# + [markdown] colab_type="text" id="33KGrE0VFd9z"
# В PEP 448 были также добавлены новые возможности для `**`, благодаря которым стало возможным перемещение пар ключ-значение из одного словаря (словарей) в новый:
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 910, "status": "ok", "timestamp": 1575298163804, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="ULVNl_GfFjNG" outputId="05c7a7b6-ecab-4393-f6d1-1601be3faa5f"
date_info = {'year': "2020", 'month': "01", 'day': "01"}
track_info = {'artist': "Beethoven", 'title': 'Symphony No 5'}
all_info = {**date_info, **track_info}
all_info = date_info.copy()
all_info.update(track_info)
print(all_info)
# -
a = [1, 2, 3]
b = [*a]
b
# + [markdown] colab_type="text" id="k3He4HC5vTDR"
# ## Анонимные функции, инструкция lambda
#
# Анонимные функции могут содержать лишь одно выражение, но и выполняются они быстрее.
#
# Анонимные функции создаются с помощью инструкции lambda. Кроме этого, их не обязательно присваивать переменной.
#
# lambda функции, в отличие от обычной, не требуется инструкция return, а в остальном, ведет себя точно так же:
# + colab={"base_uri": "https://localhost:8080/", "height": 102} colab_type="code" executionInfo={"elapsed": 1200, "status": "ok", "timestamp": 1575292510850, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="jvOnFFAqvlAK" outputId="2859db61-c49b-4174-ec52-a9bad0ba0b6e"
func = lambda x, y: x + y
print(func(1, 2))
print(func('a', 'b'))
print((lambda x, y: x + y)(1, 2))
print((lambda x, y: x + y)('a', 'b'))
# lambda функции тоже можно передавать args и kwargs
func = lambda *args: args
print(func(1, 2, 3, 4))
# -
def func(x, y):
return x + y
(lambda x, y: x + y)(1, 2)
# + [markdown] colab_type="text" id="MkL62azYwhWR"
# Как правило, lambda-выражения используются при вызове функций (или классов), которые принимают функцию в качестве аргумента.
#
# К примеру, встроенная функция сортировки Python принимает функцию в качестве ключевого аргумента. Эта ключевая функция использует для вычисления сравнительного ключа при определении порядка сортировки элементов.
# + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 1117, "status": "ok", "timestamp": 1575292758798, "user": {"displayName": "\u041d\u0430\u0434\u0435\u0436\u0434\u0430 \u0414\u0435\u043c\u0438\u0434\u0435\u043d\u043a\u043e", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mA6D7k5OgtG9hzPe8Abs8DfOKAXQoTXaPfn7EY=s64", "userId": "05224310221243935536"}, "user_tz": -180} id="Si3CQthew6u4" outputId="9b770a19-c753-4e90-9a79-5cf44b2eb7b2"
colors = ["Goldenrod", "purple", "Salmon", "turquoise", "cyan"]
print(sorted(colors, reverse=True, key=lambda s: s.lower()))
|
lecture_2/05. Functions.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="XhQf5bN2vrFV" colab_type="text"
# # Semantic parsing with PyText
#
# [PyText](https://engineering.fb.com/ai-research/pytext-open-source-nlp-framework/) is a modeling framework that blurs the boundaries between experimentation and large-scale deployment. In Portal, PyText is used for production natural language processing tasks, including [semantic parsing](https://en.wikipedia.org/wiki/Semantic_parsing). Semantic parsing involves converting natural language input to a logical form that can be easily processed by a machine. Portal by Facebook uses PyText in production to semantically parse user queries. In this notebook, we will use PyText to train a semantic parser on the freely available [Facebook Task Oriented Parsing dataset](https://fb.me/semanticparsingdialog) using the newly open-sourced Sequence-to-sequence framework. We will export the resulting parser to a Torchscript file suitable for production deployment.
#
# ## The PyText sequence-to-sequence framework
#
# We have recently open sourced our production sequence-to-sequence (Seq2Seq) framework in PyText ([framework](https://github.com/facebookresearch/pytext/commit/ff053d3388161917b189fabaa0e3058273ed4314), [Torchscript export](https://github.com/facebookresearch/pytext/commit/8dab0aec0e0456fdeb10ffac110f50e6a1382e6c)). This framework provides an encoder-decoder architecture that is suitable for any task that requires mapping a sequence of input tokens to a sequence of output tokens. Our existing implementation is based on recurrent neural networks (RNNs), which have been shown to be [unreasonably effective](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) at sequence processing tasks. The model we will train includes three major components
# 1. A bidirectional LSTM sequence encoder
# 2. An LSTM sequence decoder
# 3. A sequence generator that supports incremental decoding and beam search
#
# All of these components are Torchscript-friendly, so that the trained model can be exported directly as-is.
#
# # Instructions
#
# The remainder of this notebook installs PyText with its dependencies, downloads the training data to the local VM, trains the model, and verifies the exported Torchscript model. It should run in 15-20 minutes if a GPU is used, and will train a reasonably accurate semantic parser on the Facebook TOP dataset. As detailed below, simply increasing the number of epochs will allow a competitive result to be obtained in about an hour of training time. The notebook will also export a Torchscript model which can be used for runtime inference from Python, C++ or Java.
#
# It is *strongly recommended* that this notebook be run on a GPU.
# + [markdown] id="z7JHMBzqzVm0" colab_type="text"
# # Installing PyText
#
# As of this writing, semantic parsing requires a bleeding-edge version of PyText. The following cell will download the master branch from Github.
#
# If PyText is installed, the packages may change. The notebook will restart in this case. You may rerun the cell after this and everything should be fine.
# + id="-3OJLChpviSa" colab_type="code" colab={}
try:
from pytext.models.seq_models.seq2seq_model import Seq2SeqModel
print("Detected compatible version of PyText. Skipping install.")
print("Run the code in the except block to force PyText installation.")
except ImportError:
# !git clone https://github.com/facebookresearch/pytext.git
# %cd pytext
# !pip install -e .
print("Stopping RUNTIME because we installed new dependencies.")
print("Rerun the notebook and everything should now work.")
import os
os.kill(os.getpid(), 9)
# + [markdown] id="AjnMr9VBzvi4" colab_type="text"
# # Downloading the data
#
# We'll use the Facebook Task Oriented Parsing (TOP) dataset for our example. This dataset is publically available and can be added to the notebook with the following cells.
# + id="S1bMMBc30CE2" colab_type="code" colab={}
# !curl -o semanticparsingdialog.zip -L https://fb.me/semanticparsingdialog
# !unzip -o semanticparsingdialog.zip
# + id="c6l7IRaq5404" colab_type="code" colab={}
TOP_PATH = "/content/top-dataset-semantic-parsing/"
# + [markdown] id="huPCJO7rL0ks" colab_type="text"
# ## Preprocessing the data
#
# In the interest of time, we're going to simplify the data a bit. The notebook contains instructions on how to use the full dataset if you prefer.
#
# Following [Gupta et al.](https://arxiv.org/pdf/1810.07942.pdf), we'll use a single-valued output vocabulary so that our model focuses on predicting semantic structure.
# + id="5hmE5Va5N44C" colab_type="code" colab={}
import random
import re
from contextlib import ExitStack
def make_lotv(input_path, output_path, sample_rate=1.0):
with ExitStack() as ctx:
input_file = ctx.enter_context(open(input_path, "r"))
output_file = ctx.enter_context(open(output_path, "w"))
for line in input_file:
if random.random() > sample_rate:
continue
raw_seq, tokenized_seq, target_seq = line.split("\t")
output_file.write(
"\t".join(
[
raw_seq,
tokenized_seq,
# Change everything but IN:*, SL:*, [ and ] to 0
re.sub(
r"(?!((IN|SL):[A-Z_]+(?<!\S))|\[|\])(?<!\S)((\w)|[^\w\s])+",
"0",
target_seq
)
]
)
)
# Running on the full test set takes around 40 minutes, so using a reduced set
# here. Change to ("test.tsv", 1.0) to evaluate on the full test set.
for f, r in [("train.tsv", 1.0), ("eval.tsv", 1.0), ("test.tsv", 0.1)]:
make_lotv(f"{TOP_PATH}{f}", f"{TOP_PATH}lotv_{f}", r)
# + id="vAdHF89SSHVv" colab_type="code" colab={}
# !head /content/top-dataset-semantic-parsing/lotv_train.tsv
# + id="C3AY48fqcI1X" colab_type="code" colab={}
# Comment out the next line to train on the original target instead of the
# limited output vocabulary version.
TOP_PATH = f"{TOP_PATH}lotv_"
# + [markdown] id="tWZb3AhB4X_6" colab_type="text"
# # Preparing the PyText configuration
#
# ## Data configuration
#
# PyText includes components to iterate through and preprocess the data.
# + id="pdtbU_ZM0px3" colab_type="code" colab={}
from pytext.data import Data, PoolingBatcher
from pytext.data.sources import TSVDataSource
top_data_conf = Data.Config(
sort_key="src_seq_tokens",
source=TSVDataSource.Config(
# Columns in the TSV. These names will be used by the model.
field_names=["raw_sequence", "source_sequence", "target_sequence"],
train_filename=f"{TOP_PATH}train.tsv",
eval_filename=f"{TOP_PATH}eval.tsv",
test_filename=f"{TOP_PATH}test.tsv",
),
batcher=PoolingBatcher.Config(
num_shuffled_pools=10000,
pool_num_batches=1,
train_batch_size=64,
eval_batch_size=100,
# Testing relies on ScriptedSequenceGenerator, which
# does not support batch sizes > 1
test_batch_size=1,
),
)
# + [markdown] id="-mWvOGLWMMP9" colab_type="text"
# ## Model configuration
#
# We can use the object below to specify the architecture for the Seq2seq model
# + id="-MNwVYKPLe_Q" colab_type="code" colab={}
from pytext.data.tensorizers import TokenTensorizer
from pytext.loss import LabelSmoothedCrossEntropyLoss
from pytext.models.embeddings import WordEmbedding
from pytext.models.seq_models.rnn_decoder import RNNDecoder
from pytext.models.seq_models.rnn_encoder import LSTMSequenceEncoder
from pytext.models.seq_models.rnn_encoder_decoder import RNNModel
from pytext.models.seq_models.seq2seq_model import Seq2SeqModel
from pytext.models.seq_models.seq2seq_output_layer import Seq2SeqOutputLayer
from pytext.torchscript.seq2seq.scripted_seq2seq_generator import (
ScriptedSequenceGenerator
)
seq2seq_model_conf=Seq2SeqModel.Config(
# Source and target embedding configuration
source_embedding=WordEmbedding.Config(embed_dim=200),
target_embedding=WordEmbedding.Config(embed_dim=512),
# Configuration for the tensorizers that transform the
# raw data to the model inputs
inputs=Seq2SeqModel.Config.ModelInput(
src_seq_tokens=TokenTensorizer.Config(
# Output from the data handling. Must match one of the column
# names in TSVDataSource.Config, above
column="source_sequence",
# Add begin/end of sequence markers to the model input
add_bos_token=True,
add_eos_token=True,
),
trg_seq_tokens=TokenTensorizer.Config(
column="target_sequence",
add_bos_token=True,
add_eos_token=True,
),
),
# Encoder-decoder configuration
encoder_decoder=RNNModel.Config(
# Bi-LSTM encoder
encoder=LSTMSequenceEncoder.Config(
hidden_dim=1024,
bidirectional=True,
dropout_in=0.0,
embed_dim=200,
num_layers=2,
dropout_out=0.2,
),
# LSTM + Multi-headed attention decoder
decoder=RNNDecoder.Config(
# Needs to match hidden dimension of encoder
encoder_hidden_dim=1024,
dropout_in=0.2,
dropout_out=0.2,
embed_dim=512,
hidden_dim=256,
num_layers=1,
out_embed_dim=256,
attention_type="dot",
attention_heads=1,
),
),
# Sequence generation via beam search. Torchscript is used for
# runtime performance
sequence_generator=ScriptedSequenceGenerator.Config(
beam_size=5,
targetlen_b=3.76,
targetlen_c=72,
quantize=False,
nbest=1,
),
output_layer=Seq2SeqOutputLayer.Config(
loss=LabelSmoothedCrossEntropyLoss.Config()
),
)
# + [markdown] id="Tjzwk9ruXDmd" colab_type="text"
# ## Task configuration
#
# Given the data and model configurations, it is straightforward to configure the PyText task.
# + id="8sg-yItfWno7" colab_type="code" colab={}
from pytext.optimizer.optimizers import Adam
from pytext.optimizer.scheduler import ReduceLROnPlateau
from pytext.task.tasks import SequenceLabelingTask
from pytext.trainers import TaskTrainer
seq2seq_on_top_task_conf = SequenceLabelingTask.Config(
data=top_data_conf,
model=seq2seq_model_conf,
# Training configuration
trainer=TaskTrainer.Config(
# Setting a small number of epochs so the notebook executes more
# quickly. Set epochs=40 to get a converged model. Expect to see
# about 4 more points of frame accuracy in a converged model.
epochs=10,
# Clip gradient norm to 5
max_clip_norm=5,
# Stop if eval loss does not decrease for 5 consecutive epochs
early_stop_after=5,
# Optimizer and learning rate
optimizer=Adam.Config(lr=0.001),
# Learning rate scheduler: reduce LR if no progress made over 3 epochs
scheduler=ReduceLROnPlateau.Config(patience=3),
),
)
# + [markdown] id="TZi5B4YbaRbo" colab_type="text"
# ## Complete the PyText config
#
# PyText bundles the task along with several environment settings in to a single config object that's used for training.
# + id="M31JMHfiZUaB" colab_type="code" colab={}
from pytext.config import LATEST_VERSION as PytextConfigVersion, PyTextConfig
pytext_conf = PyTextConfig(
task=seq2seq_on_top_task_conf,
# Export a Torchscript model for runtime prediction
export_torchscript_path="/content/pytext_seq2seq_top.pt1",
# PyText configs are versioned so that configs saved by older versions can
# still be used by later versions. Since we're constructing the config
# on the fly, we can just use the latest version.
version=PytextConfigVersion,
)
# + [markdown] id="__YZR042bwsZ" colab_type="text"
# # Train the model
#
# PyText uses the configuration object for training and testing.
# + id="W6VFB_E1bJn_" colab_type="code" colab={}
from pytext.workflow import train_model
model, best_metric = train_model(pytext_conf)
# + [markdown] id="oE8G-sFoV3Be" colab_type="text"
# # Test the model
#
# PyText training saves a snapshot with the model and training state. We can use the snapshot for testing as well.
# + [markdown] id="LMvEWLsijqQ7" colab_type="text"
# TODO: this is too slow. We should see if we can get away with parallelism, and if not significantly downsample the test set.
# + id="G0hUzhuPXEDm" colab_type="code" colab={}
from pytext.workflow import test_model_from_snapshot_path
test_model_from_snapshot_path(
"/tmp/model.pt",
# Sequence generation is presently CPU-only
False,
None,
None,
"/content/pytext_seq2seq_top_results.txt"
)
# + [markdown] id="49usGDfbUZyX" colab_type="text"
# # Using the model at runtime
#
# The exported Torchscript model can be used for efficient runtime inference. We will demonstrate the API in Python here, but the file can also be loaded in [Java](https://pytorch.org/javadoc/) and [C++](https://pytorch.org/cppdocs/).
# + id="YK0Wb6lgdF8h" colab_type="code" colab={}
import torch
scripted_model = torch.jit.load("/content/pytext_seq2seq_top.pt1")
# + id="zmS8jHwAT3g6" colab_type="code" colab={}
# To use the exported model, we need to manually add begin/end of sequence
# markers.
BOS = "__BEGIN_OF_SENTENCE__"
EOS = "__END_OF_SENTENCE__"
scripted_model(f"{BOS} what is the shortest way home {EOS}".split())
# + id="9t0irQRJUD82" colab_type="code" colab={}
|
demo/notebooks/seq2seq_tutorial.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from glob import glob
import astropy.units as u
from toolkit import get_phoenix_model_spectrum, EchelleSpectrum
standard_path = ('/Users/bmmorris/data/Q3UW04/UT160706/'
'BD28_4211.0034.wfrmcpc.fits')
standard_spectrum = EchelleSpectrum.from_fits(standard_path)
target_path = glob('/Users/bmmorris/data/Q1UW09/UT170317/HD266611*wfrmcpc.fits')[0]
target_spectrum = EchelleSpectrum.from_fits(target_path)
def nearest_order(wavelength):
return np.argmin([abs(spec.wavelength.mean() - wavelength).value
for spec in target_spectrum.spectrum_list])
# nearest_order_7055 = nearest_order(7055*u.Angstrom)
# nearest_order_8860 = nearest_order(8860*u.Angstrom)
only_orders = list(range(len(target_spectrum.spectrum_list)))
target_spectrum.continuum_normalize(standard_spectrum,
polynomial_order=10,
only_orders=only_orders,
plot_masking=False)
rv_shifts = u.Quantity([target_spectrum.rv_wavelength_shift(order)
for order in only_orders])
median_rv_shift = np.median(rv_shifts)
target_spectrum.offset_wavelength_solution(median_rv_shift)
# -
from toolkit import ModelGrid, bands_TiO
model_grid = ModelGrid()
# +
from toolkit import slice_spectrum, concatenate_spectra
spec_band = []
for band in bands_TiO:
band_order = target_spectrum.get_order(nearest_order(band.core))
target_slice = slice_spectrum(band_order, band.min-5*u.Angstrom, band.max+5*u.Angstrom)
target_slice.flux /= target_slice.flux.max()
spec_band.append(target_slice)
slices = concatenate_spectra(spec_band)
slices.plot(normed=False, color='k', lw=2, marker='.')
# -
from itertools import combinations
# Limit combinations such that delta T < 2000 K
temp_combinations = [i for i in combinations(model_grid.test_temps, 2)
if abs(i[0] - i[1]) <= 2000]
n_combinations = len(temp_combinations)
n_fit_params = 4
best_parameters = np.zeros((n_combinations, n_fit_params))
# +
from toolkit import instr_model
from scipy.optimize import fmin_l_bfgs_b
from astropy.utils.console import ProgressBar
def chi2(p, temp_phot, temp_spot):
spotted_area, lam_offset, res = p
model, residuals = instr_model(temp_phot, temp_spot, spotted_area,
lam_offset, res, slices, model_grid)
return residuals
bounds = [[0, 0.5], [-1, 1], [1, 10]]
initp = [0.6, 2, 9]
# with ProgressBar(n_combinations, ipython_widget=True) as bar:
# for i in range(n_combinations):
# bar.update()
# temp_spot, temp_phot = temp_combinations[i]
# result = fmin_l_bfgs_b(chi2, initp, approx_grad=True,
# bounds=bounds, args=(temp_phot, temp_spot))
# best_parameters[i, :] = np.concatenate([result[0], result[1]])
# +
# chi2s = []
# for i in range(n_combinations):
# temp_spot, temp_phot = temp_combinations[i]
# spotted_area, lam_offset, res = best_parameters[i, :]
# model, residuals = instr_model(temp_phot, temp_spot, spotted_area,
# lam_offset, res, slices, model_grid)
# chi2s.append(residuals)
# chi2s = np.array([i[0] for i in chi2s])
# best_params = np.hstack([best_parameters, np.atleast_2d(chi2s).T])
# +
best_params_path = 'data/best_params.npy'
# np.save(best_params_path, best_parameters)
best_parameters = np.load(best_params_path)
# +
fig, ax = plt.subplots(n_fit_params, 1, figsize=(14, 8), sharex=True)
for i in range(n_fit_params):
ax[i].plot(best_parameters[:, i]);
xticks = np.arange(0, n_combinations, 20)
ax[-1].set_xticks(xticks)
xticklabels = [', '.join(map(str, x)) for x in np.array(temp_combinations)[xticks, :]]
ax[-1].set_xticklabels(xticklabels)
ax[-1].set_ylim([0, 5])
for l in ax[-1].get_xticklabels():
l.set_rotation(30)
l.set_ha('right')
ax[0].set_ylabel('covering fraction')
ax[1].set_ylabel('wavelength offset')
ax[2].set_ylabel('broadening coeff')
ax[3].set_ylabel('$\chi^2$')
# +
fig, ax = plt.subplots(n_fit_params, 1, figsize=(14, 8), sharex=True)
for i in range(n_fit_params):
ax[i].plot(best_parameters[:, i], '.-');
xticks = np.arange(0, n_combinations, 5)
ax[-1].set_xticks(xticks)
xticklabels = [', '.join(map(str, x)) for x in np.array(temp_combinations)[xticks, :]]
ax[-1].set_xticklabels(xticklabels)
ax[-1].set_ylim([0, 2])
ax[-1].set_xlim([100, 180])
ax[3].set_ylabel('$\chi^2$')
for l in ax[-1].get_xticklabels():
l.set_rotation(30)
l.set_ha('right')
ax[0].set_ylabel('covering fraction')
ax[1].set_ylabel('wavelength offset')
ax[2].set_ylabel('broadening coeff')
# ax[1].set_ylim([0.26, 0.28])
for axis in ax:
axis.grid()
# +
# from skimage.filters import threshold_isodata
# thresh = threshold_isodata(best_parameters[:, 3])
thresh = 1.5
good_fits = best_parameters[:, 3] < thresh
plt.hist(best_parameters[:, 3], 100);
plt.axvline(thresh, color='r')
# +
good_temps = np.array(temp_combinations)[good_fits, :]
fix_resolution = np.median(best_parameters[good_fits, 2])
fix_delta_lam = np.median(best_parameters[good_fits, 1])
temp_phot = np.max(good_temps, axis=1)
delta_temp = np.diff(good_temps, axis=1)[:, 0]
param_labels = ['f_S', 'd lambda', 'res']
for i, label in enumerate(param_labels):
plt.figure()
plt.hist(best_parameters[good_fits, i], 10)
plt.xlabel(label)
# -
# Determine parameter priors based on least squares fits:
# +
def random_in_range(min, max):
return (max-min)*np.random.rand(1)[0] + min
def lnprior(theta):
temp_phot, delta_temp, spotted_area = theta
if ((3000 <= temp_phot <= 6200) and (0 <= delta_temp <= 2000) and
(0 <= spotted_area <= 0.5)):
return 0.0
return -np.inf
def lnlike(theta, model_grid, observed_spectrum):
temp_phot, delta_temp, spotted_area = theta
temp_spot = temp_phot - delta_temp
model, residuals = instr_model(temp_phot, temp_spot, spotted_area, fix_delta_lam,
fix_resolution, observed_spectrum, model_grid)
return -0.5*residuals#[0] #-0.5*np.sum((y-model)**2/yerr**2)
def lnprob(theta, model_grid, observed_spectrum):
lp = lnprior(theta)
if not np.isfinite(lp):
return -np.inf
return lp + lnlike(theta, model_grid, observed_spectrum)
from emcee import EnsembleSampler
initp = np.array([4400, 500, 0.3])
ndim, nwalkers = len(initp), 10 #2*len(initp)
pos = []
indices = np.arange(np.count_nonzero(good_fits))
np.random.shuffle(indices)
counter = -1
while len(pos) < nwalkers:
counter += 1
index = indices[counter]
realization = [temp_phot[index], delta_temp[index],
best_parameters[good_fits, 0][index]]
if np.isfinite(lnprior(realization)):
pos.append(realization)
sampler = EnsembleSampler(nwalkers, ndim, lnprob, threads=4,
args=(model_grid, slices))
# -
n_steps = 50*nwalkers
sampler.run_mcmc(pos, n_steps);
from corner import corner
corner(sampler.flatchain)
plt.show()
plt.plot(sampler.lnprobability.T);
for i in range(sampler.chain.shape[-1]):
plt.figure()
plt.plot(sampler.chain[..., i].T)
# +
best_step = sampler.flatchain[np.argmax(sampler.flatlnprobability)]
temp_phot = best_step[0]
temp_spot = best_step[0] - best_step[1]
model, resid = instr_model(temp_phot, temp_spot, best_step[2], fix_delta_lam,
fix_resolution, slices, model_grid)
# -
slices.plot()
print(resid)
plt.plot(slices.wavelength, model)# - slices.flux)
for species in lines:
print(lines[species])
# +
paths = ['/Users/bmmorris/tmp/BrettMorris.016632.txt',
'/Users/bmmorris/tmp/BrettMorris.016631.txt',
'/Users/bmmorris/tmp/BrettMorris.016629.txt',]
nth = 10
vald3_wavelengths = []
vald3_names = []
for path in paths:
lines = open(path).read().splitlines()
def to_float(x):
try:
return float(x)
except ValueError:
return np.nan
rows = []
for i in range(2, len(lines)-2):
split_line = lines[i].split(',')
row = [val.strip() for val in split_line[:3]]
if len(row) == 3:
rows.append(row)
wavelengths = np.array([to_float(row[1]) for row in rows])
strengths = np.array([to_float(row[2]) for row in rows])
names = np.array([row[0][1:-1] for row in rows])
nth_strength = np.sort(strengths[np.isfinite(strengths)])[-nth]
strongest = strengths > nth_strength
vald3_wavelengths.append(wavelengths[strongest])
vald3_names.append(names[strongest])
# +
def plot_line(axis, species, wavelength, offset):
yoffset = 0 if offset % 2 == 0 else 0.05
axis.axvline(wavelength, ls=':', alpha=0.5)
axis.annotate(species, xy=(wavelength, 1.0-yoffset),
ha='left', va='bottom',
rotation=40)
def plot_spliced_spectrum(observed_spectrum, model_flux, plot_lines=False):
n_chunks = len(slices.wavelength_splits)
fig, ax = plt.subplots(n_chunks, 1, figsize=(8, 10))
for i, inds in enumerate(observed_spectrum.wavelength_splits):
min_ind, max_ind = inds
# ax[i].plot(observed_spectrum.wavelength[min_ind:max_ind],
# observed_spectrum.flux[min_ind:max_ind])
ax[i].errorbar(observed_spectrum.wavelength[min_ind:max_ind].value,
observed_spectrum.flux[min_ind:max_ind],
0.025*np.ones(max_ind-min_ind))
ax[i].plot(observed_spectrum.wavelength[min_ind:max_ind],
model_flux[min_ind:max_ind])
if plot_lines:
for j, name, wave in zip(range(len(vald3_names[i])),
vald3_names[i],
vald3_wavelengths[i]):
plot_line(ax[i], name, wave, j)
return fig, ax
fig, ax = plot_spliced_spectrum(slices, model)
# lines = {"CsII": [7121.1697, 7123.8696, 7130.5399],
# "FeII": [7134.5425, 7128.0876],
# "FI": [7127.89]}
# -
|
permute.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/BurgundyIsAPublicEnemy/EPIDEMIUM-Season-3/blob/main/Data_Preperation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="1CliuFqJ-gxL"
# # Data Preperation
# Usage: Set the variables below to the right place. Then hit run
#
# Contributions: <NAME> of JEDHA for coming up with a really elegant way of doing this
#
# Pleae keep in mind this should run on your GPU
# + id="vEoGvKt0Q5pF" outputId="a061b34b-eaf1-4b98-cc11-c0f12d9d5c22" colab={"base_uri": "https://localhost:8080/"}
# !pip install colab-env --upgrade
# + id="r62biTj0Q8LM" outputId="0c0a76b3-906d-4a35-9dea-bc7f2c79a7f2" colab={"base_uri": "https://localhost:8080/", "height": 53}
import colab_env
colab_env.__version__
# + id="xk3FBnR82M41" outputId="d1f7a44c-563d-4859-a794-191d92bf2860" colab={"base_uri": "https://localhost:8080/"}
from google.colab import drive
drive.mount('/content/drive')
# + id="tkmYRmEzVxZ3" outputId="ee1db16a-8326-41fa-f8c4-1fee9d9b797f" colab={"base_uri": "https://localhost:8080/"}
# !more /content/drive/MyDrive/vars.env
# + id="wdcelKCeRqla"
import os
IMAGEFILES = os.getenv("IMAGEFILES")
TABULARTRAINING = os.getenv("TABULARTRAINING")
TABULARTEST = os.getenv("TABULARTEST")
FULLSTACKTRAIN = os.getenv("FULLSTACKTRAIN")
TRAIN_AUGMENTED_PATH = os.getenv("TRAIN_AUGMENTED_PATH")
TEST_AUGMENTED_PATH = os.getenv("TEST_AUGMENTED_PATH")
METADATA_PATH = os.getenv("METADATA_PATH")
# + id="9bfW6HjYR4Gu" outputId="6d09a909-e646-4bee-d440-40ab19bb7bff" colab={"base_uri": "https://localhost:8080/"}
print(METADATA_PATH)
# + id="cXh02UPlDitJ"
# IMPORT ML MODEL RELATED THINGS
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os, cv2, shutil
from keras.applications.resnet import ResNet50, preprocess_input
from tensorflow.keras.preprocessing import image
# + colab={"base_uri": "https://localhost:8080/"} id="0zIE6ln1weib" outputId="f8f09658-217e-472d-e89c-e33f2cbae7ae"
# !pip install spams
# + [markdown] id="n27zZ3y2r5N1"
# ### Set up normalizations (unused in the final model but go nuts if you like it)
# Repo: https://github.com/wanghao14/Stain_Normalization
# + id="jiR-SA7CwbMS"
"""
Uses the spams package:
http://spams-devel.gforge.inria.fr/index.html
Use with python via e.g https://anaconda.org/conda-forge/python-spams
"""
from __future__ import division
import numpy as np
import cv2 as cv
import spams
import matplotlib.pyplot as plt
##########################################
def read_image(path):
"""
Read an image to RGB uint8
:param path:
:return:
"""
im = cv.imread(path)
im = cv.cvtColor(im, cv.COLOR_BGR2RGB)
return im
def show_colors(C):
"""
Shows rows of C as colors (RGB)
:param C:
:return:
"""
n = C.shape[0]
for i in range(n):
if C[i].max() > 1.0:
plt.plot([0, 1], [n - 1 - i, n - 1 - i], c=C[i] / 255, linewidth=20)
else:
plt.plot([0, 1], [n - 1 - i, n - 1 - i], c=C[i], linewidth=20)
plt.axis('off')
plt.axis([0, 1, -1, n])
def show(image, now=True, fig_size=(10, 10)):
"""
Show an image (np.array).
Caution! Rescales image to be in range [0,1].
:param image:
:param now:
:param fig_size:
:return:
"""
image = image.astype(np.float32)
m, M = image.min(), image.max()
if fig_size != None:
plt.rcParams['figure.figsize'] = (fig_size[0], fig_size[1])
plt.imshow((image - m) / (M - m), cmap='gray')
plt.axis('off')
if now == True:
plt.show()
def build_stack(tup):
"""
Build a stack of images from a tuple of images
:param tup:
:return:
"""
N = len(tup)
if len(tup[0].shape) == 3:
h, w, c = tup[0].shape
stack = np.zeros((N, h, w, c))
if len(tup[0].shape) == 2:
h, w = tup[0].shape
stack = np.zeros((N, h, w))
for i in range(N):
stack[i] = tup[i]
return stack
def patch_grid(ims, width=5, sub_sample=None, rand=False, save_name=None):
"""
Display a grid of patches
:param ims:
:param width:
:param sub_sample:
:param rand:
:return:
"""
N0 = np.shape(ims)[0]
if sub_sample == None:
N = N0
stack = ims
elif sub_sample != None and rand == False:
N = sub_sample
stack = ims[:N]
elif sub_sample != None and rand == True:
N = sub_sample
idx = np.random.choice(range(N), sub_sample, replace=False)
stack = ims[idx]
height = np.ceil(float(N) / width).astype(np.uint16)
plt.rcParams['figure.figsize'] = (18, (18 / width) * height)
plt.figure()
for i in range(N):
plt.subplot(height, width, i + 1)
im = stack[i]
show(im, now=False, fig_size=None)
if save_name != None:
plt.savefig(save_name)
plt.show()
######################################
def standardize_brightness(I):
"""
:param I:
:return:
"""
p = np.percentile(I, 90)
return np.clip(I * 255.0 / p, 0, 255).astype(np.uint8)
def remove_zeros(I):
"""
Remove zeros, replace with 1's.
:param I: uint8 array
:return:
"""
mask = (I == 0)
I[mask] = 1
return I
def RGB_to_OD(I):
"""
Convert from RGB to optical density
:param I:
:return:
"""
I = remove_zeros(I)
return -1 * np.log(I / 255)
def OD_to_RGB(OD):
"""
Convert from optical density to RGB
:param OD:
:return:
"""
return (255 * np.exp(-1 * OD)).astype(np.uint8)
def normalize_rows(A):
"""
Normalize rows of an array
:param A:
:return:
"""
return A / np.linalg.norm(A, axis=1)[:, None]
def notwhite_mask(I, thresh=0.8):
"""
Get a binary mask where true denotes 'not white'
:param I:
:param thresh:
:return:
"""
I_LAB = cv.cvtColor(I, cv.COLOR_RGB2LAB)
L = I_LAB[:, :, 0] / 255.0
return (L < thresh)
def sign(x):
"""
Returns the sign of x
:param x:
:return:
"""
if x > 0:
return +1
elif x < 0:
return -1
elif x == 0:
return 0
def get_concentrations(I, stain_matrix, lamda=0.01):
"""
Get concentrations, a npix x 2 matrix
:param I:
:param stain_matrix: a 2x3 stain matrix
:return:
"""
OD = RGB_to_OD(I).reshape((-1, 3))
return spams.lasso(OD.T, D=stain_matrix.T, mode=2, lambda1=lamda, pos=True).toarray().T
# + id="4IBFiThNr7s2"
"""
Stain normalization based on the method of:
<NAME> et al., ‘A method for normalizing histology slides for quantitative analysis’, in 2009 IEEE International Symposium on Biomedical Imaging: From Nano to Macro, 2009, pp. 1107–1110.
Uses the spams package:
http://spams-devel.gforge.inria.fr/index.html
Use with python via e.g https://anaconda.org/conda-forge/python-spams
"""
from __future__ import division
import numpy as np
def get_stain_matrix(I, beta=0.15, alpha=1):
"""
Get stain matrix (2x3)
:param I:
:param beta:
:param alpha:
:return:
"""
OD = RGB_to_OD(I).reshape((-1, 3))
OD = (OD[(OD > beta).any(axis=1), :])
_, V = np.linalg.eigh(np.cov(OD, rowvar=False))
V = V[:, [2, 1]]
if V[0, 0] < 0: V[:, 0] *= -1
if V[0, 1] < 0: V[:, 1] *= -1
That = np.dot(OD, V)
phi = np.arctan2(That[:, 1], That[:, 0])
minPhi = np.percentile(phi, alpha)
maxPhi = np.percentile(phi, 100 - alpha)
v1 = np.dot(V, np.array([np.cos(minPhi), np.sin(minPhi)]))
v2 = np.dot(V, np.array([np.cos(maxPhi), np.sin(maxPhi)]))
if v1[0] > v2[0]:
HE = np.array([v1, v2])
else:
HE = np.array([v2, v1])
return normalize_rows(HE)
###
class Macenko_Normalizer(object):
"""
A stain normalization object
"""
def __init__(self):
self.stain_matrix_target = None
self.target_concentrations = None
def fit(self, target):
target = standardize_brightness(target)
self.stain_matrix_target = get_stain_matrix(target)
self.target_concentrations = get_concentrations(target, self.stain_matrix_target)
def target_stains(self):
return OD_to_RGB(self.stain_matrix_target)
def transform(self, I):
I = standardize_brightness(I)
stain_matrix_source = get_stain_matrix(I)
source_concentrations = get_concentrations(I, stain_matrix_source)
maxC_source = np.percentile(source_concentrations, 99, axis=0).reshape((1, 2))
maxC_target = np.percentile(self.target_concentrations, 99, axis=0).reshape((1, 2))
source_concentrations *= (maxC_target / maxC_source)
return (255 * np.exp(-1 * np.dot(source_concentrations, self.stain_matrix_target).reshape(I.shape))).astype(
np.uint8)
def hematoxylin(self, I):
I = standardize_brightness(I)
h, w, c = I.shape
stain_matrix_source = get_stain_matrix(I)
source_concentrations = get_concentrations(I, stain_matrix_source)
H = source_concentrations[:, 0].reshape(h, w)
H = np.exp(-1 * H)
return H
# + id="TO6CIii7vtb3"
"""
Normalize a patch stain to the target image using the method of:
<NAME>, <NAME>, <NAME>, and <NAME>, ‘Color transfer between images’, IEEE Computer Graphics and Applications, vol. 21, no. 5, pp. 34–41, Sep. 2001.
"""
from __future__ import division
import cv2 as cv
import numpy as np
### Some functions ###
def lab_split(I):
"""
Convert from RGB uint8 to LAB and split into channels
:param I: uint8
:return:
"""
I = cv.cvtColor(I, cv.COLOR_RGB2LAB)
I = I.astype(np.float32)
I1, I2, I3 = cv.split(I)
I1 /= 2.55
I2 -= 128.0
I3 -= 128.0
return I1, I2, I3
def merge_back(I1, I2, I3):
"""
Take seperate LAB channels and merge back to give RGB uint8
:param I1:
:param I2:
:param I3:
:return:
"""
I1 *= 2.55
I2 += 128.0
I3 += 128.0
I = np.clip(cv.merge((I1, I2, I3)), 0, 255).astype(np.uint8)
return cv.cvtColor(I, cv.COLOR_LAB2RGB)
def get_mean_std(I):
"""
Get mean and standard deviation of each channel
:param I: uint8
:return:
"""
I1, I2, I3 = lab_split(I)
m1, sd1 = cv.meanStdDev(I1)
m2, sd2 = cv.meanStdDev(I2)
m3, sd3 = cv.meanStdDev(I3)
means = m1, m2, m3
stds = sd1, sd2, sd3
return means, stds
### Main class ###
class Reinhard_Normalizer(object):
"""
A stain normalization object
"""
def __init__(self):
self.target_means = None
self.target_stds = None
def fit(self, target):
target = standardize_brightness(target)
means, stds = get_mean_std(target)
self.target_means = means
self.target_stds = stds
def transform(self, I):
I = standardize_brightness(I)
I1, I2, I3 = lab_split(I)
means, stds = get_mean_std(I)
norm1 = ((I1 - means[0]) * (self.target_stds[0] / stds[0])) + self.target_means[0]
norm2 = ((I2 - means[1]) * (self.target_stds[1] / stds[1])) + self.target_means[1]
norm3 = ((I3 - means[2]) * (self.target_stds[2] / stds[2])) + self.target_means[2]
return merge_back(norm1, norm2, norm3)
# + id="3fOv-Nq7tkH6"
# Destroy folders we need
def emptyFolder(path):
folder = path
if os.path.exists(path):
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
if not os.path.exists(path):
os.makedirs(path)
emptyFolder(METADATA_PATH)
emptyFolder(TRAIN_AUGMENTED_PATH)
emptyFolder(TEST_AUGMENTED_PATH)
# + colab={"base_uri": "https://localhost:8080/", "height": 354} id="Lxaw-BXuDwxn" outputId="e214d19e-a4d8-4614-e896-143769c26c91"
train_df = pd.read_csv(TABULARTRAINING)
train_df.head()
# + colab={"base_uri": "https://localhost:8080/"} id="rsehceon2edq" outputId="78c79276-ceb2-45f4-9b42-921502fd595c"
train_df['N'].unique()
# + colab={"base_uri": "https://localhost:8080/", "height": 250} id="pWa4sTi_EdKa" outputId="30df1708-54cc-40bb-de76-48777e817a28"
test_df = pd.read_csv(TABULARTEST)
test_df.head()
# + [markdown] id="MKn8-Uxty-gx"
# ### Encode and unify the metadata
# + id="PMPQPjZLzFSC"
train_df["localisation"] = train_df["localisation"].astype('category').cat.codes
train_df["N"] = train_df["N"].astype('category').cat.codes.head()
test_df["localisation"] = test_df["localisation"].astype('category').cat.codes
test_df["N"] = test_df["N"].astype('category').cat.codes.head()
# Dates into time since current epoch
train_df['DDN'] = round((pd.Timestamp.now() - pd.to_datetime(train_df['DDN'], format="%Y-%m-%d")).astype("int64") / (31556952 * 10**9))
train_df['Date biopsie'] = round((pd.Timestamp.now() - pd.to_datetime(train_df['Date biopsie'], format="%Y-%m-%d")).astype("int64") / (31556952 * 10**9))
test_df['DDN'] = round((pd.Timestamp.now() - pd.to_datetime(test_df['DDN'], format="%Y-%m-%d")).astype("int64") / (31556952 * 10**9))
test_df['Date biopsie'] = round((pd.Timestamp.now() - pd.to_datetime(test_df['Date biopsie'], format="%Y-%m-%d")).astype("int64") / (31556952 * 10**9))
# + colab={"base_uri": "https://localhost:8080/", "height": 250} id="mqhJdE_drJgM" outputId="b7e65aea-109b-47a6-deb8-6028619e45fb"
train_df.head()
# + colab={"base_uri": "https://localhost:8080/"} id="BB2IoC28RGN5" outputId="41a63ceb-7041-4748-f7e4-e788ac82141c"
train_df['N'].unique()
# + colab={"base_uri": "https://localhost:8080/", "height": 206} id="nD2YLopyrKaZ" outputId="0e985690-c3a7-4abb-8bb3-4fa66284728f"
test_df.head()
# + id="xytNfyKfJgeH"
path = "/content/drive/MyDrive/Epidemium Season 3/ORLIAn /image_data_v2/Cellule inflamatoire 2/a4fa68_[14458,48150]_composite_image.jpg"
target_img = cv2.imread(path)
# + [markdown] id="Lz-naoZYNmjl"
# # Code Section for Images compiled from .JPGs in folders
# + colab={"base_uri": "https://localhost:8080/", "height": 372} id="oz1Z2LbzNxYS" outputId="eb089283-88a6-433e-b150-63274e61edfc"
# Demo function for augmentation
# Get colors isolated
reinhard_normalizer = Reinhard_Normalizer()
reinhard_normalizer.fit(target_img)
reinhard = reinhard_normalizer.transform(target_img)
macenko_normalizer = Macenko_Normalizer()
macenko_normalizer.fit(target_img)
macenko = macenko_normalizer.transform(target_img)
image = cv2.cvtColor(target_img, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(1, 3, figsize =(22, 5))
fig.suptitle('Normalization of the images with different methods', fontsize = 16)
ax[0].set_title('Original image')
ax[1].set_title('Reinhard Normalization')
ax[2].set_title('Macenko Normalizaiton')
ax[0].imshow(image)
ax[1].imshow(reinhard)
ax[2].imshow(macenko)
# + id="aCNKRNQkWoEg"
def MetaDataWriter(tabular, id, usage, fn, nfn, dir, layer, filetype):
new_row = {'id': id , 'usage': usage, 'image_file': fn, 'image_rename': nfn, "current_directory": dir, "layer": layer, 'img_type': filetype}
tabular = tabular.append(new_row, ignore_index=True)
return tabular
# + [markdown] id="yQIOMyZ8UCKC"
# ## Load Images in the right place
# + id="PRum5Sw9dpjw"
# Initalize variables so we can do this smoothly
unique_train_ids = train_df['id'].unique()
unique_test_ids = test_df['id'].unique()
train_img_data = pd.DataFrame(columns = ['id', 'usage', 'image_file', 'image_rename', 'current_directory', 'layer', 'img_type'])
test_img_data = pd.DataFrame(columns = ['id', 'usage', 'image_file', 'image_rename', 'current_directory', 'layer', 'img_type'])
#img_formats = ["raw", "reinhard", "macenko"]
img_formats = ["raw"]
# + [markdown] id="paOY41LQd0wb"
# ### For training
# + id="UKVB_4iBOhVg" colab={"base_uri": "https://localhost:8080/"} outputId="f771e2a8-5400-4877-932c-4bd7659dc2d1"
try:
for dirname, _, filenames in os.walk(IMAGEFILES + ''):
layers_folders = [i for i in os.listdir(dirname) if not i.endswith('.csv')]
for layer in layers_folders:
if layer != "segmentation_tissue":
img_files = [i for i in os.listdir(dirname + "/" + layer) if not i.endswith('.csv')]
for img_file in img_files:
pid = img_file.split('_')[0]
if pid in unique_train_ids:
old_image_path = IMAGEFILES + "/" + layer + "/" + img_file
tmp_img = cv2.imread(old_image_path)
new_image_path = TRAIN_AUGMENTED_PATH + "/raw_" + layer + "_" + img_file
#stash the original copy somewhere easy
shutil.copy(old_image_path, new_image_path)
for img_format in img_formats:
train_img_data = MetaDataWriter(train_img_data, pid, "train", img_file, img_format + "_" + layer + "_" + img_file, TRAIN_AUGMENTED_PATH, layer, img_format)
elif layer == 'segmentation_tissue':
img_files = [i for i in os.listdir(dirname + "/" + layer) if not i.endswith('.csv')]
for img_file in img_files:
pid = img_file.split('_')[0]
if pid in unique_train_ids:
old_image_path = IMAGEFILES + "/" + layer + "/" + img_file
tmp_img = cv2.imread(old_image_path)
new_image_path = TRAIN_AUGMENTED_PATH + "/composite_" + layer + "_" + img_file
#stash the original copy somewhere easy
shutil.copy(old_image_path, new_image_path)
train_img_data = MetaDataWriter(train_img_data, pid, "train", img_file, "composite_" + layer + "_" + img_file, TRAIN_AUGMENTED_PATH, layer, "raw")
except:
print("File found in a wrong place? Stop looking")
# + [markdown] id="504hEtxFd4vr"
# ### For validation set
# + id="e3lKNk39eGqq" colab={"base_uri": "https://localhost:8080/"} outputId="7a03ab0a-e212-4499-a6a6-71c9926bdccd"
try:
for dirname, _, filenames in os.walk(IMAGEFILES + ''):
layers_folders = [i for i in os.listdir(dirname) if not i.endswith('.csv')]
for layer in layers_folders:
if layer != "segmentation_tissue":
img_files = [i for i in os.listdir(dirname + "/" + layer) if not i.endswith('.csv')]
for img_file in img_files:
pid = img_file.split('_')[0]
if pid in unique_test_ids:
old_image_path = IMAGEFILES + "/" + layer + "/" + img_file
tmp_img = cv2.imread(old_image_path)
new_image_path = TEST_AUGMENTED_PATH + "/raw_" + layer + "_" + img_file
shutil.copy(old_image_path, new_image_path)
for img_format in img_formats:
test_img_data = MetaDataWriter(test_img_data, pid, "test", img_file, img_format + "_" + layer + "_" + img_file, TEST_AUGMENTED_PATH, layer, img_format)
elif layer == 'segmentation_tissue':
img_files = [i for i in os.listdir(dirname + "/" + layer) if not i.endswith('.csv')]
for img_file in img_files:
pid = img_file.split('_')[0]
if pid in unique_test_ids:
old_image_path = IMAGEFILES + "/" + layer + "/" + img_file
tmp_img = cv2.imread(old_image_path)
new_image_path = TEST_AUGMENTED_PATH + "/composite_" + layer + "_" + img_file
shutil.copy(old_image_path, new_image_path)
test_img_data = MetaDataWriter(test_img_data, pid, "test", img_file, "composite_" + layer + "_" + img_file, TEST_AUGMENTED_PATH, layer, "raw")
except:
print("File found in a wrong place? Stop looking")
# + id="trlpw1DtYt3H" colab={"base_uri": "https://localhost:8080/", "height": 250} outputId="4852f3a5-1cfc-424d-a591-75121fefaa60"
train_img_data.head()
# + id="ZphbvcRoDQUt" colab={"base_uri": "https://localhost:8080/", "height": 250} outputId="350f8f64-54d1-4865-caf5-11eef0489428"
test_img_data.head()
# + [markdown] id="SQ2LUXzwkH73"
# ## Mix the data together
# + [markdown] id="iEAJewGW1FY7"
# ## OPTIONAL: Build a holdout from train
# In the event test data is broken
# + id="4sVozYtRCovn" colab={"base_uri": "https://localhost:8080/"} outputId="cda830b9-12b9-4d30-83c7-e446477e6c42"
import random
train_minus_hold_df = train_df
if (True):
print(len(train_minus_hold_df))
holdout_index = []
tmp_df = train_minus_hold_df
for i in range(0, 7):
cur = random.randint(0, len(tmp_df.index))
while cur in holdout_index:
cur = random.randint(0, len(tmp_df.index))
holdout_index.append(cur)
holdout_df = pd.DataFrame()
holdout_df = tmp_df.loc[holdout_index]
train_minus_hold_df = tmp_df.drop(tmp_df.index[holdout_index])
holdout_df.head()
print(len(train_minus_hold_df))
print(len(holdout_df))
# + id="6GwXQKeDj60Q"
# all training
train_img_data_all = train_img_data.merge(train_df, on = 'id')
train_img_data_all["id_encoding"] = train_img_data_all["id"].astype('category').cat.codes
train_img_data_all["image_rename_encoding"] = train_img_data_all["image_rename"].astype('category').cat.codes
train_img_data_all = train_img_data_all.sample(frac=1)
train_img_data_all.to_csv(METADATA_PATH + "/train_img_data.csv", index=False, header=True)
if (True):
#hold out - training
train_img_data_minus_holdout = train_img_data.merge(train_minus_hold_df, on = 'id')
train_img_data_minus_holdout["id_encoding"] = train_img_data_minus_holdout["id"].astype('category').cat.codes
train_img_data_minus_holdout["image_rename_encoding"] = train_img_data_minus_holdout["image_rename"].astype('category').cat.codes
train_img_data_minus_holdout = train_img_data_minus_holdout.sample(frac=1)
train_img_data_minus_holdout.to_csv(METADATA_PATH + "/train_minus_hold_img_data.csv", index=False, header=True)
#hold out
holdout_img_data_all = train_img_data.merge(holdout_df, on = 'id')
holdout_img_data_all["id_encoding"] = holdout_img_data_all["id"].astype('category').cat.codes
holdout_img_data_all["image_rename_encoding"] = holdout_img_data_all["image_rename"].astype('category').cat.codes
holdout_img_data_all = holdout_img_data_all.sample(frac=1)
holdout_img_data_all.to_csv(METADATA_PATH + "/holdout_img_data.csv", index=False, header=True)
#all testing
test_img_data_all = test_img_data.merge(test_df, on = 'id')
test_img_data_all["id_encoding"] = test_img_data_all["id"].astype('category').cat.codes
test_img_data_all["image_rename_encoding"] = test_img_data_all["image_rename"].astype('category').cat.codes
test_img_data_all = test_img_data_all.sample(frac=1)
test_img_data_all.to_csv(METADATA_PATH + "/test_img_data.csv", index=False, header=True)
# + [markdown] id="QHfYew3C-RQM"
# # Sanity Check
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="FqOkRxpcO6sp" outputId="6b43bea5-9543-491e-b048-eef81f5d31ab"
train_img_data_all.head(20)
# + colab={"base_uri": "https://localhost:8080/"} id="bDmFxX9kRT-r" outputId="47b902dd-485c-4914-d72f-cebf45ede1db"
len(train_img_data_all['id_encoding'].unique())
# + [markdown] id="Ghrnm76BY1vw"
# # Unit Tests
# + id="37AwHxfe6AnG" colab={"base_uri": "https://localhost:8080/"} outputId="60027014-5d12-433b-c2be-4a36b6070b5e"
# List out files
for dirname, _, filenames in os.walk(IMAGEFILES + ''):
count = 0
for filename in filenames:
count = count + 1
print(count , " files detected in " + dirname)
for dirname, _, filenames in os.walk(METADATA_PATH + ''):
count = 0
for filename in filenames:
count = count + 1
print(count , " files detected in " + dirname)
# + colab={"base_uri": "https://localhost:8080/"} id="M8aUELdVY3hV" outputId="9d36862e-0f1b-459e-d3d4-83bc8e6eeb9e"
# Make sure all the IDs in the files are actually train / test
print(train_img_data_all["img_type"].unique())
print(test_img_data_all["img_type"].unique())
for ids in list(train_img_data_all['id'].unique()):
if ids not in unique_train_ids:
print("Train DF has a leak")
for ids in list(test_img_data_all['id'].unique()):
if ids not in unique_test_ids:
print("Train DF has a leak")
# + colab={"base_uri": "https://localhost:8080/"} id="Z8cyogg6jp2O" outputId="bfde1ff4-d357-4449-eb76-f97235264954"
test_img_data_all.duplicated().unique()
# + colab={"base_uri": "https://localhost:8080/"} id="_eSQ4M4WhCAb" outputId="96c18e26-e464-40f3-e7bf-4f0dd81ff516"
print(unique_train_ids)
# + colab={"base_uri": "https://localhost:8080/"} id="B0oFCjEHhEra" outputId="6c06b718-97ad-4e1c-ef34-91c30b24ff47"
print(unique_test_ids)
# + id="ZkFXYUdeNs9C"
# Make sure all the photos are in the right places
for dirname, _, filenames in os.walk(METADATA_PATH + ''):
for filename in filenames:
if (not filename.endswith(".csv")):
if (dirname.endswith("Train")):
if (filename.split("_")[2] != "tissue"):
if str(filename.split("_")[2]) not in unique_train_ids:
print("Train leakage:", filename.split("_")[2])
elif (dirname.endswith("Test")):
if (filename.split("_")[2] != "tissue"):
if str(filename.split("_")[2]) not in unique_test_ids:
print("Test leakage:", filename.split("_")[2])
#Success = No output
|
Data_Preperation.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] slideshow={"slide_type": "slide"}
# # Elementary greenhouse models
#
# This notebook is part of [The Climate Laboratory](https://brian-rose.github.io/ClimateLaboratoryBook) by [<NAME>](http://www.atmos.albany.edu/facstaff/brose/index.html), University at Albany.
# + [markdown] slideshow={"slide_type": "slide"}
# ____________
# <a id='section1'></a>
#
# ## 1. A single layer atmosphere
# ____________
#
# We will make our first attempt at quantifying the greenhouse effect in the simplest possible greenhouse model: a single layer of atmosphere that is able to absorb and emit longwave radiation.
# -
# 
# + [markdown] slideshow={"slide_type": "slide"}
# ### Assumptions
#
# - Atmosphere is a single layer of air at temperature $T_a$
# - Atmosphere is **completely transparent to shortwave** solar radiation.
# - The **surface** absorbs shortwave radiation $(1-\alpha) Q$
# - Atmosphere is **completely opaque to infrared** radiation
# - Both surface and atmosphere emit radiation as **blackbodies** ($\sigma T_s^4, \sigma T_a^4$)
# - Atmosphere radiates **equally up and down** ($\sigma T_a^4$)
# - There are no other heat transfer mechanisms
#
# We can now use the concept of energy balance to ask what the temperature need to be in order to balance the energy budgets at the surface and the atmosphere, i.e. the **radiative equilibrium temperatures**.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Energy balance at the surface
#
# $$
# \begin{align*}
# \text{energy in} &= \text{energy out} \\
# (1-\alpha) Q + \sigma T_a^4 &= \sigma T_s^4 \\
# \end{align*}
# $$
#
# The presence of the atmosphere above means there is an additional source term: downwelling infrared radiation from the atmosphere.
#
# We call this the **back radiation**.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Energy balance for the atmosphere
#
# $$
# \begin{align}
# \text{energy in} &= \text{energy out} \\
# \sigma T_s^4 &= A\uparrow + A\downarrow = 2 \sigma T_a^4 \\
# \end{align}
# $$
#
# which means that
# $$ T_s = 2^\frac{1}{4} T_a \approx 1.2 T_a $$
#
# So we have just determined that, in order to have a purely **radiative equilibrium**, we must have $T_s > T_a$.
#
# *The surface must be warmer than the atmosphere.*
# + [markdown] slideshow={"slide_type": "slide"}
# ### Solve for the radiative equilibrium surface temperature
#
# Now plug this into the surface equation to find
#
# $$ \frac{1}{2} \sigma T_s^4 = (1-\alpha) Q $$
#
# and use the definition of the emission temperature $T_e$ to write
#
# $$ (1-\alpha) Q = \sigma T_e^4 $$
#
# *In fact, in this model, $T_e$ is identical to the atmospheric temperature $T_a$, since all the OLR originates from this layer.*
# + [markdown] slideshow={"slide_type": "slide"}
# Solve for the surface temperature:
#
# $$ T_s = 2^\frac{1}{4} T_e $$
#
# From the observed outgoing longwave radiation that we studied last week, $T_e = 255$ K. Thus you can solve for the surface temperature...
# +
def surface(Te = 255):
Ts = 2**(1/4)*Te
return Ts
surface()
# + [markdown] slideshow={"slide_type": "slide"}
# This model is one small step closer to reality: surface is warmer than atmosphere, emissions to space generated in the atmosphere, atmosphere heated from below and helping to keep surface warm.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Why does this model overpredict the surface temperature
#
# Our model now overpredicts the surface temperature by about 15ºC (303 K versus the observed 288 K).
#
# Why is this? Let's discuss.
# + [markdown] slideshow={"slide_type": "slide"}
# - Te is not the same as Ta.
# - The atmosphere is not actually completely opaque to infrared radiation
# - The atmosphere has a vertical structure
# + [markdown] slideshow={"slide_type": "slide"}
# ____________
# <a id='section2'></a>
#
# ## 2. Introducing the two-layer grey gas model
# ____________
# + [markdown] slideshow={"slide_type": "slide"}
# Let's generalize the above model just a little bit to build a slighly more realistic model of longwave radiative transfer.
#
# We will address two shortcomings of our single-layer model:
# 1. No vertical structure
# 2. 100% longwave opacity
#
# Relaxing these two assumptions gives us what turns out to be a very useful prototype model for **understanding how the greenhouse effect works**.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Assumptions
#
# - The atmosphere is **transparent to shortwave radiation** (still)
# - Divide the atmosphere up into **two layers of equal mass** (the dividing line is thus at 500 hPa pressure level)
# - Each layer **absorbs only a fraction $\epsilon$** of whatever longwave radiation is incident upon it.
# - We will call the fraction $\epsilon$ the **absorptivity** of the layer.
# - Assume $\epsilon$ is the same in each layer
#
# This is called the **grey gas** model, where **grey** here means the emission and absorption have **no spectral dependence** (same at every wavelength).
#
# We can think of this model informally as a "leaky greenhouse".
# + [markdown] slideshow={"slide_type": "slide"}
# Note that the assumption that $\epsilon$ is the same in each layer is appropriate if the absorption is actually carried out by a gas that is **well-mixed** in the atmosphere.
#
# Out of our two most important absorbers:
#
# - CO$_2$ is well mixed
# - H$_2$O is not (mostly confined to lower troposphere due to strong temperature dependence of the saturation vapor pressure).
#
# But we will ignore this aspect of reality for now.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Kirchoff's Law
#
# In order to build our model, we need to introduce one additional piece of physics known as **Kirchoff's Law**:
#
# $$ \text{absorptivity} = \text{emissivity} $$
#
# So **if a layer of atmosphere at temperature $T$ absorbs a fraction $\epsilon$** of incident longwave radiation, it must **emit**
#
# $$ \epsilon ~\sigma ~T^4 $$
#
# both up and down.
# + [markdown] slideshow={"slide_type": "slide"}
# ### A sketch of the radiative fluxes in the 2-layer atmosphere
# -
# 
# + [markdown] slideshow={"slide_type": "slide"}
# - Surface temperature is $T_s$
# - Atm. temperatures are $T_0, T_1$ where $T_0$ is closest to the surface.
# - absorptivity of atm layers is $\epsilon$
# - Surface emission is $\sigma T_s^4$
# - Atm emission is $\epsilon \sigma T_0^4, \epsilon \sigma T_1^4$ (up and down)
# - Absorptivity = emissivity for atmospheric layers
# - a fraction $(1-\epsilon)$ of the longwave beam is **transmitted** through each layer
# -
# ____________
# ## 3. Tracing the upwelling beam of longwave radiation
# ____________
# + [markdown] slideshow={"slide_type": "slide"}
# Let's think about the upwelling beam of longwave radiation, which we denote $U$.
#
# ### Surface to layer 0
#
# We start at the surface. The upward flux **from the surface to layer 0** is
#
# $$U_0 = \sigma T_s^4$$
#
# (just the emission from the suface).
# -
# ### Layer 0 to layer 1
#
# Now **following this beam upward**, we first recognize that a fraction $\epsilon$ of this beam is **absorbed** in layer 0.
#
# The upward flux from layer 0 to layer 1 consists of the sum of two parts:
#
# 1. The **transmitted part** of whatever is incident from below (i.e. the part that is **not absorbed**)
# 2. **New upward emissions** from layer 0
#
# We can write this upward flux from layer 0 to layer 1 as:
#
# $$U_1 = (1-\epsilon) \sigma T_s^4 + \epsilon \sigma T_0^4$$
# ### Beyond layer 1
#
# Continuing to follow the same beam, we follow the same logic! A fraction $\epsilon$ of $U_1$ is absorbed in layer 1, and therefore the transmitted part is $(1-\epsilon) U_1$.
#
# Including new emissions from layer 1, the upwelling flux above layer 1 is
#
# $$U_2 = (1-\epsilon) U_1 + \epsilon \sigma T_1^4$$
# + [markdown] slideshow={"slide_type": "slide"}
# ### Outgoing Longwave Radiation
#
# Since there is **no more atmosphere above layer 1**, this upwelling beam is our OLR for this model:
#
# $$\text{OLR} = U_2 = (1-\epsilon) U_1 + \epsilon \sigma T_1^4$$
#
# which, plugging in the above expression for $U_1$, works out to
#
# $$\text{OLR} = (1-\epsilon)^2 \sigma T_s^4 + \epsilon(1-\epsilon)\sigma T_0^4 + \epsilon \sigma T_1^4$$
#
# Here the three terms represent **contributions to the total OLR** that **originate from each of the three levels**
# -
# ### Limits of large and small absorptivity/emissivity
#
# Think about the following two questions:
#
# - What happens to this expression if $\epsilon=1$? *What does this represent physically?*
# - What about $\epsilon=0$?
# By allowing the atmosphere to partially absorb emissions from other levels, we now see that the Outgoing Longwave Radiation to space **includes emissions from every level** - and therefore **affected by temperature at every level**!
# + [markdown] slideshow={"slide_type": "slide"}
# ____________
#
# ## 4. Tuning the grey gas model to observations
# ____________
# + [markdown] slideshow={"slide_type": "slide"}
# In building our new model we have introduced exactly **one parameter**, the absorptivity $\epsilon$. We need to choose a value for $\epsilon$.
#
# We will tune our model so that it **reproduces the observed global mean OLR** given **observed global mean temperatures**.
#
# ### Global mean air temperature observations
#
# To get appropriate temperatures for $T_s, T_0, T_1$, let's revisit the global, annual mean lapse rate plot from NCEP Reanalysis data we first encountered in the [Radiation notes](https://brian-rose.github.io/ClimateLaboratoryBook/courseware/radiation.html).
# + tags=["hide_input"]
# This code is used just to create the skew-T plot of global, annual mean air temperature
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import xarray as xr
from metpy.plots import SkewT
ncep_url = "http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis.derived/"
ncep_air = xr.open_dataset( ncep_url + "pressure/air.mon.1981-2010.ltm.nc", use_cftime=True)
# Take global, annual average and convert to Kelvin
coslat = np.cos(np.deg2rad(ncep_air.lat))
weight = coslat / coslat.mean(dim='lat')
Tglobal = (ncep_air.air * weight).mean(dim=('lat','lon','time'))
fig = plt.figure(figsize=(9, 9))
skew = SkewT(fig, rotation=30)
skew.plot(Tglobal.level, Tglobal, color='black', linestyle='-', linewidth=2, label='Observations')
skew.ax.set_ylim(1050, 10)
skew.ax.set_xlim(-75, 45)
# Add the relevant special lines
skew.plot_dry_adiabats(linewidth=0.5)
skew.plot_moist_adiabats(linewidth=0.5)
#skew.plot_mixing_lines()
skew.ax.legend()
skew.ax.set_xlabel(r'Temperature ($^{\circ} C$)')
skew.ax.set_ylabel('Atmos. pressure (hPa)')
skew.ax.set_title('Global, annual mean sounding from NCEP Reanalysis', fontsize = 16);
# + [markdown] slideshow={"slide_type": "slide"}
# ### Target temperatures for our model tuning
#
# First, we set
# $$T_s = 288 \text{ K} $$
#
# From the lapse rate plot, an average temperature for the layer between 1000 and 500 hPa is
#
# $$ T_0 = 275 \text{ K}$$
#
# Defining an average temperature for the layer between 500 and 0 hPa is more ambiguous because of the lapse rate reversal at the tropopause. We will choose
#
# $$ T_1 = 230 \text{ K}$$
#
# From the graph, this is approximately the observed global mean temperature at 275 hPa or about 10 km.
# + [markdown] slideshow={"slide_type": "slide"}
# ### OLR
#
# From the observed global energy budget (see previous weeks) we set
#
# $$\text{OLR} = 238.5 \text{ W m}^{-2}$$
# + [markdown] slideshow={"slide_type": "slide"}
# ### Solving for $\epsilon$
#
# We wrote down the expression for OLR as a function of temperatures and absorptivity in our model above.
#
# All we need to do is plug the observed values into the above expression for OLR, and solve for $\epsilon$.
#
# It is a **quadratic equation** for the unknown $\epsilon$. We could work out the exact solution using the quadratic formula.
#
# But let's do it **graphically**, using Python!
# + [markdown] slideshow={"slide_type": "slide"}
# ### Exercise: graphical solution to find the best fit value of $\epsilon$
#
# The OLR formula for the leaky greenhouse that we derived above is
#
# $$\text{OLR} = (1-\epsilon)^2 \sigma T_s^4 + \epsilon(1-\epsilon)\sigma T_0^4 + \epsilon \sigma T_1^4$$
#
# Do the following:
#
# - Write a Python function that implements this formula
# - The function should accept **four input parameters**:
# - The three temperatures $T_s, T_0, T_1$
# - The emissivity $\epsilon$
# - Using this function, make a **graph of OLR vs. $\epsilon$** for the observed temperature values $T_s = 288, T_0 = 275, T_1 = 230$
# - For the graph, $\epsilon$ should range between 0 and 1.
# - From your graph, find the approximate value of $\epsilon$ that gives $OLR = 238.5$
# -
sigma=5.67E-8
def OLR(Ts, T0, T1, epsilon):
fromsurf = ((1-epsilon)**2)*sigma*(Ts**4)
fromL0 = epsilon*(1-epsilon)*sigma*(T0**4)
fromL1 = epsilon*sigma*(T1**4)
return fromsurf+fromL0+fromL1
eps = np.linspace(0,1,num=20)
olrtests = OLR(Ts=288, T0=275, T1=230, epsilon=eps)
fig, ax=plt.subplots()
ax.plot(eps, olrtests)
ax.axhline(238.5, color='k', ls=':')
ax.set(xlabel=r'$\epsilon$', ylabel='OLR [W/m2]')
# + [markdown] slideshow={"slide_type": "slide"}
# Note if you solve the quadratic equation algebraically you will get two solutions:
#
# - $\epsilon \approx 0.586$
# - $\epsilon \approx 3.93$
#
# (for details, see [the advanced notes here](https://brian-rose.github.io/ClimateLaboratoryBook/courseware/sympy-greenhouse.html))
#
# **Why is the second solution not physically meaningful?**
#
# Hopefully your graph shows that $\epsilon = 0.586$ gives the correct value of OLR.
#
# This is the absorptivity that guarantees that **our model reproduces the observed OLR given the observed temperatures**.
# + [markdown] slideshow={"slide_type": "slide"}
# ____________
#
# ## 5. Level of emission
# ____________
# + [markdown] slideshow={"slide_type": "slide"}
# ### Contributions from each level to the outgoing radiation
#
# Now that we have tuned up our model, we can see exactly how strongly each level contributes to the OLR.
#
# The three components of the OLR are
#
# $$
# \begin{align*}
# \text{OLR}_s &= (1-\epsilon)^2 \sigma T_s^4 \\
# \text{OLR}_0 &= \epsilon(1-\epsilon)\sigma T_0^4 \\
# \text{OLR}_1 &= \epsilon \sigma T_1^4
# \end{align*}
# $$
#
# which of course add up to the total OLR we wrote down above.
# -
# ### Exercise: calculate contributions to OLR
#
# **Write some simple Python code to calculate each term in the OLR using the observed temperatures and the tuned value $\epsilon = 0.586$. Fill out the list below using your calculated numbers.**
# +
def OLR(e=0.586, sigma=5.67E-8, Ts=288, T0=275, T1=230):
OLRs = ((1-e)**2)*sigma*Ts**4
OLR0 = e*(1-e)*sigma*T0**4
OLR1 = e*sigma*T1**4
return OLRs, OLR0, OLR1
OLR()
# + [markdown] slideshow={"slide_type": "slide"}
# **Contributions to the OLR originating from each level, in W/m2:**
#
# - Surface: 66.86
# - Level 0: 78.67
# - Level 1: 92.98
# -
Temp=sum(OLR())
print(Temp)
# Notice that the largest single contribution is coming from the top layer.
#
# *This is in spite of the fact that the emissions from this layer are weak, because it is so cold.*
# + [markdown] slideshow={"slide_type": "slide"}
# ### Changing the level of emission by adding absorbers
# + [markdown] slideshow={"slide_type": "-"}
# Adding some **extra greenhouse absorbers** will mean that a **greater fraction** of incident longwave radiation is **absorbed in each layer**.
#
# Thus **$\epsilon$ must increase** as we add greenhouse gases.
# + [markdown] slideshow={"slide_type": "slide"}
# Suppose we have $\epsilon$ initially, and the absorptivity increases to $\epsilon_2 = \epsilon + \Delta \epsilon$.
#
# Suppose further that this increase happens **abruptly** so that there is no time for the temperatures to respond to this change. **We hold the temperatures fixed** in the column and ask how the radiative fluxes change.
#
# **Question: Do you expect the OLR to increase or decrease?**
# -
# ### Calculating the change in level of emission
#
# Let's use our two-layer leaky greenhouse model to investigate the answer.
# + [markdown] slideshow={"slide_type": "slide"}
# The components of the OLR before the perturbation are
#
# $$
# \begin{align*}
# \text{OLR}_s &= (1-\epsilon)^2 \sigma T_s^4 \\
# \text{OLR}_0 &= \epsilon(1-\epsilon)\sigma T_0^4 \\
# \text{OLR}_1 &= \epsilon \sigma T_1^4
# \end{align*}
# $$
# + [markdown] slideshow={"slide_type": "slide"}
# and after the perturbation we have
#
# $$
# \begin{align*}
# \text{OLR}_s &= (1-\epsilon - \Delta \epsilon)^2 \sigma T_s^4 \\
# \text{OLR}_0 &= (\epsilon + \Delta \epsilon)(1-\epsilon - \Delta \epsilon)\sigma T_0^4 \\
# \text{OLR}_1 &= (\epsilon + \Delta \epsilon) \sigma T_1^4
# \end{align*}
# $$
# + [markdown] slideshow={"slide_type": "slide"}
# Let's subtract off the original components to get the contributions to the **change in OLR** from each layer:
# -
# $$
# \begin{align*}
# \Delta \text{OLR}_s &= \left[(1-\epsilon - \Delta \epsilon)^2 - (1-\epsilon)^2\right]\sigma T_s^4 \\
# \Delta \text{OLR}_0 &= \left[(\epsilon + \Delta \epsilon)(1-\epsilon - \Delta \epsilon) - \epsilon(1-\epsilon) \right] \sigma T_0^4 \\
# \Delta \text{OLR}_1 &= \left[(\epsilon + \Delta \epsilon) - \epsilon \right] \sigma T_1^4
# \end{align*}
# $$
# + [markdown] slideshow={"slide_type": "slide"}
# Now expand this out, but to make things easier to deal with, neglect term in $\Delta \epsilon^2$ (very small - we will be considering changes of less than 10% in $\epsilon$):
#
# $$
# \begin{align*}
# \Delta \text{OLR}_s &\approx (\Delta \epsilon) \left[ -2(1-\epsilon) \right] \sigma T_s^4 \\
# \Delta \text{OLR}_0 &\approx (\Delta \epsilon) (1 - 2 \epsilon) \sigma T_0^4 \\
# \Delta \text{OLR}_1 &\approx (\Delta \epsilon) \sigma T_1^4
# \end{align*}
# $$
# + [markdown] slideshow={"slide_type": "fragment"}
# Now look at the **sign** of each term. Recall that $0 < \epsilon < 1$. **Which terms in the OLR go up and which go down?**
#
# **THIS IS VERY IMPORTANT, SO STOP AND THINK ABOUT IT.**
# + [markdown] slideshow={"slide_type": "fragment"}
# The contribution from the **surface** must **decrease**, while the contribution from the **top layer** must **increase**.
#
# **When we add absorbers, the average level of emission goes up!**
# + [markdown] slideshow={"slide_type": "slide"}
# ____________
#
# ## 6. Radiative forcing in the 2-layer grey gas model
# ____________
# -
# ### Definition of Radiative Forcing
#
# We now define a very important quantity:
#
# **"Radiative forcing" is the change in total radiative flux at TOA after adding absorbers**
# + [markdown] slideshow={"slide_type": "-"}
# In this model, **only the longwave flux can change**, so we calculate the radiative forcing as
#
# $$ R = - \Delta \text{OLR} $$
#
# (with the minus sign so that $R$ is **positive when the climate system is gaining extra energy**).
# + [markdown] slideshow={"slide_type": "slide"}
# ### Connection between radiative forcing and level of emission
#
# We just worked out that whenever we **add some extra absorbers**, the **emissions to space** (on average) will originate from **higher levels** in the atmosphere.
#
# What does this mean for OLR? Will it increase or decrease?
#
# To get the answer, we just have to sum up the three contributions we wrote above:
# + [markdown] slideshow={"slide_type": "slide"}
# $$
# \begin{align*}
# R &= -\Delta \text{OLR}_s - \Delta \text{OLR}_0 - \Delta \text{OLR}_1 \\
# &= -\Delta \epsilon \left[ -2(1-\epsilon) \sigma T_s^4 + (1 - 2 \epsilon) \sigma T_0^4 + \sigma T_1^4 \right]
# \end{align*}
# $$
# -
# Is this a positive or negative number? The key point is this:
#
# **It depends on the temperatures, i.e. on the lapse rate.**
# + [markdown] slideshow={"slide_type": "slide"}
# ### Greenhouse effect for an isothermal atmosphere
#
# Stop and think about this question:
#
# If the **surface and atmosphere are all at the same temperature**, does the OLR go up or down when $\epsilon$ increases (i.e. we add more absorbers)?
#
# Understanding this question is key to understanding how the greenhouse effect works.
# + [markdown] slideshow={"slide_type": "slide"}
# #### Let's solve the isothermal case
#
# We will just set $T_s = T_0 = T_1$ in the above expression for the radiative forcing.
#
# What do you get?
# -
R = 0
# + [markdown] slideshow={"slide_type": "slide"}
# #### The answer is $R=0$
#
# For an isothermal atmosphere, there is **no change** in OLR when we add extra greenhouse absorbers. Hence, no radiative forcing and no greenhouse effect.
#
# # Why?
#
# The level of emission still must go up. But since the temperature at the upper level is the **same** as everywhere else, the emissions are exactly the same.
# + [markdown] slideshow={"slide_type": "-"}
# ### The radiative forcing (change in OLR) depends on the lapse rate!
# + [markdown] slideshow={"slide_type": "slide"}
# For a more realistic example of radiative forcing due to an increase in greenhouse absorbers, we use our observed temperatures and the tuned value for $\epsilon$.
#
# We'll express the answer in W m$^{-2}$ for a 2% increase in $\epsilon$:
#
# $$ \Delta \epsilon = 0.02 \times 0.58 $$
# + slideshow={"slide_type": "-"}
epsilon = 0.586041150248834
delta_epsilon = 0.02 * epsilon
delta_epsilon
# + [markdown] slideshow={"slide_type": "slide"}
# Calculate the three components of the radiative forcing:
# + slideshow={"slide_type": "slide"}
sigma = 5.67E-8
Ts = 288.
T0 = 275.
T1 = 230.
# + slideshow={"slide_type": "slide"}
# Component originating from the surface
Rs = -delta_epsilon * (-2*(1-epsilon)*sigma * Ts**4)
Rs
# + slideshow={"slide_type": "slide"}
# Component originating from level 0
R0 = -delta_epsilon * (1-2*epsilon) * sigma * (T0**4)
print(R0)
# + slideshow={"slide_type": "slide"}
# Component originating from level 1
R1 = -delta_epsilon * sigma*T1**4
print(R1)
# + [markdown] slideshow={"slide_type": "slide"}
# So just add them up to get the total radiative forcing:
# -
R = Rs + R0 + R1
R
# + [markdown] slideshow={"slide_type": "slide"}
# So in our example, **the OLR decreases by 2.6 W m$^{-2}$**, or equivalently, the **radiative forcing is +2.6 W m$^{-2}$.**
#
# What we have just calculated is this:
#
# **Given the observed lapse rates, a small increase in absorbers will cause a small decrease in OLR.**
#
# The **greenhouse effect** thus gets **stronger**, and energy will begin to accumulate in the system -- which will eventually **cause temperatures to increase** as the system adjusts to a new equilibrium.
# + [markdown] slideshow={"slide_type": "slide"}
# ____________
#
# ## 7. Summary
# ____________
# + [markdown] slideshow={"slide_type": "slide"}
# ### Key physical lessons
#
# - Putting a **layer of longwave absorbers** above the surface keeps the **surface substantially warmer**, because of the **backradiation** from the atmosphere (greenhouse effect).
# - The **grey gas** model assumes that each layer absorbs and emits a fraction $\epsilon$ of its blackbody value, independent of wavelength.
# + [markdown] slideshow={"slide_type": "slide"}
# - With **incomplete absorption** ($\epsilon < 1$), there are contributions to the OLR from every level and the surface (there is no single **level of radiative emission**)
# - Adding more absorbers means that **contributions to the OLR** from **upper levels** go **up**, while contributions from the surface go **down**.
# + [markdown] slideshow={"slide_type": "slide"}
# - The **radiative forcing** caused by an increase in absorbers **depends on the lapse rate** (decrease in temperature with altitude in the atmosphere).
# - For an **isothermal atmosphere** the radiative forcing is zero and there is **no greenhouse effect**
# - The radiative forcing is positive for our atmosphere **because tropospheric temperatures tend to decrease with height**.
# + [markdown] slideshow={"slide_type": "skip"}
# ____________
#
# ## Credits
#
# This notebook is based on a chapter of [The Climate Laboratory](https://brian-rose.github.io/ClimateLaboratoryBook), an open-source textbook developed and maintained by [<NAME>](http://www.atmos.albany.edu/facstaff/brose/index.html), University at Albany.
#
# It is licensed for free and open consumption under the
# [Creative Commons Attribution 4.0 International (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/) license.
#
# Development of these notes and the [climlab software](https://github.com/brian-rose/climlab) is partially supported by the National Science Foundation under award AGS-1455071 to <NAME>. Any opinions, findings, conclusions or recommendations expressed here are mine and do not necessarily reflect the views of the National Science Foundation.
# ____________
|
Lab 4.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:tptyw]
# language: python
# name: conda-env-tptyw-py
# ---
# +
import json
import os
import pickle
import psycopg2
import pandas as pd
import sqlalchemy
import sys
sys.path.append("..")
from connect_db import db_connection
import geopandas as gpd
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pylab as plt
import matplotlib.cm as cm
import seaborn as sns
get_ipython().magic(u'matplotlib inline')
# %matplotlib inline
username='ywang99587'
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.metrics import pairwise_distances
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from scipy.spatial import distance
import scipy.spatial.distance
from scipy.spatial.distance import cdist, pdist
import pylab as pl
# -
#df_feature_all = pd.read_csv('/mnt/data/shared/Germany_Aug_features_with_locs.csv')
df_feature_all = pd.read_csv('/mnt/data/shared/ger3.csv')
df_feature_all.shape
# +
#df_feature_all['num_loc_per_hr_tusc'] = df_feature_all['num_loc_in_tusc']/df_feature_all['hrs_in_tusc']
# +
#df_feature_all2 = df_feature_all[(df_feature_all['num_loc_per_hr_tusc']>0.04) & (df_feature_all['num_loc_per_hr_tusc']<100)]
# -
df_feature_all.columns
feature_hrs = ['hrs_in_tusc', 'hrs_outside_tuscany']
feature_locs = []
## standardize all continuous features
df_feature_cont = df_feature_all[['hrs_in_italy', 'hr_arvl_italy', 'day_of_wk_arvl_italy', 'mon_arvl_italy', 'day_arvl_italy',
'num_unique_loc_in_italy', 'num_loc_in_italy','num_unique_loc_in_tusc', 'num_loc_in_tusc', 'hrs_in_tusc',
'hr_arvl_tusc', 'day_of_wk_arvl_tusc', 'mon_arvl_tusc', 'day_arvl_tusc',
'hrs_outside_tuscany', 'locs_outside_tuscany', 'unique_locs_outside_tuscany',
'start_lat', 'start_lon','start_lat_tusc', 'start_lon_tusc',
'end_lat', 'end_lon', 'avg_lat',
'avg_lon', 'top_lat', 'top_lon' ]]#,
#'forest', 'water', 'river', 'park', 'arezzo', 'florence', 'livorno',
#'lucca', 'pisa', 'pistoia', 'siena', 'coast', 'num_attrs', 'towns',
#'subrub']]
#df_feature_mcc = df_feature.join(mcc_fac)
scaler = StandardScaler()
scaled_feature_all = pd.DataFrame(scaler.fit_transform(df_feature_cont), columns = df_feature_cont.columns)
scaled_feature_all.head()
## relevant features
scaled_feature = scaled_feature_all[['unique_locs_outside_tuscany', 'locs_outside_tuscany','num_unique_loc_in_tusc',
'num_loc_in_tusc', 'hrs_in_tusc','hrs_outside_tuscany',
'start_lat', 'start_lon', 'start_lat_tusc', 'start_lon_tusc',
'end_lat', 'end_lon', 'avg_lat',
'avg_lon', 'top_lat', 'top_lon']]#,
# 'forest', 'water', 'river', 'park', 'arezzo', 'florence', 'livorno',
#'lucca', 'pisa', 'pistoia', 'siena', 'coast', 'num_attrs', 'towns',
# 'subrub']]
scaled_feature.corr()
## scaled features and lon lat
df_scaled_loc = pd.concat([scaled_feature.reset_index(drop=True), df_feature_all[['std_lat', 'std_lon']]], axis=1)
df_scaled_loc.head()
data=df_scaled_loc[df_scaled_loc['std_lat']>0]
data.columns
df_feature_data = df_feature_all[df_feature_all['std_lat']>0] ## for descriptives
df_feature_data.shape
data.shape
kmeans = KMeans(n_clusters=5, n_jobs=-1)
kmeans.fit(data)
labels = kmeans.labels_
data.head()
rdf = data[['num_loc_in_tusc','num_unique_loc_in_tusc',
'locs_outside_tuscany', 'unique_locs_outside_tuscany',
'start_lat', 'start_lon',
'end_lat', 'end_lon', 'avg_lat',
'avg_lon', 'top_lat', 'top_lon', 'std_lat', 'std_lon']]
rdf[rdf.columns]=rdf[rdf.columns].astype(float)
rdf['col']=labels.astype(str)
sns.pairplot(rdf,hue='col')
len(labels)
pd.DataFrame(labels).hist()
data['label']=labels
data.label.hist()
# +
## desc by cluster? - use unscaled data
# -
df_feature_data['label']=labels
# +
#df_feature_data.to_csv('/mnt/data/shared/customer_clustering_label.csv')
# -
df_feature_data_redc = df_feature_data[['avg_lat', 'avg_lon', 'top_lat', 'top_lon', 'label']]
df_feature_data_redc.head()
provinces = r"/mnt/data/shared/Boundaries regions and municipalities Italy 2016/CMProv2016_WGS84_g/CMprov2016_WGS84_g.shp"
territories = r"/mnt/data/shared/Tus_28districts.shp"
# +
gdf_pro = gpd.read_file(provinces)
gdf_ter = gpd.read_file(territories)
# Convert coordinates in WGS84 to Lat Lon format
# see http://geopandas.org/projections.html
#gdf_reg['geometry'] = gdf_reg['geometry'].to_crs(epsg=4326)
gdf_pro['geometry'] = gdf_pro['geometry'].to_crs(epsg=4326)
#gdf_mun['geometry'] = gdf_mun['geometry'].to_crs(epsg=4326)
# important cities
important_cities_tuscany = r"/mnt/data/shared/important_cities.csv"
df_impcit = pd.read_csv(important_cities_tuscany)
# 9 is for Tuscany only
#gdf_reg_tus = gdf_reg[gdf_reg["COD_REG"] == 9]
gdf_pro_tus = gdf_pro[gdf_pro["COD_REG"] == 9]
gdf_ter_tus = gdf_ter # this one is already Tuscany only
#gdf_mun_tus = gdf_mun[gdf_mun["COD_REG"] == 9]
# -
df_impcit.head()
# +
from geopandas import GeoDataFrame
from shapely.geometry import Point
geometry = [Point(xy) for xy in zip(df_impcit.long, df_impcit.lat)]
df_impcit = df_impcit.drop(['long', 'lat'], axis=1)
crs = {'init': 'epsg:4326'}
geo_df_impcit = GeoDataFrame(df_impcit, crs=crs, geometry=geometry)
geo_df_impcit.head()
# +
## plot avg
fig = plt.figure(figsize=(12, 10))
ax = plt.gca()
cluster = df_feature_data_redc[df_feature_data_redc['label'] == 0]
plt.plot(cluster['avg_lon'].iloc[:], cluster['avg_lat'].iloc[:], 'go', markersize=0.9, alpha=0.1)
#cluster = df_feature_data_redc[df_feature_data_redc['label'] == 1]
#plt.plot(cluster['avg_lon'].iloc[:], cluster['avg_lat'].iloc[:], 'bo', markersize=0.5, alpha=0.3)
#cluster = df_feature_data_redc[df_feature_data_redc['label'] == 2]
#plt.plot(cluster['top_lon'].iloc[:], cluster['top_lat'].iloc[:], 'go', markersize=0.5, alpha=0.3)
cluster = df_feature_data_redc[df_feature_data_redc['label'] == 1]
plt.plot(cluster['avg_lon'].iloc[:], cluster['avg_lat'].iloc[:], 'bo', markersize=0.9, alpha=0.1)
cluster = df_feature_data_redc[df_feature_data_redc['label'] == 2]
plt.plot(cluster['avg_lon'].iloc[:], cluster['avg_lat'].iloc[:], 'ro', markersize=0.9, alpha=0.1)
gdf_pro_tus.plot(ax=ax, color='white', edgecolor='gray', alpha=0.99)
#important_cities(df_impcit)
geo_df_impcit.plot(ax=ax, color='black');
plt.tight_layout();
plt.ylim([42.3, 44.5])
plt.xlim([9.5, 12.5])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
# +
## plot avg
fig = plt.figure(figsize=(12, 10))
ax = plt.gca()
cluster = df_feature_data_redc[df_feature_data_redc['label'] == 0]
plt.plot(cluster['top_lon'].iloc[:], cluster['top_lat'].iloc[:], 'go', markersize=0.9, alpha=0.1)
#cluster = df_feature_data_redc[df_feature_data_redc['label'] == 1]
#plt.plot(cluster['top_lon'].iloc[:], cluster['top_lat'].iloc[:], 'bo', markersize=0.5, alpha=0.3)
#cluster = df_feature_data_redc[df_feature_data_redc['label'] == 2]
#plt.plot(cluster['top_lon'].iloc[:], cluster['top_lat'].iloc[:], 'go', markersize=0.5, alpha=0.3)
cluster = df_feature_data_redc[df_feature_data_redc['label'] == 1]
plt.plot(cluster['top_lon'].iloc[:], cluster['top_lat'].iloc[:], 'bo', markersize=0.9, alpha=0.1)
cluster = df_feature_data_redc[df_feature_data_redc['label'] == 2]
plt.plot(cluster['top_lon'].iloc[:], cluster['top_lat'].iloc[:], 'ro', markersize=0.9, alpha=0.1)
gdf_pro_tus.plot(ax=ax, color='white', edgecolor='gray', alpha=0.99)
#important_cities(df_impcit)
geo_df_impcit.plot(ax=ax, color='black');
plt.tight_layout();
plt.ylim([42.3, 44.5])
plt.xlim([9.5, 12.5])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
# -
clusters=[]
clen=0
for i in range(0,5):
cluster=df_feature_data[df_feature_data['label']==i]
clusters.append(cluster)
clen+=len(cluster)
print(clusters[i].shape)
70149/clen
df_feature_data.columns
cols = ['hrs_in_tusc','hrs_outside_tuscany', #'hrs_in_italy',
'num_loc_in_tusc','num_unique_loc_in_tusc',
'locs_outside_tuscany', 'unique_locs_outside_tuscany',
#'num_loc_in_italy', 'num_uniuqe_loc_in_italy',
'start_lat', 'start_lon', 'start_lat_tusc', 'start_lon_tusc',
'end_lat', 'end_lon', 'avg_lat',
'avg_lon', 'top_lat', 'top_lon', 'std_lat', 'std_lon']#,
#'forest', 'water', 'river', 'park', 'arezzo', 'florence', 'livorno',
#'lucca', 'pisa', 'pistoia', 'siena', 'coast', 'num_attrs', 'towns',
#'subrub']
cluster_stats = []
for col in cols:
ls_col = []
for i in range(0,5):
statsdf = clusters[i].describe()
statscol = statsdf[col]
ls_col.append(statscol)
df_col = pd.concat(ls_col, axis=1).round(2)
cluster_stats.append(df_col)
print(df_col)
df_cluster = pd.concat(cluster_stats, axis=1)
top_start_locs = []
top_start_ratio = []
for cluster in clusters:
cluster['start_lat2'] = cluster.start_lat.round(2)
cluster['start_lon2'] = cluster.start_lon.round(2)
cluster_loc = pd.DataFrame(cluster.groupby(['start_lat2','start_lon2']).count())
cluster_loc = cluster_loc.sort_values('mcc',ascending=False)
top_start_locs.append(pd.Series(cluster_loc.iloc[0].name))
top_start_ratio.append(cluster_loc.iloc[0,1]/len(cluster))
df_top_start = pd.concat(top_start_locs, axis=1)
df_top_start
top_start_ratio
top_end_locs = []
top_end_ratio = []
for cluster in clusters:
cluster['end_lat2'] = cluster.end_lat.round(2)
cluster['end_lon2'] = cluster.end_lon.round(2)
cluster_loc = pd.DataFrame(cluster.groupby(['end_lat2','end_lon2']).count())
cluster_loc = cluster_loc.sort_values('mcc',ascending=False)
top_end_locs.append(pd.Series(cluster_loc.iloc[0].name))
top_end_ratio.append(cluster_loc.iloc[0,1]/len(cluster))
df_top_end = pd.concat(top_end_locs, axis=1)
df_top_end
top_end_ratio
cluster=df_feature_data[df_feature_data['label']==0]
cluster['start_lat2'] = cluster.start_lat.round(2)
cluster['start_lon2'] = cluster.start_lon.round(2)
cluster_loc = pd.DataFrame(cluster.groupby(['start_lat2','start_lon2']).count())
cluster_loc = cluster_loc.sort_values('mcc',ascending=False)
len(cluster_loc)
# +
#cluster_loc
# -
aa=cluster_loc.iloc[0].name
type(aa)
pd.Series(cluster_loc.iloc[0].name)
cluster_stats[9]
df_cluster
df_cluster.to_csv('/mnt/data/shared/cluster_stats.csv')
ls_col = []
for i in range(0,5):
statsdf = clusters[i].describe()
statscol = statsdf['end_lon']
ls_col.append(statscol)
df_col = pd.concat(ls_col, axis=1).round(2)
df_col
clusters[i]['mcc'].mean()
df_feature_all[['avg_lat', 'avg_lon', 'std_lat','std_lon']].describe()
means=df_feature_all[['avg_lat', 'avg_lon', 'std_lat','std_lon']].mean()
len(means)
df_feature_all[['avg_lat', 'avg_lon', 'std_lat','std_lon']].mean()
places=[12,13,31,32]
stds=df_feature_all[['avg_lat', 'avg_lon', 'std_lat','std_lon']].std()
centers = kmeans.cluster_centers_
centers.shape
means, stds
avg_lat_centers = []
for i in range(0,5):
for j in range(0,len(places)):
print(centers[i,places[j]])
avg_lat_centers.append(centers[i,places[j]]*stds[j]+means[j])
avg_lat_centers
lats=avg_lat_centers[::4]
lons=avg_lat_centers[1::4]
lats_std=avg_lat_centers[2::4]
lons_std=avg_lat_centers[3::4]
a=pd.DataFrame()
a['lats']=lats
a['lons']=lons
a['lats_std']=lats_std
a['lons_std']=lons_std
a.head()
a.to_csv("/mnt/data/shared/coordinates_for_bruno_in_florence_after_croatia_won.csv")
avg_lat_centers
avg_lon_centers = []
for i in range(0,5):
avg_lon_centers.append(centers[i,13]*1.1709+11.1432)
avg_lon_centers
avg_lat_centers = []
for i in range(0,5):
avg_lat_centers.append(centers[i,31]*+43.2289)
avg_lon_centers = []
for i in range(0,5):
avg_lon_centers.append(centers[i,13]*1.1709+11.1432)
kmeans.cluster_centers_
# +
## recluster biggest one -- check labels first
# -
data2 = data[data['label']==0]
len(data2)
data2.head()
df_feature_data2 = df_feature_data[df_feature_data['label']==0]
df_feature_data2.head()
kmeans2 = KMeans(n_clusters=2, n_jobs=-1)
kmeans2.fit(data2)
labels2 = kmeans2.labels_
type(labels2)
np.unique(labels2)
pd.DataFrame(labels2).hist()
df_feature_data2['label2']=labels2
# +
#df_feature_data2.label2.unique
# -
clusters2=[]
clen=0
for i in range(0,2):
cluster=df_feature_data2[df_feature_data2['label2']==i]
clusters2.append(cluster)
clen+=len(cluster)
print(clusters2[i].shape)
print(clen)
cluster_stats2 = []
for col in cols:
ls_col2 = []
for i in range(0,2):
statsdf = clusters2[i].describe()
statscol = statsdf[col]
ls_col2.append(statscol)
df_col2 = pd.concat(ls_col2, axis=1).round(2)
print(df_col2)
cluster_stats2.append(df_col2)
df_cluster2 = pd.concat(cluster_stats2, axis=1)
df_cluster2
kmeans.cluster_centers_
data_db=df_scaled_loc[df_scaled_loc['std_lat']>0]
#df_feature = StandardScaler().fit_transform(df_feature)
#db = DBSCAN().fit(df_feature, eps=0.95, min_samples=10)
db = DBSCAN(eps=0.5, min_samples=50).fit(data_db)
core_samples = db.core_sample_indices_
labels = db.labels_
pd.DataFrame(labels).hist()
# +
## calculate distance between each component pair????
# -
# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
|
dev/descriptives/customer_clustering_German.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Jigsaw unintended bias in toxicity classification
# ### About the problem
#
# The Conversation AI team, a research initiative founded by Jigsaw and Google (both part of Alphabet), builds technology to protect voices in conversation. A main area of focus is machine learning models that can identify toxicity in online conversations, where toxicity is defined as anything rude, disrespectful or otherwise likely to make someone leave a discussion.
#
# Previously in 2018 the same competition was held with the task of classification comment text as toxic or not but the model built back then were focusing words like male, female ,white,black,gay_lesbian etc and marked those comments containing these words as more toxic when compared to comments without these words.
# ### Problem statement
#
# Given comment text we need to predict whether the given comment is toxic or not .
# ### Loss
#
# Jigsaw built a custom AUC for this problem especially to remove unintended bias towards certain words.
#
#
# #### Understanding the evalution metrics
# https://medium.com/jash-data-sciences/measuring-unintended-bias-in-text-classification-a1d2e6630742
#
# a. Subgroup AUC — This calculates AUC on only the examples from the subgroup. It represents model understanding and performance within the group itself. A low value in this metric means the model does a poor job of distinguishing between toxic and non-toxic comments that mention the identity.
#
# b. BNSP AUC — This calculates AUC on the positive examples from the background and the negative examples from the subgroup. A low value here means that the model confuses toxic examples that mention the identity with non-toxic examples that do not.
#
# c. BPSN AUC — This calculates AUC on the negative examples from the background and the positive examples from the subgroup. A low value in this metric means that the model confuses non-toxic examples that mention the identity with toxic examples that do not.
#
# d. Final Metrics — We combine the overall AUC with the generalized mean of the Bias AUCs to calculate the final model score:
#
# score=w0AUCoverall+∑a=1AwaMp(ms,a) where:
#
# A = number of submetrics (3)
#
# ms,a = bias metric for identity subgroup s using submetric a
#
# wa = a weighting for the relative importance of each submetric; all four w values set to 0.25
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from wordcloud import WordCloud
from textblob import TextBlob
from sklearn.model_selection import train_test_split
import string
from nltk.sentiment import SentimentIntensityAnalyzer
from nltk.stem.snowball import SnowballStemmer
from sklearn.metrics import confusion_matrix
from sklearn import metrics
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import roc_curve, auc
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
import re
# ## Reading the data
# +
# reading the data
df_train = pd.read_csv('train.csv')
df_test= pd.read_csv('test.csv')
print("shape of train data:", df_train.shape)
df_train.head()
# -
df_train.columns
# There lots of attriutes along with text data where some of those attributes are meta data .
#
# 1.As mentioned in description of the competiton,identity columns are 'male', 'female', 'homosexual_gay_or_lesbian', 'christian', 'jewish','muslim', 'black', 'white' and 'psychiatric_or_mental_illness'
#
# 2.Subtype attributes are:severe_toxicity,obscene,threat,insult,identity_attackandsexual_explicit
#
#
# ##### Creating target class
# +
# assigning class labels based on kaggle's criteria , if target value is < 0.5 then it's non toxic else toxic
def label(target):
return 0 if target < 0.5 else 1
df_train['class'] = df_train.apply(lambda x: label(x['target']), axis= 1)
# -
# I am dividing this case study into two parts
#
# 1.Applying ML classification models and ensembling them at the end .
#
# 2.Applying DL models with various approaches
# ## PART1
# Iam only considering comment_text and dropping all other features.
# # EDA
# #### Plotting target varible
df_train.hist('target')
plt.xlabel("toxity between 0 and 1")
plt.ylabel("comments count")
# Most of the comments are not toxic which means data should be hugely imbalanced.
n_unique_comments = df_train['comment_text'].nunique()
print('unique comments {} out of {}'.format(n_unique_comments,df_train.shape[0]))
# #### Plotting derived target class
df_train.hist('class')
plt.xlabel("Classes")
plt.ylabel("comments count")
# #### Distributions of size of comment text
# no.of words in each comment text
df_train['comment_length'] = df_train['comment_text'].apply(lambda x : len(x))
df_test['comment_length'] = df_test['comment_text'].apply(lambda x : len(x))
sns.distplot(df_train['comment_length'],color="y")
sns.distplot(df_test['comment_length'],color="b")
plt.show()
# Most comments are of lenght less then 1000 words and maximum comment lenght is approximately 1600 words
# ## Frequent words appeared in toxic comments
# +
toxic_Words=(df_train.loc[df_train['target'] >= 0.5]['comment_text'].sample(100000))
wordcloud = WordCloud(width = 800, height = 800,
background_color ='black').generate(str(toxic_Words))
plt.figure(figsize = (10, 10), facecolor = None)
plt.title('Words which appeared more in toxic comments')
plt.imshow(wordcloud)
plt.show()
# -
# 1. We can see some words like idoit ,tax forbes etc are appeared most of the times and note that even though forbes is not a toxic word but it appeared here because it might be due to following reasons:
#
#
# (i)We just selected toxicity as greater than or equals to 0.5 that means the word containing forbes might be appeared close to 0.5 and may not be close to 1.
#
# (ii)Another reason might be that the context of sentence made forbes as toxic .
# ## Frequent words appeared in non toxic comments
# +
ntoxic_Words=(df_train.loc[df_train['target'] < 0.5]['comment_text'].sample(100000))
wordcloud = WordCloud(width = 800, height = 800,
background_color ='black').generate(str(ntoxic_Words))
plt.figure(figsize = (10, 10), facecolor = None)
plt.title('Words which appeared more in non-toxic comments')
plt.imshow(wordcloud)
plt.show()
# -
# 1. Words like testimony ,precincts ,canada ,canadians etc are appeared most of the times in non-toxic comments.
# # Data Prepocessing
# Function to remove all contractions and auxillary words using 're' librabry
def decontracted(phrase):
# specific
phrase = re.sub(r"won't", "will not", phrase)
phrase = re.sub(r"can\'t", "can not", phrase)
# general
phrase = re.sub(r"n\'t", " not", phrase)
phrase = re.sub(r"\'re", " are", phrase)
phrase = re.sub(r"\'s", " is", phrase)
phrase = re.sub(r"\'d", " would", phrase)
phrase = re.sub(r"\'ll", " will", phrase)
phrase = re.sub(r"\'t", " not", phrase)
phrase = re.sub(r"\'ve", " have", phrase)
phrase = re.sub(r"\'m", " am", phrase)
return phrase
# ## Splitting data into train and cv
X_train, X_cv, y_train, y_cv = train_test_split(df_train, df_train['class'], test_size=0.33)
print('Data points in train {} and cv {}'. format(X_train.shape[0],X_cv.shape[0]))
# ### NLP on comment
from tqdm import tqdm
preprocessed_text_train= []
for sentance in tqdm(X_train['comment_text'].values):
sent1 = decontracted(sentance)# applying above defined function to remove auxillary words
sent1 = sent1.replace('\\r', ' ')
sent1 = sent1.replace('\\"', ' ')
sent1 = sent1.replace('\\n', ' ')
sent1 = re.sub('[^A-Za-z0-9]+', ' ', sent1)
# https://gist.github.com/sebleier/554280
stops = set(stopwords.words("english"))
sent1 = ' '.join(e for e in sent1.split() if e not in stops)
preprocessed_text_train.append(sent1.lower().strip())
# +
preprocessed_text_cv= []
for sentance in tqdm(X_cv['comment_text'].values):
sent1 = decontracted(sentance)
sent1 = sent1.replace('\\r', ' ')
sent1 = sent1.replace('\\"', ' ')
sent1 = sent1.replace('\\n', ' ')
sent1 = re.sub('[^A-Za-z0-9]+', ' ', sent1)
# https://gist.github.com/sebleier/554280
stops = set(stopwords.words("english"))
sent1 = ' '.join(e for e in sent1.split() if e not in stops)
preprocessed_text_cv.append(sent1.lower().strip())
# -
preprocessed_text_test = []
for sentance in tqdm(df_test['comment_text'].values):
sent1 = decontracted(sentance)
sent1 = sent1.replace('\\r', ' ')
sent1 = sent1.replace('\\"', ' ')
sent1 = sent1.replace('\\n', ' ')
sent1 = re.sub('[^A-Za-z0-9]+', ' ', sent1)
# https://gist.github.com/sebleier/554280
stops = set(stopwords.words("english"))
sent1 = ' '.join(e for e in sent1.split() if e not in stops)
preprocessed_text_test.append(sent1.lower().strip())
# # Sentiment analysis on comment text
# ###### TEST
# +
# POSITIVE,NEGATIVE ,NEURAL AND COMPOUND sentiment anlaysis on text
test_neg = []
test_neu = []
test_pos = []
test_compound = []
#intializing SentimentIntensityAnalyzer
sis = SentimentIntensityAnalyzer()
for words in preprocessed_text_test:
pos1 = sis.polarity_scores(words)['pos']# these command line returns positive sentiment score if it finds any positive words
neg1 = sis.polarity_scores(words)['neg']# these command line returns negative sentiment score if it finds any negative words
neu1 = sis.polarity_scores(words)['neu']
coump1 = sis.polarity_scores(words)['compound']
#appending them in lists for further use
test_neg.append(neg1)
test_pos.append(pos1)
test_neu.append(neu1)
test_compound.append(coump1)
# adding them into the data frame as features
df_test["senti_pos"]=test_pos
df_test["senti_neg"] =test_neg
df_test["senti_neu"] =test_neu
df_test["senti_com"] =test_compound
# -
# ###### TRAIN
# +
train_pos = []
train_neg = []
train_neu = []
train_compound = []
for words in preprocessed_text_train :
pos1 = sis.polarity_scores(words)['pos']
neg1 = sis.polarity_scores(words)['neg']
neu1 = sis.polarity_scores(words)['neu']
coump1 = sis.polarity_scores(words)['compound']
train_neg.append(neg1)
train_pos.append(pos1)
train_neu.append(neu1)
train_compound.append(coump1)
X_train["senti_pos"] =train_pos
X_train["senti_neg"] =train_neg
X_train["senti_neu"] =train_neu
X_train["senti_com"] =train_compound
# -
# ###### CV
# +
Cv_neg = []
Cv_neu = []
Cv_pos = []
Cv_compound = []
sis = SentimentIntensityAnalyzer()
for words in preprocessed_text_cv:
pos1 = sis.polarity_scores(words)['pos']
neg1 = sis.polarity_scores(words)['neg']
neu1 = sis.polarity_scores(words)['neu']
coump1 = sis.polarity_scores(words)['compound']
Cv_neg.append(neg1)
Cv_pos.append(pos1)
Cv_neu.append(neu1)
Cv_compound.append(coump1)
X_cv["senti_pos"] =Cv_pos
X_cv["senti_neg"] =Cv_neg
X_cv["senti_neu"] =Cv_neu
X_cv["senti_com"] =Cv_compound
# -
# #### Dropping other attritubes
# Dropping all other colunms
cols = [i for i in range (0 ,46)]
X_train.drop(X_train.columns[cols],axis=1,inplace=True)
X_cv.drop(X_cv.columns[cols],axis=1,inplace=True)
df_test.drop(['id','comment_text'],axis=1,inplace=True)
print('Data for training:')
X_train
# ## BOW on comment_text
# +
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(min_df=10,ngram_range=(1,2))
vectorizer.fit(preprocessed_text_train)
text_bow_train = vectorizer.transform(preprocessed_text_train)
text_bow_test = vectorizer.transform(preprocessed_text_test)
text_bow_cv = vectorizer.transform(preprocessed_text_cv)
print("Shape of matrix after one hot encoding ",text_bow_train.shape)
print("Shape of matrix after one hot encoding ",text_bow_test.shape)
print("Shape of matrix after one hot encoding ",text_bow_cv.shape)
# -
from scipy.sparse import hstack
from scipy.sparse import csr_matrix
X_bow_train= hstack((text_bow_train,X_train)).tocsr()
X_bow_test= hstack((text_bow_test,df_test)).tocsr()
X_bow_cv= hstack((text_bow_cv,X_cv)).tocsr()
# ## TFIDF on comment_text
# +
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(min_df=10,ngram_range=(1,2))
vectorizer.fit(preprocessed_text_train)
text_tfidf_train = vectorizer.transform(preprocessed_text_train)
text_tfidf_test = vectorizer.transform(preprocessed_text_test)
text_tfidf_cv = vectorizer.transform(preprocessed_text_cv)
print("Shape of matrix after one hot encoding ",text_tfidf_train.shape)
print("Shape of matrix after one hot encoding ",text_tfidf_test.shape)
print("Shape of matrix after one hot encoding ",text_tfidf_cv.shape)
# -
X_tfidf_train= hstack((text_tfidf_train,X_train)).tocsr()
X_tfidf_test= hstack((text_tfidf_test,df_test)).tocsr()
X_tfidf_cv= hstack((text_tfidf_cv,X_cv)).tocsr()
def plot_confusion_matrix(test_y, predict_y):
C = confusion_matrix(test_y, predict_y)
plt.figure(figsize=(10,4))
labels = [0,1]
# representing A in heatmap format
cmap=sns.light_palette("blue")
sns.heatmap(C, annot=True, cmap=cmap, fmt=".3f", xticklabels=labels, yticklabels=labels)
plt.xlabel('Predicted Class')
plt.ylabel('Original Class')
plt.title("Confusion matrix")
# # Applying ML models
# ## Logistic Regression
# ### Logistic Regression with BOW on text
# +
alpha = [10 ** x for x in range(-5, 3)]# tuning alpha
cv_log_error_array = []
for i in alpha:
print("\nfor alpha =", i)
clf = SGDClassifier(class_weight='balanced', alpha=i, penalty='l2', loss='log', random_state=42, n_jobs=-1)
clf.fit(X_bow_train, y_train)
sig_clf = CalibratedClassifierCV(clf, method="sigmoid")
sig_clf.fit(X_bow_train, y_train)
sig_clf_probs = sig_clf.predict_proba(X_bow_cv)
cv_log_error_array.append(log_loss(y_cv, sig_clf_probs, labels=clf.classes_, eps=1e-15))
# to avoid rounding error while multiplying probabilites we use log-probability estimates
print("Log Loss of CV :",log_loss(y_cv, sig_clf_probs))
fig, ax = plt.subplots()
ax.plot(alpha, cv_log_error_array,c='b')
for i, txt in enumerate(np.round(cv_log_error_array,3)):
ax.annotate((alpha[i],str(txt)), (alpha[i],cv_log_error_array[i]))
plt.grid()
plt.title("Cross Validation Error for each alpha")
plt.xlabel("Alpha i's")
plt.ylabel("Error measure")
plt.show()
best_alpha = np.argmin(cv_log_error_array)
print("\nThe best alpha is : ",alpha[best_alpha])
# +
# Fitting for best alpha =0.001
lr1=SGDClassifier(alpha=0.001,class_weight='balanced',loss='log')
lr1.fit(X_bow_train, y_train)
y_train_pred = lr1.predict_proba(X_bow_train) [:,1]
y_test_pred = lr1.predict_proba( X_bow_cv)[:,1]
train_fpr, train_tpr, tr_thresholds = roc_curve(y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(y_cv, y_test_pred)
plt.plot(train_fpr, train_tpr, label="train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("fpr")
plt.ylabel("tpr")
plt.title("ERROR PLOTS ")
plt.grid()
plt.show()
# +
y_test_pred = lr1.predict( X_bow_cv)
plot_confusion_matrix(y_cv, y_test_pred)
# -
# 1. We can see that both FP and FN values are high that means logistic regression with bow on text is not able to distinguish between the toxic and non toxic comment.
#
#
#
# ### Logistic Regression with tfidf on text
# +
alpha = [10 ** x for x in range(-5, 3)]
cv_log_error_array = []
for i in alpha:
print("\nfor alpha =", i)
clf = SGDClassifier(class_weight='balanced', alpha=i, penalty='l2', loss='log', random_state=42, n_jobs=-1)
clf.fit(X_tfidf_train, y_train)
# Using CalibratedClassifierCv to get probabilities close to exact probabilities
sig_clf = CalibratedClassifierCV(clf, method="sigmoid")
sig_clf.fit(X_tfidf_train, y_train)
sig_clf_probs = sig_clf.predict_proba(X_tfidf_cv)
cv_log_error_array.append(log_loss(y_cv, sig_clf_probs, labels=clf.classes_, eps=1e-15))
# to avoid rounding error while multiplying probabilites we use log-probability estimates
print("Log Loss of CV :",log_loss(y_cv, sig_clf_probs))
fig, ax = plt.subplots()
ax.plot(alpha, cv_log_error_array,c='b')
for i, txt in enumerate(np.round(cv_log_error_array,3)):
ax.annotate((alpha[i],str(txt)), (alpha[i],cv_log_error_array[i]))
plt.grid()
plt.title("Cross Validation Error for each alpha")
plt.xlabel("Alpha i's")
plt.ylabel("Error measure")
plt.show()
best_alpha = np.argmin(cv_log_error_array)
print("\nThe best alpha is : ",alpha[best_alpha])
# +
# fitting for best alpha
lr=SGDClassifier(alpha=0.0001,class_weight='balanced',loss='log')
lr.fit(X_tfidf_train, y_train)
y_train_pred = lr.predict_proba(X_tfidf_train) [:,1]
y_test_pred = lr.predict_proba( X_tfidf_cv)[:,1]
train_fpr, train_tpr, tr_thresholds = roc_curve(y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(y_cv, y_test_pred)
plt.plot(train_fpr, train_tpr, label="train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("fpr")
plt.ylabel("tpr")
plt.title("ERROR PLOTS ")
plt.grid()
plt.show()
# +
y_test_pred = lr.predict( X_tfidf_cv)
plot_confusion_matrix(y_cv, y_test_pred)
# -
# We can see that Logistic regression with tfidf on text has worse performance than LR with bow on text.
# ## SVM
#
# ##### SVM with BOW on text
#
# +
alpha = [10 ** x for x in range(-5, 3)]
cv_log_error_array = []
for i in alpha:
print("\nfor alpha =", i)
clf = SGDClassifier(class_weight='balanced', alpha=i, penalty='l2', loss='hinge', random_state=42, n_jobs=-1)
clf.fit(X_bow_train, y_train)
sig_clf = CalibratedClassifierCV(clf, method="sigmoid")
sig_clf.fit(X_bow_train, y_train)
sig_clf_probs = sig_clf.predict_proba(X_bow_cv)
cv_log_error_array.append(log_loss(y_cv, sig_clf_probs, labels=clf.classes_, eps=1e-15))
# to avoid rounding error while multiplying probabilites we use log-probability estimates
print("Log Loss of CV :",log_loss(y_cv, sig_clf_probs))
fig, ax = plt.subplots()
ax.plot(alpha, cv_log_error_array,c='b')
for i, txt in enumerate(np.round(cv_log_error_array,3)):
ax.annotate((alpha[i],str(txt)), (alpha[i],cv_log_error_array[i]))
plt.grid()
plt.title("Cross Validation Error for each alpha")
plt.xlabel("Alpha i's")
plt.ylabel("Error measure")
plt.show()
best_alpha = np.argmin(cv_log_error_array)
print("\nThe best alpha is : ",alpha[best_alpha])
# +
svm1=SGDClassifier(alpha=0.00001,class_weight='balanced',loss='hinge')
svm1.fit(X_bow_train, y_train)
y_train_pred = svm1.decision_function(X_bow_train)
y_test_pred = svm1.decision_function( X_bow_cv)
train_fpr, train_tpr, tr_thresholds = roc_curve(y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(y_cv, y_test_pred)
plt.plot(train_fpr, train_tpr, label="train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="cv AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("fpr")
plt.ylabel("tpr")
plt.title("ERROR PLOTS ")
plt.grid()
plt.show()
# +
y_test_pred = svm1.predict( X_bow_cv)
plot_confusion_matrix(y_cv, y_test_pred)
# -
# Both logistic regression and SVM with BOW encoding performed significantly well .
# #### SVM with TFIDF on text
# +
alpha = [10 ** x for x in range(-5, 3)]
cv_log_error_array = []
for i in alpha:
print("\nfor alpha =", i)
clf = SGDClassifier(class_weight='balanced', alpha=i, penalty='l2', loss='hinge', random_state=42, n_jobs=-1)
clf.fit(X_tfidf_train, y_train)
sig_clf = CalibratedClassifierCV(clf, method="sigmoid")
sig_clf.fit(X_tfidf_train, y_train)
sig_clf_probs = sig_clf.predict_proba(X_tfidf_cv)
cv_log_error_array.append(log_loss(y_cv, sig_clf_probs, labels=clf.classes_, eps=1e-15))
# to avoid rounding error while multiplying probabilites we use log-probability estimates
print("Log Loss of CV :",log_loss(y_cv, sig_clf_probs))
fig, ax = plt.subplots()
ax.plot(alpha, cv_log_error_array,c='b')
for i, txt in enumerate(np.round(cv_log_error_array,3)):
ax.annotate((alpha[i],str(txt)), (alpha[i],cv_log_error_array[i]))
plt.grid()
plt.title("Cross Validation Error for each alpha")
plt.xlabel("Alpha i's")
plt.ylabel("Error measure")
plt.show()
best_alpha = np.argmin(cv_log_error_array)
print("\nThe best alpha is : ",alpha[best_alpha])
# +
svm2=SGDClassifier(alpha=0.00001,class_weight='balanced',loss='hinge')
svm2.fit(X_tfidf_train, y_train)
# roc_auc_score(y_true, y_score) the 2nd parameter should be probability estimates of the positive class
# not the predicted outputs
y_train_pred = svm2.decision_function(X_tfidf_train)
y_test_pred = svm2.decision_function( X_tfidf_cv)
train_fpr, train_tpr, tr_thresholds = roc_curve(y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(y_cv, y_test_pred)
plt.plot(train_fpr, train_tpr, label="train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="cv AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("fpr")
plt.ylabel("tpr")
plt.title("ERROR PLOTS ")
plt.grid()
# +
y_test_pred = svm2.predict( X_tfidf_cv)
plot_confusion_matrix(y_cv, y_test_pred)
# -
# ## Stacking above all generated models
# Just simply tried to stack each model created above
# +
from mlxtend.classifier import StackingClassifier
sclf = StackingClassifier(classifiers=[lr, svm1, svm2],
meta_classifier=lr1)
sclf.fit(X_bow_train, y_train)
y_train_pred = sclf.predict_proba(X_bow_train) [:,1]
y_test_pred = sclf.predict_proba( X_bow_cv)[:,1]
train_fpr, train_tpr, tr_thresholds = roc_curve(y_train, y_train_pred)
test_fpr, test_tpr, te_thresholds = roc_curve(y_cv, y_test_pred)
plt.plot(train_fpr, train_tpr, label="train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="cv AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("fpr")
plt.ylabel("tpr")
plt.title("ERROR PLOTS ")
plt.grid()
plt.show()
# +
y_test_pred = sclf.predict( X_bow_cv)
plot_confusion_matrix(y_cv, y_test_pred)
# -
# # Conclusion
# +
from prettytable import PrettyTable
conclusion= PrettyTable()
conclusion.field_names = ["Vectorizer", "Model", "standard cv AUC"]
conclusion.add_row(["BOW", "Logistic regression",0.89])
conclusion.add_row(["BOW", "SVM", 0.90])
conclusion.add_row(["TFIDF", "Logistic regression", 0.73])
conclusion.add_row(["TFIDF", "SVM", 0.79])
conclusion.add_row(["bow,tfidf", "Stacking models", 0.85])
print(conclusion)
|
part1.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Seminar 02: Naive Bayes from scratch
# Today we will write Naive Bayes classifier supporting different feature probabilities.
#
# _Authors: [<NAME>](https://github.com/neychev), [<NAME>](https://github.com/v-goncharenko)_
# ## Loading data
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn import datasets
matplotlib.rcParams["font.size"] = 11
# First to load dataset we're going to use [`sklearn`](https://scikit-learn.org/stable/) package which we will extensively use during the whole course.
#
# `sklearn` implement most of classical and frequently used algorithms in Machine Learning. Also it provides [User Guide](https://scikit-learn.org/stable/user_guide.html) describing principles of every bunch of algorithms implemented.
#
# As an entry point to main `sklearn`'s concepts we recommend [getting started tutorial](https://scikit-learn.org/stable/getting_started.html) (check it out yourself). [Further tutorials](https://scikit-learn.org/stable/tutorial/index.html) can also be handy to develop your skills.
# First functionality we use is cosy loading of [common datasets](https://scikit-learn.org/stable/modules/classes.html#module-sklearn.datasets). All we need to do is just one function call.
#
# Object generated by [`load_iris`](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) is described as:
#
# > Dictionary-like object, the interesting attributes are:
# >
# > ‘data’, the data to learn,
# >
# >‘target’, the classification labels,
# >
# >‘target_names’, the meaning of the labels,
# >
# >‘feature_names’, the meaning of the features,
# >
# >‘DESCR’, the full description of the dataset,
# >
# >‘filename’, the physical location of iris csv dataset (added in version 0.20)
#
# Let's see what we have
# +
dataset = datasets.load_iris()
print(dataset.DESCR)
# -
# If you aren't familiar with Iris dataset - take a minute to read description above =) (as always [more info about it in Wikipedia](https://en.wikipedia.org/wiki/Iris_flower_data_set))
#
# __TL;DR__ 150 objects equally distributed over 3 classes each described with 4 continuous features
#
# Just pretty table to look at:
# for now you don't need to understand what happens in this code - just look at the table
ext_target = dataset.target[:, None]
pd.DataFrame(
np.concatenate((dataset.data, ext_target, dataset.target_names[ext_target]), axis=1),
columns=dataset.feature_names + ["target label", "target name"],
)
# Now give distinct names to the data we will use
# +
features = dataset.data
target = dataset.target
features.shape, target.shape
# -
# __Please, remember!!!__
#
# Anywhere in our course we have an agreement to shape design matrix (named `features` in code above) as
#
# `(#number_of_items, #number_of_features)`
# ## Visualize dataset
# Our dataset has 4 dimensions however humans are more common to 3 or even 2 dimensional data, so let's plot first 3 features colored with labels values
from mpl_toolkits.mplot3d import Axes3D
# +
fig = plt.figure(figsize=(8, 8))
ax = Axes3D(fig)
ax.scatter(features[:, 0], features[:, 1], features[:, 3], c=target, marker="o")
ax.set_xlabel(dataset.feature_names[0])
ax.set_ylabel(dataset.feature_names[1])
ax.set_zlabel(dataset.feature_names[2])
plt.show()
# -
# Then have a look on feature distributions
# +
# remember this way to make subplots! It could be useful for you later in your work
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
for i, axis in enumerate(axes.flat):
axis.hist(features[:, i])
axis.set_xlabel(dataset.feature_names[i])
axis.set_ylabel("number of objects")
# -
# Note that every plot above have own scale
# ## Classifier implementation
# Since we aiming to implement Naive Bayes algorithm first we need some prior distribution defined.
#
# The most common distribution is (of course) Gaussian and it's params are mean and standard deviation. Let's implement class taking list of feature values, estimating distribution params and able to give probability density of any given feature value.
# Denote the normal distribution $\mathcal{N}(\mu, \sigma^2)$ PDF:
# $$
# f(x|\mu, \sigma^2) = \frac{1}{\sigma\sqrt{2\pi}}\exp(-\frac{(x - \mu)^2}{2\sigma^2})
# $$
# Let's implement the `GaussianDistribution` class. (Of course in practice one could always use something like `scipy.stats.norm`).
#
# Please note, that making computations with log probabilities is more stable.
class GaussianDistribution:
def __init__(self, feature):
"""
Args:
feature: column of design matrix, represents all available values
of feature to model.
axis=0 stays for samples.
"""
self.mean = feature.mean(axis=0)
self.std = feature.std(axis=0)
def logpdf(self, value):
"""Logarithm of probability density at value"""
return # <YOUR CODE HERE>
def pdf(self, value):
return (
1
/ (np.sqrt(2 * np.pi) * self.std)
* np.exp(-((x - self.mean) ** 2 / (2 * self.std ** 2)))
)
# Let's check the result:
# +
import scipy
_test = scipy.stats.norm(loc=features[:, :2].mean(axis=0), scale=features[:, :2].std(axis=0))
assert np.allclose(
GaussianDistribution(features[:, :2]).logpdf(features[:5, :2]), _test.logpdf(features[:5, :2])
)
print("Seems fine!")
# -
# Let's focus on the classification problem now. For the case of $K$ classes label $y_i \in \{C_1, \ldots, C_k\}$. Iris classification problem has 3 classes, so $K=3$. Bayes' Theorem takes the following form:
#
# $$
# P(y_i = C_k|\mathbf{x}_i) = \frac{P(\mathbf{x}_i|y_i = C_k) P(y_i = C_k)}{P(\mathbf{x}_i)}
# $$
# Please note, we prefer working with log probabilities here as well. So the equation above will take the following form:
# $$
# \log P(y_i = C_k|\mathbf{x}_i) = \log P(\mathbf{x}_i|y_i = C_k) + \log P(y_i = C_k) - \log P(\mathbf{x}_i)
# $$
#
# As one could mention, to find the class label with the highest probability we even do not need the last term $P(\mathbf{x}_i)$. However, we need it to get the correct estimation of the probability $P(y_i = C_k|\mathbf{x}_i)$. The $P(\mathbf{x}_i)$ term can be computed using the following property:
# $$
# P(\mathbf{x}_i) = \sum_{k=1}^K P(\mathbf{x}_i|y_i=C_k) P(y_i = C_k).
# $$
# It can be computed from $\log P(\mathbf{x}_i|y_i=C_k)$ values using `logsumexp` function located in `scipy.special`.
#
# Now let's implement the Naive Bayes classifier itself. The class below is inherited from `sklearn` base classes and provides all the main methods.
# +
from sklearn.base import BaseEstimator, ClassifierMixin
from scipy.special import logsumexp
class NaiveBayes(BaseEstimator, ClassifierMixin):
'''
Please note, using `X` and `y` for design matrix and labels in general is not a good choice,
better stick to more informative naming conventions.
However, to make the code consistent with sklearn implementation, we use `X` and `y` variables here.
'''
def fit(self, X, y, sample_weight=None, distributions=None):
'''
sample_weight
The argument is ignored. For comatibility only.
'''
self.unique_labels = np.unique(y)
# If distributions of features are not specified, they a treated Gaussian
if distributions is None:
distributions = [GaussianDistribution] * X.shape[1]
else:
# Check whether distributions are passed for all features
assert len(distributions) == X.shape[1]
# Here we find distribution parameters for every feature in every class subset
# so P(x^i|y=C_k) will be estimated only using information from i-th feature of C_k class values
self.conditional_feature_distributions = {} # label: [distibution for feature 1, ...]
for label in self.unique_labels:
feature_distribution = []
for column_index in range(X.shape[1]):
# `column_index` feature values for objects from `label` class
feature_column = X[y == label, column_index]
fitted_distr = distributions[column_index](feature_column)
feature_distribution.append(fitted_distr)
self.conditional_feature_distributions[label] = feature_distribution
# Prior label distributions (unconditional probability of each class)
self.prior_label_distibution = {
# <YOUR CODE HERE>
}
def predict_log_proba(self, X):
# Matrix of shape (n_objects : n_classes)
class_log_probas = np.zeros((X.shape[0], len(self.unique_labels)), dtype=float)
# Here we compute the class log probabilities for each class sequentially b
for label_idx, label in enumerate(self.unique_labels):
for idx in range(X.shape[1]):
# All loglikelihood for every feature w.r.t. fixed label
class_log_probas[:, label_idx] += # <YOUR CODE HERE>
# Add log proba of label prior
class_log_probas[:, label_idx] += # <YOUR CODE HERE>
for idx in range(X.shape[1]):
# If you want to get probabilities, you need to substract the log proba for every feature
class_log_probas -= # <YOUR CODE HERE>
return class_log_probas
def predict_proba(self, X):
return np.exp(self.predict_log_proba(X))
def predict(self, X):
log_probas = self.predict_log_proba(X)
# we need to cast labels to their original form (they may start from number other than 0)
return np.array([self.unique_labels[idx] for idx in log_probas.argmax(axis=1)])
# -
nb = NaiveBayes()
nb.fit(features, target)
print("log probas:\n{}".format(nb.predict_log_proba(features[:2])))
print("predicted labels:\n{}".format(nb.predict(features[:2])))
print("\nIt`s alive! More tests coming.")
# Now let's check our Naive Bayes classifier on the unseed data. To do so we will use `train_test_split` from `sklearn`.
# +
from sklearn.model_selection import train_test_split
features_train, features_test, target_train, target_test = train_test_split(
features, target, test_size=0.25
)
print(features_train.shape, features_test.shape)
# -
nb = NaiveBayes()
nb.fit(features_train, target_train, distributions=[GaussianDistribution] * 4)
nb_test_log_proba = nb.predict_log_proba(features_test)
print(
"Naive Bayes classifier accuracy on the train set: {}".format(
nb.score(features_train, target_train)
)
)
print(
"Naive Bayes classifier accuracy on the test set: {}".format(
nb.score(features_test, target_test)
)
)
# Finally, let's comapre the Naive Bayes classifier with the `sklearn` implementations.
# +
from sklearn import naive_bayes
sklearn_nb = naive_bayes.GaussianNB()
sklearn_nb.fit(features_train, target_train)
sklearn_nb_test_log_proba = sklearn_nb.predict_log_proba(features_test)
# -
print(
"sklearn implementation accuracy on the train set: {}".format(
sklearn_nb.score(features_train, target_train)
)
)
print(
"sklearn implementation accuracy on the test set: {}".format(
sklearn_nb.score(features_test, target_test)
)
)
# And let's even check the predictions. If you used Gaussian distribution and done everything correctly, the log probabilities should be the same.
assert np.allclose(nb_test_log_proba, sklearn_nb_test_log_proba), "log probabilities do not match"
print("Seems alright!")
# ## Advanced distribution for NaiveBayes
#
# Let's take a look at violin plots for every feature in our dataset:
plt.figure(figsize=(15, 15))
plt.violinplot(features, showmedians=True)
# Although we do love Gaussian distribution it is still unimodal while our features are substantially multimodal (see histograms above). So we have to implement more robust distribution estimator - Kernel Density Estimator (KDE).
#
# Idea for this method is simple: we assign some probability density to a region around actual observation. (We will return to density estimation methods to describe them carefully later in this course).
#
# Fortunately `sklearn` have KDE implemented for us already. All it needs is vector of feature values.
# To get probability estimations using KDE one can easily access the `sklearn.neighbors` module.
# +
from sklearn.neighbors import KernelDensity
kde = KernelDensity(bandwidth=0.28, kernel="gaussian")
feature_col = features[target == 2, 2]
kde.fit(feature_col.reshape((-1, 1)))
linspace = np.linspace(feature_col.min(), feature_col.max(), 1000)
plt.plot(linspace, np.exp(kde.score_samples(linspace.reshape((-1, 1)))))
plt.grid()
plt.xlabel("feature value")
plt.ylabel("probability")
# -
# To make it compatible with the Naive Bayes classifier we have implemented above, we need to create class with the same methods:
class GaussianKDE:
def __init__(self, feature):
self.kde = KernelDensity(bandwidth=1.0)
self.kde.fit(feature.reshape((-1, 1)))
def logpdf(self, value):
return self.kde.score_samples(value.reshape((-1, 1)))
def pdf(self, value):
return np.exp(self.log_proba(value))
nb_kde = NaiveBayes()
nb_kde.fit(features, target, distributions=[GaussianKDE] * 4)
print("log probas:\n{}".format(nb_kde.predict_log_proba(features[:2])))
print("predicted labels:\n{}".format(nb_kde.predict(features[:2])))
print("\nIt`s alive!")
print(
"KDE Naive Bayes classifier accuracy on the train set: {}".format(
nb_kde.score(features_train, target_train)
)
)
print(
"KDE Naive Bayes classifier accuracy on the test set: {}".format(
nb_kde.score(features_test, target_test)
)
)
# Seems like the accuracy of the classifier has decreased. What is going on?
#
# _Hint: try varying the `bandwidth` parameter of the `KernelDensity` constructor in `GaussianKDE` class (around 0.3)._
#
# Let's take a closer look on the features distributions. Here comes the histogram:
# +
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
for ax_idx, feature_idx in enumerate([2, 3]):
for label in range(3):
ax = axes[ax_idx, label]
feature_col = features[target == label, feature_idx]
ax.hist(feature_col, bins=7)
ax.grid()
ax.set_title(
"class: {}, feature: {}".format(
dataset.target_names[label], dataset.feature_names[feature_idx]
)
)
# -
# We see, than the distributions within every class are unimodal. That's how KDE is approximating the PDF:
# +
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
kde = KernelDensity(bandwidth=1.0, kernel="gaussian")
for ax_idx, feature_idx in enumerate([2, 3]):
for label in range(3):
ax = axes[ax_idx, label]
feature_col = features[target == label, feature_idx]
kde.fit(feature_col.reshape((-1, 1)))
linspace = np.linspace(0.8 * feature_col.min(), 1.2 * feature_col.max(), 1000)
ax.plot(linspace, np.exp(kde.score_samples(linspace.reshape((-1, 1)))))
ax.grid()
ax.set_title(
"class: {}, feature: {}".format(
dataset.target_names[label], dataset.feature_names[feature_idx]
)
)
# -
# One could mention, that every feature need different `bandwidth` parameter.
#
# And that's how Gaussian distribution fits to the data:
# +
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
for ax_idx, feature_idx in enumerate([2, 3]):
for label in range(3):
ax = axes[ax_idx, label]
feature_col = features[target == label, feature_idx]
gaussian_distr = GaussianDistribution(feature_col)
linspace = np.linspace(feature_col.min(), feature_col.max(), 1000)
ax.plot(linspace, gaussian_distr.pdf(linspace.reshape((-1, 1))))
ax.grid()
ax.set_title(
"class: {}, feature: {}".format(
dataset.target_names[label], dataset.feature_names[feature_idx]
)
)
# -
# Looks a bit better. Moreover, hypothesis of the normal distribution over the features seems more promising (the features are petal length and width).
# So, the __conclusion__: always check the distribution and the assumptions you make. They should be appropriate for the data you work with.
|
02_math_recap/day02_naive_bayes.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/NetzaiHernandez/daa_2021_1/blob/master/O2ctubre.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="JK9MSAtkh7oV"
# # Meteorología en México
# En Sistema meteorológico nacional lleva el registro de la lluvias desde el año 1985 y lo pone a disposición de la población por medio de la pagina datos.gob.mx.
#
# En la siguiente liga se encuentran 2 archivos separados por comas CSV correspondientes a los registros de lluvias
# En los renglones se encuentran 33, correspondientes a cada cada uno de los 32 estados y a nivel nacional.
#
# https://drive.google.com/file/d/1lamkxgq2AsXRu81Y4JTNXLVld4og7nxt/view?usp=sharing
#
# ## Planteamiento del problema
# Diseñar un algoritmo y programarlo para que:
# 1. Solicite por teclado el año, el estado y el mes, en base a esa información:
# - muestre en pantalla el promedio de ese mes en ese estado en el año seleccionado.
# - muestre en pantalla el promedio anual del estado seleccionado.
# - muestre la suma de los 12 meses de ese estado en el año selecc
# ionado.
#
# 2. Busque el mes que mas llovió en todos los estados durante esos dos años. Imprimir año, estado y mes.
# 3. Busque el mes que menos llovió en los dos. Imprimir año, estado y mes.
#
# + id="L-lS6wYy2OMg"
import xlrd
class Array3D:
def _init_(self,row,col,deep):
self.__x=row #Fila
self.__y=col #Columna
self.__z=deep #Profundidad
self._cubo=[[[None for x in range(self.x)] for y in range(self.y)] for z in range(self._z)]
def to_string(self):
print(self.__cubo)
def get_num_x(self):
return self.__x
def get_num_y(self):
return self.__y
def get_num_z(self):
return self.__z
def set_item(self,x,y,z,value):
self.__cubo[z][y][x]=value
def get_item(self,x,y,z):
return self.__cubo[z][y][x]
def clearing(self,value):
for i in range(self.__z):
for j in range(self.__y):
for k in range(self.__x):
self.__cubo[i][j][k]=value
def main():
data=Array3D(35,14,34)
print("espere un momento, se estan cargando los datos...")
for anio in range(2017,2018):
for x in range(35):
for y in range(14):
if anio ==2017:
Archivo = xlrd.open_workbook("/content/2017Precip.xls")
hoja=Archivo.sheet_by_index(0)
data.set_item(x,y,anio-2016,hoja.cell_value(x,y))
elif anio == 2018:
Archivo = xlrd.open_workbook("/content/2018Precip.xls")
hoja = Archivo.sheet_by_index(1)
data.set_item(x,y,anio-2016,hoja.cell_value(x,y))
pass
Salida=False
regreso_al_menu_principal=False
regreso_al_menu=False
Anio=None
mes=None
estado=None
while Salida !=True:
anio=None
anio=int(input("Dijite el año del que quieres buscar la precipitacion:"))
if anio > 2016 and anio <= 2018:
while regreso_al_menu_principal!=True:
estado=None
print("Dijite el estado o el nacional del que quiere informacion ")
for i in range(data.get_num_x()-2):
print(f"{i+1}) {data.get_item(i+2,0,anio-2016)}")
pass
estado=int(input("Opcion: "))
if estado>=1 and estado<=33:
while regreso_al_menu!=True:
print("digite el mes o el total del que quiere saber la informacion")
for i in range(data.get_num_y()-1):
print(f"{i+1} {data.get_item(1,i+1,anio-2016)}")
pass
mes=int(input("Opcion: "))
if mes>=1 and mes<=13:
print(f"La pricipitacion en el año {anio} del estado {data.get_item(estado+1,0,0)} del mes de {data.get_item(1,mes,0)} fue: {data.get_item(estado+1,mes,anio-1985)}")
pass
elif mes==0:
regreso_al_menu=True
pass
else:
print("opcion equivocada")
pass
pass
regreso_al_menu=False
pass
elif estado==0:
regreso_al_menu_principal=True
pass
else:
print("Estado incorrecto")
pass
pass
regreso_al_menu_principal=False
pass#fin primer if
elif anio==0:
print("fin del Programa")
Salida=True
pass
else:
print("Año incorrecto")
pass
pass#fin while
main()
|
O2ctubre.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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
% matplotlib inline
plt.rcParams["savefig.dpi"] = 300
plt.rcParams['savefig.bbox'] = 'tight'
# +
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import scale
cancer = load_breast_cancer()
X, y = scale(cancer.data), cancer.target
X.shape
# +
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y)
logreg = LogisticRegression()
logreg.fit(X_train[:, :2], y_train)
# -
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap="bwr")
coef = logreg.coef_.ravel()
line = np.linspace(X_train[:, 1].min(), X_train[:, 1].max())
line2 = - (line * coef[1] + logreg.intercept_) / coef[0]
plt.plot(line2, line, c='k', linewidth=2)
plt.arrow(line2[20], line[20], .4 * coef[0], .4 * coef[1], color='#00dd00', linewidth=2, head_width=.1)
plt.text(-1, .6, "w", color='#00dd00', fontsize=20)
plt.ylim(-2, 3)
plt.gca().set_aspect("equal")
plt.savefig("images/linear_boundary_vector.png")
# +
xmin, xmax = -4, 4
xx = np.linspace(xmin, xmax, 100)
lw = 2
plt.plot([xmin, 0, 0, xmax], [1, 1, 0, 0], color='gold', lw=lw,
label="Zero-one loss")
plt.plot(xx, np.where(xx < 1, 1 - xx, 0), color='teal', lw=lw,
label="Hinge loss")
plt.plot(xx, np.log2(1 + np.exp(-xx)), color='cornflowerblue', lw=lw,
label="Log loss")
#plt.plot(xx, np.where(xx < 1, 1 - xx, 0) ** 2, color='orange', lw=lw,
# label="Squared hinge loss")
#plt.ylim((0, 8))
plt.legend(loc="upper right")
plt.xlabel(r"Decision function $w^Tx + b$")
plt.ylabel("$L(y=1, w^Tx + b) $")
plt.savefig("images/binary_loss.png")
# +
from mpl_toolkits.axes_grid.axislines import SubplotZero
fig = plt.figure()
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
for direction in ["xzero", "yzero"]:
ax.axis[direction].set_axisline_style("-|>")
ax.axis[direction].set_visible(True)
for direction in ["left", "right", "bottom", "top"]:
ax.axis[direction].set_visible(False)
line = np.linspace(-5, 5, 100)
ax.plot(line, 1. / (1 + np.exp(-line)))
# +
from sklearn.datasets import make_blobs
from sklearn.svm import SVC
X, y = make_blobs(centers=2, random_state=4, n_samples=30)
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
# a carefully hand-designed dataset lol
y[7] = 0
y[27] = 0
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
for ax, C in zip(axes, [1e-1, 1, 1e2]):
ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bwr, s=30)
svm = LogisticRegression(solver='lbfgs', C=C, tol=0.00001).fit(X, y)
# using SVC instead of LinearSVC so we can get support vectors more easily
w = svm.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(6, 13)
yy = a * xx - (svm.intercept_[0]) / w[1]
ax.plot(xx, yy, c='k')
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xticks(())
ax.set_yticks(())
ax.set_title("C = %.2f" % C)
plt.savefig("images/logreg_regularization.png")
# -
# # Multiclass
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
print(X.shape)
print(np.bincount(y))
# +
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
logreg = LogisticRegression(multi_class="multinomial", solver="lbfgs").fit(X, y)
linearsvm = LinearSVC().fit(X, y)
print(logreg.coef_.shape)
print(linearsvm.coef_.shape)
# -
logreg.coef_
logreg.intercept_
from sklearn.preprocessing import scale
logreg = LogisticRegression(fit_intercept=False, multi_class="multinomial", solver="lbfgs").fit(scale(X), y)
# +
fig, axes = plt.subplots(1, 3, figsize=(6, 1.5))
for ax, coef, classname in zip(axes, logreg.coef_, iris.target_names):
ax.barh(range(4), coef, height=.5, color=plt.cm.bwr_r(np.sign(coef)))
ax.set_xlim(logreg.coef_.min() - .1, logreg.coef_.max() + .1)
ax.set_title(classname)
ax.set_frame_on(False)
ax.set_yticks(())
axes[0].set_yticks(range(4))
axes[0].set_yticklabels(iris.feature_names)
plt.tight_layout()
# -
from sklearn.datasets import make_blobs
X, y = make_blobs(random_state=27)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap="Accent")
ax = plt.gca()
ax.set_aspect("equal")
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# # OVR
from sklearn.svm import LinearSVC
linear_svm = LinearSVC(C=100).fit(X, y)
points = plt.scatter(X[:, 0], X[:, 1], c=y, cmap="Accent")
colors = [plt.cm.Accent(i) for i in [0, 4, 7]]
line = np.linspace(X[:, 1].min() - 5, X[:, 1].max() + 5)
for coef, intercept, color in zip(linear_svm.coef_, linear_svm.intercept_, colors):
plt.plot(-(line * coef[1] + intercept) / coef[0], line, c=color)
plt.gca().set_aspect("equal")
plt.xlim(xlim)
plt.ylim(ylim)
plt.savefig("images/ovr_lines.png")
# +
import matplotlib as mpl
xs = np.linspace(xlim[0], xlim[1], 1000)
ys = np.linspace(ylim[0], ylim[1], 1000)
xx, yy = np.meshgrid(xs, ys)
pred = linear_svm.predict(np.c_[xx.ravel(), yy.ravel()])
plt.imshow(pred.reshape(xx.shape), cmap="Accent", alpha=.2, extent=(xlim[0], xlim[1], ylim[1], ylim[0]))
points = plt.scatter(X[:, 0], X[:, 1], c=y, cmap="Accent")
for coef, intercept, color in zip(linear_svm.coef_, linear_svm.intercept_, colors):
plt.plot(-(line * coef[1] + intercept) / coef[0], line, c=color)
plt.xlim(xlim)
plt.ylim(ylim)
plt.gca().set_aspect("equal")
plt.savefig("images/ovr_boundaries.png")
# -
# # OVO
# +
from sklearn.svm import SVC
svm = SVC(kernel="linear", C=100).fit(X, y)
points = plt.scatter(X[:, 0], X[:, 1], c=y, cmap="Accent")
line = np.linspace(X[:, 1].min() - 5, X[:, 1].max() + 5)
classes = [(0, 1), (0, 2), (1, 2)]
for coef, intercept, col in zip(svm.coef_, svm.intercept_, classes):
line2 = -(line * coef[1] + intercept) / coef[0]
plt.plot(line2, line, "-", c=colors[col[0]])
plt.plot(line2, line, "--", c=colors[col[1]])
plt.xlim(xlim)
plt.ylim(ylim)
plt.gca().set_aspect("equal")
plt.savefig("images/ovo_lines.png")
# +
from sklearn.svm import SVC
from sklearn.datasets import make_blobs
X, y = make_blobs(random_state=27)
svm = SVC(kernel="linear", C=100).fit(X, y)
points = plt.scatter(X[:, 0], X[:, 1], c=y, cmap="Accent")
pred = svm.predict(np.c_[xx.ravel(), yy.ravel()])
plt.imshow(pred.reshape(xx.shape), cmap="Accent", alpha=.2, extent=(xlim[0], xlim[1], ylim[1], ylim[0]))
for coef, intercept, col in zip(svm.coef_, svm.intercept_, classes):
line2 = -(line * coef[1] + intercept) / coef[0]
plt.plot(line2, line, "-", c=colors[col[0]])
plt.plot(line2, line, "--", c=colors[col[1]])
plt.xlim(xlim)
plt.ylim(ylim)
plt.gca().set_aspect("equal")
plt.savefig("images/ovo_boundaries.png")
# -
# # kernel SVMS
# +
from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples=50, centers=2,
random_state=0, cluster_std=0.60)
plt.scatter(X[:, 0], X[:, 1], c=plt.cm.Dark2(y), s=50);
plt.xlim(-.6, 3.5)
xfit = np.linspace(-1, 3.5)
for m, b, d in [(1, 0.65, 0.3), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.14)]:
yfit = m * xfit + b
line, = plt.plot(xfit, yfit)
plt.fill_between(xfit, yfit - d, yfit + d, edgecolor='none',
alpha=0.4, color=line.get_color())
plt.xlim(-1, 3.5)
plt.savefig("images/max_margin.png")
# +
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
X, y = make_blobs(n_samples=50, centers=2,
random_state=0, cluster_std=0.60)
X[:, 0] *= 1.5
# fit the model
clf = svm.SVC(kernel='linear')
clf.fit(X, y)
# get the separating hyperplane
w = clf.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(X[:, 0].min() - .2, X[:, 0].max() + .2)
yy = a * xx - (clf.intercept_[0]) / w[1]
# plot the parallels to the separating hyperplane that pass through the
# support vectors
margin = 1 / np.sqrt(np.sum(clf.coef_ ** 2))
yy_down = yy - np.sqrt(1 + a ** 2) * margin
yy_up = yy + np.sqrt(1 + a ** 2) * margin
# plot the line, the points, and the nearest vectors to the plane
plt.plot(xx, yy, 'k-')
plt.plot(xx, yy_down, 'k--')
plt.plot(xx, yy_up, 'k--')
plt.fill_between(xx, yy_down, yy_up, alpha=.3)
plt.scatter(X[:, 0], X[:, 1], c=plt.cm.Dark2(y))
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
s=80, facecolors='none', edgecolor='k')
plt.arrow(xx[25], yy[25], w[0], w[1])
plt.gca().set_aspect("equal")
plt.xlim(xx[0], xx[-1])
plt.title("C=1")
plt.savefig("images/max_margin_C_1.png")
# +
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
# fit the model
clf = svm.SVC(kernel='linear', C=.1)
clf.fit(X, y)
# get the separating hyperplane
w = clf.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(X[:, 0].min() - .2, X[:, 0].max() + .2)
yy = a * xx - (clf.intercept_[0]) / w[1]
# plot the parallels to the separating hyperplane that pass through the
# support vectors
margin = 1 / np.sqrt(np.sum(clf.coef_ ** 2))
yy_down = yy - np.sqrt(1 + a ** 2) * margin
yy_up = yy + np.sqrt(1 + a ** 2) * margin
# plot the line, the points, and the nearest vectors to the plane
plt.plot(xx, yy, 'k-')
plt.plot(xx, yy_down, 'k--')
plt.plot(xx, yy_up, 'k--')
plt.fill_between(xx, yy_down, yy_up, alpha=.3)
plt.scatter(X[:, 0], X[:, 1], c=plt.cm.Dark2(y))
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
s=80, facecolors='none', edgecolor='k')
plt.gca().set_aspect("equal")
plt.arrow(xx[25], yy[25], w[0], w[1])
plt.gca().set_aspect("equal")
plt.xlim(xx[0], xx[-1])
plt.title("C=0.1")
plt.savefig("images/max_margin_C_0.1.png")
# -
from sklearn.svm import SVC
from sklearn.preprocessing import PolynomialFeatures
from sklearn.datasets import make_blobs
X, y = make_blobs(random_state=3)
y = (y == 0).astype(np.int)
plt.scatter(X[:, 0], X[:, 1], c=plt.cm.tab10(y))
poly = PolynomialFeatures(include_bias=False)
X_poly = poly.fit_transform(X)
X.shape, X_poly.shape
poly.get_feature_names()
linear_svm = SVC(kernel="linear").fit(X_poly, y)
poly_svm = SVC(kernel="poly", degree=2, coef0=1).fit(X, y)
linear_svm.coef_
linear_svm.dual_coef_
linear_svm.support_
poly_svm.dual_coef_
poly_svm.support_
# create a grid for plotting decision functions...
x_lin = np.linspace(X[:, 0].min() - .5, X[:, 0].max() + .5, 1000)
y_lin = np.linspace(X[:, 1].min() - .5, X[:, 1].max() + .5, 1000)
x_grid, y_grid = np.meshgrid(x_lin, y_lin)
X_grid = np.c_[x_grid.ravel(), y_grid.ravel()]
from sklearn.pipeline import make_pipeline
colors = [plt.cm.tab10(0), plt.cm.tab10(0), plt.cm.tab10(1), plt.cm.tab10(1)]
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
for ax, model, name in zip(axes, [poly_svm, make_pipeline(poly, linear_svm)], ["kernel", "features"]):
ax.set_title(name)
support_vectors = getattr(model, "support_", None)
if support_vectors is None:
support_vectors = model.steps[1][1].support_
predictions = model.predict(X_grid)
ax.contourf(x_grid, y_grid, predictions.reshape(x_grid.shape), alpha=.1, colors=colors)
ax.scatter(X[:, 0], X[:, 1], c=plt.cm.tab10(y))
ax.scatter(X[support_vectors, 0], X[support_vectors, 1], facecolor='none', edgecolor='k', linewidths=1)
ax.set_xlim(x_lin[0], x_lin[-1])
ax.set_ylim(y_lin[0], y_lin[-1])
plt.savefig("images/poly_kernel_features.png")
# # Scaling with number of samples
# +
from time import time
from sklearn.svm import LinearSVC
linear, kernel = [], []
samples = [100, 1000, 10000, 100000] #, 1e6, 1e7]
for n_samples in samples:
X, y = make_blobs(n_samples=int(n_samples), random_state=0)
y = (y == 0).astype(np.int)
X_poly = PolynomialFeatures(include_bias=False).fit_transform(X)
tick = time()
LinearSVC(dual=False).fit(X_poly, y)
linear.append(time() - tick)
tick = time()
SVC(kernel="poly", degree=2, coef0=1).fit(X, y)
kernel.append(time() - tick)
# -
kernel
fig, axes = plt.subplots(2, 1)
for ax in axes:
ax.plot(samples, linear, label="linear + features")
ax.plot(samples, kernel, label="kernel")
ax.set_ylabel("runtime (s)")
ax.set_xlabel("n_samples")
ax.legend()
axes[1].set_xscale("log")
axes[1].set_yscale("log")
# # Scaling with n_features # FIXME NOT VERY GOOD
from sklearn.datasets import make_classification
linear, kernel = [], []
features = []
for n_features in features:
X, y = make_classification(n_samples=10000, random_state=0, n_features=int(n_features))
y = (y == 0).astype(np.int)
X_poly = PolynomialFeatures(degree=2, include_bias=False).fit_transform(X)
tick = time()
LinearSVC(loss="hinge").fit(X_poly, y)
linear.append(time() - tick)
tick = time()
SVC(kernel="poly", degree=2, coef0=1).fit(X, y)
kernel.append(time() - tick)
fig, axes = plt.subplots(2, 1)
for ax in axes:
ax.plot(features, linear, label="linear + features")
ax.plot(features, kernel, label="kernel")
ax.set_ylabel("runtime (s)")
ax.set_xlabel("degree")
ax.legend()
axes[1].set_yscale("log")
# +
line = np.linspace(-50, 50, 1000)
def rbf(gamma):
return np.exp(-gamma * line**2)
for gamma in [1e-4, 1e-3, 1e-2, 1e-1, 1, 10]:
plt.plot(line, rbf(gamma), label="gamma={}".format(gamma))
plt.legend(loc=(1, 0))
# +
colors = [plt.cm.tab10(0), plt.cm.tab10(0), plt.cm.tab10(1), plt.cm.tab10(1)]
def make_handcrafted_dataset():
# a carefully hand-designed dataset lol
X, y = make_blobs(centers=2, random_state=4, n_samples=30)
y[np.array([7, 27])] = 0
mask = np.ones(len(X), dtype=np.bool)
mask[np.array([0, 1, 5, 26])] = 0
X, y = X[mask], y[mask]
return X, y
def plot_svm(log_C, log_gamma, ax=None):
C = 10. ** log_C
gamma = 10. ** log_gamma
svm = SVC(kernel='rbf', C=C, gamma=gamma).fit(X, y)
if ax is None:
ax = plt.gca()
predictions = svm.decision_function(X_grid)
ax.contourf(x_grid, y_grid, predictions.reshape(x_grid.shape), alpha=.3, cmap='coolwarm') #, colors=colors)
ax.contour(x_grid, y_grid, predictions.reshape(x_grid.shape), levels=[0])
# plot data
ax.scatter(X[:, 0], X[:, 1], c=y, s=70, cmap='coolwarm')
# plot support vectors
support_vectors = svm.support_
ax.scatter(X[support_vectors, 0], X[support_vectors, 1], facecolor='none', edgecolor='k', linewidths=1, s=150)
ax.set_title("C = %.4f gamma = %.2f" % (C, gamma))
X, y = make_handcrafted_dataset()
# create a grid for plotting decision functions...
x_lin = np.linspace(X[:, 0].min() - .5, X[:, 0].max() + .5, 1000)
y_lin = np.linspace(X[:, 1].min() - .5, X[:, 1].max() + .5, 1000)
x_grid, y_grid = np.meshgrid(x_lin, y_lin)
X_grid = np.c_[x_grid.ravel(), y_grid.ravel()]
fig, axes = plt.subplots(3, 4, figsize=(15, 10), subplot_kw={'xticks':(), 'yticks': ()})
for ax, C in zip(axes, [-1, 0, 3]):
for a, gamma in zip(ax, [-2, -1, 0, .7]):
plot_svm(log_C=C, log_gamma=gamma, ax=a)
# +
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_digits
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(
digits.data, digits.target, stratify=digits.target, random_state=0)
fig, axes = plt.subplots(4, 4)
for x, y, ax in zip(X_train, y_train, axes.ravel()):
ax.set_title(y)
ax.imshow(x.reshape(8, 8), cmap="gray_r")
ax.set_xticks(())
ax.set_yticks(())
plt.tight_layout()
# -
scaled_svc = make_pipeline(StandardScaler(), SVC())
print(np.mean(cross_val_score(SVC(), X_train, y_train, cv=10)))
print(np.mean(cross_val_score(scaled_svc, X_train, y_train, cv=10)))
# X_train.std() is also good for global scaling - if the features were on the same scale.
# this dataset is very atypical.
print(np.mean(cross_val_score(SVC(gamma=(1. / (X_train.shape[1] * X_train.var()))), X_train, y_train, cv=10)))
np.set_printoptions(precision=6, suppress=True)
# using pipeline of scaler and SVC. Could also use SVC and rescale gamma
param_grid = {'svc__C': np.logspace(-3, 2, 6),
'svc__gamma': np.logspace(-3, 2, 6) / X_train.shape[0]}
param_grid
grid = GridSearchCV(scaled_svc, param_grid=param_grid, cv=10)
grid.fit(X_train, y_train)
results = pd.DataFrame(grid.cv_results_)
results.head()
plt.title("testing accuracy")
plt.imshow(results.mean_test_score.values.reshape(6, 6))
plt.yticks(range(len(param_grid['svc__C'])), param_grid['svc__C'])
plt.ylabel("C")
plt.xticks(range(len(param_grid['svc__gamma'])), ["{:.6f}".format(g) for g in param_grid['svc__gamma']], rotation=40, ha="right")
plt.xlabel("gamma")
plt.colorbar()
plt.title("training accuracy")
plt.imshow(results.mean_train_score.values.reshape(6, 6))
plt.yticks(range(len(param_grid['svc__C'])), param_grid['svc__C'])
plt.ylabel("C")
plt.xticks(range(len(param_grid['svc__gamma'])), ["{:.6f}".format(g) for g in param_grid['svc__gamma']], rotation=40, ha="right")
plt.xlabel("gamma")
plt.colorbar()
from sklearn.kernel_approximationmation import RBFSampler
gamma = grid.best_params_['svc__gamma']
approx_rbf = RBFSampler(gamma=gamma, n_features=100)
approx_rbf.tran
# +
"""
===================================================================
Support Vector Regression (SVR) using linear and non-linear kernels
===================================================================
Toy example of 1D regression using linear, polynomial and RBF kernels.
"""
print(__doc__)
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt
###############################################################################
# Generate sample data
X = np.sort(5 * np.random.rand(40, 1), axis=0)
y = np.sin(X).ravel()
###############################################################################
# Add noise to targets
y[::5] += 3 * (0.5 - np.random.rand(8))
###############################################################################
# Fit regression model
svr_rbf = SVR(kernel='rbf', C=100, gamma=0.1, epsilon=.1)
svr_poly = SVR(kernel='poly', C=100, degree=3, epsilon=.1, coef0=1)
y_rbf = svr_rbf.fit(X, y).predict(X)
y_poly = svr_poly.fit(X, y).predict(X)
###############################################################################
# look at the results
lw = 2
plt.scatter(X, y, color='darkorange', label='data')
plt.plot(X, y_rbf, color='navy', lw=lw, label='RBF model')
plt.plot(X, y_poly, color='cornflowerblue', lw=lw, label='Polynomial model')
plt.scatter(X[svr_rbf.support_], y[svr_rbf.support_], facecolor="none", edgecolor="k", marker='8',
label='rbf support vectors', s=100)
plt.scatter(X[svr_poly.support_], y[svr_poly.support_], facecolor="none", edgecolor="k", marker='s',
label='poly support vectors', s=100)
plt.xlabel('data')
plt.ylabel('target')
plt.title('Support Vector Regression')
plt.legend()
plt.show()
# -
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(
digits.data, digits.target, stratify=digits.target, random_state=0)
from sklearn.kernel_approximation import RBFSampler
gamma = 1. / (X_train.shape[1] * X_train.var())
approx_rbf = RBFSampler(gamma=gamma, n_components=5000)
print(X_train.shape)
X_train_rbf = approx_rbf.fit_transform(X_train)
print(X_train_rbf.shape)
np.mean(cross_val_score(LinearSVC(), X_train, y_train, cv=10))
np.mean(cross_val_score(SVC(gamma=gamma), X_train, y_train, cv=10))
np.mean(cross_val_score(LinearSVC(), X_train_rbf, y_train, cv=10))
from sklearn.kernel_approximation import Nystroem
nystroem = Nystroem(gamma=gamma, n_components=200)
X_train_ny = nystroem.fit_transform(X_train)
print(X_train_ny.shape)
from sklearn.svm import LinearSVC
np.mean(cross_val_score(LinearSVC(), X_train_ny, y_train, cv=10))
rng = np.random.RandomState(0)
w = rng.normal(size=(X_train.shape[1], 100))
X_train_wat = np.tanh(scale(np.dot(X_train, w)))
print(X_train_wat.shape)
np.mean(cross_val_score(LinearSVC(), X_train_wat, y_train, cv=10))
|
Applied_Machine_Learning_S22/aml-06-linear-models-classification/aml-06-linear-models-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
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/christianadriano/Bandits_FaultUnderstanding/blob/master/Intro_BellStatesCircuit.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="nYmwKipdE--G"
# # Hands-on Example with Bell State Circuit
# + [markdown] id="G-Zwt5DcHZR3"
# ## Environment setup
# + id="vM0Kxnx-E8oF"
try:
import cirq
except ImportError:
print("installing cirq...")
# !pip install --quiet cirq
print("installed cirq.")
# + [markdown] id="_JONuCHvVvmT"
# ## Creating and Measuring Superposition - The Hadarmard Gate
#
# The Hadamard gate corresponds to multiplying the qbit with the following matrix
# $ H = \frac{1}{\sqrt{2}} \begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix}$.
#
# This maps the basis state $|0\rangle$ to $\frac{|0\rangle + |1\rangle}{\sqrt{2}}$ and $|1\rangle$ to $\frac{|0\rangle - |1\rangle}{\sqrt{2}}$
#
# This means that the qbit will be 50% of time on 0 and 50% of on 1.
#
# So, to see this happening we need to do three steps:
# 1. Create a circuit with Hadamard gate
# 2. Simulate its execution
# 3. Measure the results
# + [markdown] id="q2eXTIjDZPsI"
# ### Create the circuit with the Hadamard gate
# + id="XBLZYckHXR0k"
# + colab={"base_uri": "https://localhost:8080/"} id="yE1f6iqBUmzo" outputId="27d7c259-0435-4b9e-ed1d-0138ef191116"
# Create a cicuit to put one qbit in superposition
hello_world_circuit = cirq.Circuit()
q = cirq.NamedQubit("qbit_hello_from_quantum_realm")
hello_world_circuit.append(cirq.H(q))
print(hello_world_circuit)
# + [markdown] id="3czN6Z_DanFA"
#
# + colab={"base_uri": "https://localhost:8080/"} id="7uu4ZOTvVu2i" outputId="cca4dc04-6011-4af3-f286-b4d396524d36"
# Initialize Simulator
s=cirq.Simulator()
print('Simulate the circuit:')
results=s.simulate(hello_world_circuit)
print(results)
print()
# + colab={"base_uri": "https://localhost:8080/"} id="5bB4qFZWa8jk" outputId="ca2a121f-8821-45af-b359-8e05ec4a9300"
#Add a measurement so we can emulate the superposition by sampling the result
hello_world_circuit.append(cirq.measure(q, key='result'))
print(hello_world_circuit)
# + colab={"base_uri": "https://localhost:8080/"} id="40J6gJhRbWcS" outputId="a0030b9e-7514-40e2-aed4-89217a515923"
# Now we can sample, which is done by the command run
print('Sample the circuit:')
samples=s.run(hello_world_circuit, repetitions=1000)
# Print a histogram of results
print(samples.histogram(key='result'))
# + id="iPpSUA7Vbh6Q"
#Let's print it a bit prettier
import matplotlib.pyplot as plt
# + [markdown] id="_j1dS7Z4GFl_"
# ##Create the Bell State Circuit that we learned in class
#
# We will use two gates:
# * Hadamard(H) to convert the qubit from clustering state to uniform superposed state.
# * Control not (CNOT)
#
#
# + colab={"base_uri": "https://localhost:8080/"} id="88cUXC_QGQho" outputId="ce661066-5603-4703-83c3-34230e020841"
# Create a circuit to generate a Bell State:
# 1/sqrt(2) * ( |00⟩ + |11⟩ )
bell_circuit = cirq.Circuit()
q0, q1 = cirq.LineQubit.range(2)
bell_circuit.append(cirq.H(q0))
bell_circuit.append(cirq.CNOT(q0,q1))
# print circuit
print("circuit")
print(bell_circuit)
# + [markdown] id="bBdSjtbqHvUa"
# **TASK**: Pick three gates to study and explain to us in the next lecture https://quantumai.google/cirq/gates
# + [markdown] id="uiRNQvDlH0yE"
# # Simuate the executiong of the circuit
#
#
# + colab={"base_uri": "https://localhost:8080/"} id="Sr7YzSgxE-gj" outputId="067245b5-998e-404c-a91d-87b5f04e1d07"
# Initialize Simulator
s=cirq.Simulator()
print('Simulate the circuit:')
results=s.simulate(bell_circuit)
print(results)
print()
# + [markdown] id="SHEKETytIINy"
# ### Sample the results
#
# This is necessary because we are not using a Quantum Computer here. The results printed before are only single-point measure.
# + colab={"base_uri": "https://localhost:8080/"} id="UKppnOBeIHI7" outputId="336b3630-b3b1-46ec-b851-ae81dd29f016"
# However for sampling, we need to add a measurement at the end
bell_circuit.append(cirq.measure(q0, q1, key='result'))
#bell_circuit.append(cirq.measure(q0, key='result q0'))
#bell_circuit.append(cirq.measure(q1, key='result q1'))
print(bell_circuit)
# + colab={"base_uri": "https://localhost:8080/"} id="gxtkrAWLLdFF" outputId="89156ec8-64c3-4d2b-d105-4bf22706cbc3"
# Now we can sample, which is done by the command run
print('Sample the circuit:')
samples=s.run(bell_circuit, repetitions=1000)
# Print a histogram of results
print(samples.histogram(key='result q0'))
print(samples.histogram(key='result q1'))
# + id="SXIXPnFsS03w"
#create a copy to compare measurements
bell_circuit_2 = bell_circuit.copy()
# Initialize Simulator
s=cirq.Simulator()
print('Simulate the circuit:')
results=s.simulate(bell_circuit)
print(results)
print()
|
Intro_BellStatesCircuit.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/1985shree/Data-science-Zoomcamp-projects/blob/main/MML_zoomcamp_week3_classification_churn_prediction.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + colab={"resources": {"http://localhost:8080/nbextensions/google.colab/files.js": {"data": "<KEY>", "ok": true, "headers": [["content-type", "application/javascript"]], "status": 200, "status_text": "OK"}}, "base_uri": "https://localhost:8080/", "height": 75} id="BdC-qKp8ATZj" outputId="0064c671-8632-41dc-9761-92e9f0af5157"
#uploading ipynb from local folder to google drive/colab folder
from google.colab import files
uploaded = files.upload()
# + id="xP1KKVOPDaOo"
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# + colab={"base_uri": "https://localhost:8080/", "height": 417} id="dPHHaJbIenHL" outputId="9e5875d6-1040-488d-eb53-31afa7d4049a"
import io
df = pd.read_csv(io.BytesIO(uploaded['AB_NYC_2019.csv']))
df.head()
# + id="ZS4z7t9mgy9J"
data = df [['neighbourhood_group', 'room_type','latitude','longitude','price','minimum_nights', 'number_of_reviews', 'reviews_per_month', 'calculated_host_listings_count', 'availability_365']]
# + colab={"base_uri": "https://localhost:8080/", "height": 363} id="85naq2KmhIPR" outputId="7c3180a4-b533-4bc3-e2fd-376b6706d1ba"
data.head(10).T
# + colab={"base_uri": "https://localhost:8080/", "height": 300} id="U4tigdOrhbJ6" outputId="91db9f09-ce0d-449b-e19a-d16cda8dfb69"
data.describe().T
# + colab={"base_uri": "https://localhost:8080/"} id="4GV07THG6k2X" outputId="2a7d6606-5b5d-4ec6-dc79-15a1138204f9"
pd.value_counts(data.neighbourhood_group)
# + [markdown] id="34qSPGt37B-T"
# Q1 Answer: Manhattan
# + [markdown] id="VFbiGY0gB-aq"
# **setting up validation framework**
# + colab={"base_uri": "https://localhost:8080/"} id="HE7jVp5K9Pd8" outputId="cbd4739a-6a10-4b97-9cf3-3de4035a8abc"
# !pip install scikit-learn
# + id="S5Fpwo4lCORK"
from sklearn.model_selection import train_test_split
# + colab={"base_uri": "https://localhost:8080/"} id="S66KyzR6gyBj" outputId="6545e681-619e-4f73-c25b-a213dae0a9f5"
data.copy()
df_full_train, df_test = train_test_split(data, test_size = 0.2, random_state = 42)
df_train, df_val = train_test_split(df_full_train, test_size = 0.25, random_state = 42)
print( len (df_train), len(df_val), len(df_test))
df_train.reset_index(drop = True)
df_val.reset_index(drop = True)
df_test.reset_index(drop = True)
y_train = df_train['price']
y_val = df_val['price']
y_test = df_test['price']
# + id="MBCNeiRkL-39"
del(df_train['price'])
del(df_val['price'])
del(df_test['price'])
# + id="EKVVDXsHL-9J"
# + [markdown] id="jBuWekm5CRsf"
# **EDA**
# + id="FDHTo7RJCUln" colab={"base_uri": "https://localhost:8080/", "height": 269} outputId="7969410c-83df-4f1c-9508-2189d3ed1be8"
# + colab={"base_uri": "https://localhost:8080/", "height": 504} id="Tq8zNXrCON0Z" outputId="9726e5ec-a49e-4f1d-b4d4-f49f9fd3658e"
# + id="RplxKtS_RVcz"
above_average_train = (y_train >= 152).astype(int)
above_average_val =(y_val >= 152).astype(int)
above_average_test = (y_test >= 152).astype(int)
# + colab={"base_uri": "https://localhost:8080/"} id="zz-WcxZvVLKZ" outputId="5e2de528-b364-4462-d212-f8bfe8a22f6f"
df_train.dtypes
# + id="g4FDXxW9Ywe7"
# + id="loLPps26Y6eV"
# + [markdown] id="jQllWI8wCZFK"
# **feature importance/feature engineering: churn rate and risk ratio**
# + id="m-QdVyYXCjPY"
# + id="I2qhRGGXalbe"
# + [markdown] id="ylDjKOqfbvgb"
# Answer to Q3 : room type
# + [markdown] id="qHVqpSQqCjf5"
# **feature importance: mutual information**
# + id="TQsXMcqlCz_Z"
categorical = ['neighbourhood_group', 'room_type']
df_train_categorical = df_train[categorical]
# + colab={"base_uri": "https://localhost:8080/"} id="sdPuc2dXcHTy" outputId="18e0a338-aeb3-47b3-ecbf-99cea5cf22af"
from sklearn.metrics import mutual_info_score
neighbourhood_score = mutual_info_score(df_train_categorical.neighbourhood_group, y_train )
room_type_score = mutual_info_score(df_train_categorical.room_type, y_train )
print (round(neighbourhood_score, 2), round(room_type_score, 2))
# + [markdown] id="KIVzPJDjC0fJ"
# **feature importance: correlation**
# + id="5ILxH_vzC58K" colab={"base_uri": "https://localhost:8080/", "height": 269} outputId="8e75ca37-af49-4abc-d8d9-bb2469efd32e"
#correlation matrix
train_corr = df_train.corr()
train_corr
# + colab={"base_uri": "https://localhost:8080/", "height": 504} id="DgwqmIwXcQsS" outputId="6ea4626f-8612-461b-98f3-885d2e16fd02"
#visualizing correlation matrix
import seaborn as sns
ax = sns.heatmap(train_corr, vmin = -1, vmax = 1, center = 0, cmap=sns.diverging_palette(20, 500, n=200), square=True)
ax.set_xticklabels(ax.get_xticklabels(),rotation=45, horizontalalignment='right')
# + [markdown] id="DzMRPKWhcZxy"
# reviews per month, number of reviews
# + [markdown] id="cAWVvwbHcVHZ"
#
# + [markdown] id="iCt9OmK9C-SP"
# **one-hot encoding**
# + id="QjKxFMq7DB0g" colab={"base_uri": "https://localhost:8080/"} outputId="179357a0-39a6-4f24-f72e-30165eec885d"
from sklearn.feature_extraction import DictVectorizer
train_dicts = df_train.to_dict(orient = 'records')
train_dicts[0]
# + id="CNR5Y4KPfX1y"
dv = DictVectorizer()
X_train = dv.fit_transform(train_dicts)
# + id="VryG9CPKgveJ"
val_dicts = train_dicts = df_val.to_dict(orient = 'records')
# + id="b52SIiGUgsLR"
X_val = dv.transform(val_dicts)
# + id="hvNY6PRRDEAh" colab={"base_uri": "https://localhost:8080/"} outputId="35820ae4-27c4-4602-f29d-ddf293d24ba3"
print(X_train[0])
# + [markdown] id="TWxbXez5DEgK"
# **logistic regression**
# + id="jTnPclcjDHEZ"
# + [markdown] id="TdAMFPdoDKZY"
# **training logistic regression with scikit-learn**
# + id="rkxikA6nDTQq"
# + [markdown] id="JCjXYPg0DhtC"
# **model interpretation**
# + id="Apps-5uRDpIo"
# + [markdown] id="elnw5y0zDpV4"
# **using the model**
|
MML_zoomcamp_week3_classification_churn_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.9.7 64-bit (''kamil'': conda)'
# language: python
# name: python3
# ---
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
# Read CSV file
df2 = pd.read_csv('../csv/d2.csv')
# Print first 5 rows
df2.head()
# Print shape of dataframe (columns, rows)
df2.shape
# Drop useless columns
df2.drop(['Unnamed: 0','Date', 'Round', 'Opening', 'WhiteRatingDiff', 'White', 'Black'], axis = 1, inplace = True)
# Print 5 new rows
df2.head()
# Checking for null values
df2.isnull().sum()
# Drop NaN values
df2.dropna(inplace=True)
# Change type of column *Event* into string
df2['Event'] = df2.Event.astype('string')
# Print count of unique value in column *Event*
df2.Event.nunique()
# Cut strings in column *Event*. This cell cut strings from 6 index of string
df2['Event'] = df2['Event'].map(lambda x: str(x)[6:])
# Split string when 'tournament' appears and left values (string) before this word
df2['Event'] = df2['Event'].map(lambda x: x.split('tournament',1)[0])
# Count values of column *Event*
df2.Event.value_counts()
# Merge similiar values into one
df2['Event'] = df2['Event'].replace(['Classical game', 'Classical '], 'Classical')
df2['Event'] = df2['Event'].replace(['Blitz game','Blitz '], 'Blitz')
df2['Event'] = df2['Event'].replace(['Rapid game','Rapid '], 'Rapid')
# Replacing result values into numeric, because it will help in the future.
#
# 1 - means White wins
# 2 - means Black wins
# 3 - means it's a draw
df2['Result'] = df2['Result'].replace(['1-0'], 1)
df2['Result'] = df2['Result'].replace(['0-1'], 2)
df2['Result'] = df2['Result'].replace(['1/2-1/2'], 3)
# Create new dataframe and drop rows where termination were *time forfeit* and it was a draw.
df2 = df2.drop(df2[(df2['Termination'] == 'Time forfeit') & (df2['Result'] == 3)].index)
# Drop rows where termination were *rules infraction* or *abandoned* because I will focus only on games ended by checkmate or time forfeit
df2 = df2[df2['Termination'] != "Rules infraction"]
df2 = df2[df2['Termination'] != "Abandoned"]
# Split strings in *TimeControl* column. Only values before *+* will stay.
df2['TimeControl'] = df2['TimeControl'].str.split('+').str[0]
df2['TimeControl'] = df2['TimeControl'].astype('int64')
df2.shape
df_blitz = df2[df2['Event'] == 'Blitz']
df_rapid = df2[df2['Event'] == 'Rapid']
df_classical = df2[df2['Event'] == 'Classical']
# Create new column *EloDiff*. This column contain difference of Elo points between players. If value is lower than 0, it means that player who plays as Black had higher Elo.
df2['EloDiff'] = df2['WhiteElo'] - df2['BlackElo']
df2.head()
df2_enc = df2
# I'm changing values into numeric
df2_enc['Event'] = df2_enc['Event'].replace(['Blitz'], 0)
df2_enc['Event'] = df2_enc['Event'].replace(['Classical'], 2)
df2_enc['Event'] = df2_enc['Event'].replace(['Rapid'], 4)
df2_enc['Termination'] = df2_enc['Termination'].replace(['Normal'], 0)
df2_enc['Termination'] = df2_enc['Termination'].replace(['Time forfeit'], 1)
df2_enc = df2_enc[df2_enc['ECO'] != '?']
df2_enc['ECO'].nunique()
labelencoder = LabelEncoder()
df2_enc.dropna(inplace=True)
# In this and next cells I'm changing values manually, because I need the same values in dataset D1 and D2
df2_enc.loc[99913,'ECO'] = 'D62'
df2_enc.loc[99914,'ECO'] = 'D98'
df2_enc.loc[99915,'ECO'] = 'E57'
df2_enc.tail()
df2_enc.info()
df2_enc['ECO_enc'] = labelencoder.fit_transform(df2_enc['ECO'])
df2_enc.dropna(inplace=True)
df2_enc.tail()
df2_enc['Event'] = df2_enc['Event'].astype('int64')
df2_enc['Result'] = df2_enc['Result'].astype('int64')
df2_enc['BlackElo'] = df2_enc['BlackElo'].astype('int64')
df2_enc['Termination'] = df2_enc['Termination'].astype('int64')
df2_enc['TimeControl'] = df2_enc['TimeControl'].astype('int64')
df2_enc['WhiteElo'] = df2_enc['WhiteElo'].astype('int64')
df2_enc['EloDiff'] = df2_enc['EloDiff'].astype('int64')
df2_enc['TimeControl_enc'] = df2_enc['TimeControl']
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(15, 34)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(60, 3)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(120, 5)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(180, 6)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(240, 7)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(300, 8)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(360, 9)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(420, 10)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(480, 11)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(600, 13)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(660, 14)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(780, 16)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(840, 17)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(900, 18)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(1200, 23)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(1500, 24)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(1800, 25)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(2700, 28)
df2_enc['TimeControl_enc'] = df2_enc['TimeControl_enc'].replace(5400, 30)
df2_enc.head()
df2_final = df2_enc[['Result','WhiteElo','BlackElo','EloDiff','Event','ECO_enc','Termination','TimeControl_enc']]
df2_final
df2_final.to_csv('../csv/d2_final.csv')
|
notebooks/D2 - data_preprocessing.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
# ---
# GeoViews is a [Python](http://python.org) library that makes it easy to explore and visualize geographical, meteorological, and oceanographic datasets, such as those used in weather, climate, and remote sensing research.
#
# GeoViews is built on the [HoloViews](http://holoviews.org) library for building flexible visualizations of multidimensional data. GeoViews adds a family of geographic plot types based on the [Cartopy](http://scitools.org.uk/cartopy) library, plotted using either the [Matplotlib](http://matplotlib.org) or [Bokeh](http://bokeh.pydata.org) packages. Each of the new `GeoElement` plot types is a new HoloViews `Element` that has an associated geographic projection based on `cartopy.crs`. The `GeoElements` currently include `Feature`, `WMTS`, `Tiles`, `Points`, `Contours`, `Image`, `QuadMesh`, `TriMesh`, `RGB`, `HSV`, `Labels`, `Graph`, `HexTiles`, `VectorField` and `Text` objects, each of which can easily be overlaid in the same plots. E.g. an object with temperature data can be overlaid with coastline data using an expression like ``gv.Image(temperature) * gv.Feature(cartopy.feature.COASTLINE)``. Each `GeoElement` can also be freely combined in layouts with any other HoloViews `Element`, making it simple to make even complex multi-figure layouts of overlaid objects.
#
# With GeoViews, you can now work easily and naturally with large, multidimensional geographic datasets, instantly visualizing any subset or combination of them, while always being able to access the raw data underlying any plot. Here's a simple example:
# +
import geoviews as gv
import geoviews.feature as gf
import xarray as xr
from cartopy import crs
gv.extension('bokeh', 'matplotlib')
# -
(gf.ocean + gf.land + gf.ocean * gf.land * gf.coastline * gf.borders).opts(
'Feature', projection=crs.Geostationary(), global_extent=True, height=325).cols(3)
# GeoViews is designed to work well with the [Iris](http://scitools.org.uk/iris) and [xarray](http://xarray.pydata.org) libraries for working with multidimensional arrays, such as those stored in netCDF files. GeoViews also accepts data as NumPy arrays and Pandas data frames. In each case, the data can be left stored in its original, native format, wrapped in a HoloViews or GeoViews object that provides instant interactive visualizations.
#
# The following example loads a dataset originally taken from [iris-sample-data](https://github.com/SciTools/iris-sample-data) and quickly builds an interactive tool for exploring how the data changes over time:
# +
dataset = gv.Dataset(xr.open_dataset('./data/ensemble.nc'))
ensemble = dataset.to(gv.Image, ['longitude', 'latitude'], 'surface_temperature')
gv.output(ensemble.opts(cmap='viridis', colorbar=True, fig_size=200, backend='matplotlib') * gf.coastline(),
backend='matplotlib')
# -
# GeoViews also natively supports geopandas datastructures allowing us to easily plot shapefiles and choropleths:
import geopandas as gpd
gv.Polygons(gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')), vdims=['pop_est', ('name', 'Country')]).opts(
tools=['hover'], width=600, projection=crs.Robinson()
)
|
datashader-work/geoviews-examples/Homepage.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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'] = ''
# -
import malaya_speech.train.model.conformer as conformer
import malaya_speech.train.model.transducer as transducer
import malaya_speech
import tensorflow as tf
import numpy as np
subwords_malay = malaya_speech.subword.load('bahasa-512.subword')
subwords_singlish = malaya_speech.subword.load('singlish-512.subword')
subwords_mandarin = malaya_speech.subword.load('mandarin-512.subword')
langs = [subwords_malay, subwords_singlish, subwords_mandarin]
len_vocab = [l.vocab_size for l in langs]
featurizer = malaya_speech.tf_featurization.STTFeaturizer(
normalize_per_feature = True
)
X = tf.compat.v1.placeholder(tf.float32, [None, None], name = 'X_placeholder')
X_len = tf.compat.v1.placeholder(tf.int32, [None], name = 'X_len_placeholder')
# +
batch_size = tf.shape(X)[0]
features = tf.TensorArray(dtype = tf.float32, size = batch_size, dynamic_size = True, infer_shape = False)
features_len = tf.TensorArray(dtype = tf.int32, size = batch_size)
init_state = (0, features, features_len)
def condition(i, features, features_len):
return i < batch_size
def body(i, features, features_len):
f = featurizer(X[i, :X_len[i]])
f_len = tf.shape(f)[0]
return i + 1, features.write(i, f), features_len.write(i, f_len)
_, features, features_len = tf.while_loop(condition, body, init_state)
features_len = features_len.stack()
padded_features = tf.TensorArray(dtype = tf.float32, size = batch_size)
padded_lens = tf.TensorArray(dtype = tf.int32, size = batch_size)
maxlen = tf.reduce_max(features_len)
init_state = (0, padded_features, padded_lens)
def condition(i, padded_features, padded_lens):
return i < batch_size
def body(i, padded_features, padded_lens):
f = features.read(i)
len_f = tf.shape(f)[0]
f = tf.pad(f, [[0, maxlen - tf.shape(f)[0]], [0,0]])
return i + 1, padded_features.write(i, f), padded_lens.write(i, len_f)
_, padded_features, padded_lens = tf.while_loop(condition, body, init_state)
padded_features = padded_features.stack()
padded_lens = padded_lens.stack()
padded_lens.set_shape((None,))
padded_features.set_shape((None, None, 80))
padded_features = tf.expand_dims(padded_features, -1)
padded_features, padded_lens
# -
padded_features = tf.identity(padded_features, name = 'padded_features')
padded_lens = tf.identity(padded_lens, name = 'padded_lens')
config = malaya_speech.config.conformer_base_encoder_config
config['dropout'] = 0.0
conformer_model = conformer.Model(**config)
decoder_config = malaya_speech.config.conformer_base_decoder_config
decoder_config['embed_dropout'] = 0.0
transducer_model = transducer.rnn.Model(
conformer_model, vocabulary_size = sum(len_vocab), **decoder_config
)
p = tf.compat.v1.placeholder(tf.int32, [None, None])
z = tf.zeros((tf.shape(p)[0], 1),dtype=tf.int32)
c = tf.concat([z, p], axis = 1)
p_len = tf.compat.v1.placeholder(tf.int32, [None])
c
training = True
logits = transducer_model([padded_features, c, p_len], training = training)
logits
sess = tf.Session()
sess.run(tf.global_variables_initializer())
var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
saver = tf.train.Saver(var_list = var_list)
saver.restore(sess, 'asr-base-conformer-transducer-3mixed/model.ckpt-1625000')
decoded = transducer_model.greedy_decoder(padded_features, padded_lens, training = training)
decoded = tf.identity(decoded[0], name = 'greedy_decoder')
decoded
# +
encoded = transducer_model.encoder(padded_features, training = training)
encoded = tf.identity(encoded, name = 'encoded')
encoded_placeholder = tf.placeholder(tf.float32, [config['dmodel']], name = 'encoded_placeholder')
predicted_placeholder = tf.placeholder(tf.int32, None, name = 'predicted_placeholder')
t = transducer_model.predict_net.get_initial_state().shape
states_placeholder = tf.placeholder(tf.float32, [int(i) for i in t], name = 'states_placeholder')
ytu, new_states = transducer_model.decoder_inference(
encoded=encoded_placeholder,
predicted=predicted_placeholder,
states=states_placeholder,
training = training
)
ytu = tf.identity(ytu, name = 'ytu')
new_states = tf.identity(new_states, name = 'new_states')
ytu, new_states
# -
initial_states = transducer_model.predict_net.get_initial_state()
initial_states = tf.identity(initial_states, name = 'initial_states')
# +
# sess = tf.Session()
# sess.run(tf.global_variables_initializer())
# +
# var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
# saver = tf.train.Saver(var_list = var_list)
# saver.restore(sess, 'asr-small-conformer-transducer/model.ckpt-325000')
# +
files = [
'speech/record/savewav_2020-11-26_22-36-06_294832.wav',
'speech/record/savewav_2020-11-26_22-40-56_929661.wav',
'speech/record/675.wav',
'speech/record/664.wav',
'mandarin-test/597.wav',
'mandarin-test/584.wav',
'speech/example-speaker/husein-zolkepli.wav',
'speech/example-speaker/mas-aisyah.wav',
'speech/example-speaker/khalil-nooh.wav',
'speech/example-speaker/shafiqah-idayu.wav',
'speech/khutbah/wadi-annuar.wav',
'singlish0.wav',
'singlish1.wav',
'singlish2.wav',
'singlish3.wav',
'singlish4.wav'
]
front_pad = 200
back_pad = 2000
inputs = [malaya_speech.load(f)[0] for f in files]
padded, lens = malaya_speech.padding.sequence_1d(inputs, return_len = True)
back = np.zeros(shape = (len(inputs), back_pad))
front = np.zeros(shape = (len(inputs), front_pad))
padded = np.concatenate([front, padded, back], axis = -1)
lens = [l + front_pad + back_pad for l in lens]
# +
# import collections
# import numpy as np
# import tensorflow as tf
# BeamHypothesis = collections.namedtuple(
# 'BeamHypothesis', ('score', 'prediction', 'states')
# )
# def transducer(
# enc,
# total,
# initial_states,
# encoded_placeholder,
# predicted_placeholder,
# states_placeholder,
# ytu,
# new_states,
# sess,
# beam_width = 10,
# norm_score = True,
# ):
# kept_hyps = [
# BeamHypothesis(score = 0.0, prediction = [0], states = initial_states)
# ]
# B = kept_hyps
# for i in range(total):
# A = B
# B = []
# while True:
# y_hat = max(A, key = lambda x: x.score)
# A.remove(y_hat)
# ytu_, new_states_ = sess.run(
# [ytu, new_states],
# feed_dict = {
# encoded_placeholder: enc[i],
# predicted_placeholder: y_hat.prediction[-1],
# states_placeholder: y_hat.states,
# },
# )
# for k in range(ytu_.shape[0]):
# beam_hyp = BeamHypothesis(
# score = (y_hat.score + float(ytu_[k])),
# prediction = y_hat.prediction,
# states = y_hat.states,
# )
# if k == 0:
# B.append(beam_hyp)
# else:
# beam_hyp = BeamHypothesis(
# score = beam_hyp.score,
# prediction = (beam_hyp.prediction + [int(k)]),
# states = new_states_,
# )
# A.append(beam_hyp)
# if len(B) > beam_width:
# break
# if norm_score:
# kept_hyps = sorted(
# B, key = lambda x: x.score / len(x.prediction), reverse = True
# )[:beam_width]
# else:
# kept_hyps = sorted(B, key = lambda x: x.score, reverse = True)[
# :beam_width
# ]
# return kept_hyps[0].prediction
# +
import re
from malaya_speech.utils.subword import decode
def decode_multilanguage(row, langs):
if not len(row):
return ''
len_vocab = [l.vocab_size for l in langs]
def get_index_multilanguage(r):
for i in range(len(langs)):
sum_v = sum(len_vocab[:i + 1])
if r < sum(len_vocab[:i + 1]):
return i, r - sum(len_vocab[:i])
last_index, v = get_index_multilanguage(row[0])
d, q = [], [v]
for r in row[1:]:
index, v = get_index_multilanguage(r)
if index != last_index:
d.append(decode(langs[last_index], q))
q = [v]
last_index = index
else:
q.append(v)
if len(q):
d.append(decode(langs[last_index], q))
d = re.sub(r'[ ]+', ' ', ' '.join(d)).strip()
d = d.replace(' lah', 'lah')
return d
# +
# %%time
r = sess.run(decoded, feed_dict = {X: padded, X_len: lens})
for row in r:
print(decode_multilanguage(row[row > 0], langs))
# +
# # %%time
# encoded_, padded_lens_ = sess.run([encoded, padded_lens], feed_dict = {X: padded, X_len: lens})
# padded_lens_ = padded_lens_ // conformer_model.conv_subsampling.time_reduction_factor
# s = sess.run(initial_states)
# for i in range(len(encoded_)):
# r = transducer(
# enc = encoded_[i],
# total = padded_lens_[i],
# initial_states = s,
# encoded_placeholder = encoded_placeholder,
# predicted_placeholder = predicted_placeholder,
# states_placeholder = states_placeholder,
# ytu = ytu,
# new_states = new_states,
# sess = sess,
# beam_width = 1,
# )
# print(decode_multilanguage(r, langs))
# -
l = padded_lens // transducer_model.encoder.conv_subsampling.time_reduction_factor
encoded = transducer_model.encoder(padded_features, training = training)
g = transducer_model._perform_greedy(encoded[0], l[0],
tf.constant(0, dtype = tf.int32),
transducer_model.predict_net.get_initial_state())
g
indices = g.prediction
minus_one = -1 * tf.ones_like(indices, dtype=tf.int32)
blank_like = 0 * tf.ones_like(indices, dtype=tf.int32)
indices = tf.where(indices == minus_one, blank_like, indices)
num_samples = tf.cast(X_len[0], dtype=tf.float32)
total_time_reduction_factor = featurizer.frame_step
stime = tf.range(0, num_samples, delta=total_time_reduction_factor, dtype=tf.float32)
stime /= tf.cast(featurizer.sample_rate, dtype=tf.float32)
stime = stime[::tf.shape(stime)[0] // tf.shape(indices)[0]]
stime.set_shape((None,))
non_blank = tf.where(tf.not_equal(indices, 0))
non_blank_transcript = tf.gather_nd(indices, non_blank)
non_blank_stime = tf.gather_nd(stime, non_blank)
non_blank_transcript = tf.identity(non_blank_transcript, name = 'non_blank_transcript')
non_blank_stime = tf.identity(non_blank_stime, name = 'non_blank_stime')
# +
# %%time
r = sess.run([non_blank_transcript, non_blank_stime], feed_dict = {X: padded, X_len: lens})
# -
r
def decode_multilanguage_subwords(tokenizers, ids):
"""
Decode integer representation to string using list of tokenizer objects.
Parameters
-----------
tokenizers: List[object]
List of tokenizer objects.
ids: List[int]
Returns
--------
result: str
"""
if not len(ids):
return ''
len_vocab = [l.vocab_size for l in tokenizers]
def get_index_multilanguage(r):
for i in range(len(tokenizers)):
sum_v = sum(len_vocab[:i + 1])
if r < sum(len_vocab[:i + 1]):
return i, r - sum(len_vocab[:i])
last_index, v = get_index_multilanguage(ids[0])
d, q = [], [v]
for r in ids[1:]:
index, v = get_index_multilanguage(r)
if index != last_index:
d.append(tokenizers[last_index]._id_to_subword(q - 1))
q = [v]
last_index = index
else:
q.append(v)
if len(q):
d.append(tokenizers[last_index]._id_to_subword(q - 1))
return d
def get_index_multilanguage(r, tokenizers, len_vocab):
for i in range(len(tokenizers)):
sum_v = sum(len_vocab[:i + 1])
if r < sum(len_vocab[:i + 1]):
return i, r - sum(len_vocab[:i])
get_index_multilanguage(1050, langs, len_vocab)
words, indices = [], []
for no, ids in enumerate(r[0]):
last_index, v = get_index_multilanguage(ids, langs, len_vocab)
w = langs[last_index]._id_to_subword(v - 1)
if type(w) == bytes:
w = w.decode()
words.extend([w, None])
indices.extend([no, None])
words, indices
# +
import six
from malaya_speech.utils import text_encoder
def _trim_underscore_and_tell(token):
if token.endswith('_'):
return token[:-1], True
return token, False
def decode(ids):
ids = text_encoder.pad_decr(ids)
subword_ids = ids
del ids
subwords_ = []
prev_bytes = []
prev_ids = []
ids = []
def consume_prev_bytes():
if prev_bytes:
subwords_.extend(prev_bytes)
ids.extend(prev_ids)
return [], []
for no, subword_id in enumerate(subword_ids):
last_index, v = get_index_multilanguage(subword_id, langs, len_vocab)
subword = langs[last_index]._id_to_subword(v)
if isinstance(subword, six.binary_type):
# Byte-encoded
prev_bytes.append(subword.decode('utf-8', 'replace'))
if subword == b' ':
prev_ids.append(None)
else:
prev_ids.append(no)
else:
# If there were bytes previously, convert to unicode.
prev_bytes, prev_ids = consume_prev_bytes()
trimmed, add_space = _trim_underscore_and_tell(subword)
ids.append(no)
subwords_.append(trimmed)
if add_space:
subwords_.append(' ')
ids.append(None)
prev_bytes = consume_prev_bytes()
return subwords_, ids
words, indices = decode(r[0])
len(words), len(indices)
# -
def combined_indices(subwords, ids, l, reduction_factor = 160, sample_rate = 16000):
result, temp_l, temp_r = [], [], []
for i in range(len(subwords)):
if ids[i] is not None:
temp_l.append(subwords[i])
temp_r.append(l[ids[i]])
else:
data = {'text': ''.join(temp_l),
'start': round(temp_r[0],4),
'end': round(temp_r[-1] + (reduction_factor / sample_rate), 4)}
result.append(data)
temp_l, temp_r = [], []
if len(temp_l):
data = {'text': ''.join(temp_l),
'start': round(temp_r[0],4),
'end': round(temp_r[-1] + (reduction_factor / sample_rate), 4)}
result.append(data)
return result
combined_indices(words, indices, r[1])
saver = tf.train.Saver()
saver.save(sess, 'output-base-stack-3mixed-conformer/model.ckpt')
strings = ','.join(
[
n.name
for n in tf.get_default_graph().as_graph_def().node
if ('Variable' in n.op
or 'gather' in n.op.lower()
or 'placeholder' in n.name
or 'encoded' in n.name
or 'decoder' in n.name
or 'ytu' in n.name
or 'new_states' in n.name
or 'padded_' in n.name
or 'initial_states' in n.name
or 'non_blank' in n.name)
and 'adam' not in n.name
and 'global_step' not in n.name
and 'Assign' not in n.name
and 'ReadVariableOp' not in n.name
and 'Gather' 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('output-base-stack-3mixed-conformer', 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('output-base-stack-3mixed-conformer/frozen_model.pb')
input_nodes = [
'X_placeholder',
'X_len_placeholder',
'encoded_placeholder',
'predicted_placeholder',
'states_placeholder',
]
output_nodes = [
'greedy_decoder',
'encoded',
'ytu',
'new_states',
'padded_features',
'padded_lens',
'initial_states',
'non_blank_transcript',
'non_blank_stime'
]
inputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in input_nodes}
outputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in output_nodes}
# +
# test_sess = tf.Session(graph = g)
# +
# r = test_sess.run(outputs['greedy_decoder'], feed_dict = {inputs['X_placeholder']: padded,
# inputs['X_len_placeholder']: lens})
# +
# for row in r:
# print(malaya_speech.subword.decode(subwords, row[row > 0]))
# +
# encoded_, padded_lens_, s = test_sess.run([outputs['encoded'], outputs['padded_lens'], outputs['initial_states']],
# feed_dict = {inputs['X_placeholder']: padded,
# inputs['X_len_placeholder']: lens})
# padded_lens_ = padded_lens_ // conformer_model.conv_subsampling.time_reduction_factor
# +
# i = 0
# r = transducer(
# enc = encoded_[i],
# total = padded_lens_[i],
# initial_states = s,
# encoded_placeholder = inputs['encoded_placeholder'],
# predicted_placeholder = inputs['predicted_placeholder'],
# states_placeholder = inputs['states_placeholder'],
# ytu = outputs['ytu'],
# new_states = outputs['new_states'],
# sess = test_sess,
# beam_width = 1,
# )
# malaya_speech.subword.decode(subwords, r)
# -
from tensorflow.tools.graph_transforms import TransformGraph
# +
transforms = ['add_default_attributes',
'remove_nodes(op=Identity, op=CheckNumerics, op=Dropout)',
'fold_batch_norms',
'fold_old_batch_norms',
'quantize_weights(fallback_min=-10, fallback_max=10)',
'strip_unused_nodes',
'sort_by_execution_order']
input_nodes = [
'X_placeholder',
'X_len_placeholder',
'encoded_placeholder',
'predicted_placeholder',
'states_placeholder',
]
output_nodes = [
'greedy_decoder',
'encoded',
'ytu',
'new_states',
'padded_features',
'padded_lens',
'initial_states',
'non_blank_transcript',
'non_blank_stime'
]
pb = 'output-base-stack-3mixed-conformer/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,
input_nodes,
output_nodes, transforms)
with tf.gfile.GFile(f'{pb}.quantized', 'wb') as f:
f.write(transformed_graph_def.SerializeToString())
# +
# g = load_graph('output-base-stack-mixed-conformer/frozen_model.pb.quantized')
# +
# inputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in input_nodes}
# outputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in output_nodes}
# test_sess = tf.Session(graph = g)
# +
# r = test_sess.run(outputs['greedy_decoder'], feed_dict = {inputs['X_placeholder']: padded,
# inputs['X_len_placeholder']: lens})
# +
# for row in r:
# print(malaya_speech.subword.decode(subwords, row[row > 0]))
# +
# encoded_, padded_lens_, s = test_sess.run([outputs['encoded'], outputs['padded_lens'], outputs['initial_states']],
# feed_dict = {inputs['X_placeholder']: padded,
# inputs['X_len_placeholder']: lens})
# padded_lens_ = padded_lens_ // conformer_model.conv_subsampling.time_reduction_factor
# +
# i = 0
# r = transducer(
# enc = encoded_[i],
# total = padded_lens_[i],
# initial_states = s,
# encoded_placeholder = inputs['encoded_placeholder'],
# predicted_placeholder = inputs['predicted_placeholder'],
# states_placeholder = inputs['states_placeholder'],
# ytu = outputs['ytu'],
# new_states = outputs['new_states'],
# sess = test_sess,
# beam_width = 1,
# )
# malaya_speech.subword.decode(subwords, r)
# -
b2_application_key_id = os.environ['b2_application_key_id']
b2_application_key = os.environ['b2_application_key']
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-speech-model')
directory = 'output-base-stack-3mixed-conformer'
tar = 'output-base-stack-3mixed-conformer.tar.gz'
os.system(f'tar -czvf {tar} {directory}')
outPutname = f'pretrained/{tar}'
b2_bucket.upload_local_file(
local_file=tar,
file_name=outPutname,
file_infos=file_info,
)
# !rm {tar}
file = 'output-base-stack-3mixed-conformer/frozen_model.pb'
outPutname = 'speech-to-text-transducer/conformer-stack-3mixed/model.pb'
b2_bucket.upload_local_file(
local_file=file,
file_name=outPutname,
file_infos=file_info,
)
file = 'output-base-stack-3mixed-conformer/frozen_model.pb.quantized'
outPutname = 'speech-to-text-transducer/conformer-stack-3mixed-quantized/model.pb'
b2_bucket.upload_local_file(
local_file=file,
file_name=outPutname,
file_infos=file_info,
)
# !rm -rf output-base-stack-3mixed-conformer
|
pretrained-model/stt/conformer/export/base-stack-3mixed.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
# ---
import os
import cv2
import h5py
import random
import numpy as np
from skimage import img_as_float32
from scipy.ndimage.interpolation import shift,rotate
from scipy import ndimage
import matplotlib.pyplot as plt
from sklearn.base import BaseEstimator
from sklearn.base import TransformerMixin
# %matplotlib inline
class ImageDataIncrease(BaseEstimator,TransformerMixin):
'''
* Esse algoritmo tem como objetivo aumentar a base de Dados de imagens:
** Rotacionando as Images em varias angulo [45,90,135,180,225,270,315,360]
** Fazer um deslocamento para Esquerda, Direita, Abaixo e Acima
* É preciso dar como entrada ao Algoritmo o Caminho da Pasta e O Nome do Attributo Desejada aumentar
* No que diz respeito ao algoritmos de Deslocamento é Préciso dar como entrada a Hora de Fit, o Numero do Pixel
Desejado na deslocamento
'''
def __init__(self, path, attributes):
self.path = path
self.attributes = attributes
def fit(seft,*_):
return self
def get_files(self, attribute):
files = sorted([os.path.join(self.path, attribute, file)
for file in os.listdir(self.path + "/"+attribute)
if file.endswith('.jpg')])
random.shuffle(files)
return files
def shift_image(self,image,shape,dx,dy,mode=""):
image = image.reshape(shape)
shifted_image = shift(image, [dy, dx], cval=0,mode=mode)
return shifted_image.reshape([-1])
def rotate_image(self,image, angle):
rotate_image = rotate(image,angle=angle,reshape=False)
return rotate_image
def load_image(self,item):
'''
* Carregar a imagem
* Converter a cor em Cinza
* Normalizar os valores do pixel entre 0 e 1
'''
image = cv2.imread(item)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.resize(gray,(255,255), interpolation=cv2.INTER_LINEAR)
return gray
def make_shift_image(self, Pixel_shift):
for attribute in self.attributes:
#print(attribute)
r,l,d,u = 0,0,0,0
data = self.get_files(attribute)
for item in data:
image = self.load_image(item)
#print(item)
for (dx,dy) in ((Pixel_shift, 0), (-Pixel_shift, 0), (0, Pixel_shift), (0, -Pixel_shift)):
if (dx,dy) == (Pixel_shift,0):
cv2.imwrite("{}/{}/Right_{}.jpg".format(self.path,attribute,r),
self.shift_image(image,shape=(255,255), dx=dx, dy=dy,mode="constant").reshape(255,255))
r=r+1
if (dx,dy) == (-Pixel_shift,0):
cv2.imwrite("{}/{}/Left_{}.jpg".format(self.path,attribute,l),
self.shift_image(image,shape=(255,255), dx=dx, dy=dy,mode="constant").reshape(255,255))
l=l+1
if (dx,dy) == (0,Pixel_shift):
cv2.imwrite("{}/{}/Down_{}.jpg".format(self.path,attribute,d),
self.shift_image(image,shape=(255,255), dx=dx, dy=dy,mode="constant").reshape(255,255))
d=d+1
if (dx,dy) == (0,-Pixel_shift):
cv2.imwrite("{}/{}/Up_{}.jpg".format(self.path,attribute,u),
self.shift_image(image,shape=(255,255), dx=dx, dy=dy,mode="constant").reshape(255,255))
u=u+1
print("Shift imagens criada com sucesso \n\n Verifique a pasta de Dados")
def make_rotate_image(self,*_):
for attribute in self.attributes:
data = self.get_files(attribute)
a,b,c,d,e,f,g,h = 0,0,0,0,0,0,0,0
for item in data:
image = self.load_image(item)
for angle in [45,90,135,180,225,270,315,360]:
if (angle == 45):
cv2.imwrite("{}/{}/45_{}.jpg".format(self.path,attribute,a),
self.rotate_image(image,angle=angle))
a=a+1
if (angle == 90):
cv2.imwrite("{}/{}/90_{}.jpg".format(self.path,attribute,b),
self.rotate_image(image,angle=angle))
b=b+1
if (angle == 135):
cv2.imwrite("%{}/{}/135_{}.jpg".format(self.path,attribute,c),
self.rotate_image(image,angle=angle))
c=c+1
if (angle == 180):
cv2.imwrite("{}/{}/180_{}.jpg".format(self.path,attribute,d),
self.rotate_image(image,angle=angle))
d=d+1
if (angle == 225):
cv2.imwrite("{}/{}/225_{}.jpg".format(self.path,attribute,e),
self.rotate_image(image,angle=angle))
e=e+1
if (angle == 270):
cv2.imwrite("{}/{}/270_{}.jpg".format(self.path,attribute,f),
self.rotate_image(image,angle=angle))
f=f+1
if (angle == 315):
cv2.imwrite("{}/{}/315_{}.jpg".format(self.path,attribute,g),
self.rotate_image(image,angle=angle))
g=g+1
if (angle == 360):
cv2.imwrite("{}/{}/360_{}.jpg".format(self.path,attribute,h),
self.rotate_image(image,angle=angle))
h=h+1
print("Rotação das imagens criada com sucesso \n\n Verifique a pasta de Dados")
def transform(self,Pixel_shift,Shift=False,Rotate=True):
if Shift:
self.make_shift_image(Pixel_shift)
if Rotate:
self.make_rotate_image()
path = "DATA/100-300"
# attributes = ["Tri_Bru"]
attributes = ["Ar_Bru","Ca_PodVer","Mil_ManTur","Tri_Bru","Tri_Fer","Tri_Oid"]
SR=ImageDataIncrease(path,attributes)
_=SR.transform(20)
|
Data Increase Process.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/cotozelo/Data_Science_Machine_Learning_-_Data_ICMC/blob/main/Notebooks/Classificacao_KNN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="_mtajbkPCESl"
# #K-Nearest Neighbors (ou K-Vizinhos mais próximos)
#
# * Chamado geramlente de KNN.
# * Algoritmo de classificação ( com adaptações pode ser usado para regressão).
# * Todas as features devem ser numéricas.
# * Pressuposto: ocorrências de mesma classe devem estar localizadas próximas no espaço, mesmo podendo ser um espaço n-dimensional.
# * O treino é muito rápido, mas o teste é demorado.
# * Distâncias mais usadas:
# * Distância de Euclides
# * Distância Manhattan
# * <a href="https://www.youtube.com/watch?v=BbYV8UfMJSA&t=67s">Lecture 4 'Curse of Dimensionality / Perceptron' -Cornell CS4780 SP17</a>
# * Explição sobre quanto maior a quantidade de dimensões, menos os vizinho são possíveis de calcular, pois todos os pontos estão distante e a mesma distância, <a href="http://www.cs.cornell.edu/courses/cs4780/2018fa/lectures/lecturenote02_kNN.html">Explicação Textual</a>
# * <a href="https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm">Referência</a>
#
#
# + [markdown] id="gh4PEN2WQi48"
# ## Exercício 01 - Imagens de números
# + [markdown] id="3dZRabBzQn43"
# ###Import e Sets
# + id="MmxCYtoeCEEi"
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
from sklearn.model_selection import GridSearchCV
# Essas linhas sao apenas configuracoes de plotting.
# Elas nao sao importantes para o seu aprendizado, entao as trataremos como "magica" por agora, ok?
# %matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# Abaixo encontram-se os hiperparametros do modelo que sera construido.
# A nao ser que seja instruido, voce nao deve modifica-los
TRAIN_TEST_SPLIT_SIZE = 0.2 # Define que o TESTE correspondera a 20% do total do dataset
# + [markdown] id="gc5q7ZK7Q3fL"
# ### Carregar os dados
#
# Usaremos o dataset mnist
# + colab={"base_uri": "https://localhost:8080/", "height": 501} id="BmTOTcwJCC7n" outputId="d396e9d0-8fc8-4b55-8b9f-38111fcebd2c"
dataset = datasets.load_digits()
datasetSize = len(dataset.images)
print("O dataset possui", datasetSize, " imagens.")
# Mostraremos uma imagem aleatoria dentro do dataset
plt.imshow(dataset.images[np.random.randint(datasetSize)])
plt.show()
# + [markdown] id="dwfkD-QiRdy2"
# ### Separando o dataset em treino e teste
# + colab={"base_uri": "https://localhost:8080/"} id="zywxYSQMRkrq" outputId="79acbb40-f365-48f4-8bac-43d8743cee47"
X_train, X_test, y_train, y_test = train_test_split(dataset.data, dataset.target, test_size=TRAIN_TEST_SPLIT_SIZE)
print("Train shapes - X =", X_train.shape," y =", y_train.shape)
print("Test shapes - X =", X_test.shape," y =", y_test.shape)
print()
print(f"Exemplo de uma linha de X:\n{X_train[0]}\n")
print(f"Exemplo de uma linha de Y:\n{y_train[0]}")
# + [markdown] id="g4LPSfAPAeow"
# ### O modelo
# + colab={"base_uri": "https://localhost:8080/", "height": 514} id="vvJ3vLm6Af5D" outputId="60f039d8-93c7-42d0-c07d-de0fb46c0f5e"
k = 1 # usarndo k = 1 ou seja, somente um vizinho
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
score = knn.score(X_test, y_test)
y_predito = knn.predict(X_test)
print(f'O score do modelo com k={k} é {score}')
plt.scatter(x=y_test, y=y_predito)
plt.xlabel("y de teste")
plt.ylabel("y de predito")
plt.show()
# + [markdown] id="qz21yfNUMuub"
# ###Métricas
# + colab={"base_uri": "https://localhost:8080/"} id="22L7LI33A1KK" outputId="3d7d8e23-6312-4807-e0d0-180bb9ef4ebe"
print(metrics.classification_report(y_test, y_predito)
# + [markdown] id="K0P0m-sBOwju"
# * *Precision* é intuitivamente a capacidade do classificador de não rotular como **positiva** uma amostra **negativa**
#
# Precision = tp / (tp + fp)
# * tp é o verdadeiro positivo
# * fp é o falso positivo
#
# * *Recall* é intuitivamente a capacidade do classificador de encontrar **todas** as amostras **positivas**.
#
# Recall = tp / (tp + fn)
# * tp é o verdadeiro positivo
# * fn é o falso negativo
#
# * *F1-Score* pode ser interpretada como uma média pondera da *precision* e *recall*, onde 1 é o melhor valor e 0 o pior valor.
#
# f1 = 2 * (precision * recall) / (precision + recall)
#
# * *Support* é o número de cada classe no conjunto de teste, ou seja **y_test**.
#
# * *Accuracy* é a quantidade de acerto frente o total de amostras.
#
#
# + [markdown] id="PJjdiDGAT8hd"
# ###Ajuste de hiper-parâmetros
#
# Como esse ajuste podemos encontrar o melhor modelo, a partir de um conjunto de parâmetros. <a href=" https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html">[ref]</a>
# + colab={"base_uri": "https://localhost:8080/", "height": 514} id="9w8eNJVWTv3i" outputId="4bb82a08-3314-4e31-ef8a-a2481ca6ae94"
knn = KNeighborsClassifier(n_neighbors=2)
k_list = list(range(1, 31)) # k variando de 1 a 30
parametros = dict(n_neighbors=k_list) # converte a liste em dicionários de parâmetros
grid = GridSearchCV(knn, parametros, cv=2, scoring='accuracy')
# knn é o modelo que faremos o ajuste
# cv quantidade de rodadas, maior que zero
# scoring qual métrica usaremos para selecionar o melhor
grid.fit(X_train, y_train)
print(f"Melhores parametros {grid.best_params_} com o valor de acurácia {grid.best_score_} ")
plt.plot(k_list, grid.cv_results_['mean_test_score'], color='red', linestyle='dashed', marker='o')
plt.xlabel("K (vizinhos)")
plt.ylabel("Accuracy")
plt.show()
# + [markdown] id="oJeFG7_RdYp7"
# ## Exercício 02 - Classificação de vinhos
# + [markdown] id="rCTMmQ08d5N9"
# ### imports
# + id="su38bighdag5"
from sklearn import datasets
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
# + [markdown] id="iWT_So0ed7bd"
# ### biblioteca de visualização
# http://rasbt.github.io/mlxtend/
# + colab={"base_uri": "https://localhost:8080/"} id="IYtnmCV7d6wL" outputId="e239636f-8c1e-469c-bd65-5ffcf408dac4"
# !pip install mlxtend
from mlxtend.plotting import plot_decision_regions
# + [markdown] id="lz60rqcAeR1K"
# ### Dataset base de vinhos
# https://archive.ics.uci.edu/ml/datasets/wine
#
# https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_wine.html#sklearn.datasets.load_wine
#
# + colab={"base_uri": "https://localhost:8080/"} id="wG0G1AMWebwA" outputId="c4b2fd36-e095-45f9-c272-49bd1baee2d2"
wine = datasets.load_wine()
wine
# + colab={"base_uri": "https://localhost:8080/", "height": 217} id="AioPu9dOeihf" outputId="b0fac074-88b4-4cc2-bcde-2f5246923e09"
# Criando um df a partir da base carregada
df_wine = pd.DataFrame(data=wine.data, columns=wine.feature_names)
df_wine['class'] = wine.target
df_wine.head()
# + [markdown] id="b8qn7oUse1wz"
# ### Explorando os dados
# + colab={"base_uri": "https://localhost:8080/"} id="Q8HkCdDpfE6s" outputId="93218c82-558c-482e-ae3e-ad32da37b0fe"
# informações gerais sobre os dados.
df_wine.info()
# + [markdown] id="2U2gf4GGfOS4"
# * Podemos concluir que não há dados nulos.
# * Todas as colunas são numéricas, float64 ou int64
# * Existem 178 ocorrências (ou linhas)
# * Existem 14 colunas. Podemos intuir que são 13 features (caracteristicas) e 1 target (class).
#
# + colab={"base_uri": "https://localhost:8080/", "height": 307} id="rNWLk_xxe31v" outputId="01778192-53b4-4745-bc44-7363db99c9c1"
# analisando algumas métricas estatísticas sobre os dados
df_wine.describe()
# + colab={"base_uri": "https://localhost:8080/"} id="734hV7ObgESY" outputId="e3a00bbb-b3d9-4e1a-aeb3-21e38cbe6067"
# analisando as classes
df_wine['class'].value_counts()
# + [markdown] id="sStru-OSgNrB"
# A quantidade de ocorrência por classe não é balanceda.
# + [markdown] id="zy0PUhLMgXlp"
# ### Separação dos dados em train e test
# + id="hWNOVJRygMxV"
# usaremos uma proporção de 80% para train e 20% para teste, indicadda em test_size=0.2
X_train, X_test, y_train, y_test = train_test_split(df_wine.drop('class',axis=1), df_wine['class'], test_size=0.2)
# + [markdown] id="g3SyRxrlgzTT"
# ### O modelo - <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html">KNN</a>
#
# * n_neighbors: Número de vizinhos (Default=5)
# * weights: Peso de amostras vizinhas (Default=uniform).
# * metric: Métrica utilizada para o cálculo de distância (Default=minkowski).
# * p: Parametro de poder para a métrica (Default=2).
# * n_jobs: Número de jobs paralelos para executar no momento da busca de vizinhos. (Default=1)
# + id="lqM4n9v9gwgF"
# para nosso caso usaremos k = 1, ou seja, somente 1 (um) vizinho
knn = KNeighborsClassifier(n_neighbors=1)
# + colab={"base_uri": "https://localhost:8080/"} id="pR_5BANQhXEC" outputId="cb29499b-d23b-425f-e265-0ca4d9f0c080"
knn.fit(X_train, y_train)
# + colab={"base_uri": "https://localhost:8080/"} id="_bqA1d6whYxi" outputId="cd245db2-fc89-46e0-8c9a-83e73321eb25"
y_predito = knn.predict(X_test)
y_predito
# + [markdown] id="Rk65EqnPhd2w"
# ### Métricas
# + [markdown] id="DELaFVvOiptk"
# #### Matriz de confusão
# + colab={"base_uri": "https://localhost:8080/"} id="8ScFXxX5hfsr" outputId="48bf4fdd-d713-4001-da8b-b44da9e94bd1"
print(pd.crosstab(y_test, y_predito, rownames=['Real'], colnames=['Predito'], margins=True))
# + [markdown] id="cLN-3rgFiUHO"
# Na matriz de confusão, qualque valor for da diagonal principal é um erro.
# + [markdown] id="epUKiebvisO9"
# #### Recall, Precision, f1-score, ...
# + colab={"base_uri": "https://localhost:8080/"} id="0Wz08D49ickl" outputId="876019cd-af2b-4e20-8727-8ca42e8ec79a"
print(metrics.classification_report(y_test, y_predito, target_names=wine.target_names))
# + [markdown] id="70btoO_Ei7S8"
# ### Ajustando os hiper-parâmetros
#
# Nesse caso vamos ajustar a quantidade de vizinhos, com isso encontraremos a quantidade de vizinho que fornece o menor erro.**negrito**
# + colab={"base_uri": "https://localhost:8080/"} id="dT2ihYwEjPvb" outputId="92f1afba-262c-4284-b1e3-65e3a6f75ab7"
# variamos os viznhos de 1 a 30
k_list = list(range(1,31))
# Variamos os pesos entre uniforme e distance
weight_list = ['uniform','distance']
# variamos p entre 1 e 2
p_list = [1,2]
parametros = dict(n_neighbors=k_list, weights=weight_list, p=p_list)
parametros
# + colab={"base_uri": "https://localhost:8080/"} id="zaQGzDLcj2X8" outputId="9cf13df3-7f92-4aed-dbff-476f6c97cb36"
# cv é a quantidade de varificações por conjunto
# scoring é a métrica usada para obter o melhor modelo, estamos usando accuracy
grid = GridSearchCV(knn, parametros, cv=5, scoring='accuracy')
grid.fit(df_wine.drop('class',axis=1),df_wine['class'])
# + colab={"base_uri": "https://localhost:8080/"} id="yJPW2v7xkhmS" outputId="c4cc0357-e6be-4e5c-df61-e2be59300024"
# o atributo cv_results_ contém todos os resultados coletados.
grid.cv_results_
# + colab={"base_uri": "https://localhost:8080/"} id="6cllbCTDkst4" outputId="383acc62-c04b-4d7a-cd9d-749830c22cf2"
# obtendo os scores
scores = grid.cv_results_.get('mean_test_score')
print(scores)
# rank dos melhores modelos
k_rank = grid.cv_results_.get('rank_test_score')
print(k_rank)
print(f"Melhores parametros {grid.best_params_} com o valor de acurácia {grid.best_score_} ")
# + colab={"base_uri": "https://localhost:8080/", "height": 501} id="-_1_-XKTk6VO" outputId="5d1b16e9-0b3a-4228-e9c6-861f1d9bc445"
plt.plot(scores, color='red', linestyle='dashed', marker='o')
# + [markdown] id="_jF_Q-2RmV0y"
# ### Analisando a fronteira
# + colab={"base_uri": "https://localhost:8080/", "height": 774} id="nokfUE93lm_I" outputId="da4b8ddf-28aa-49ed-def9-c929145dfc84"
def plot_fronteiras(X, y, n_vizinhos):
knn = KNeighborsClassifier(n_neighbors=n_vizinhos)
knn.fit(X, y)
plt.figure(figsize=(8,5))
plot_decision_regions(X, y, clf=knn, legend=2)
plt.xlabel('alcohol')
plt.ylabel('malic_acid')
plt.title(f'Fronteiras de Complexidade - KNN {n_vizinhos} vizinhos')
plt.show()
plot_fronteiras(wine.data[:,[0,2]], wine.target, 1)
plot_fronteiras(wine.data[:,[0,2]], wine.target, 2)
# + [markdown] id="kgl0psZVL4Th"
# ## Exemplo 03 - Iris
# + [markdown] id="QdyS3OqfL-4C"
# ### imports
# + id="dqq5pWSiL8cT"
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import GridSearchCV
# + [markdown] id="XZhb9jJuMYLK"
# ### dataset
# + colab={"base_uri": "https://localhost:8080/", "height": 197} id="Nuw87x06MZbZ" outputId="846a20b4-a4b7-488e-820a-65c1970a8f2c"
iris = datasets.load_iris()
df_iris = pd.DataFrame(iris.data, columns=iris.feature_names)
df_iris['class'] = iris.target
df_iris.head()
# + [markdown] id="Cbuh7DebNI9s"
# ### Analisando os dados
# + colab={"base_uri": "https://localhost:8080/"} id="_-Nx7kYJNKzn" outputId="9fc373f9-682c-4455-9142-384749e1bc5a"
df_iris.info()
# + [markdown] id="MUFbE_EwNO9o"
# Podemos verificar que o conjunto de dados contém 5 colunas, sendo 4 de features e 1 de classificação.
#
# Todas as colunas são numéricas.
#
# Não há dados faltantes ou nulos.
# + colab={"base_uri": "https://localhost:8080/", "height": 287} id="MTZsXMomOnRw" outputId="ccee2d0e-b1f5-4961-cfec-4387cef97e17"
df_iris.describe()
# + colab={"base_uri": "https://localhost:8080/"} id="CIYqVxWcOsHn" outputId="b41f51ce-39ca-4a83-c5f0-a9781cfbf518"
df_iris['class'].value_counts()
# + [markdown] id="E99JXcM9OxD1"
# Há 3 classe diferentes, e são totamente balanceadas.
# + [markdown] id="BMdc_g5DPx0j"
# ### Dados de treino e validação
# + id="ud7raMeGO24j"
X = df_iris.iloc[:, :-1].values
print(X)
y = df_iris.iloc[:, 4].values
print(y)
# + colab={"base_uri": "https://localhost:8080/"} id="RwFEOYbSQjDi" outputId="cd96b0d1-744c-45ae-adf6-d87bdc097ee4"
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
print(f'Tamanhos do X de treino {X_train.shape}')
print(f'Tamanhos do y de treino {y_train.shape}')
print(f'Tamanhos do X de teste {X_test.shape}')
print(f'Tamanhos do y de teste {y_test.shape}')
# + [markdown] id="ksifoJSIRRZx"
# ### Normalizando os dados
# + [markdown] id="4Kx_TVXtRmOx"
# Note que o fit da normalização será no X_train, isso pq o X_test na prática não sabemos a priore, ou seja, o conjunto de dados que temos a mão para saber fazer a normalização é o X_train, e o X_test são os dados que viram futuramente para aplicarmos o modelo.
# + id="fC3vHaP5RUWB"
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# + [markdown] id="GsVg3ItzSInz"
# ### O modelo KNN
# + id="hAldLTrLR_D_"
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
# predizendo
y_predito = knn.predict(X_test)
# + [markdown] id="h027VmKnSpXD"
# ### Métricas
# + colab={"base_uri": "https://localhost:8080/"} id="RG8KcizcSqcg" outputId="49775102-1d7f-44a6-db40-b026a2fbd560"
# Matriz de confusao
matriz_confusao = confusion_matrix(y_true=y_test, y_pred=y_predito)
print(matriz_confusao)
print('\n---\n')
# melhorando a visualização da matriz de confusao
print(pd.crosstab(y_test, y_predito, rownames=['Real'], colnames=['Predito'], margins=True))
# + colab={"base_uri": "https://localhost:8080/"} id="yJXiiUzITcCo" outputId="87a077bb-0612-4ae4-b5b8-9f9d6284c77e"
print(classification_report(y_test, y_predito, target_names=iris.target_names))
# + [markdown] id="Gyt5J8gyU3ZO"
# ### Grid search
# + colab={"base_uri": "https://localhost:8080/", "height": 296} id="mANrj0YXVGZD" outputId="c06b9abc-17b9-44d3-a736-866439c77824"
knn = KNeighborsClassifier(n_neighbors=2)
k_list = list(range(1, 31)) # k variando de 1 a 30
parametros = dict(n_neighbors=k_list) # converte a liste em dicionários de parâmetros
grid = GridSearchCV(knn, parametros, cv=2, scoring='accuracy')
# knn é o modelo que faremos o ajuste
# cv quantidade de rodadas, maior que zero
# scoring qual métrica usaremos para selecionar o melhor
grid.fit(X_train, y_train)
print(f"Melhores parametros {grid.best_params_} com o valor de acurácia {grid.best_score_} ")
plt.plot(k_list, grid.cv_results_['mean_test_score'], color='red', linestyle='dashed', marker='o')
plt.xlabel("K (vizinhos)")
plt.ylabel("Accuracy")
plt.show()
# + [markdown] id="RfCoz7dETFyy"
#
|
Notebooks/Classificacao_KNN.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# !pip3 install Orange3-Associate
# +
import pandas as pd
import numpy as np
import sys,getopt
import requests
import csv
import Orange
from Orange.data import Table,Domain, DiscreteVariable, ContinuousVariable
from orangecontrib.associate.fpgrowth import *
#stats
from scipy import sparse
import scipy.stats as ss
#viz
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
from PIL import Image
import matplotlib_venn as venn
# %matplotlib inline
# -
# # Download data set
#
# go to "https://raw.githubusercontent.com/stedy/Machine-Learning-with-R-datasets/master/groceries.csv" and download .csv
#
# read csv with delimiter as ',' and create a list of all items as columns.
#
# # Read the csv and convert it to DataFrame
# +
items=set()
with open('groceries_dataset.csv') as data:
read_data = csv.reader(data,delimiter=",")
for i,line in enumerate(read_data):
items.update(line)
output_list = list()
with open('groceries_dataset.csv') as data:
read_data = csv.reader(data,delimiter=",")
for i,line in enumerate(read_data):
row_value = {item:0 for item in items}
row_value.update({item:1 for item in line}) #if item is present in that transcation, set row_value to 1 for that item
output_list.append(row_value)
grocery_df = pd.DataFrame(output_list)
# -
grocery_df.head()
# # Shape of the DataFrame
grocery_df.shape
# # Statistical Description
grocery_df.describe()
# # Top 20 "sold items" that occur in the dataset
# +
total_count_of_items = sum(grocery_df.sum())
print("Total count of items: ", total_count_of_items)
item_sort_df = grocery_df.sum().sort_values(ascending = False).reset_index()
item_sort_df.rename(columns={item_sort_df.columns[0]:'item_name',item_sort_df.columns[1]:'item_count'}, inplace=True)
item_sort_df.head(20)
# -
# # Visualization of top 20 "sold items" that occur in the dataset
# +
objects = (list(item_sort_df['item_name'].head(20)))
y = np.arange(len(objects))
count = list(item_sort_df['item_count'].head(20))
plt.bar(y, count, align='center', alpha=0.8)
plt.xticks(y, objects, rotation='vertical')
plt.ylabel('Item count')
plt.title('Sales distribution of top 20 sold items')
# -
# # Contribution of top 20 "sold items" to total sales
# +
item_sort_df['item_perc'] = item_sort_df['item_count']/total_count_of_items #each item's contribution
item_sort_df['total_perc'] = item_sort_df.item_perc.cumsum() #cumulative contribution of top items
print(item_sort_df[item_sort_df.total_perc <= 0.5].shape)
item_sort_df.head(20)
# + active=""
# This shows us that:
# 1. The Top 5 items are responsible for 21.4% of the entire sales!
# 2. The top 20 items are responsible for over 50% of the sales!
#
# This is important for us, as we don’t want to find association rules foritems which are bought very infrequently.
# With this information, we can limit the items we want to explore for creating our association rules.
# This also helps us in keeping our possible item set number to a manageable figure.
# -
# # Make Orange Table
# +
#refer : https://docs.biolab.si//3/data-mining-library/reference/data.domain.html
#refer: https://docs.biolab.si//3/data-mining-library/reference/data.variable.html
input_assoc_rules = grocery_df
domain_grocery = Domain([DiscreteVariable.make(name='item',values=['0', '1']) for item in input_assoc_rules.columns])
data_gro_1 = Orange.data.Table.from_numpy(domain=domain_grocery, X=input_assoc_rules.as_matrix(),Y= None)
data_gro_1
# -
# # Prune Dataset for frequently purchased items
def prune_dataset(input_df, length_trans, total_sales_perc, start_item = None, end_item = None):
if 'total_items' in input_df.columns:
del(input_df['total_items'])
item_count = input_df.sum().sort_values(ascending = False).reset_index()
total_items = sum(input_df.sum().sort_values(ascending = False))
item_count.rename(columns={item_count.columns[0]:'item_name',item_count.columns[1]:'item_count'}, inplace=True)
if not start_item and not end_item:
item_count['item_perc'] = item_count['item_count']/total_items #each percent
item_count['total_perc'] = item_count.item_perc.cumsum() #cumulative
selected_items= list(item_count[item_count.total_perc < total_sales_perc].item_name.sort_values())
input_df['total_items'] = input_df[selected_items].sum(axis = 1)
input_df = input_df[input_df.total_items >= length_trans] #transactions with at least length_trans items
del(input_df['total_items'])
return input_df[selected_items], item_count[item_count.total_perc < total_sales_perc] #comparing cumulative perc
elif end_item > start_item:
selected_items = list(item_count[start_item:end_item].item_name)
input_df['total_items'] = input_df[selected_items].sum(axis = 1)
input_df = input_df[input_df.total_items >= length_trans]
del(input_df['total_items'])
return input_df[selected_items],item_count[start_item:end_item]
output_df, item_counts = prune_dataset(input_df=grocery_df, length_trans=2,total_sales_perc=0.4)
print("Shape: ",output_df.shape)
print("Selected items: ", list(output_df.columns))
# # Association Rule Mining with FP Growth
input_assoc_rules = output_df
domain_grocery = Domain([DiscreteVariable.make(name=item,values=['0', '1']) for item in input_assoc_rules.columns])
data_gro_1 = Orange.data.Table.from_numpy(domain=domain_grocery, X=input_assoc_rules.as_matrix(),Y= None)
data_gro_1_en, mapping = OneHot.encode(data_gro_1, include_class=False)
min_support=0.01
num_trans = input_assoc_rules.shape[0]*min_support
print("Number of required transactions = ", int(num_trans))
itemsets = dict(frequent_itemsets(data_gro_1_en, min_support=min_support)) #dict-- key:value pair
print(len(itemsets), " itemsets have a support of ", min_support*100, "%")
# +
confidence = 0.3
rules_df = pd.DataFrame()
if len(itemsets) < 1000000:
rules = [(P, Q, supp, conf)
for P, Q, supp, conf in association_rules(itemsets, confidence)
if len(Q) == 1 ]
print(len(rules))
names = {item: '{}={}'.format(var.name, val)
for item, var, val in OneHot.decode(mapping, data_gro_1, mapping)}
eligible_antecedent = [v for k,v in names.items() if v.endswith("1")]
N = input_assoc_rules.shape[0]
rule_stats = list(rules_stats(rules, itemsets, N))
rule_list_df = []
for ex_rule_from_rule_stat in rule_stats:
ante = ex_rule_from_rule_stat[0]
cons = ex_rule_from_rule_stat[1]
named_cons = names[next(iter(cons))]
if named_cons in eligible_antecedent:
rule_lhs = [names[i][:-2] for i in ante if names[i] in eligible_antecedent]
ante_rule = ', '.join(rule_lhs)
if ante_rule and len(rule_lhs)>1 :
rule_dict = {'support' : ex_rule_from_rule_stat[2],
'confidence' : ex_rule_from_rule_stat[3],
'coverage' : ex_rule_from_rule_stat[4],
'strength' : ex_rule_from_rule_stat[5],
'lift' : ex_rule_from_rule_stat[6],
'leverage' : ex_rule_from_rule_stat[7],
'antecedent': ante_rule,
'consequent':named_cons[:-2] }
rule_list_df.append(rule_dict)
rules_df = pd.DataFrame(rule_list_df)
print("Raw rules data frame of {} rules generated".format(rules_df.shape[0]))
if not rules_df.empty:
pruned_rules_df = rules_df.groupby(['antecedent','consequent']).max().reset_index()
else:
print("Unable to generate any rule")
# -
# # Sorting the rules in grocery dataset
(pruned_rules_df[['antecedent','consequent',
'support','confidence','lift']].groupby('consequent')
.max()
.reset_index()
.sort_values(['lift', 'support','confidence'],
ascending=False))
# + active=""
# Generating sample rules using transactions that explain 40% of total sales, min-support of 1% (required number
# of transactions >=45) and confidence greater than 30%.
# Here, we have collected rules having maximum lift for each of the items that can be a consequent (that appear on the right side)
# + active=""
# The pattern that the rule states in the equation is easy to understand—people who bought yogurt, whole milk, and tropical fruit also tend to buy root vegetables.
# -
|
Apriori-on-groceries.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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 pymc3 as pm
import arviz as az
import xarray as xr
rng = np.random.default_rng()
# +
data = pd.DataFrame({
'var1': rng.uniform(size=1000),
'var2': rng.uniform(size=1000),
})
x = data[['var1','var2']]
y = 3 + data.var1 - .7 * data.var2 + rng.normal(loc=0, scale=1.3, size=1000)
with pm.Model() as model:
pm.glm.GLM.from_formula('y ~ x', data)
idata = pm.sample(3000, cores=2, return_inferencedata=True)
# -
idata
# We will now create `new_data_0` and `new_data_1` also as an xarray object to be able to take advantage of xarray's broadcasting capabilities. We can do this using `xr.DataArray` and passing a numpy array and a list with the dimension names. We are then able to add a `(2, 3000)` array with a `(5,)` and everything works automatically to generate the desired 3d array.
n = 5
new_data_0 = xr.DataArray(
rng.uniform(1, 1.5, size=n),
dims=["pred_id"]
)
new_data_1 = xr.DataArray(
rng.uniform(1, 1.5, size=n),
dims=["pred_id"]
)
pred_mean = (
idata.posterior["Intercept"] +
idata.posterior["x[0]"] * new_data_0 +
idata.posterior["x[1]"] * new_data_1
)
pred_mean.shape
predictions = xr.apply_ufunc(lambda mu, sd: rng.normal(mu, sd), pred_mean, idata.posterior["sd"])
# `xr.apply_ufunc` broadcasts and keeps the labels (dimensions and coord values) when using a numpy function on xarray objects.
az.plot_density((pred_mean, predictions), data_labels=("means", "predictions"));
|
pymc_discourse/linreg_predictions_xarray.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
# ---
# 1. [Cross Validation](#CrossValidation)
# * [Value-based join of two Matrices](#JoinMatrices)
# * [Filter Matrix to include only Frequent Column Values](#FilterMatrix)
# * [Construct (sparse) Matrix from (rowIndex, colIndex, values) triplets](#Construct_sparse_Matrix)
# * [Find and remove duplicates in columns or rows](#Find_and_remove_duplicates)
# * [Set based Indexing](#Set_based_Indexing)
# * [Group by Aggregate using Linear Algebra](#Multi_column_Sorting)
# * [Cumulative Summation with Decay Multiplier](#CumSum_Product)
# * [Invert Lower Triangular Matrix](#Invert_Lower_Triangular_Matrix)
# +
from systemml import MLContext, dml, jvm_stdout
ml = MLContext(sc)
print (ml.buildTime())
# -
# ## Cross Validation<a id="CrossValidation" />
# Perform kFold cross validation by running in parallel fold creation, training algorithm, test algorithm, and evaluation.
# +
prog = """
holdOut = 1/3
kFolds = 1/holdOut
nRows = 6; nCols = 3;
X = matrix(seq(1, nRows * nCols), rows = nRows, cols = nCols) # X data
y = matrix(seq(1, nRows), rows = nRows, cols = 1) # y label data
Xy = cbind (X,y) # Xy Data for CV
sv = rand (rows = nRows, cols = 1, min = 0.0, max = 1.0, pdf = "uniform") # sv selection vector for fold creation
sv = (order(target=sv, by=1, index.return=TRUE)) %% kFolds + 1 # with numbers between 1 .. kFolds
stats = matrix(0, rows=kFolds, cols=1) # stats per kFolds model on test data
parfor (i in 1:kFolds)
{
# Skip empty training data or test data.
if ( sum (sv == i) > 0 & sum (sv == i) < nrow(X) )
{
Xyi = removeEmpty(target = Xy, margin = "rows", select = (sv == i)) # Xyi fold, i.e. 1/k of rows (test data)
Xyni = removeEmpty(target = Xy, margin = "rows", select = (sv != i)) # Xyni data, i.e. (k-1)/k of rows (train data)
# Skip extreme label inbalance
distinctLabels = aggregate( target = Xyni[,1], groups = Xyni[,1], fn = "count")
if ( nrow(distinctLabels) > 1)
{
wi = trainAlg (Xyni[ ,1:ncol(Xy)-1], Xyni[ ,ncol(Xy)]) # wi Model for i-th training data
pi = testAlg (Xyi [ ,1:ncol(Xy)-1], wi) # pi Prediction for i-th test data
ei = evalPrediction (pi, Xyi[ ,ncol(Xy)]) # stats[i,] evaluation of prediction of i-th fold
stats[i,] = ei
print ( "Test data Xyi" + i + "\n" + toString(Xyi)
+ "\nTrain data Xyni" + i + "\n" + toString(Xyni)
+ "\nw" + i + "\n" + toString(wi)
+ "\nstats" + i + "\n" + toString(stats[i,])
+ "\n")
}
else
{
print ("Training data for fold " + i + " has only " + nrow(distinctLabels) + " distinct labels. Needs to be > 1.")
}
}
else
{
print ("Training data or test data for fold " + i + " is empty. Fold not validated.")
}
}
print ("SV selection vector:\n" + toString(sv))
trainAlg = function (matrix[double] X, matrix[double] y)
return (matrix[double] w)
{
w = t(X) %*% y
}
testAlg = function (matrix[double] X, matrix[double] w)
return (matrix[double] p)
{
p = X %*% w
}
evalPrediction = function (matrix[double] p, matrix[double] y)
return (matrix[double] e)
{
e = as.matrix(sum (p - y))
}
"""
with jvm_stdout(True):
ml.execute(dml(prog))
# -
# ## Value-based join of two Matrices<a id="JoinMatrices"/>
# Given matrix M1 and M2, join M1 on column 2 with M2 on column 2, and return matching rows of M1.
prog = """
M1 = matrix ('1 1 2 3 3 3 4 4 5 3 6 4 7 1 8 2 9 1', rows = 9, cols = 2)
M2 = matrix ('1 1 2 8 3 3 4 3 5 1', rows = 5, cols = 2)
I = rowSums (outer (M1[,2], t(M2[,2]), "==")) # I : indicator matrix for M1
M12 = removeEmpty (target = M1, margin = "rows", select = I) # apply filter to retrieve join result
print ("M1 \n" + toString(M1))
print ("M2 \n" + toString(M2))
print ("M1[,2] joined with M2[,2], and return matching M1 rows\n" + toString(M12))
"""
with jvm_stdout():
ml.execute(dml(prog))
# ## Filter Matrix to include only Frequent Column Values <a id="FilterMatrix"/>
# Given a matrix, filter the matrix to only include rows with column values that appear more often than MinFreq.
prog = """
MinFreq = 3 # minimum frequency of tokens
M = matrix ('1 1 2 3 3 3 4 4 5 3 6 4 7 1 8 2 9 1', rows = 9, cols = 2)
gM = aggregate (target = M[,2], groups = M[,2], fn = "count") # gM: group by and count (grouped matrix)
gv = cbind (seq(1,nrow(gM)), gM) # gv: add group values to counts (group values)
fg = removeEmpty (target = gv * (gv[,2] >= MinFreq), margin = "rows") # fg: filtered groups
I = rowSums (outer (M[,2] ,t(fg[,1]), "==")) # I : indicator of size M with filtered groups
fM = removeEmpty (target = M, margin = "rows", select = I) # FM: filter matrix
print (toString(M))
print (toString(fM))
"""
with jvm_stdout():
ml.execute(dml(prog))
# ## Construct (sparse) Matrix from (rowIndex, colIndex, values) triplets<a id="Construct_sparse_Matrix"></a>
# Given rowIndex, colIndex, and values as column vectors, construct (sparse) matrix.
prog = """
I = matrix ("1 3 3 4 5", rows = 5, cols = 1)
J = matrix ("2 3 4 1 6", rows = 5, cols = 1)
V = matrix ("10 20 30 40 50", rows = 5, cols = 1)
M = table (I, J, V)
print (toString (M))
"""
ml.execute(dml(prog).output('M')).get('M').toNumPy()
# ## Find and remove duplicates in columns or rows<a id="Find_and_remove_duplicates"></a>
# ### Assuming values are sorted.
prog = """
X = matrix ("1 2 3 3 3 4 5 10", rows = 8, cols = 1)
I = rbind (matrix (1,1,1), (X[1:nrow (X)-1,] != X[2:nrow (X),])); # compare current with next value
res = removeEmpty (target = X, margin = "rows", select = I); # select where different
"""
ml.execute(dml(prog).output('res')).get('res').toNumPy()
# ### No assumptions on values.
prog = """
X = matrix ("3 2 1 3 3 4 5 10", rows = 8, cols = 1)
I = aggregate (target = X, groups = X[,1], fn = "count") # group and count duplicates
res = removeEmpty (target = seq (1, max (X[,1])), margin = "rows", select = (I != 0)); # select groups
"""
ml.execute(dml(prog).output('res')).get('res').toNumPy()
# ### Order the values and then remove duplicates.
prog = """
X = matrix ("3 2 1 3 3 4 5 10", rows = 8, cols = 1)
X = order (target = X, by = 1) # order values
I = rbind (matrix (1,1,1), (X[1:nrow (X)-1,] != X[2:nrow (X),]));
res = removeEmpty (target = X, margin = "rows", select = I);
"""
ml.execute(dml(prog).output('res')).get('res').toNumPy()
# ## Set based Indexing<a id="Set_based_Indexing"></a>
# Given a matrix X, and a indicator matrix J with indices into X.
# Use J to perform operation on X, e.g. add value 10 to cells in X indicated by J.
prog = """
X = matrix (1, rows = 1, cols = 100)
J = matrix ("10 20 25 26 28 31 50 67 79", rows = 1, cols = 9)
res = X + table (matrix (1, rows = 1, cols = ncol (J)), J, 10)
print (toString (res))
"""
ml.execute(dml(prog).output('res')).get('res').toNumPy()
# ## Group by Aggregate using Linear Algebra<a id="Multi_column_Sorting"></a>
# Given a matrix PCV as (Position, Category, Value), sort PCV by category, and within each category by value in descending order. Create indicator vector for category changes, create distinct categories, and perform linear algebra operations.
# +
prog = """
C = matrix ('50 40 20 10 30 20 40 20 30', rows = 9, cols = 1) # category data
V = matrix ('20 11 49 33 94 29 48 74 57', rows = 9, cols = 1) # value data
PCV = cbind (cbind (seq (1, nrow (C), 1), C), V); # PCV representation
PCV = order (target = PCV, by = 3, decreasing = TRUE, index.return = FALSE);
PCV = order (target = PCV, by = 2, decreasing = FALSE, index.return = FALSE);
# Find all rows of PCV where the category has a new value, in comparison to the previous row
is_new_C = matrix (1, rows = 1, cols = 1);
if (nrow (C) > 1) {
is_new_C = rbind (is_new_C, (PCV [1:nrow(C) - 1, 2] < PCV [2:nrow(C), 2]));
}
# Associate each category with its index
index_C = cumsum (is_new_C); # cumsum
# For each category, compute:
# - the list of distinct categories
# - the maximum value for each category
# - 0-1 aggregation matrix that adds records of the same category
distinct_C = removeEmpty (target = PCV [, 2], margin = "rows", select = is_new_C);
max_V_per_C = removeEmpty (target = PCV [, 3], margin = "rows", select = is_new_C);
C_indicator = table (index_C, PCV [, 1], max (index_C), nrow (C)); # table
sum_V_per_C = C_indicator %*% V
"""
res = ml.execute(dml(prog).output('PCV','distinct_C', 'max_V_per_C', 'C_indicator', 'sum_V_per_C'))
print (res.get('PCV').toNumPy())
print (res.get('distinct_C').toNumPy())
print (res.get('max_V_per_C').toNumPy())
print (res.get('C_indicator').toNumPy())
print (res.get('sum_V_per_C').toNumPy())
# -
# ## Cumulative Summation with Decay Multiplier<a id="CumSum_Product"></a>
# Given matrix X, compute:
#
# Y[i] = X[i]
# + X[i-1] * C[i]
# + X[i-2] * C[i] * C[i-1]
# + X[i-3] * C[i] * C[i-1] * C[i-2]
# + ...
#
cumsum_prod_def = """
cumsum_prod = function (Matrix[double] X, Matrix[double] C, double start)
return (Matrix[double] Y)
# Computes the following recurrence in log-number of steps:
# Y [1, ] = X [1, ] + C [1, ] * start;
# Y [i+1, ] = X [i+1, ] + C [i+1, ] * Y [i, ]
{
Y = X; P = C; m = nrow(X); k = 1;
Y [1,] = Y [1,] + C [1,] * start;
while (k < m) {
Y [k + 1:m,] = Y [k + 1:m,] + Y [1:m - k,] * P [k + 1:m,];
P [k + 1:m,] = P [1:m - k,] * P [k + 1:m,];
k = 2 * k;
}
}
"""
# In this example we use cumsum_prod for cumulative summation with "breaks", that is, multiple cumulative summations in one.
prog = cumsum_prod_def + """
X = matrix ("1 2 3 4 5 6 7 8 9", rows = 9, cols = 1);
#Zeros in C cause "breaks" that restart the cumulative summation from 0
C = matrix ("0 1 1 0 1 1 1 0 1", rows = 9, cols = 1);
Y = cumsum_prod (X, C, 0);
print (toString(Y))
"""
with jvm_stdout():
ml.execute(dml(prog))
# In this example, we copy selected rows downward to all consecutive non-selected rows.
prog = cumsum_prod_def + """
X = matrix ("1 2 3 4 5 6 7 8 9", rows = 9, cols = 1);
# Ones in S represent selected rows to be copied, zeros represent non-selected rows
S = matrix ("1 0 0 1 0 0 0 1 0", rows = 9, cols = 1);
Y = cumsum_prod (X * S, 1 - S, 0);
print (toString(Y))
"""
with jvm_stdout():
ml.execute(dml(prog))
# This is a naive implementation of cumulative summation with decay multiplier.
cumsum_prod_naive_def = """
cumsum_prod_naive = function (Matrix[double] X, Matrix[double] C, double start)
return (Matrix[double] Y)
{
Y = matrix (0, rows = nrow(X), cols = ncol(X));
Y [1,] = X [1,] + C [1,] * start;
for (i in 2:nrow(X))
{
Y [i,] = X [i,] + C [i,] * Y [i - 1,]
}
}
"""
# There is a significant performance difference between the <b>naive</b> implementation and the <b>tricky</b> implementation.
prog = cumsum_prod_def + cumsum_prod_naive_def + """
X = rand (rows = 20000, cols = 10, min = 0, max = 1, pdf = "uniform", sparsity = 1.0);
C = rand (rows = 20000, cols = 10, min = 0, max = 1, pdf = "uniform", sparsity = 1.0);
Y1 = cumsum_prod_naive (X, C, 0.123);
"""
with jvm_stdout():
ml.execute(dml(prog))
prog = cumsum_prod_def + cumsum_prod_naive_def + """
X = rand (rows = 20000, cols = 10, min = 0, max = 1, pdf = "uniform", sparsity = 1.0);
C = rand (rows = 20000, cols = 10, min = 0, max = 1, pdf = "uniform", sparsity = 1.0);
Y2 = cumsum_prod (X, C, 0.123);
"""
with jvm_stdout():
ml.execute(dml(prog))
# ## Invert Lower Triangular Matrix<a id="Invert_Lower_Triangular_Matrix"></a>
# In this example, we invert a lower triangular matrix using a the following divide-and-conquer approach. Given lower triangular matrix L, we compute its inverse X which is also lower triangular by splitting both matrices in the middle into 4 blocks (in a 2x2 fashion), and multiplying them together to get the identity matrix:
#
# \begin{equation}
# L \text{ %*% } X = \left(\begin{matrix} L_1 & 0 \\ L_2 & L_3 \end{matrix}\right)
# \text{ %*% } \left(\begin{matrix} X_1 & 0 \\ X_2 & X_3 \end{matrix}\right)
# = \left(\begin{matrix} L_1 X_1 & 0 \\ L_2 X_1 + L_3 X_2 & L_3 X_3 \end{matrix}\right)
# = \left(\begin{matrix} I & 0 \\ 0 & I \end{matrix}\right)
# \nonumber
# \end{equation}
#
# If we multiply blockwise, we get three equations:
#
# $
# \begin{equation}
# L1 \text{ %*% } X1 = 1\\
# L3 \text{ %*% } X3 = 1\\
# L2 \text{ %*% } X1 + L3 \text{ %*% } X2 = 0\\
# \end{equation}
# $
#
# Solving these equation gives the following formulas for X:
#
# $
# \begin{equation}
# X1 = inv(L1) \\
# X3 = inv(L3) \\
# X2 = - X3 \text{ %*% } L2 \text{ %*% } X1 \\
# \end{equation}
# $
#
# If we already recursively inverted L1 and L3, we can invert L2. This suggests an algorithm that starts at the diagonal and iterates away from the diagonal, involving bigger and bigger blocks (of size 1, 2, 4, 8, etc.) There is a logarithmic number of steps, and inside each step, the inversions can be performed in parallel using a parfor-loop.
#
# Function "invert_lower_triangular" occurs within more general inverse operations and matrix decompositions. The divide-and-conquer idea allows to derive more efficient algorithms for other matrix decompositions.
#
invert_lower_triangular_def = """
invert_lower_triangular = function (Matrix[double] LI)
return (Matrix[double] LO)
{
n = nrow (LI);
LO = matrix (0, rows = n, cols = n);
LO = LO + diag (1 / diag (LI));
k = 1;
while (k < n)
{
LPF = matrix (0, rows = n, cols = n);
parfor (p in 0:((n - 1) / (2 * k)), check = 0)
{
i = 2 * k * p;
j = i + k;
q = min (n, j + k);
if (j + 1 <= q) {
L1 = LO [i + 1:j, i + 1:j];
L2 = LI [j + 1:q, i + 1:j];
L3 = LO [j + 1:q, j + 1:q];
LPF [j + 1:q, i + 1:j] = -L3 %*% L2 %*% L1;
}
}
LO = LO + LPF;
k = 2 * k;
}
}
"""
prog = invert_lower_triangular_def + """
n = 1000;
A = rand (rows = n, cols = n, min = -1, max = 1, pdf = "uniform", sparsity = 1.0);
Mask = cumsum (diag (matrix (1, rows = n, cols = 1)));
L = (A %*% t(A)) * Mask; # Generate L for stability of the inverse
X = invert_lower_triangular (L);
print ("Maximum difference between X %*% L and Identity = " + max (abs (X %*% L - diag (matrix (1, rows = n, cols = 1)))));
"""
with jvm_stdout():
ml.execute(dml(prog))
# This is a naive implementation of inverting a lower triangular matrix.
invert_lower_triangular_naive_def = """
invert_lower_triangular_naive = function (Matrix[double] LI)
return (Matrix[double] LO)
{
n = nrow (LI);
LO = diag (matrix (1, rows = n, cols = 1));
for (i in 1:n - 1)
{
LO [i,] = LO [i,] / LI [i, i];
LO [i + 1:n,] = LO [i + 1:n,] - LI [i + 1:n, i] %*% LO [i,];
}
LO [n,] = LO [n,] / LI [n, n];
}
"""
# The naive implementation is significantly slower than the divide-and-conquer implementation.
prog = invert_lower_triangular_naive_def + """
n = 1000;
A = rand (rows = n, cols = n, min = -1, max = 1, pdf = "uniform", sparsity = 1.0);
Mask = cumsum (diag (matrix (1, rows = n, cols = 1)));
L = (A %*% t(A)) * Mask; # Generate L for stability of the inverse
X = invert_lower_triangular_naive (L);
print ("Maximum difference between X %*% L and Identity = " + max (abs (X %*% L - diag (matrix (1, rows = n, cols = 1)))));
"""
with jvm_stdout():
ml.execute(dml(prog))
|
samples/jupyter-notebooks/DML Tips and Tricks (aka Fun With DML).ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [default]
# language: python
# name: python3
# ---
# # Example 1: Preprocessing Workflow
#
# This is meant as a very simple example for a preprocessing workflow. In this workflow we will conduct the following steps:
#
# 1. Motion correction of functional images with FSL's MCFLIRT
# 2. Coregistration of functional images to anatomical images (according to FSL's FEAT pipeline)
# 3. Smoothing of coregistrated functional images with FWHM set to 4mm and 8mm
# 4. Artifact Detection in functional images (to detect outlier volumes)
# ## Preparation
#
# Before we can start with anything we first need to download the data (the other 9 subjects in the dataset). This can be done very quickly with the following `datalad` command.
#
# **Note:** This might take a while, as datalad needs to download ~700MB of data
# + language="bash"
# datalad get -J4 /data/ds000114/derivatives/fmriprep/sub-*/anat/*preproc.nii.gz \
# /data/ds000114/sub-*/ses-test/func/*fingerfootlips*
# -
# ## Inspect the data
#
# For every subject we have one anatomical T1w and 5 functional images. As a short recap, the image properties of the anatomy and the **fingerfootlips** functional image are:
# + language="bash"
# cd /data/ds000114/
# nib-ls derivatives/fmriprep/sub-01/*/*t1w_preproc.nii.gz sub-01/ses-test/f*/*fingerfootlips*.nii.gz
# -
# **So, let's start!**
# ## Imports
#
# First, let's import all modules we later will be needing.
# %matplotlib inline
from os.path import join as opj
import os
import json
from nipype.interfaces.fsl import (BET, ExtractROI, FAST, FLIRT, ImageMaths,
MCFLIRT, SliceTimer, Threshold)
from nipype.interfaces.spm import Smooth
from nipype.interfaces.utility import IdentityInterface
from nipype.interfaces.io import SelectFiles, DataSink
from nipype.algorithms.rapidart import ArtifactDetect
from nipype import Workflow, Node
# ## Experiment parameters
#
# It's always a good idea to specify all parameters that might change between experiments at the beginning of your script. We will use one functional image for fingerfootlips task for ten subjects.
# +
experiment_dir = '/output'
output_dir = 'datasink'
working_dir = 'workingdir'
# list of subject identifiers
subject_list = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
# list of session identifiers
task_list = ['fingerfootlips']
# Smoothing widths to apply
fwhm = [4, 8]
# TR of functional images
with open('/data/ds000114/task-fingerfootlips_bold.json', 'rt') as fp:
task_info = json.load(fp)
TR = task_info['RepetitionTime']
# Isometric resample of functional images to voxel size (in mm)
iso_size = 4
# -
# ## Specify Nodes for the main workflow
#
# Initiate all the different interfaces (represented as nodes) that you want to use in your workflow.
# +
# ExtractROI - skip dummy scans
extract = Node(ExtractROI(t_min=4, t_size=-1, output_type='NIFTI'),
name="extract")
# MCFLIRT - motion correction
mcflirt = Node(MCFLIRT(mean_vol=True,
save_plots=True,
output_type='NIFTI'),
name="mcflirt")
# SliceTimer - correct for slice wise acquisition
slicetimer = Node(SliceTimer(index_dir=False,
interleaved=True,
output_type='NIFTI',
time_repetition=TR),
name="slicetimer")
# Smooth - image smoothing
smooth = Node(Smooth(), name="smooth")
smooth.iterables = ("fwhm", fwhm)
# Artifact Detection - determines outliers in functional images
art = Node(ArtifactDetect(norm_threshold=2,
zintensity_threshold=3,
mask_type='spm_global',
parameter_source='FSL',
use_differences=[True, False],
plot_type='svg'),
name="art")
# -
# ## Coregistration Workflow
#
# Initiate a workflow that coregistrates the functional images to the anatomical image (according to FSL's FEAT pipeline).
# +
# BET - Skullstrip anatomical Image
bet_anat = Node(BET(frac=0.5,
robust=True,
output_type='NIFTI_GZ'),
name="bet_anat")
# FAST - Image Segmentation
segmentation = Node(FAST(output_type='NIFTI_GZ'),
name="segmentation")
# Select WM segmentation file from segmentation output
def get_wm(files):
return files[-1]
# Threshold - Threshold WM probability image
threshold = Node(Threshold(thresh=0.5,
args='-bin',
output_type='NIFTI_GZ'),
name="threshold")
# FLIRT - pre-alignment of functional images to anatomical images
coreg_pre = Node(FLIRT(dof=6, output_type='NIFTI_GZ'),
name="coreg_pre")
# FLIRT - coregistration of functional images to anatomical images with BBR
coreg_bbr = Node(FLIRT(dof=6,
cost='bbr',
schedule=opj(os.getenv('FSLDIR'),
'etc/flirtsch/bbr.sch'),
output_type='NIFTI_GZ'),
name="coreg_bbr")
# Apply coregistration warp to functional images
applywarp = Node(FLIRT(interp='spline',
apply_isoxfm=iso_size,
output_type='NIFTI'),
name="applywarp")
# Apply coregistration warp to mean file
applywarp_mean = Node(FLIRT(interp='spline',
apply_isoxfm=iso_size,
output_type='NIFTI_GZ'),
name="applywarp_mean")
# Create a coregistration workflow
coregwf = Workflow(name='coregwf')
coregwf.base_dir = opj(experiment_dir, working_dir)
# Connect all components of the coregistration workflow
coregwf.connect([(bet_anat, segmentation, [('out_file', 'in_files')]),
(segmentation, threshold, [(('partial_volume_files', get_wm),
'in_file')]),
(bet_anat, coreg_pre, [('out_file', 'reference')]),
(threshold, coreg_bbr, [('out_file', 'wm_seg')]),
(coreg_pre, coreg_bbr, [('out_matrix_file', 'in_matrix_file')]),
(coreg_bbr, applywarp, [('out_matrix_file', 'in_matrix_file')]),
(bet_anat, applywarp, [('out_file', 'reference')]),
(coreg_bbr, applywarp_mean, [('out_matrix_file', 'in_matrix_file')]),
(bet_anat, applywarp_mean, [('out_file', 'reference')]),
])
# -
# ## Specify input & output stream
#
# Specify where the input data can be found & where and how to save the output data.
# +
# Infosource - a function free node to iterate over the list of subject names
infosource = Node(IdentityInterface(fields=['subject_id', 'task_name']),
name="infosource")
infosource.iterables = [('subject_id', subject_list),
('task_name', task_list)]
# SelectFiles - to grab the data (alternativ to DataGrabber)
anat_file = opj('derivatives', 'fmriprep', 'sub-{subject_id}', 'anat', 'sub-{subject_id}_t1w_preproc.nii.gz')
func_file = opj('sub-{subject_id}', 'ses-test', 'func',
'sub-{subject_id}_ses-test_task-{task_name}_bold.nii.gz')
templates = {'anat': anat_file,
'func': func_file}
selectfiles = Node(SelectFiles(templates,
base_directory='/data/ds000114'),
name="selectfiles")
# Datasink - creates output folder for important outputs
datasink = Node(DataSink(base_directory=experiment_dir,
container=output_dir),
name="datasink")
## Use the following DataSink output substitutions
substitutions = [('_subject_id_', 'sub-'),
('_task_name_', '/task-'),
('_fwhm_', 'fwhm-'),
('_roi', ''),
('_mcf', ''),
('_st', ''),
('_flirt', ''),
('.nii_mean_reg', '_mean'),
('.nii.par', '.par'),
]
subjFolders = [('fwhm-%s/' % f, 'fwhm-%s_' % f) for f in fwhm]
substitutions.extend(subjFolders)
datasink.inputs.substitutions = substitutions
# -
# ## Specify Workflow
#
# Create a workflow and connect the interface nodes and the I/O stream to each other.
# +
# Create a preprocessing workflow
preproc = Workflow(name='preproc')
preproc.base_dir = opj(experiment_dir, working_dir)
# Connect all components of the preprocessing workflow
preproc.connect([(infosource, selectfiles, [('subject_id', 'subject_id'),
('task_name', 'task_name')]),
(selectfiles, extract, [('func', 'in_file')]),
(extract, mcflirt, [('roi_file', 'in_file')]),
(mcflirt, slicetimer, [('out_file', 'in_file')]),
(selectfiles, coregwf, [('anat', 'bet_anat.in_file'),
('anat', 'coreg_bbr.reference')]),
(mcflirt, coregwf, [('mean_img', 'coreg_pre.in_file'),
('mean_img', 'coreg_bbr.in_file'),
('mean_img', 'applywarp_mean.in_file')]),
(slicetimer, coregwf, [('slice_time_corrected_file', 'applywarp.in_file')]),
(coregwf, smooth, [('applywarp.out_file', 'in_files')]),
(mcflirt, datasink, [('par_file', 'preproc.@par')]),
(smooth, datasink, [('smoothed_files', 'preproc.@smooth')]),
(coregwf, datasink, [('applywarp_mean.out_file', 'preproc.@mean')]),
(coregwf, art, [('applywarp.out_file', 'realigned_files')]),
(mcflirt, art, [('par_file', 'realignment_parameters')]),
(coregwf, datasink, [('coreg_bbr.out_matrix_file', 'preproc.@mat_file'),
('bet_anat.out_file', 'preproc.@brain')]),
(art, datasink, [('outlier_files', 'preproc.@outlier_files'),
('plot_files', 'preproc.@plot_files')]),
])
# -
# ## Visualize the workflow
#
# It always helps to visualize your workflow.
# +
# Create preproc output graph
preproc.write_graph(graph2use='colored', format='png', simple_form=True)
# Visualize the graph
from IPython.display import Image
Image(filename=opj(preproc.base_dir, 'preproc', 'graph.png'))
# -
# Visualize the detailed graph
preproc.write_graph(graph2use='flat', format='png', simple_form=True)
Image(filename=opj(preproc.base_dir, 'preproc', 'graph_detailed.png'))
# ## Run the Workflow
#
# Now that everything is ready, we can run the preprocessing workflow. Change ``n_procs`` to the number of jobs/cores you want to use. **Note** that if you're using a Docker container and FLIRT fails to run without any good reason, you might need to change memory settings in the Docker preferences (6 GB should be enough for this workflow).
preproc.run('MultiProc', plugin_args={'n_procs': 8})
# ## Inspect output
#
# Let's check the structure of the output folder, to see if we have everything we wanted to save.
# !tree /output/datasink/preproc
# ## Visualize results
#
# Let's check the effect of the different smoothing kernels.
from nilearn import image, plotting
out_path = '/output/datasink/preproc/sub-01/task-fingerfootlips'
plotting.plot_epi(
'/data/ds000114/derivatives/fmriprep/sub-01/anat/sub-01_t1w_preproc.nii.gz',
title="T1", display_mode='ortho', annotate=False, draw_cross=False, cmap='gray');
plotting.plot_epi(opj(out_path, 'sub-01_ses-test_task-fingerfootlips_bold_mean.nii.gz'),
title="fwhm = 0mm", display_mode='ortho', annotate=False, draw_cross=False, cmap='gray');
plotting.plot_epi(image.mean_img(opj(out_path, 'fwhm-4_ssub-01_ses-test_task-fingerfootlips_bold.nii')),
title="fwhm = 4mm", display_mode='ortho', annotate=False, draw_cross=False, cmap='gray');
plotting.plot_epi(image.mean_img(opj(out_path, 'fwhm-8_ssub-01_ses-test_task-fingerfootlips_bold.nii')),
title="fwhm = 8mm", display_mode='ortho', annotate=False, draw_cross=False, cmap='gray');
# Now, let's investigate the motion parameters. How much did the subject move and turn in the scanner?
import numpy as np
import matplotlib.pyplot as plt
par = np.loadtxt('/output/datasink/preproc/sub-01/task-fingerfootlips/sub-01_ses-test_task-fingerfootlips_bold.par')
fig, axes = plt.subplots(2, 1, figsize=(15, 5))
axes[0].set_ylabel('rotation (radians)')
axes[0].plot(par[0:, :3])
axes[1].plot(par[0:, 3:])
axes[1].set_xlabel('time (TR)')
axes[1].set_ylabel('translation (mm)');
# There seems to be a rather drastic motion around volume 102. Let's check if the outliers detection algorithm was able to pick this up.
# +
import numpy as np
outlier_ids = np.loadtxt('/output/datasink/preproc/sub-01/task-fingerfootlips/art.sub-01_ses-test_task-fingerfootlips_bold_outliers.txt')
print('Outliers were detected at volumes: %s' % outlier_ids)
from IPython.display import SVG
SVG(filename='/output/datasink/preproc/sub-01/task-fingerfootlips/plot.sub-01_ses-test_task-fingerfootlips_bold.svg')
|
notebooks/example_preprocessing.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (Ubuntu Linux)
# language: python
# metadata:
# cocalc:
# description: Python 3 programming language
# priority: 100
# url: https://www.python.org/
# name: python3
# ---
# Member 3 Tear-out Resistance - E.Durham - 10-Jun-2019
# Case: Determine CSA S157-05 (R2015) 192.168.3.11 Tear-out of bolt and rivet groups (block shear) for M20 Bolts in RT3x2x0.25 6061-T6 Extruded Aluminum Tube. This is tension member in 1.5m Wall Bracket in Modified Case 2 configuration.
from pint import UnitRegistry
unit = UnitRegistry()
# Define symbols for common units
m = unit.meter; mm = unit.millimeter; inch = unit.inch;
kN = unit.kilonewton; MPa = unit.megapascal; psi = unit.psi
# +
# Case parameters
d_fastener = 20*mm # M20 bolt
d_side = 1*inch; d_side.ito(mm)
d_end_tension = 1.25*inch; d_end_tension.ito(mm)
d_end_compression = 800*mm - d_end_tension
d_end = d_end_tension # this case
n_fasteners = 1 # number of fasteners
d_fasteners = 0*mm # distance between fasteners
t = 0.25*inch; t.ito(mm) # thickness of tube wall
# Material Properties of 6061-T6 Extruded Aluminum from Table 2 of S157-05
F_u = 260*MPa # Ultimate Strength of Base Metal from Table 2 of S157-05 (R2015)
# F_u = 262*MPa # Ultimate Strength of Base Metal from ADM2015
F_y = 240*MPa # Yield Strength of Base Metal
F_wy = 110*MPa # Yield Strength of welded heat-affected-zone
E = 70000*MPa # Elastic Modulus from S157-05 4.3(b)
# Resistance Factors CSA S157-05 (R2015) 5.5
phi_y = 0.9 # tension, compression, and shear in beams: on yield
phi_c = 0.9 # compression in columns: on collapse due to buckling
phi_u = 0.75 # tension and shear in beams: on ultimate
phi_u = 0.75 # tension on a net section, bearing stress, tear-out: on ultimate
phi_u = 0.75 # tension and compression on butt welds: on ultimate
phi_f = 0.67 # shear stress on fillet welds: on ultimate
phi_f = 0.67 # tension and shear stress on fasteners: on ultimate
# +
# Check Fastener Spacing Clause 192.168.127.12
# centres not less than 1.25d from edge parallel to direction of loading
# nor less than 1.5d from end edges towards which the load is directed
# Distance between fasteners not less than 2.5d
# where
# d is fastener diameter
#
if (d_side < 1.25*d_fastener):
print('Minimum edge distance parallel to direction of loading is: ',
1.25*d_fastener)
print('Actual distance to parallel edge is: ', d_side)
print('Therefore, NG for distance to parallel edge.\n')
else:
print('Distance to edge parallel to loading is: ', d_side)
print('This is greater than the required minimum of: ', 1.25*d_fastener)
print('Therefore, OK for distance to parallel edge. \n')
if (d_end < 1.5*d_fastener):
print('Minimum edge distance perpendicular to direction of loading is: ',
1.5*d_fastener)
print('Actual distance to perpendicular edge is: ', d_end)
print('Therefore, NG for distance to perdendicular edge.\n')
else:
print('Distance to edge parallel to loading is: ', d_end)
print('This is greater than the required minimum of: ', 1.5*d_fastener)
print('Therefore, OK for distance to perpendicular edge.\n')
if (n_fasteners > 1):
if (d_fasteners < 2.5*d_fastener):
print('Distance between fasteners is: ', d_fasteners)
print('Minimum distance required between fasteners is: ', 2.5*d_fastener)
print('Therefore, NG for distance between fasteners')
else:
print('Distance between fasteners is: ', d_fasteners)
print('Minimum distance required between fasteners is: ', 2.5*d_fastener)
print('Therefore, OK for distance between fasteners')
else:
print('Number of fasteners is less than 2.')
print('Therefore, minimum spacing between fasteners does not apply')
# -
# Check Bearing strength per CSA S157-05 (R2015) 11.2.4.1
B_ra = phi_u*d_end*t*F_u
B_ra.ito(kN)
B_rb = phi_u*2*d_fastener*t*F_u
B_rb.ito(kN)
B_r = min(B_ra, B_rb)
print('Bearing resistance is: ', B_r)
# The tube has 2 sides or walls. Therefore, the bearing resistance of the Member is:
2*B_r
# Check Tear-out (Block Shear) per CSA S157-05 (R2015) 192.168.3.11
m = 1 # number of fasteners in the first transverse row
g = 0*mm # fastener spacing measured perpendicular to direction of the force
d_o = 21.43*mm # hole diameter
n = 1 # number of transverse rows of fasteners
s = 0*mm # fastener spacing in direction of force
e = d_end # edge distance in the direction of force for the first row
# but not less than 1.5d; e = 2d when e > 2d
N = 1 # total number of fasteners
d = d_fastener # fastener diameter
R_ba = phi_u*((m-1)*(g-d_o)+(n-1)*(s-d_o)+e)*t*F_u
R_ba.ito(kN)
R_bb = phi_u*2*N*d*t*F_u
R_bb.ito(kN)
R_b = min(R_ba, R_bb)
print('Tear-out Resistance is: ', R_b)
# The tube has 2 sides or walls. Therefore, the tear-out resistance of the Member is:
2*R_b
# 11.2.4.1 Bearing Strength
# The factored bearing resistance, $B_r$, of the connected material for each loaded fastener shall be the lesser of the values given by the following formulas:
# (a) $B_r = \phi_u e t F_u$; and
# (b) $B_r = \phi_u 2 d t F_u$
#
# where
# $\phi_u$ = ultimate resistance factor
# $e$ = perpendicular distance from the hole centre to the end edge in the direction of the loading (not less than 1.5d)
# $t$ = plate thickness
# $F_u$ = ultimate strength of the connected material
# $d$ = fastener diameter
|
Aluminum/RT_3x2x0.25/Member_3_Tear-out_Resistance.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Autoencoder for Anomaly Detection with scikit-learn, Keras and TensorFlow
#
# This script trains an autoencoder for anomaly detection. We use Python, scikit-learn, TensorFlow and Keras to prepare the data and train the model.
#
# The input data is sensor data. Here is one example:
#
# "Time","V1","V2","V3","V4","V5","V6","V7","V8","V9","V10","V11","V12","V13","V14","V15","V16","V17","V18","V19","V20","V21","V22","V23","V24","V25","V26","V27","V28","Amount","Class"
#
# 0,-1.3598071336738,-0.0727811733098497,2.53634673796914,1.37815522427443,-0.338320769942518,0.462387777762292,0.239598554061257,0.0986979012610507,0.363786969611213,0.0907941719789316,-0.551599533260813,-0.617800855762348,-0.991389847235408,-0.311169353699879,1.46817697209427,-0.470400525259478,0.207971241929242,0.0257905801985591,0.403992960255733,0.251412098239705,-0.018306777944153,0.277837575558899,-0.110473910188767,0.0669280749146731,0.128539358273528,-0.189114843888824,0.133558376740387,-0.0210530534538215,149.62,"0"
#
# The autoencoder compresses the data and tries to reconstruct it. The reconstruction error finds anomalies.
#
# This Jupyter notebook was tested with Python 3.6.7, Numpy 1.16.4, scikit-learn 0.20.1 and tensorflow 2.0.0-alpha0.
#
# Kudos to <NAME> who created the foundation for this example: https://www.datascience.com/blog/fraud-detection-with-tensorflow
# # TODOs:
#
# Replace CSV data import with TF IO Kafka plugin...
#
# Open question: What are the steps to do this?
# (most of below code is for visualisation, not for training => Focus of this Notebook should be model ingestion and training - the visualisation is nice to have but can be neglected)
#
#
# ### Code to change?
# This is the key line:
# df = pd.read_csv("../../data/sensor_data.csv")
#
# => Needs to be replaced with something like:
# kafka_sensordata = kafka_io.KafkaDataset(['sensor-topic'], group='xx', eof=True)
#
# => Then we can build the Keras model and do training with the KafkaDataSet as parameter:
#
# model = tf.keras.Sequential([...])
# model.compile(optimizer='adam',
# loss='sparse_categorical_crossentropy',
# metrics=['accuracy'])
#
# model.fit(kafka_sensordata, epochs=1, steps_per_epoch=1000, callbacks=[tensorboard_callback])
#
# ### Optional: Visualization
#
# Optional (if easy to do): convert kafka input data into pandas dataframe (optional, just for visualisation)
#
# df = kafka_sensordata.???convertToPandasDataframe???
#
#
#
#
# import packages
# matplotlib inline
import pandas as pd
import numpy as np
from scipy import stats
import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, precision_recall_curve
from sklearn.metrics import recall_score, classification_report, auc, roc_curve
from sklearn.metrics import precision_recall_fscore_support, f1_score
from sklearn.preprocessing import StandardScaler
from pylab import rcParams
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard
from tensorflow.keras import regularizers
#check TensorFlow verson: 1.x or 2.0?
print(tf.__version__)
# +
#set random seed and percentage of test data
RANDOM_SEED = 314 #used to help randomly select the data points
TEST_PCT = 0.2 # 20% of the data
#set up graphic style in this case I am using the color scheme from xkcd.com
rcParams['figure.figsize'] = 14, 8.7 # Golden Mean
LABELS = ["Normal","Fraud"]
#col_list = ["cerulean","scarlet"]# https://xkcd.com/color/rgb/
#sns.set(style='white', font_scale=1.75, palette=sns.xkcd_palette(col_list))
# -
df = pd.read_csv("../../data/sensor_data.csv") #unzip and read in data downloaded to the local directory
df.head(n=5) #just to check you imported the dataset properly
df.shape #secondary check on the size of the dataframe
df.isnull().values.any() #check to see if any values are null, which there are not
pd.value_counts(df['Class'], sort = True) #class comparison 0=Normal 1=Fraud
#if you don't have an intuitive sense of how imbalanced these two classes are, let's go visual
count_classes = pd.value_counts(df['Class'], sort = True)
count_classes.plot(kind = 'bar', rot=0)
plt.xticks(range(2), LABELS)
plt.title("Frequency by observation number")
plt.xlabel("Class")
plt.ylabel("Number of Observations");
normal_df = df[df.Class == 0] #save normal_df observations into a separate df
fraud_df = df[df.Class == 1] #do the same for frauds
normal_df.Amount.describe()
fraud_df.Amount.describe()
#plot of high value transactions
bins = np.linspace(200, 2500, 100)
plt.hist(normal_df.Amount, bins, alpha=1, normed=True, label='Normal')
plt.hist(fraud_df.Amount, bins, alpha=0.6, normed=True, label='Fraud')
plt.legend(loc='upper right')
plt.title("Amount by percentage of transactions (transactions \$200+)")
plt.xlabel("Transaction amount (USD)")
plt.ylabel("Percentage of transactions (%)");
plt.show()
bins = np.linspace(0, 48, 48) #48 hours
plt.hist((normal_df.Time/(60*60)), bins, alpha=1, normed=True, label='Normal')
plt.hist((fraud_df.Time/(60*60)), bins, alpha=0.6, normed=True, label='Fraud')
plt.legend(loc='upper right')
plt.title("Percentage of transactions by hour")
plt.xlabel("Transaction time as measured from first transaction in the dataset (hours)")
plt.ylabel("Percentage of transactions (%)");
#plt.hist((df.Time/(60*60)),bins)
plt.show()
plt.scatter((normal_df.Time/(60*60)), normal_df.Amount, alpha=0.6, label='Normal')
plt.scatter((fraud_df.Time/(60*60)), fraud_df.Amount, alpha=0.9, label='Fraud')
plt.title("Amount of transaction by hour")
plt.xlabel("Transaction time as measured from first transaction in the dataset (hours)")
plt.ylabel('Amount (USD)')
plt.legend(loc='upper right')
plt.show()
#data = df.drop(['Time'], axis=1) #if you think the var is unimportant
df_norm = df
df_norm['Time'] = StandardScaler().fit_transform(df_norm['Time'].values.reshape(-1, 1))
df_norm['Amount'] = StandardScaler().fit_transform(df_norm['Amount'].values.reshape(-1, 1))
# +
train_x, test_x = train_test_split(df_norm, test_size=TEST_PCT, random_state=RANDOM_SEED)
train_x = train_x[train_x.Class == 0] #where normal transactions
train_x = train_x.drop(['Class'], axis=1) #drop the class column (as Autoencoder is unsupervised and does not need / use labels for training)
# test_x (without class) for validation; test_y (with Class) for prediction + calculating MSE / reconstruction error
test_y = test_x['Class'] #save the class column for the test set
test_x = test_x.drop(['Class'], axis=1) #drop the class column
train_x = train_x.values #transform to ndarray
test_x = test_x.values
# -
train_x.shape
# +
# Reduce number of epochs and batch_size if your Jupyter crashes (due to memory issues)
# or if you just want to demo and not run it for so long.
# nb_epoch = 100 instead of 5
# batch_size = 128 instead of 32
nb_epoch = 5
batch_size = 32
# Autoencoder: 30 => 14 => 7 => 7 => 14 => 30 dimensions
input_dim = train_x.shape[1] #num of columns, 30
encoding_dim = 14
hidden_dim = int(encoding_dim / 2) #i.e. 7
learning_rate = 1e-7
# Dense = fully connected layer
input_layer = Input(shape=(input_dim, ))
# First parameter is output units (14 then 7 then 7 then 30) :
encoder = Dense(encoding_dim, activation="tanh", activity_regularizer=regularizers.l1(learning_rate))(input_layer)
encoder = Dense(hidden_dim, activation="relu")(encoder)
decoder = Dense(hidden_dim, activation='tanh')(encoder)
decoder = Dense(input_dim, activation='relu')(decoder)
autoencoder = Model(inputs=input_layer, outputs=decoder)
# +
autoencoder.compile(metrics=['accuracy'],
loss='mean_squared_error',
optimizer='adam')
cp = ModelCheckpoint(filepath="../../models/autoencoder_sensor_anomaly_detection_fully_trained_100_epochs.h5",
save_best_only=True,
verbose=0)
tb = TensorBoard(log_dir='./logs',
histogram_freq=0,
write_graph=True,
write_images=True)
history = autoencoder.fit(train_x, train_x, # Autoencoder => Input == Output dimensions!
epochs=nb_epoch,
batch_size=batch_size,
shuffle=True,
validation_data=(test_x, test_x), # Autoencoder => Input == Output dimensions!
verbose=1,
callbacks=[cp, tb]).history
# +
autoencoder = load_model('../../models/autoencoder_sensor_anomaly_detection.h5')
# -
plt.plot(history['loss'], linewidth=2, label='Train')
plt.plot(history['val_loss'], linewidth=2, label='Test')
plt.legend(loc='upper right')
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
#plt.ylim(ymin=0.70,ymax=1)
plt.show()
test_x_predictions = autoencoder.predict(test_x)
mse = np.mean(np.power(test_x - test_x_predictions, 2), axis=1)
error_df = pd.DataFrame({'Reconstruction_error': mse,
'True_class': test_y})
error_df.describe()
# +
false_pos_rate, true_pos_rate, thresholds = roc_curve(error_df.True_class, error_df.Reconstruction_error)
roc_auc = auc(false_pos_rate, true_pos_rate,)
plt.plot(false_pos_rate, true_pos_rate, linewidth=5, label='AUC = %0.3f'% roc_auc)
plt.plot([0,1],[0,1], linewidth=5)
plt.xlim([-0.01, 1])
plt.ylim([0, 1.01])
plt.legend(loc='lower right')
plt.title('Receiver operating characteristic curve (ROC)')
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()
# -
precision_rt, recall_rt, threshold_rt = precision_recall_curve(error_df.True_class, error_df.Reconstruction_error)
plt.plot(recall_rt, precision_rt, linewidth=5, label='Precision-Recall curve')
plt.title('Recall vs Precision')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.show()
plt.plot(threshold_rt, precision_rt[1:], label="Precision",linewidth=5)
plt.plot(threshold_rt, recall_rt[1:], label="Recall",linewidth=5)
plt.title('Precision and recall for different threshold values')
plt.xlabel('Threshold')
plt.ylabel('Precision/Recall')
plt.legend()
plt.show()
# +
threshold_fixed = 5
groups = error_df.groupby('True_class')
fig, ax = plt.subplots()
for name, group in groups:
ax.plot(group.index, group.Reconstruction_error, marker='o', ms=3.5, linestyle='',
label= "Fraud" if name == 1 else "Normal")
ax.hlines(threshold_fixed, ax.get_xlim()[0], ax.get_xlim()[1], colors="r", zorder=100, label='Threshold')
ax.legend()
plt.title("Reconstruction error for different classes")
plt.ylabel("Reconstruction error")
plt.xlabel("Data point index")
plt.show();
# +
pred_y = [1 if e > threshold_fixed else 0 for e in error_df.Reconstruction_error.values]
conf_matrix = confusion_matrix(error_df.True_class, pred_y)
plt.figure(figsize=(12, 12))
sns.heatmap(conf_matrix, xticklabels=LABELS, yticklabels=LABELS, annot=True, fmt="d");
plt.title("Confusion matrix")
plt.ylabel('True class')
plt.xlabel('Predicted class')
plt.show()
# -
|
python-scripts/autoencoder-anomaly-detection/Python-Tensorflow-2.0-Kafka-Streaming-Ingestion-Keras-Fraud-Detection-Autoencoder.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .jl
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Julia 1.3.0-alpha.26
# language: julia
# name: julia-1.3
# ---
# Load Julia packages (libraries) needed for the snippets in chapter 0
using StatisticalRethinking, CmdStan, LinearAlgebra
#gr(size=(600,600));
# CmdStan uses a tmp directory to store the output of cmdstan
ProjDir = rel_path("..", "scripts", "04")
cd(ProjDir)
# ### snippet 4.7
howell1 = CSV.read(rel_path("..", "data", "Howell1.csv"), delim=';')
df = convert(DataFrame, howell1);
# Use only adults
df2 = filter(row -> row[:age] >= 18, df);
first(df2, 5)
# Use data from m4.1s
# Check if the m4.1s.jls file is present. If not, run the model.
# +
!isfile(joinpath(ProjDir, "m4.1s.jls")) && include(joinpath(ProjDir, "m4.1s.jl"))
chn = deserialize(joinpath(ProjDir, "m4.1s.jls"))
# -
# Describe the draws
MCMCChains.describe(chn)
# Plot the density of posterior draws
density(chn, lab="All heights", xlab="height [cm]", ylab="density")
# Compute cor
mu_sigma = hcat(chn.value[:, 2, 1], chn.value[:,1, 1])
LinearAlgebra.diag(cov(mu_sigma))
# Compute cov
cor(mu_sigma)
# End of `clip_07.0s.jl`
# *This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
|
notebooks/04/clip-30s.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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 pylab as plt
# %matplotlib inline
# ## Define the covariance functions
# Constants
alpha = 1
gamma = 0.1
# standard RBF
def covyy(x1,x2):
return alpha*np.exp(-0.5*gamma*(x1-x2)**2)
# covariance between function and gradient
def covdy(x1,x2):
return -gamma*(x1-x2)*covyy(x1,x2)
def covdd(x1,x2):
return covyy(x1,x2)*gamma*(1 - gamma*(x1-x2)**2)
# define some training points
N = 10
trainx = np.linspace(-1,1,N)
C = np.zeros((N,N))
for n in range(N):
for m in range(N):
C[n,m] = covyy(trainx[n],trainx[m])
noise_ss = 0.1
C += noise_ss*np.eye(N)
plt.imshow(C,aspect='auto')
zero_mean = np.zeros((N))
f = np.random.multivariate_normal(zero_mean,C)
plt.plot(trainx,f,'ko')
# ## Predict the function
testN = 100
testx = np.linspace(-1,2,testN)
testC = np.zeros((testN,N))
testCC = np.zeros((testN,testN))
for n in range(testN):
for m in range(N):
testC[n,m] = covyy(testx[n],trainx[m])
for m in range(testN):
testCC[n,m] = covyy(testx[n],testx[m])
# +
# predictive mean
postMu = np.dot(np.dot(testC,np.linalg.inv(C)),f)
postCov = testCC - np.dot(np.dot(testC,np.linalg.inv(C)),testC.T)
m = postMu
upper = postMu+3*np.sqrt(np.diag(postCov))
lower = postMu-3*np.sqrt(np.diag(postCov))
plt.figure()
plt.plot(testx,upper,'k--')
plt.plot(testx,lower,'k--')
ax = plt.gca()
ax.fill_between(testx,upper,lower,color = [0.9,0.9,0.9])
plt.plot(testx,m,'r')
plt.plot(trainx,f,'ko')
plt.title("Function estimates")
# -
# ## Predict the gradients
testCg = np.zeros((testN,N))
testCCg = np.zeros((testN,testN))
for n in range(testN):
for m in range(N):
testCg[n,m] = covdy(testx[n],trainx[m])
for m in range(testN):
testCCg[n,m] = covdd(testx[n],testx[m])
# +
postMu = np.dot(np.dot(testCg,np.linalg.inv(C)),f)
postCov = testCCg - np.dot(np.dot(testCg,np.linalg.inv(C)),testCg.T)
m = postMu
upper = postMu+3*np.sqrt(np.diag(postCov))
lower = postMu-3*np.sqrt(np.diag(postCov))
plt.figure()
plt.plot(testx,upper,'k--')
plt.plot(testx,lower,'k--')
ax = plt.gca()
ax.fill_between(testx,upper,lower,color = [0.9,0.9,0.9])
plt.plot(testx,m,'r')
plt.title('Gradient estimates')
# -
# compute the probability of a positive gradient
from scipy.stats import norm
prob_pos = 1 - norm.cdf(0,postMu,np.sqrt(np.diag(postCov)))
plt.figure()
plt.plot(testx,prob_pos)
plt.title("Probability of +ve gradient")
# ## Try with a ROI
# +
import os,sys
qcb_root = '/Users/simon/University of Glasgow/Vinny Davies - CLDS Metabolomics Project/TopNvsTopNroi/QCB/'
mzml_QCB_TopN = os.path.join(qcb_root,'from_controller_TopN_QCB.mzML')
mzml_QCB_TopN_Roi = os.path.join(qcb_root,'from_controller_ROI_QCB.mzML')
mzml_QCB_fullscan = os.path.join(qcb_root,'QCB_22May19_1.mzML')
sys.path.append('/Users/simon/git/vimms')
# -
from vimms.Roi import make_roi
good,bad = make_roi(mzml_QCB_fullscan)
example_roi = good[909] # 3
print(len(example_roi.mz_list))
plt.plot(example_roi.rt_list,example_roi.intensity_list,'ro')
totalN = len(example_roi.mz_list)
# +
N = 5 # window width - needs to be odd
testN = 20
pos_probs = []
for i in range(int(np.floor(N/2))):
pos_probs.append(0.5)
plots = False
mid_point = int(np.floor(testN/2))
for i,start_pos in enumerate(range(0,totalN - N + 1)):
if i == 0:
plots = True
else:
plots = False
trainx = np.array(example_roi.rt_list[start_pos:start_pos + N])
testx = np.linspace(trainx[0],trainx[-1],testN)
C = np.zeros((N,N))
for n in range(N):
for m in range(N):
C[n,m] = covyy(trainx[n],trainx[m])
noise_ss = 0.1
C += noise_ss*np.eye(N)
f = np.array(np.log(example_roi.intensity_list[start_pos:start_pos + N]))
f -= f.mean()
f /= f.std()
testC = np.zeros((testN,N))
testCC = np.zeros((testN,testN))
for n in range(testN):
for m in range(N):
testC[n,m] = covyy(testx[n],trainx[m])
for m in range(testN):
testCC[n,m] = covyy(testx[n],testx[m])
postMu = np.dot(np.dot(testC,np.linalg.inv(C)),f)
postCov = testCC - np.dot(np.dot(testC,np.linalg.inv(C)),testC.T)
m = postMu
upper = postMu+3*np.sqrt(np.diag(postCov))
lower = postMu-3*np.sqrt(np.diag(postCov))
if plots:
plt.figure(figsize=(4,10))
plt.subplot(3,1,1)
plt.plot(testx,upper,'k--')
plt.plot(testx,lower,'k--')
ax = plt.gca()
ax.fill_between(testx,upper,lower,color = [0.9,0.9,0.9])
plt.plot(testx,m,'r')
plt.plot(trainx,f,'ko')
plt.title("Function estimates")
plt.plot([testx[mid_point],testx[mid_point]],plt.ylim(),'k--')
testCg = np.zeros((testN,N))
testCCg = np.zeros((testN,testN))
for n in range(testN):
for m in range(N):
testCg[n,m] = covdy(testx[n],trainx[m])
for m in range(testN):
testCCg[n,m] = covdd(testx[n],testx[m])
postMu = np.dot(np.dot(testCg,np.linalg.inv(C)),f)
postCov = testCCg - np.dot(np.dot(testCg,np.linalg.inv(C)),testCg.T)
m = postMu
upper = postMu+3*np.sqrt(np.diag(postCov))
lower = postMu-3*np.sqrt(np.diag(postCov))
if plots:
plt.subplot(3,1,2)
plt.plot(testx,upper,'k--')
plt.plot(testx,lower,'k--')
ax = plt.gca()
ax.fill_between(testx,upper,lower,color = [0.9,0.9,0.9])
plt.plot(testx,m,'r')
plt.plot(testx,np.zeros_like(testx),'b--')
plt.title('Gradient estimates')
plt.plot([testx[mid_point],testx[mid_point]],plt.ylim(),'k--')
prob_pos = 1 - norm.cdf(0,postMu,np.sqrt(np.diag(postCov)))
if plots:
plt.subplot(3,1,3)
plt.plot(testx,prob_pos)
plt.plot([testx[mid_point],testx[mid_point]],plt.ylim(),'k--')
pos_probs.append(prob_pos[mid_point])
print(prob_pos[mid_point])
for i in range(int(np.floor(N/2))):
pos_probs.append(0.5)
plt.savefig('individual.png')
# +
fig, ax1 = plt.subplots()
ax1.set_xlabel('time (s)')
ax1.set_ylabel('Intensity', color='r')
ax1.plot(example_roi.rt_list, np.log(example_roi.intensity_list), 'ro')
ax1.tick_params(axis='y', labelcolor='r')
ax2 = ax1.twinx()
ax2.plot(example_roi.rt_list,pos_probs,'b.-',alpha = 0.5)
ax2.tick_params(axis='y', labelcolor='b')
ax2.set_ylabel('Probability of +ve grad', color='b')
ax2.set_ylim([0,1])
plt.savefig('grad_example.png')
# -
|
experimental/GradientEstimatesForPeaks.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [conda env:python3]
# language: python
# name: conda-env-python3-py
# ---
# ### Loading up required libraries and configurations
# +
import quandl
import pandas_datareader.data as web
import datetime
import pandas as pd
import sklearn
import numpy as np
from collections import defaultdict
from IPython.display import display
import scipy as sp
from operator import methodcaller
import time
# evaluate usage
pd.options.mode.chained_assignment = None # default='warn'
# -
""""
usage of this API key is monitored
please don't use this key for any other work, neither make it available on the web by any means
if you would like to access the same API for a different project,
please create an account in quandl.com (it is free) and generate your own API key
"""
quandl.ApiConfig.api_key = "<KEY>"
# ### Getting the data
# #### Stock data
# For the stock market general data, we will use Yahoo API, which contains reliable free access data for a number of stock markets, including Bovespa.
def get_stock_data(symbol='PETR4.SA', start_date, end_date):
df = web.DataReader(symbol, 'yahoo', start_date, end_date)
return df
df = get_stock_data(start_date = '1998-1-1', end_date = '2014-12-31')
# #### General Market Data
# For the general market data, there is excelent data made available by Banco Central do Brasil (brazilian central bank). The data is available through a webservice, but there is a neat API quandl which makes it easier to access this same data. With a free profile we have limited access, but it is enough for the following tests.
#
# There are over 1,300 different indicators available, from different time periods including daily, weekly, monthly, yearly, etc. At the moment we will stick with 10 relevant indicators which are available daily, and then move on to add more data as we see fit.
# +
daily = {
'Selic': 'BCB/432',
'Exchange Rate USD Sell': 'BCB/1',
'Exchange Rate USD Buy': 'BCB/10813',
'BM&F Gold gramme': 'BCB/4',
'Bovespa total volume': 'BCB/8',
'International Reserves': 'BCB/13621',
'Bovespa index': 'BCB/7',
'Foreign exchange operations balance': 'BCB/13961',
'Nasdaq index': 'BCB/7810',
'Dow Jones index': 'BCB/7809'
}
## removed montly indicators for now - to be added later
# monthly = {
# 'IPCA-E': 'BCB/10764',
# 'IGP-M': 'BCB/7451',
# 'IPCA-15': 'BCB/74/78',
# 'Net public debt': 'BCB/4473'
# }
# -
def get_market_data(input_df, start_date, end_date):
df = input_df.copy()
for var, code in daily.items():
df = pd.concat([df, quandl.get(code, start_date=start_date , end_date=end_date)], join='inner', axis=1)
df = df.rename(columns={'Value': var})
return df
df = get_market_data(df, start_date = '1998-1-1', end_date = '2014-12-31')
# #### Trend indicators
# The trend indicators are borrowed from the field known as technical analysis, or graphism, that aims to find patterns by analyzing the trend of price and volume.
#
# We will start with the most known: Moving Averages (indicator: MACD, moving average convergence divergence), Momentum, Daily Returns,
# Already included in the dataset
# * Momentum: momentum is nothing but the current price, divided by the price X days earlier. The momentum is already included the dataset when we analyse the trend for Adj Close and all other variables
# * Daily Return: it is the same as the momentum, but for one day before.
# To include:
# * Moving Average: moving average for X days. important to understand longer term trends
# * Bollinger Bands: 95% confidence interval for the moving averages.
# * CandleStick
# * <NAME>
# * Volume/Price
# moving average and bollinger bands
def get_tech_indicators(input_df):
df = input_df.copy()
for n in range(10,61,10):
df['sma'+str(n)] = df['Adj Close'].rolling(window=n, center=False).mean()
std =df['Adj Close'].rolling(window=n, center=False).std()
df['bb_lower'+str(n)] = df['sma'+str(n)] - (2 * std)
df['bb_upper'+str(n)] = df['sma'+str(n)] + (2 * std)
return df
df = get_tech_indicators(df)
# ### Creating the labels
# The general approach to the stock market problem is to use non-linear regressors to predict future prices. Although it is easy to predict the price for the day ahead, as you move days further the r2_score sinks and the prediction becomes useless.
# The inovative approach we will follow here is meant to treat this problem as a classification problem. In order to treat this problem as a classifier, we will pre-define a trading strategy, backtest it to the full dataset, and define the label to be whether this trading strategy results in a successful trade or not.
# ##### Swing Trade
# The first and most simple analysis is a swing trade strategy. We will buy the stock, and hold it for n days. If it reaches an upper boundary (+x%), we sell. If it reaches a lower boundary (-y%), we will also short our position.
#
# So the challenge is within the next n days the stock needs to reach the upper boundary, before it reaches the lower boundary. That will be counted as a successful trade. If it reaches the lower boundary before, or n days passes without reaching the upper boundary, the trading is considered a failure.
#
# The name swing trade means we are speculating on the week/bi-week pattern, the swing, not necessarily on the longer term trend.
#
# The parameters n, x, and y, will be optimized through a genetic algorithm to achieve the optimal trading strategy for this setup.
def create_labels(input_df, forward=19, profit_margin=.042, stop_loss=.020):
df = input_df.copy()
for row in range(df.shape[0]-forward):
# initialize max and min ticks
max_uptick = 0
min_downtick = 0
# move all days forward
for i in range(1,forward+1):
delta = (df.ix[row+i, 'Adj Close'] / df.ix[row, 'Adj Close'])-1
if delta > max_uptick:
max_uptick = delta
if delta < min_downtick:
min_downtick = delta
# evaluate ticks against predefined strategy parameters
if max_uptick >= profit_margin and min_downtick <= -stop_loss:
df.ix[row,'Label'] = 1
else:
df.ix[row,'Label'] = 0
return df.dropna()
df = create_labels(df)
# ### Rounding up the features
# Now we've got the main data, and the label, let's start creating our features. There is also some innovation going on here, we are running from the traditional approach of stock price prediction.
# The first and foremost difference is that instead of analyzing the raw data, I want to analyze the trend for each variable. So in a single day I will look at how the variable increased or decreased in the last N days.
# To center at 0, for each variable I will calculate (value / value in n-1). The number of days I will look back may also vary, and it will also depend on the trading strategy to follow. But for simplicity we will start with a round number such as 60 days for the swing trading strategy of around 10 days.
def create_features(input_df, base = 60):
""" Receives a dataframe as input
Returns a new dataframe with ratios calculated
"""
# avoid modifying in place
df = input_df.copy()
# get all columns ubt the label
cols = list(df.columns)
if 'Label' in cols:
cols.remove('Label')
# create the new columns for the number of days
for n in range(1,base+1):
new_cols = list(map(lambda x: "{}-{}".format(x,n), cols))
df[new_cols] = (df.loc[:, cols] / df.shift(n).loc[:, cols]) - 1
# remove inf and drop na
df.replace([np.inf, -np.inf], np.nan, inplace=True)
df.dropna(axis=0, inplace=True)
# leave or remove original columns? for now I will leave them
#return df.drop(cols, axis=1)
return df
df = create_features(df)
df.shape
# ### Understanding the label and features
# Let's start by analizying the label distribution. This will tell us a lot about the dataset, which optimal classifier to choose, and whether we will need to use a stratified approach when splitting the dataset for testing or cross-validation.
# break up X and y arrays, convert to numpy array
def split_features_labels(df):
features = [x for x in df.columns if x != "Label"]
X = df[features].values
y = df['Label'].values
return X, y
X,y = split_features_labels(df)
X.shape, y.shape
np.bincount(y.astype(int)) / len(y)
# As expected, there will be only a few occurrences where such a trading strategy results in success. Only 6,25% of the observations have label 1(success), while 93,75% have label 0 (failure). A stratified approach will be required when splitting the dataset later.
# Next step is to take a look at the features we have. I will start standardizing to z-score, then checking and removing outliers, and finally analyse which features are most relevant and attempt to extract principal components.
# For now, I will keep working with the full data, since I'm looking for understanding data, I'm doing predictions at this point. I will come back later to this point to divide the dataset
# scaling
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X = scaler.fit_transform(X)
# feature selection
from sklearn.feature_selection import SelectKBest
f_selector = SelectKBest()
f_selector.fit(X, y)
sorted(zip(features, f_selector.scores_, f_selector.pvalues_), key=lambda x: -x[1])
# Strangely enough, it shows an incredible high importance for International Reserves features, as well for other features related to the outside market, such as Nasdaq, and Exchange Rate.
#
# Petrobras, the company being analyzed, is very influenced by the price and availability of USD in brazilian market. It is debts are most in dollar and the price of its main product, oil, is set globally. So these findings that my be accurate, just random noise, or due to some mistake in the data preprocessing
#
# Will come back later to this point if this correlation is not confirmed with other analysis.
# +
# pca conversion
# okay, I've got all these data points
from sklearn.decomposition import PCA
pca = PCA(n_components = 32)
pca.fit(X)
sum(pca.explained_variance_ratio_)
# why 32? I'm aiming at 80% explained variance, with the minimum number of components
# I just tried a few and got to the required number of components
# this could also be optimized later, aimed at performance
# -
X_transformed = pca.transform(X)
# Okay, now we've transformed into fewer principal components, thus helping to avoid the curse of dimensionality, let's take a step back and see which are the main variables impacting each of the first components. Are they the same variables which stand out in the Anova F-value tests conducted before?
# checking the variables with most impact on the first component
i = np.identity(len(features)) # identity matrix
coef = pca.transform(i)
sorted(zip(features, coef[:, 1]), key=lambda x:-x[1])
# The results hardly show something relevant. The coefficientes between the features are very similar for the first principal component
# I will try feature selection again, with the components
from sklearn.feature_selection import f_classif
f_selector = SelectKBest(f_classif)
f_selector.fit(X_transformed,y)
sorted(zip(f_selector.scores_, f_selector.pvalues_), key=lambda x: -x[0])
# The p values for the Anova F-value test, all above 0.5, tell a worrisome story. None has a verifiable correlation with the label. Nevertheless, let's push forward and see how good a prediction we can make with this data
# ### Predicting
# Let's move on to prediction and see which results we can get with the work that is already done.
#
# A previous work was done using several classifiers, and Gradient Boosting was the most promising. It is a model that can fit well complex models, and is one of the top perfomer algorithms used in the wide. Let's start with it and check the results
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.ensemble import GradientBoostingClassifier as GBC
from sklearn.neighbors import KNeighborsClassifier as kNN
from sklearn.model_selection import cross_val_score
import warnings; warnings.filterwarnings("ignore")
# define cross validation strategy
cv = StratifiedShuffleSplit(n_splits=10, test_size=.1, random_state=42)
# initiate, train and evaluate classifier
clf = GBC(random_state=42)
scores = cross_val_score(clf, X, y, cv=cv, scoring='precision')
print("Precision: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
# same, with kNN
clf = kNN()
scores = cross_val_score(clf, X, y, cv=cv, scoring='precision')
print("Precision: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
# 40% is a reasonable precision, considering it is a highly skewed dataset, with only 6,25% of the observations with label 'Succeess'. But still a lot of variation - with a 95% confidence interval, the precision can be as low as .17. Let's check with the principal components, to see if we can get better results.
#
# I will try with different number of components
# components = [20,50,100,150,200,300,400,len(features)]
components = [10,20,50,100, 200, 300]
for n in components:
# pca
pca = PCA(n_components = n, random_state=42)
X_transformed = pca.fit_transform(X)
# predict
clf = GBC(random_state=42)
scores = cross_val_score(clf, X_transformed, y, cv=cv, scoring='precision')
print("Precision {} components: {:0.2f} (+/- {:0.2f})".format(
n, scores.mean(), scores.std() * 2))
# same, with knn
components = [10, 20, 50, 100, 200, 300]
for n in components:
# pca
pca = PCA(n_components = n, random_state=42)
X_transformed = pca.fit_transform(X)
# predict
clf = kNN()
scores = cross_val_score(clf, X_transformed, y, cv=cv, scoring='precision')
print("Precision {} components: {:0.2f} (+/- {:0.2f})".format(
n, scores.mean(), scores.std() * 2))
# The results with the principal components doesn't seem any better. I've also tried with 20 folds in the cross validation to reduce the margin of error, and between 100 to 200 components I get a precision of around .38 and a margin of error of around .5, which too high.
# ### Optimizing parameters
# I see I got a 75% precision with a GBC, considering a time span of 19 days, a profit margin of 4.2% and a stop loss of 2.0%. If I can play this strategy consistently, it means profit.
#
# Well, let's test this strategy. Let's begin by testing the classifier in a new test_dataset and see if we get the same results
## Steps to generate df:
# 1. get stock data
df_test = get_stock_data(symbol='PETR4.SA', start_date = '2014-7-1', end_date = '2016-12-31')
print(df_test.shape)
# 2. get market data
df_test = get_market_data(df_test, start_date = '2014-7-1', end_date = '2016-12-31')
print(df_test.shape)
# 3. get stock indicators
df_test = get_tech_indicators(df_test)
print(df_test.shape)
# 4. create features
df_test = create_features(df_test, base=60)
print(df_test.shape)
# 5. create labels
df_test = create_labels(df_test)
print(df_test.shape)
# 6. split features and labels
X_test, y_test = split_features_labels(df_test)
# 7. scale features
X_test = StandardScaler().fit_transform(X_test)
np.bincount(y_test.astype(int)) / len(y_test)
# test classifier on new dataset
from sklearn.metrics import precision_score
clf = GBC(random_state=42)
clf.fit(X, y)
y_pred = clf.predict(X_test)
precision = precision_score(y_test, y_pred)
print("Precision: {:0.2f}".format(precision))
# We were able to replicate that precision in the test dataset, with a 0.62 precision. Let's use this classifier to simulate a trading strategy in this period, using only this stock.
#
# We will follow the exact same strategy defined to create the label: buy the stock, hold it for up 19 days; short the position if the asset valuates 4.2% or devaluate 2.0%.
# +
#start_date='2015-01-01'
#end_date='2015-12-31'
#rng = pd.date_range(start=start_date, end=end_date, freq='D')
#df_test.loc['2015-01-02', 'Adj Close']
# +
class Operation():
def __init__(self, price, qty, start_date, span, end_date=None):
self.price = price
self.qty = qty
self.start_date = start_date
self.end_date = end_date
self.days_left = span
def close(self, end_date, sell_price):
self.end_date = end_date
self.gain_loss = (sell_price / self.price) -1
def report(self):
print("Start: {}, End: {}, Gain_loss: {:.2f}%, R$ {:.2f}".format(
self.start_date, self.end_date, self.gain_loss*100, self.price*self.qty*self.gain_loss))
class Operator():
def __init__(self, data, clf, strategy, capital=0, start_date='2015-01-01', end_date='2015-12-31'):
self.data = data.copy()
self.clf = clf
self.capital = capital
self.stocks = 0.0
self.period = pd.date_range(start=start_date, end=end_date, freq='D')
self.operations = []
self.strategy = strategy
def run(self):
for day in self.period:
# needs to be a working day
if day in self.data.index:
# check if there any open operations that needs to be closed
self.check_operations(day)
# try to predict
label = clf.predict(self.data.loc[day].drop('Label', axis=0))
if label:
print(day)
if self.capital > 0:
self.buy(day)
def check_operations(self, day):
for operation in self.operations:
span, profit, loss = self.strategy
if not operation.end_date:
# remove one more day
operation.days_left -= 1
# calc valuation
valuation = (self.data.loc[day, 'Adj Close'] / operation.price)-1
# sell if it reaches the target or the ends the number of days
if valuation >= profit or valuation <= loss or operation.days_left<=0:
self.sell(day, operation)
def buy(self, day):
span, _, _ = self.strategy
price = self.data.loc[day, 'Adj Close']
qty = self.capital / price
# update stocks and capital
self.stocks += qty
self.capital = 0
# open operation
self.operations.append(Operation(price = price, qty = qty, start_date = day, span=span))
def sell(self, day, operation):
price = self.data.loc[day, 'Adj Close']
# update stocks and capital
self.capital += self.stocks * price
print(self.capital)
self.stocks = 0
# close operation
operation.close(day, price)
# -
op = Operator(df_test, clf, (19, .042, -.020), capital=100000, start_date='2015-01-01', end_date='2015-12-31')
op.run()
op.capital
for operation in op.operations:
operation.report()
# +
# I need a lot more signals in order for this idea to work
# But I feel I'm on the right track
# No high and lows involved
# -
# ### Optimizing parameters with genetic algorithm
# Well, next step is to change my strategy. In the swing trade strategy, if I set number of days 10, profit margin(x) to 5% and stop loss(y) to 5%, I have to be right at least 51% of the times to actually win some money. That is not the case, as my current precision lower boundary is 17%.
#
# But I might have a better chance identifying a different variation of this strategy. So as discussed before, let's try to optimize these 3 parameters: n, x and y. We will use a genetic algorithm which will use precision score from the cross validation function as its own scoring function, to determine which variation will perpetuate.
# In order to that, we will organize the code to create the dataset into classes and modules, along with the Genetic Algoritm, in the attached files stock.py and strategies.py, and import them to the notebook.
# +
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
class Backtester():
def __init__(self, df):
self.df = df
def create_labels(self, forward=10, profit_margin=.05, stop_loss=.05):
for row in range(self.df.shape[0]-forward):
# initialize max and min ticks
max_uptick = 0
min_downtick = 0
# move all days forward
for i in range(1,forward+1):
delta = (self.df.ix[row+i, 'Adj Close'] / self.df.ix[row, 'Adj Close'])-1
if delta > max_uptick:
max_uptick = delta
if delta < min_downtick:
min_downtick = delta
# evaluate ticks against predefined strategy parameters
if max_uptick >= profit_margin and min_downtick <= -stop_loss:
self.df.ix[row,'Label'] = 1
else:
self.df.ix[row,'Label'] = 0
self.df.dropna(inplace=True)
def prep_data(self):
features = [x for x in self.df.columns if x != "Label"]
X = self.df[features].values
y = self.df['Label'].values
return X,y
def score(self, X, y):
# apply PCA
pca = PCA(n_components = 10, random_state=42)
X_transformed = pca.fit_transform(X)
#predict
clf = GBC(random_state=42)
cv = StratifiedShuffleSplit(n_splits=10, test_size=.1, random_state=42)
scores = cross_val_score(clf, X_transformed, y, cv=cv, scoring='precision')
# return score
return (scores.mean())
def evaluate(self, forward, profit_margin, stop_loss):
self.create_labels(forward=forward, profit_margin=profit_margin, stop_loss=stop_loss)
score = self.score(*self.prep_data())
print("span: {}, profit_margin: {:.3f}, stop_loss: {:.3f} -- score: {:.3f}".format(
forward, profit_margin, stop_loss, score))
return score
# +
class Strategy():
def __init__(self, span = 7, profit_margin = .06, stop_loss = .04):
self.span = span
self.profit_margin = profit_margin
self.stop_loss = stop_loss
self.mutations = [
self.increase_span,
self.decrease_span,
self.increase_stop_loss,
self.decrease_stop_loss,
self.increase_profit_margin,
self.decrease_profit_margin
]
def mutate(self):
np.random.choice(self.mutations)()
def inform_params(self):
return self.span, self.profit_margin, self.stop_loss
def report(self):
print("span: {}, profit_margin: {:.3f}, stop_loss: {:.3f}".format(
self.span, self.profit_margin, self.stop_loss))
# add a random component to mutation
# allow 'wild' mutations
def increase_span(self):
self.span += 2
def decrease_span(self):
self.span -= 2
def increase_profit_margin(self):
self.profit_margin = self.profit_margin * 1.3
def decrease_profit_margin(self):
self.profit_margin = self.profit_margin * .7
def increase_stop_loss(self):
self.stop_loss = self.stop_loss * 1.3
def decrease_stop_loss(self):
self.stop_loss = self.stop_loss * .7
class GA():
def __init__(self, df):
""" Seed 2 initial strategies and an instance of backtester """
self.backtester = Backtester(df.copy())
self.strategies = pd.DataFrame(np.zeros((2,2)), columns = ['strat', 'score'])
self.strategies['strat'] = self.strategies['strat'].apply(lambda x:Strategy())
self.strategies['score'] = self.strategies['strat'].apply(self.evaluate)
def fit(self, cycles):
""" Run evolution for n cycles """
i = 0
while i < cycles:
self.reproduce()
# self.select()
i += 1
def best_strategy(self):
""" Sort and return top perform in available strategies """
self.strategies = self.strategies.sort_values(by='score', ascending=False)
self.strategies.iloc[0, 0].report()
print("score: {:.4f}".format(self.strategies.iloc[0, 1]))
def evaluate(self, strat):
""" To implement:
Should evaluate only for those which value is zero, to avoid the cost of re-evaluating
"""
return self.backtester.evaluate(*strat.inform_params())
def reproduce(self):
""" Create new strategy based on its parents. """
# sort and take top two performers in the list
parents = self.strategies.sort_values(by='score', ascending=False).iloc[:2, 0]
# create six offsprings
for _ in range(6):
stratN = self.crossover(*parents)
stratN.mutate()
# setting with enlargement using index based selection (not available for position based)
self.strategies.ix[self.strategies.shape[0]] = (stratN, self.evaluate(stratN))
# remove identical offspring, there is no use
def crossover(self, stratA, stratB):
""" Choose between parents attributes randomly. Return new strategy """
span = np.random.choice([stratA.span, stratB.span])
stop_loss = np.random.choice([stratA.stop_loss, stratB.stop_loss])
profit_margin = np.random.choice([stratA.profit_margin, stratB.profit_margin])
return Strategy(span=span, stop_loss=stop_loss, profit_margin=profit_margin)
def select(self):
""" Remove strategies which are bad performers
Define bad as 50 percent worst than best """
# define cut off score as 50% of the max score
cut_off = self.strategies['score'].max() * .75
# remove strategies with scores below the cut-off
self.strategies = self.strategies[self.strategies['score'] >= cut_off]
# +
# ga = GA(df)
# ga.fit(20)
# ga.best_strategy()
# -
# GA is not helping too much. I will leave this as an option to optimize in the end, but for now, I will go back to the basics.
#
# I went in the PCA line. Let's try feature selecting and see what results we can get
# ### Feature Selection
# How many features is the optimal number?
# Which classifier should I use?
# Which parameter can I get?
X.mean(), y.mean()
X_test.mean(), y_test.mean()
# ### Removed Code
|
ENIAC-experiments/v-previous/quandl-v3.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] tags=[]
# # MHKiT River Module
#
# The following example will familiarize the user with the [MHKIT river module](https://mhkit-software.github.io/MHKiT/mhkit-python/api.river.html) by stepping through the calculation of annual energy produced for one turbine in the Tanana River near Nenana, Alaska. The data file used in this example is retrieved from the USGS website, a local version of the data is stored in the [\\\\MHKiT\\\\examples\\\\data](https://github.com/MHKiT-Software/MHKiT-Python/tree/master/examples/data) directory.
#
# Start by importing the necessary python packages and MHKiT module.
# -
import pandas as pd
from mhkit import river
#
# ## Test
#
# ## Importing Data from USGS
#
# We will start by requesting daily discharge data from the USGS website for the Tanana River near Nenana, Alaska. The function `request_usgs_data` in the river IO module returns a Pandas DataFrame. The function requires the station number, parameter number, timeframe, and type of data.
#
# The station number can be found on the USGS website, though this is more difficult than searching the web for "USGS Tanana near Nenana" which should return a link to https://waterdata.usgs.gov/nwis/inventory/?site_no=15515500. This page contains an overview of the available data, including daily discharge data.
#
# The IEC standard recommends 10 years of daily discharge data for calculations of annual energy produced (AEP). The timeframe shows that at least 10 years of data is available. Clicking on the "Daily Data" will bring up a page that would allow the user to request data from the site. Each of the "Available Parameters" has a 5 digit code in front of it which will depend on the data type and reported units. The user at this point could use the website to download the data, however, the `request_usgs_data` function is used here.
# +
# Use the requests method to obtain 10 years of daily discharge data
data = river.io.usgs.request_usgs_data(station="15515500",
parameter='00060',
start_date='2009-08-01',
end_date='2019-08-01',
data_type='Daily')
# Print data
print(data)
# -
# The `request_usgs_data` function returned a pandas DataFrame indexed by time. For this example, the column name "Discharge, cubic feet per second" is long and therefore is renamed to "Q". Furthermore, MHKiT expects all units to be in SI so the discharge values is converted to $m^3/s$. Finally, we can plot the discharge time series.
# +
# Store the original DataFrame column name
column_name = data.columns[0]
# Rename to a shorter key name e.g. 'Q'
data = data.rename(columns={column_name: 'Q'})
# Convert to discharge data from ft3/s to m3/s
data.Q = data.Q / (3.28084)**3
# Plot the daily discharge
ax = river.graphics.plot_discharge_timeseries(data.Q)
# -
# ## Flow Duration Curve
#
# The flow duration curve (FDC) is a plot of discharge versus exceedance probability which quantifies the percentage of time that the discharge in a river exceeds a particular magnitude. The curve is typically compiled on a monthly or annual basis.
#
# The exceedance probability for the highest discharge is close to 0% since that value is rarely exceeded. Conversely, the lowest discharge is found closer to 100% as they are most often exceeded.
# +
# Calculate exceedence probability
data['F'] = river.resource.exceedance_probability(data.Q)
# Plot the flow duration curve (FDC)
ax = river.graphics.plot_flow_duration_curve(data.Q, data.F)
# -
# ## Velocity Duration Curve
#
# At each river energy converter location we must provide a curve that relates the velocity at the turbine location to the river discharge levels. IEC 301 recommends using at least 15 different discharges and that only velocities within the turbine operating conditions need to be included.
#
# Here we only provide 6 different discharge to velocities relationships created using a hydrological model. The data is loaded into a pandas DataFrame using the pandas method `read_csv`.
# +
# Load discharge to velocity curve at turbine location
DV_curve = pd.read_csv('data/river/tanana_DV_curve.csv')
# Create a polynomial fit of order 2 from the discharge to velocity curve.
# Return the polynomial fit and and R squared value
p, r_squared = river.resource.polynomial_fit(DV_curve.D, DV_curve.V, 2)
# Plot the polynomial curve
river.graphics.plot_discharge_vs_velocity(DV_curve.D, DV_curve.V, polynomial_coeff=p)
# Print R squared value
print(r_squared)
# -
# The IEC standard recommends a polynomial fit of order 3. By changing the order above and replotting the polynomial fit to the curve data it can be seen this is not a good fit for the provided data. Therefore the order was set to 2.
#
# Next, we calculate velocity for each discharge using the polynomial and plot the VDC.
# +
# Use polynomial fit from DV curve to calculate velocity ('V') from discharge at turbine location
data['V'] = river.resource.discharge_to_velocity(data.Q, p)
# Plot the velocity duration curve (VDC)
ax = river.graphics.plot_velocity_duration_curve(data.V, data.F )
# -
# ## Power Duration Curve
# The power duration curve is created in a nearly identical manner to the VDC. Here, a velocity to power curve is used to create a polynomial fit. The polynomial fit is used to calculate the power produced between the turbine cut-in and cut-out velocities. The velocity to power curve data is loaded into a pandas DataFrame using the pandas method `read_csv`.
# +
# Calculate the power produced from turbine velocity to power curve
VP_curve = pd.read_csv('data/river/tanana_VP_curve.csv')
# Calculate the polynomial fit for the VP curve
p2, r_squared_2 = river.resource.polynomial_fit(VP_curve.V, VP_curve.P, 2)
# Plot the VP polynomial curve
ax = river.graphics.plot_velocity_vs_power(VP_curve.V, VP_curve.P, polynomial_coeff=p2)
# Print the r_squared value
print(r_squared_2)
# -
# The second-order polynomial fits the data well. Therefore, the polynomial is used to calculate the power using the min and max of the curves velocities as the turbine operational limits.
# Calculate power from velocity at the turbine location
data['P'] = river.resource.velocity_to_power(data.V,
polynomial_coefficients=p2,
cut_in=VP_curve.V.min(),
cut_out=VP_curve.V.max())
# Plot the power duration curve
ax = river.graphics.plot_power_duration_curve(data.P, data.F)
# ## Annual Energy Produced
# Finally, annual energy produced is computed, as shown below.
#
# Note: The function `energy_produced` returns units of Joules(3600 Joules = 1 Wh).
# +
# Calculate the Annual Energy produced
s = 365. * 24 * 3600 # Seconds in a year
AEP = river.resource.energy_produced(data.P, s)
print(f"Annual Energy Produced: {AEP/3600000:.2f} kWh")
|
examples/river_example.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %pylab inline
style.use('http://johannesfeist.eu/misc/jf.mplstyle')
np.set_printoptions(linewidth=200)
from qutip import *
from numba import jit
# %reload_ext Cython
# %reload_ext fortranmagic
from scipy.sparse import lil_matrix
N = 100000
H = lil_matrix((N,N))
H[range(N),range(N)] = -2.
H[range(N-1),range(1,N)] = 1
H[range(1,N),range(N-1)] = 1
nvals = 100*N
ii = random.randint(N,size=(2,nvals))
H[ii[0],ii[1]] = random.rand(nvals)
H = H.tocsr()
Hc = H.astype(np.complex128)
phi0 = exp(-(arange(N)-15000)**2/(2*300**2)-1.5j*arange(N)) + exp(-(arange(N)-5000)**2/(2*50**2)+1j*arange(N))
phi0 /= norm(phi0)
phir = randn(N).astype(complex)
phir /= norm(phir)
@jit(nopython=True,nogil=True)
def csr_matvec_numba(n_row,n_col,Ap,Aj,Ax,Xx,Yx):
for i in range(n_row):
val = Yx[i]
for j in range(Ap[i],Ap[i+1]):
val += Ax[j] * Xx[Aj[j]]
Yx[i] = val
# %%fortran --opt "-O3 -finline-functions -fomit-frame-pointer -fno-strict-aliasing" --arch "-march=native"
subroutine csr_matvec_fort(n_row,Ap,Aj,Ax,Xx,a,Yx)
integer, intent(in) :: n_row,Ap(:),Aj(:)
real(8), intent(in) :: Ax(:), a
complex(8), intent(in) :: Xx(:)
complex(8), intent(inout) :: Yx(:)
integer :: i, j
complex(8) :: val
do i = 1, n_row
val = 0.
do j = Ap(i)+1,Ap(i+1)
val = val + Ax(j)*Xx(Aj(j)+1)
end do
Yx(i) = Yx(i) + a*val
end do
end subroutine
# %%fortran --opt "-O3 -finline-functions -fomit-frame-pointer -fno-strict-aliasing" --arch "-march=native"
subroutine save_vecs(n_row,Ap,Aj,Ax)
implicit none
integer, intent(in) :: n_row,Ap(:),Aj(:)
real(8), intent(in) :: Ax(:)
write(501) n_row, size(Aj)
write(502) Ap, Aj, Ax
write(60,*) n_row, size(Aj)
write(60,*) Ap(1:3)
write(60,*) Aj(1:3)
write(60,*) Ax(1:3)
close(501)
close(502)
close(60)
end subroutine
save_vecs(H.shape[0],H.indptr,H.indices,H.data)
# !cat fort.60
# + magic_args="-a -c=-O3 -c=-march=native" language="cython"
# import cython
# @cython.boundscheck(False)
# @cython.wraparound(False)
# @cython.embedsignature(True)
# def csr_matvec_cy(size_t n_row, size_t n_col, int[::1] Ap, int[::1] Aj, double[::1] Ax,
# double complex[::1] Xx, double a, double complex[::1] Yx):
# cdef:
# size_t i,j
# double complex val
# for i in range(n_row):
# val = 0. #Yx[i]
# for j in range(Ap[i],Ap[i+1]):
# val += Ax[j] * Xx[Aj[j]]
# Yx[i] = Yx[i] + a*val
#
# @cython.boundscheck(False)
# @cython.wraparound(False)
# @cython.embedsignature(True)
# def csr_matvec_cyc(size_t n_row, size_t n_col, int[::1] Ap, int[::1] Aj, complex[::1] Ax, complex[::1] Xx, complex[::1] Yx):
# cdef:
# size_t i,j
# complex val
# for i in range(n_row):
# val = Yx[i]
# for j in range(Ap[i],Ap[i+1]):
# val += Ax[j] * Xx[Aj[j]]
# Yx[i] = val
# -
from qutip.cy.spmatfuncs import spmvpy
from scipy.sparse._sparsetools import csr_matvec
phitest = H.dot(phi0)
phir *= 0.
csr_matvec(N,N,H.indptr,H.indices,H.data,phi0,phir)
print(norm(phitest-phir))
phitest = H.dot(phi0)
def testfunc(f):
import timeit
global phir
phir *= 0.
f()
print("%.1e"%norm((phitest-phir)/phitest),end=' ')
t1 = timeit.Timer(f)
print("%5.1f ms"%(t1.timeit(10)/10 * 1e3))
testfunc(lambda: csr_matvec(N,N,H.indptr,H.indices,H.data,phi0,phir))
def testd(H,phi,Hphi):
Hphi[:] = H.dot(phi)
testfunc(lambda: testd(H,phi0,phir))
testfunc(lambda: csr_matvec(N,N,H.indptr,H.indices,H.data,phi0,phir))
testfunc(lambda: csr_matvec_numba(N,N,H.indptr,H.indices,H.data,phi0,phir))
testfunc(lambda: csr_matvec_cy(N,N,H.indptr,H.indices,H.data,phi0,1.,phir))
testfunc(lambda: csr_matvec_cyc(N,N,Hc.indptr,Hc.indices,Hc.data,phi0,phir))
testfunc(lambda: csr_matvec_fort(N,H.indptr,H.indices,H.data,phi0,1.,phir))
testfunc(lambda: spmvpy(Hc.data,Hc.indices,Hc.indptr,phi0,1.,phir))
|
dev/bench_spmv.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
# ---
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# +
# Test the preorder traverse using tree in Example 2 [3,5,1,6,2,0,8,null,null,7,4]
# 3
# / \
# 5 1
# / \ / \
# 6 2 0 8
# / \
# 7 4
values = [3,5,1,6,2,0,8,None,None,7,4]
nodes = [TreeNode(x) for x in values if x != None]
root = nodes[0]
nodes[0].left, nodes[0].right = nodes[1], nodes[2]
nodes[1].left, nodes[1].right = nodes[3], nodes[4]
nodes[2].left, nodes[2].right = nodes[5], nodes[6]
nodes[4].left, nodes[4].right = nodes[7], nodes[8]
# +
# Preorder: Processes the root before the traversals of left and right children.
def traverse_tree_preorder(node, path=[]):
if not node: return path
path.append(node.val) # or node
if node.left:
traverse_tree_preorder(node.left, path)
if node.right:
traverse_tree_preorder(node.right, path)
return path
# -
traverse_tree_preorder(root)
# +
# find path to a node value
# refs: https://www.baeldung.com/cs/path-from-root-to-node-binary-tree
def find_path(root, value):
def search(node, target):
if not node:
return False
path.append(node.val)
if node.val == target or search(node.left, target) or search(node.right, target):
return True
else:
path.pop()
return False
path = []
search(root, value)
return path
# -
find_path(root, 4)
|
tree/Traverse a Binary Tree.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Predicting beer style with a neural network model
# +
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.model_selection import train_test_split
from joblib import dump
import category_encoders as ce
from torch.utils.data import Dataset, DataLoader
import torch
import torch.nn as nn
import torch.nn.functional as F
# -
# ### Section 1: Data exploration from BeerAdvocates
#
# We import data from BeerAdvocates.com
df = pd.read_csv("../data/raw/beer_reviews.csv")
# There are 1.6 million reviews and 13 columns
df.shape
df.head()
# The expected API parameter brewery name has 15 null values.
# The expected API parameter beer_abv (alcohol level) has ~70000 nulls
df.info()
df.describe(include='all')
# There are 104 styles of beer. The most common type of beer is 7% of the total.
# There are 5742 breweries. This could be why there's lots of different styles as the breweries have their specialties.
beer_name = df['beer_style'].str.strip()
beer_name.value_counts(normalize=True) * 100
# <b> The top 10 beer style </b>
#
# The most common beer style in the dataset are American-style beers
chart_data = pd.DataFrame(beer_name.value_counts())
chart_data['beer_style_type'] = chart_data.index
chart_data
sns.catplot(y='beer_style_type', x='beer_style', data=chart_data[:10], height=10, kind="bar")
# ### Section 2: Dealing with null values
# There were null values for brewery names
len(df[df['brewery_name'].isnull()])
# As there's only 15 with null values, we will drop these rows
df_clean = df.copy()
df_clean = df_clean.dropna(subset=['brewery_name'])
df_clean.info()
#Reset the index
df_clean.reset_index(drop=True, inplace=True)
df_clean.describe(include="all")
# There were ~70000 null alcohol level values.
# We will estimate these null values by using the average alcohol level for the beer style
#Replace na alcohol levels by the average alcohol level for the beer style
df_clean["beer_abv"]=df_clean.groupby("beer_style")["beer_abv"].transform(lambda x: x.fillna(x.mean()))
df_clean.info()
# Now there is no more null values for the API parameter fields.
# The overall alcohol level stats remain unchanged
#overall stats unchanged
df_clean.describe(include="all")
# ### Section 3. Create the target variables and feature engineering the brewery ids
# The target variable - beer style- will be converted to an array of integers
#pop target into another y list
target = df_clean['beer_style']
target.head()
# We fit target to a label encoder
le = LabelEncoder()
fitted_target = le.fit_transform(target)
fitted_target
#Dump the label encoder into the models folder
dump(le, '../models/le.joblib')
# <b> Feature engineering the brewery ids </b>
#
# There are 5742 breweries in the data set.
#
# We were unable to one-hot encode the brewery id due to its high cardinality.
#
# We will now look at its distribution to see if we can group them into smaller groups.
brewery_id = df_clean['brewery_id']
chart_data_2 = pd.DataFrame(brewery_id.value_counts())
chart_data_2.describe()
# A lot of breweries have a small amount of reviews. This could lead to overfitting if they try to model the reviews for these breweries
#
# There 5838 brewery ids vs 5742 brewery names, meaning there are some breweries with the same name (but potentially different location. Location is not in the dataset.
sns.distplot(chart_data_2)
# Only 1209 out of the 5838 brewery ids have more than 100 reviews
len(chart_data_2[chart_data_2['brewery_id']>100])
# Even if group brewery ids with less than 100 are grouped as 'Other', still too much classes for one-hot encoding.
#
# Will have to convert the brewery id into a numerical feature. We will use target encoding.
#
# But first, we will create a new brewery id feature
# +
#Create a brewery id feature where if less than 100 reviews, the id is '0'
# +
brewery_id_new = pd.DataFrame(df_clean['brewery_id'])
brewery_id_new['brewery_id_count']=brewery_id_new.groupby('brewery_id')['brewery_id'].transform('count')
brewery_id_new['id_new'] = brewery_id_new['brewery_id_count'].transform(lambda x: x if x > 100 else 0)
brewery_id_new['id_new'] = brewery_id_new.loc[brewery_id_new['id_new'] > 100, 'brewery_id'].fillna(0)
brewery_id_new.fillna(0, inplace=True)
brewery_id_new
# -
# Now we will target encode the id_bew column. To prevent overfitting groups with small sample sizes, we will use a minimum sample size of 270 per batch. A smoothing co-efficient of 0.5 applied to still incorporate average for groups that had sufficient sample
ce_target = ce.TargetEncoder(cols = ['id_new'], min_samples_leaf=270, smoothing = 0.5)
X=pd.DataFrame(brewery_id_new['id_new'])
Y=pd.DataFrame(fitted_target)
ce_target.fit(X,Y)
# Now the brewery id has been converted to a numerical feature
encoded_brewery_id=ce_target.transform(X,Y)
encoded_brewery_id
# There are 702 unique values in the brewery id after target encoding
len(encoded_brewery_id.drop_duplicates())
#dump the category encoder into the models folder
dump(ce_target, '../models/ce_target.joblib')
# Add the target encoded brewery id into the dataframe.
df_clean['encoded_brewery_id'] = encoded_brewery_id
# ### Section 4. Creating training, testing, and validation datasets
# We create the create a matrix of the features to be used in the model
num_cols=['review_aroma', 'review_appearance', 'review_palate', 'review_taste', 'beer_abv', 'encoded_brewery_id']
#Create matrix of X variables
X_analysis = df_clean[num_cols]
X_analysis
#All the features are now numerical. Scale the features.
sc = StandardScaler()
X_analysis= sc.fit_transform(X_analysis)
X_analysis
#dump the scaler into the models folder
dump(sc, '../models/sc.joblib')
#Split model into train, validation, and test dataset
X_train, X_test, y_train, y_test = train_test_split(X_analysis, fitted_target, test_size=0.2, random_state=8)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=8)
# ### Section 5. Fit a neural network model using PyTorch
# We will convert our dataset into tensors
# +
from src.models.pytorch import PytorchDataset
train_dataset = PytorchDataset(X=X_train, y=y_train)
val_dataset = PytorchDataset(X=X_val, y=y_val)
test_dataset = PytorchDataset(X=X_test, y=y_test)
# -
# We will fit a model with three hidden layers. Each layer is normalised. The layers are activated with a
# non-linear tanh function
class PytorchMultiClass(nn.Module):
def __init__(self, num_features):
super(PytorchMultiClass, self).__init__()
self.layer_1 = nn.Linear(num_features, 512)
self.norm_1=nn.LayerNorm(512)
self.layer_2 = nn.Linear(512, 256)
self.norm_2=nn.LayerNorm(256)
self.layer_3 = nn.Linear(256, 128)
self.norm_3=nn.LayerNorm(128)
self.layer_out = nn.Linear(128, 104)
def forward(self, x):
x = F.tanh(self.layer_1(x))
x = self.norm_1(x)
x = F.tanh(self.layer_2(x))
x = self.norm_2(x)
x = F.tanh(self.layer_3(x))
x = self.norm_3(x)
x = self.layer_out(x)
model = PytorchMultiClass(X_train.shape[1])
# +
from src.models.pytorch import get_device
device = get_device()
model.to(device)
# -
# As it is multi-classification model, a cross entropy loss function is applied
criterion = nn.CrossEntropyLoss()
# The loss function is optimised using ADAM optimiser, learning rate = 0.001
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
from src.models.pytorch import train_classification
from src.models.pytorch import test_classification
# The accuracy level of stabilised at around 67% after 100 epochs
N_EPOCHS = 10
BATCH_SIZE = 1000
for epoch in range(N_EPOCHS):
train_loss, train_acc = train_classification(train_dataset, model=model, criterion=criterion, optimizer=optimizer, batch_size=BATCH_SIZE, device=device)
valid_loss, valid_acc = test_classification(val_dataset, model=model, criterion=criterion, batch_size=BATCH_SIZE, device=device)
print(f'Epoch: {epoch}')
print(f'\t(train)\t|\tLoss: {train_loss:.4f}\t|\tAcc: {train_acc * 100:.1f}%')
print(f'\t(valid)\t|\tLoss: {valid_loss:.4f}\t|\tAcc: {valid_acc * 100:.1f}%')
# +
#torch.save(model.state_dict(), "../models/beeroracle_final_normal.pt")
# -
test_loss, test_acc = test_classification(test_dataset, model=model, criterion=criterion, batch_size=BATCH_SIZE, device=device)
print(f'\tLoss: {test_loss:.4f}\t|\tAccuracy: {test_acc:.2f}')
|
notebooks/Final_model.ipynb
|
# ---
# title: First notebook (in R)
# params:
# out_file: NULL
# ---
# + name="setup"
library(ggplot2)
library(dplyr)
library(readr)
# -
# # A plot.
ggplot(iris, aes(x=Sepal.Width, y=Sepal.Length, color=Species)) +
geom_point() +
theme_bw()
# # Export data
# + message=false
write_tsv(iris, params$out_file)
# -
#
#
|
tests/notebooks/01_generate_data.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Support Vector Classification - Experimento
#
# O Classificador Support-Vector Machine (SVM) é um dos algorítmos de predição mais robustos, e é baseado em métodos de aprendizagem estatística.
#
# <img src="https://upload.wikimedia.org/wikipedia/commons/7/72/SVM_margin.png" alt="SVM" width="400"/>
#
# O SVM mapeia dados de treinamento para maximizar o espaço entre as classes de dados a serem separadas. Além de fazer classificações lineares, os SVMs também podem realizar eficientemente predições não-lineares, utilizando abordagens como o [kernel trick](https://en.wikipedia.org/wiki/Kernel_method#Mathematics:_the_kernel_trick)
#
# Este componente treina um modelo Support Vector Classification usando [Scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html). <br>
#
# Scikit-learn é uma biblioteca open source de machine learning que suporta apredizado supervisionado e não supervisionado. Também provê diversas ferramentas para montagem de modelo, pré-processamento de dados, seleção e avaliação de modelos, e muitos outros utilitários.
# ## Declaração de parâmetros e hiperparâmetros
#
# Declare parâmetros com o botão <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAABhWlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV9TtaIVB<KEY>" /> na barra de ferramentas.<br>
# A variável `dataset` possui o caminho para leitura do arquivos importados na tarefa de "Upload de dados".<br>
# Você também pode importar arquivos com o botão <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAABhWlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV9TtaIVBzuIOASpThb8QhylikWwUNoKrTqYXPohNGlIUlwcBdeCgx+LVQcXZ10dXAVB8APEydFJ0UVK/F9SaBHjwXE/3t173L0DhFqJqWbbGKBqlpGMRcVMdkUMvKID3QhiCOMSM/V4aiENz/F1Dx9f7yI8y/vcn6NHyZkM8InEs0w3LOJ14ulNS+e8TxxiRUkhPiceNeiCxI9cl11+41xwWOCZISOdnCMOEYuFFpZbmBUNlXiKOKyoGuULGZcVzluc1VKFNe7JXxjMacsprtMcRAyLiCMBETIq2EAJFiK0aqSYSNJ+1MM/4PgT5JLJtQFGjnmUoUJy/OB/8LtbMz854SYFo0D7i21/DAOBXaBete3vY9uunwD+Z+BKa/rLNWDmk/RqUwsfAb3bwMV1U5P3gMsdoP9JlwzJkfw0hXweeD+jb8oCfbdA16rbW2Mfpw9AmrpaugEODoGRAmWveby7s7W3f880+vsBocZyukMJsmwAAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAADdcAAA3XAUIom3gAAAAHdElNRQfkBgsOBy6ASTeXAAAC/0lEQVQ4y5WUT2gcdRTHP29m99B23Uiq6dZisgoWCxVJW0oL9dqLfyhCvGWY2YUBI95MsXgwFISirQcLhS5hfgk5CF3wJIhFI7aHNsL2VFZFik1jS1qkiZKdTTKZ3/MyDWuz0fQLc/m99/vMvDfv+4RMlUrlkKqeAAaBAWAP8DSgwJ/AXRG5rao/WWsvTU5O3qKLBMD3fSMiPluXFZEPoyj67PGAMzw83PeEMABHVT/oGpiamnoAmCcEWhH5tFsgF4bh9oWFhfeKxeJ5a+0JVT0oImWgBPQCKfAQuAvcBq67rltX1b+6ApMkKRcKhe9V9QLwbavV+qRer692Sx4ZGSnEcXw0TdP3gSrQswGYz+d/S5IkVtXTwOlCoZAGQXAfmAdagAvsAErtdnuXiDy6+023l7qNRsMODg5+CawBzwB9wFPA7mx8ns/KL2Tl3xCRz5eWlkabzebahrHxPG+v4zgnc7ncufHx8Z+Hhoa29fT0lNM03Q30ikiqqg+ttX/EcTy3WTvWgdVqtddaOw/kgXvADHBHROZVNRaRvKruUNU+EdkPfGWM+WJTYOaSt1T1LPDS/4zLWWPMaLVaPWytrYvIaBRFl/4F9H2/JCKvGmMu+76/X0QOqGoZKDmOs1NV28AicMsYc97zvFdc1/0hG6kEeNsY83UnsCwivwM3VfU7YEZE7lhr74tIK8tbnJiYWPY8b6/ruleAXR0ftQy8boyZXi85CIIICDYpc2ZgYODY3NzcHmvt1eyvP64lETkeRdE1yZyixWLx5U2c8q4x5mIQBE1g33/0d3FlZeXFR06ZttZesNZejuO4q1NE5CPgWVV9E3ij47wB1IDlJEn+ljAM86urq7+KyAtZTgqsO0VV247jnOnv7/9xbGzMViqVMVX9uANYj6LonfVtU6vVkjRNj6jqGeCXzGrPAQeA10TkuKpOz87ONrayhnIA2Qo7BZwKw3B7kiRloKSqO13Xja21C47jPNgysFO1Wi0GmtmzQap6DWgD24A1Vb3SGf8Hfstmz1CuXEIAAAAASUV<KEY> /> na barra de ferramentas.
# + tags=["parameters"]
# parameters
dataset = "/tmp/data/iris.csv" #@param {type:"string"}
target = "Species" #@param {type:"feature", label:"Atributo alvo", description: "Seu modelo será treinado para prever os valores do alvo."}
# selected features to perform the model
filter_type = "remover" #@param ["incluir","remover"] {type:"string",multiple:false,label:"Modo de seleção das features",description:"Se deseja informar quais features deseja incluir no modelo, selecione a opção 'incluir'. Caso deseje informar as features que não devem ser utilizadas, selecione 'remover'. "}
model_features = "" #@param {type:"feature",multiple:true,label:"Features para incluir/remover no modelo",description:"Seu modelo será feito considerando apenas as features selecionadas. Caso nada seja especificado, todas as features serão utilizadas"}
# features to apply Ordinal Encoder
ordinal_features = "" #@param {type:"feature",multiple:true,label:"Features para fazer codificação ordinal", description: "Seu modelo utilizará a codificação ordinal para as features selecionadas. As demais features categóricas serão codificadas utilizando One-Hot-Encoding."}
# hyperparameters
kernel = "rbf" #@param ["linear", "poly", "rbf", "sigmoid", "precomputed"] {type:"string", label:"Kernel", description:"Especifica o tipo de kernel a ser usado no algoritmo"}
C = 1.0 #@param {type:"number", label:"Regularização", description:"A força da regularização é inversamente proporcional a C. Deve ser positivo. Penalidade é l2²"}
degree = 3 #@param {type:"integer", label:"Grau", description:"Grau da função polinomial do kernel ('poly'). Ignorado por outros kernels"}
gamma = "auto" #@param ["scale", "auto"] {type: "string", label:"Gama", description:"Coeficiente de kernel para 'rbf', 'poly' e 'sigmoid'"}
max_iter = -1 #@param {type:"integer", label:"Iteração", description:"Limite fixo nas iterações no solver, ou -1 sem limite"}
probability = True #@param {type: "boolean", label:"Probabilidade", description:"Se é necessário ativar estimativas de probabilidade. Deve ser ativado antes da chamada fit() do modelo, reduzirá a velocidade desse método, pois ele usa internamente o 5-fold-cross-validation, e predict_proba pode ser inconsistente com a chamada predict()"}
# predict method
method = "predict_proba" #@param ["predict_proba", "predict"] {type:"string", label:"Método de Predição", description:"Se optar por 'predict_proba', o método de predição será a probabilidade estimada de cada classe, já o 'predict' prediz a qual classe pertence"}
# Plots to ignore
plots_ignore = [""] #@param ["Dados de Teste", "Matriz de Confusão", "Métricas Comuns", "Curva ROC", "Tabelas de Dados", "SHAP"] {type:"string",multiple:true,label:"Gráficos a serem ignorados", description: "Diversos gráficos são gerados ao executar o treinamento e validação do modelo, selecione quais não devem ser gerados."}
# -
# ## Acesso ao conjunto de dados
#
# O conjunto de dados utilizado nesta etapa será o mesmo carregado através da plataforma.<br>
# O tipo da variável retornada depende do arquivo de origem:
# - [pandas.DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) para CSV e compressed CSV: .csv .csv.zip .csv.gz .csv.bz2 .csv.xz
# - [Binary IO stream](https://docs.python.org/3/library/io.html#binary-i-o) para outros tipos de arquivo: .jpg .wav .zip .h5 .parquet etc
# +
import pandas as pd
df = pd.read_csv(dataset)
# -
# ## Acesso aos metadados do conjunto de dados
#
# Utiliza a função `stat_dataset` do [SDK da PlatIAgro](https://platiagro.github.io/sdk/) para carregar metadados. <br>
# Por exemplo, arquivos CSV possuem `metadata['featuretypes']` para cada coluna no conjunto de dados (ex: categorical, numerical, or datetime).
# +
import numpy as np
from platiagro import stat_dataset
metadata = stat_dataset(name=dataset)
featuretypes = metadata["featuretypes"]
columns = df.columns.to_numpy()
featuretypes = np.array(featuretypes)
target_index = np.argwhere(columns == target)
columns = np.delete(columns, target_index)
featuretypes = np.delete(featuretypes, target_index)
# -
# ## Remoção de linhas com valores faltantes no atributo alvo
#
# Caso haja linhas em que o atributo alvo contenha valores faltantes, é feita a remoção dos casos faltantes.
df.dropna(subset=[target], inplace=True)
y = df[target].to_numpy()
# ## Filtragem das features
#
# Seleciona apenas as features que foram declaradas no parâmetro model_features. Se nenhuma feature for especificada, todo o conjunto de dados será utilizado para a modelagem.
# +
columns_to_filter = columns
if len(model_features) >= 1:
if filter_type == "incluir":
columns_index = (np.where(np.isin(columns, model_features)))[0]
columns_index.sort()
columns_to_filter = columns[columns_index]
featuretypes = featuretypes[columns_index]
else:
columns_index = (np.where(np.isin(columns, model_features)))[0]
columns_index.sort()
columns_to_filter = np.delete(columns, columns_index)
featuretypes = np.delete(featuretypes, columns_index)
# keep the features selected
df_model = df[columns_to_filter]
X = df_model.to_numpy()
# -
# ## Codifica labels do atributo alvo
#
# As labels do atributo alvo são convertidos em números inteiros ordinais com valor entre 0 e n_classes-1.
# +
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(y)
# -
# ## Divide dataset em subconjuntos de treino e teste
#
# Subconjunto de treino: amostra de dados usada para treinar o modelo.<br>
# Subconjunto de teste: amostra de dados usada para fornecer uma avaliação imparcial do treinamento do modelo no subconjunto de dados de treino.
# +
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7)
# -
# ## Configuração dos atributos
# +
from platiagro.featuretypes import NUMERICAL
# Selects the indexes of numerical and non-numerical features
numerical_indexes = np.where(featuretypes == NUMERICAL)[0]
non_numerical_indexes = np.where(~(featuretypes == NUMERICAL))[0]
# Selects non-numerical features to apply ordinal encoder or one-hot encoder
ordinal_features = np.array(ordinal_features)
non_numerical_indexes_ordinal = np.where(
~(featuretypes == NUMERICAL) & np.isin(columns_to_filter, ordinal_features)
)[0]
non_numerical_indexes_one_hot = np.where(
~(featuretypes == NUMERICAL) & ~(np.isin(columns_to_filter, ordinal_features))
)[0]
# After the step handle_missing_values,
# numerical features are grouped in the beggining of the array
numerical_indexes_after_handle_missing_values = np.arange(len(numerical_indexes))
non_numerical_indexes_after_handle_missing_values = np.arange(
len(numerical_indexes), len(featuretypes)
)
ordinal_indexes_after_handle_missing_values = non_numerical_indexes_after_handle_missing_values[
np.where(np.isin(non_numerical_indexes, non_numerical_indexes_ordinal))[0]
]
one_hot_indexes_after_handle_missing_values = non_numerical_indexes_after_handle_missing_values[
np.where(np.isin(non_numerical_indexes, non_numerical_indexes_one_hot))[0]
]
# -
# ## Treina um modelo usando sklearn.svm.SVC
# +
from category_encoders.one_hot import OneHotEncoder
from category_encoders.ordinal import OrdinalEncoder
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
pipeline = Pipeline(
steps=[
(
"handle_missing_values",
ColumnTransformer(
[
("imputer_mean", SimpleImputer(strategy="mean"), numerical_indexes),
(
"imputer_mode",
SimpleImputer(strategy="most_frequent"),
non_numerical_indexes,
),
],
remainder="drop",
),
),
(
"handle_categorical_features",
ColumnTransformer(
[
(
"feature_encoder_ordinal",
OrdinalEncoder(),
ordinal_indexes_after_handle_missing_values,
),
(
"feature_encoder_onehot",
OneHotEncoder(),
one_hot_indexes_after_handle_missing_values,
),
],
remainder="passthrough",
),
),
(
"estimator",
SVC(
C=C,
kernel=kernel,
degree=degree,
gamma=gamma,
probability=probability,
max_iter=max_iter,
),
),
]
)
# Fit model
pipeline.fit(X_train, y_train)
features_after_pipeline = np.concatenate(
(columns_to_filter[numerical_indexes], columns_to_filter[non_numerical_indexes])
)
# -
# ## Visualização de desempenho
#
# A [**Matriz de Confusão**](https://en.wikipedia.org/wiki/Confusion_matrix) (Confusion Matrix) é uma tabela que nos permite a visualização do desempenho de um algoritmo de classificação. <br>
# É extremamente útil para mensurar [Accuracy](https://en.wikipedia.org/wiki/Accuracy_and_precision#In_binary_classification), [Recall, Precision, and F-measure](https://en.wikipedia.org/wiki/Precision_and_recall).
# +
from sklearn.metrics import confusion_matrix
# uses the model to make predictions on the Test Dataset
y_pred = pipeline.predict(X_test)
y_prob = pipeline.predict_proba(X_test)
# computes confusion matrix
labels = np.unique(y)
data = confusion_matrix(y_test, y_pred, labels=labels)
# puts matrix in pandas.DataFrame for better format
labels_dec = label_encoder.inverse_transform(labels)
confusion_matrix = pd.DataFrame(data, columns=labels_dec, index=labels_dec)
# -
# ## Salva métricas
#
# Utiliza a função `save_metrics` do [SDK da PlatIAgro](https://platiagro.github.io/sdk/) para salvar métricas. Por exemplo: `accuracy`, `precision`, `r2_score`, `custom_score` etc.<br>
# +
from platiagro import save_metrics
save_metrics(confusion_matrix=confusion_matrix)
# -
# ## Visualiza resultados
# A avaliação do desempenho do modelo pode ser feita por meio da análise da Curva ROC (ROC). Esse gráfico permite avaliar a performance de um classificador binário para diferentes pontos de cortes. A métrica AUC (Area under curve) também é calculada e indicada na legenda do gráfico. Se a variável resposta tiver mais de duas categorias, o cálculo da curva ROC e AUC é feito utilizando o algoritmo one-vs-rest, ou seja, calcula-se a curva ROC e AUC de cada classe em relação ao restante.
import matplotlib.pyplot as plt
# +
from platiagro.plotting import plot_classification_data
if "Dados de Teste" not in plots_ignore:
plot_classification_data(pipeline, columns_to_filter, X_train, y_train, X_test, y_test, y_pred)
plt.show()
# +
from platiagro.plotting import plot_matrix
if "Matriz de Confusão" not in plots_ignore:
plot_matrix(confusion_matrix)
plt.show()
# +
from platiagro.plotting import plot_common_metrics
if "Métricas Comuns" not in plots_ignore:
plot_common_metrics(y_test, y_pred, labels, labels_dec)
plt.show()
# +
from platiagro.plotting import plot_roc_curve
if "Curva ROC" not in plots_ignore:
plot_roc_curve(y_test, y_prob, labels_dec)
plt.show()
# -
# Por meio da bibiloteca SHAP retornamos o gráfico abaixo, através do qual é possível visualziar o impacto das features de entrada para cada possível classe na saída.
# +
from platiagro.plotting import plot_shap_classification_summary
if "SHAP" not in plots_ignore:
plot_shap_classification_summary(pipeline, X_train,y_train,columns_to_filter,label_encoder,non_numerical_indexes)
# -
# Visualização da tabela contendo os resultados finais
# +
from platiagro.plotting import plot_data_table
if "Tabelas de Dados" not in plots_ignore:
df_test = pd.DataFrame(X_test, columns=columns_to_filter)
labels_prob = list(label_encoder.inverse_transform(np.unique(y)))
labels_prob = [str(label) +'_prob' for label in labels_prob]
new_cols = [target] + labels_prob
y_pred_expanded = np.expand_dims(label_encoder.inverse_transform(y_pred), axis=1)
y_arrays = np.concatenate((y_pred_expanded, y_prob), axis=1)
for col, y_array in zip(new_cols,y_arrays.T):
df_test[col] = y_array
ax = plot_data_table(df_test)
plt.show()
# -
# ## Salva alterações no conjunto de dados
#
# O conjunto de dados será salvo (e sobrescrito com as respectivas mudanças) localmente, no container da experimentação, utilizando a função `pandas.DataFrame.to_csv`.<br>
# +
from re import sub
def generate_col_names(labels_dec):
return [
sub("[^a-zA-Z0-9\n\.]", "_", str("SVC_predict_proba" + "_" + str(class_i)))
for i, class_i in enumerate(labels_dec)
]
pipeline.fit(X, y)
y_prob = pipeline.predict_proba(X)
y_pred = pipeline.predict(X)
new_columns = generate_col_names(labels_dec)
df.loc[:, new_columns] = y_prob
y_pred = label_encoder.inverse_transform(y_pred)
df.loc[:, "SVC_predict_class"] = y_pred
new_columns = new_columns + ["SVC_predict_class"]
# save dataset changes
df.to_csv(dataset, index=False)
# -
# ## Salva resultados da tarefa
#
# A plataforma guarda o conteúdo de `/tmp/data/` para as tarefas subsequentes.
# +
from joblib import dump
artifacts = {
"pipeline": pipeline,
"label_encoder": label_encoder,
"columns": columns,
"columns_to_filter": columns_to_filter,
"new_columns": new_columns,
"method": method,
"features_after_pipeline": features_after_pipeline,
}
dump(artifacts, "/tmp/data/svc.joblib")
|
tasks/svc/Experiment.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
import os
import xarray as xr
from IPython.display import display
from IPython.core.display import HTML
import glob
display(HTML("<h1 style='text-align:center;'>S3,S2,S1 Products Data Structures and Formatting</h1>"))
# +
# Get all Sentinels products samples
products = glob.glob("data/*.SEN3") + glob.glob("data/*.SAFE")
# create a navigation links
navigation = '<ul style="font-size:14px;">'
for product in products:
product_name = os.path.basename(product)
sat = product_name[:2]
product_type = product_name[:15]
if 'S2' in product_name:
product_type = product_name[:10]
link = product_type + ".html"
navigation += '<li style="display: inline; padding-left:12px;"><a href="'+link+'">' + product_type + ' </a></li>'
navigation += '</ul>'
display(HTML(navigation))
# +
"""
products : list of paths to S3 products
product_type : product type to be displayed
"""
def s3_display_product(products,product_type):
for product in products:
product_name = os.path.basename(product)
if product_type in product_name:
display(HTML("<h1>Product: "+product_name[:15]+"</h1>"))
# get all netcdf files of the current product
nc_files = glob.glob(product + "/*.nc")
for nc_file in nc_files:
ds = xr.open_dataset(nc_file,decode_times=False,mask_and_scale=False)
file_name = os.path.basename(nc_file)
display(HTML("<h3>Group: "+file_name+"</h3>"))
display(ds)
# + tags=["parameters"]
product_type = "SR_1_SRA___"
# -
s3_display_product(products,product_type)
|
eopf-notebooks/s3_products_data_structures.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
# ---
# # Aula 12 - Autoencoders
#
# ### Temas:
# 1. Representação eficiente de dados
# 2. PCA como autoencoder
# 3. Stacked Autoencoders
# 4. Pretreinar de forma nâo supervisada um classificador CNN usando um autoencoder
# 5. Denoising dos autoencoders
# 6. Sparse autoencoders
# 7. Variational autoencoders
# 8. Outros autoencoders
|
lessons/12 - Autoencoders.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# [](http://colab.research.google.com/github/Yquetzal/tnetwork/blob/master/demo_DCD.ipynb)
# # Dynamic Communities detection and evaluation
# If tnerwork library is not installed, you need to install it, for instance using the following command
# +
# #%%capture #avoid printing output
# #!pip install --upgrade git+https://github.com/Yquetzal/tnetwork.git
# -
# %load_ext autoreload
# %autoreload 2
import tnetwork as tn
import seaborn as sns
import pandas as pd
import networkx as nx
import numpy as np
# ## Creating an example dynamic graph with changing community structure
# We create a simple example of dynamic community evolution using the generator provided in the library. We generate a simple ship of Theseus scenario. Report to the corresponding tutorial to fully understand the generation part if needed.
# +
my_scenario = tn.ComScenario(alpha=0.8,random_noise=0.1)
[com1,com2] = my_scenario.INITIALIZE([6,6],["c1","c2"])
(com2,com3)=my_scenario.THESEUS(com2,delay=20)
my_scenario.CONTINUE(com3,delay=10)
#visualization
(generated_network_IG,generated_comunities_IG) = my_scenario.run()
plot = tn.plot_longitudinal(generated_network_IG,generated_comunities_IG,height=200)
generated_network_SN = generated_network_IG.to_DynGraphSN(slices=1)
generated_communities_SN = generated_comunities_IG.to_DynCommunitiesSN(slices=1)
# -
# Let's look at the graph at different stages. There are no communities.
last_time = generated_network_IG.end()
print(last_time)
times_to_plot = [0,int(last_time/3),int(last_time/3*2),last_time-1]
plot = tn.plot_as_graph(generated_network_IG,ts=times_to_plot,width=200,height=200)
# Algorithms for community detection are located in the tnetwork.DCD package
import tnetwork.DCD as DCD
# ## First algorithm: Iterative match
# Iterative match consists in applying a static algorithm at each step and matching communities in successive snapshots if they are similar. Check the doc for more details.
#
# Without particular parameters, it uses the louvain method and the jaccard coefficient.
com_iterative = DCD.iterative_match(generated_network_SN)
# The static algorithm, the similarity function and the threashold to consider similar can be changed
custom_match_function = lambda x,y: len(x&y)/max(len(x),len(y))
com_custom = DCD.iterative_match(generated_network_SN,match_function=custom_match_function,CDalgo=nx.community.greedy_modularity_communities,threshold=0.5)
# ## Visualizing communities
# One way to visualize the evolution of communities is to plot the graph at some snapshots.
# By calling the `plot_as_graph` function with several timestamps, we plot graphs at those timestamps while ensuring:
#
# * That the position of nodes stay the same between snapshots
# * That the same color in different plots means that nodes belong to the same dynamic communities
last_time = generated_network_IG.end()
times_to_plot = [0,int(last_time/3),int(last_time/3*2),last_time-1]
plot = tn.plot_as_graph(generated_network_IG,com_iterative,ts=times_to_plot,auto_show=True,width=200,height=200)
# Another solution is to plot a longitudinal visualization: each horizontal line corresponds to a node, time is on the x axis, and colors correspond to communities. Grey means that a node corresponds to no community, white that the node is not present in the graph (or has no edges)
to_plot = tn.plot_longitudinal(generated_network_SN,com_iterative,height=200)
# ### Survival Graph
# This method matches communities not only between successive snaphsots, but between any snapshot, constituting a survival graph on which a community detection algorithm detects communities of communities => Dynamic communities
com_survival = DCD.label_smoothing(generated_network_SN)
plot = tn.plot_longitudinal(generated_network_SN,com_survival,height=200)
# ### Smoothed louvain
# The smoothed Louvain algorihm is very similar to the simple iterative match, at the difference that, at each step, it initializes the partition of the Louvain algorithm with the previous partition instead of having each node in its own community as in usual Louvain.
#
# It has the same options as iterative match, since only the community detection process at each step changes, not the matching
com_smoothed = DCD.smoothed_louvain(generated_network_SN)
plot = tn.plot_longitudinal(generated_network_SN,com_smoothed,height=200)
# ### Smoothed graph
# The smoothed-graph algorithm is similar to the previous ones, but the graph at each step is *smoothed* by the community structure found in the previous step. (An edge with a small weight is added between any pair of nodes that where in the same community previously. This weight is determined by a parameter `alpha`)
com_smoothed_graph = DCD.smoothed_graph(generated_network_SN)
plot = tn.plot_longitudinal(generated_network_SN,com_smoothed_graph,height=200)
# ### Matching with a custom function
# The iterative match and survival graph methods can also be instantiated with any custom community detection algorithm at each step, and any matching function, as we can see below. The match function takes as input the list of nodes of both communities, while the community algorithm must follow the signature of networkx community detection algorithms
custom_match_function = lambda x,y: len(x&y)/max(len(x),len(y))
com_custom2 = DCD.iterative_match(generated_network_SN,match_function=custom_match_function,CDalgo=nx.community.greedy_modularity_communities)
plot = tn.plot_longitudinal(generated_network_SN,com_custom2,height=200)
# ### Another algoritm in python: CPM
# CPM stands for Clique Percolation Method. An originality of this approach is that it yiealds overlapping communities.
#
# Be careful, the visualization is not currently adapted to overlapping clusters...
com_CPM = DCD.rollingCPM(generated_network_SN,k=3)
plot = tn.plot_longitudinal(generated_network_SN,com_CPM,height=200)
# ## Dynamic partition evaluation
# The goal of this section is to present the different types of dynamic community evalutation implemented in tnetwork.
#
# For all evaluations below, no conclusion should be drawn about the quality of algorithms... .
#Visualization
plot = tn.plot_longitudinal(communities=generated_comunities_IG,height=200,sn_duration=1)
# ### Quality at each step
# The first type of evaluation we can do is simply to compute, at each type, a quality measure. By default, the method uses Modularity, but one can provide to the function its favorite quality function instead. It is the simplest adaptation of *internal evaluation*.
#
# Note that
# * The result of an iterative approach is identical to the result of simply applying a static algorithm at each step
# * Smoothing therefore tends to lesser the scores.
# * The result migth or might not be computable at each step depending on the quality function used (e.g., modularity requires a complete partition of the networks to be computed)
# +
quality_ref,sizes_ref = DCD.quality_at_each_step(generated_communities_SN,generated_network_SN)
quality_iter,sizes_iter = DCD.quality_at_each_step(com_iterative,generated_network_SN)
quality_survival,sizes_survival = DCD.quality_at_each_step(com_survival,generated_network_SN)
quality_smoothed,sizes_smoothed = DCD.quality_at_each_step(com_smoothed,generated_network_SN)
df = pd.DataFrame({"reference":quality_ref,"iterative":quality_iter,"survival":quality_survival,"smoothed":quality_smoothed})
df.plot(subplots=True,sharey=True)
# -
# ### Average values
# One can of course compute average values over all steps. Be careful however when interpreting such values, as there are many potential biases:
# * Some scores (such as modularity) are not comparable between graphs of different sizes/density, so averaging values obtained on different timesteps might be incorrect
# * The *clarity* of the community structure might not be homogeneous, and your score might end up depending mostly on results on a specific period
# * Since the number of nodes change in every step, we have the choice of weighting the values by the size of the network
# * etc.
#
# Since the process is the same for all later functions, we won't repeat it for the others in this tutorial
print("iterative=", np.average(quality_iter),"weighted:", np.average(quality_iter,weights=sizes_iter))
print("survival=", np.average(quality_survival),"weighted:", np.average(quality_survival,weights=sizes_survival))
print("smoothed=", np.average(quality_smoothed),"weighted:", np.average(quality_smoothed,weights=sizes_smoothed))
# ### Similarity at each step
# A second type of evaluation consists in adaptating *external evaluation*, i.e., comparison with a known reference truth.
#
# It simply computes at each step the similarity between the computed communities and the ground truth. By default, the function uses the Adjusted Mutual Information (AMI or aNMI), but again, any similarity measure can be provided to the function.
#
# Note that, as for quality at each step, smoothing is not an advantage, community identities accross steps has no impact.
#
# There is a subtility here: since, often, the dynamic ground truth might have some nodes without affiliations, we make the choice of comparing only what is known in the ground truth, i.e., if only 5 nodes out of 10 have a community in the ground truth at time t, the score of the proposed solution will depends only on those 5 nodes, and the affiliations of the 5 others is ignored
# +
quality_iter,sizes = DCD.similarity_at_each_step(generated_communities_SN,com_iterative)
quality_survival,sizes = DCD.similarity_at_each_step(generated_communities_SN,com_survival)
quality_smoothed,sizes = DCD.similarity_at_each_step(generated_communities_SN,com_smoothed)
df = pd.DataFrame({"iterative":quality_iter,"survival":quality_survival,"smoothed":quality_smoothed})
df.plot(subplots=True,sharey=True)
# -
# ## Smoothness Evaluation
# We can evaluate the smoothness of a partition by comparing how the partition in each step is similar to the partition in the next. Again, any measure can be used, by default the overlapping NMI, because two adjacent partitions do not necessarily have the same nodes.
# * This evaluation is *internal*.
# * This time, it depends on the *labels* given to nodes accross steps, so a static algorithm applied at each step would have a score of zero.
# * The score does not depends at all on the quality of the solution, i.e., having all nodes in the same partition at every step would obtain a perfect score of 1
# +
quality_ref,sizes_ref = DCD.consecutive_sn_similarity(generated_communities_SN)
quality_iter,sizes_iter = DCD.consecutive_sn_similarity(com_iterative)
quality_survival,sizes_survival = DCD.consecutive_sn_similarity(com_survival)
quality_smoothed,sizes_smoothed = DCD.consecutive_sn_similarity(com_smoothed)
df = pd.DataFrame({"reference":quality_ref,"iterative":quality_iter,"survival":quality_survival,"smoothed":quality_smoothed})
df.plot(subplots=True,sharey=True)
# -
# ## Global scores
# Another family of scores we can compute are not based on step by step computations, but rather compute directly a single score on whole communities
# ### Longitudinal Similarity
# This score is computed using a usual similarity measure, by default the AMI. But instead of computing the score for each step independently, it is computed once, consider each (node,time) pair as a data point (instead of each node in a static network).
# * The evaluation is *external*, it requires a (longitudinal) reference partition
# * It takes into account both the similarity at each step and the labels accros steps
# * Similar to step by step similarity, only (node,time) couples with a known affiliation in the reference partition are used, others are ignored
# +
quality_iter = DCD.longitudinal_similarity(generated_communities_SN,com_iterative)
quality_survival = DCD.longitudinal_similarity(generated_communities_SN,com_survival)
quality_smoothed = DCD.longitudinal_similarity(generated_communities_SN,com_smoothed)
print("iterative: ",quality_iter)
print("survival: ",quality_survival)
print("smoothed: ",quality_smoothed)
# -
# ### Global Smoothness
# Trhee methods are proposed to evaluate the smoothness at the global level.
#
# The first is the average value of partition smoothness as presented earlier, and is called `SM-P` for Partition Smoothness
#
# The second one computes how many changes in affiliation there are, and the score `SM-N` (Node Smoothness) is 1/number of changes
# * It penalizes methods with many *glitches*, i.e., transient affiliation change.
# * It does not penalize long term changes
#
# The third computes instead the entropy per node, and the score `SM-L` (Label smoothness) is 1/average node entropy.
# * It does not penalize much glitches
# * It advantages solutions in which nodes tend to belong to few communities
#
# For all 3 scores, higher is better.
print("iterative: SM-P" ,DCD.SM_P(com_iterative), "SM-N:",DCD.SM_N(com_iterative), " SM-L:",DCD.SM_L(com_iterative))
print("survival: SM-P ",DCD.SM_P(com_survival), "SM-N:",DCD.SM_N(com_survival), " SM-L:",DCD.SM_L(com_survival))
print("smoothed: SM-P:",DCD.SM_P(com_smoothed), "SM-N:",DCD.SM_N(com_smoothed), " SM-L:",DCD.SM_L(com_smoothed))
|
demo_DCD.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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 datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import yfinance as yf
import pickle
import plotly.express as px
import plotly.graph_objects as go
# from myportfolio import myportfolio as mp
from demoportfolio import demo_portfolio as dp
style.use('ggplot')
# -
# # Setting up the portfolio or choosing the stocks
#
# `myportfolio` is a hidden file. It's a dictionary with the following structure
# `demo_portfolio = {'AAPL': [{'action':'buy', 'date': dt.date(year=2010, month=1, day=1), 'amount': 2000}],
# 'MSFT': [{'action':'buy', 'date': dt.date(year=2000, month=1, day=1), 'amount': 2000}]}`
# It's a dictionary with
# <ul><li> keys: name of the stock
# <li>values: A list (or lists) of dictionary(ies) with:
# <ul><li> key `action` and values the string `buy` or `sell` for the corresponding action</li>
# <li> key `date` and value a datetime object with the date of buying</li>
# <li> key `amount` a float with the number of shares bought</li> </ul>
# Each value of the dictionary can have longer than 1 length of lists, if a share was bought or sold multiple times.</ul>
# +
stocks = list(dp.keys())
# Use your own portfolio
# stocks = list(myportfolio.keys())
# or set your own stocks
# stocks = ['AAPL', 'MSFT']
# print example, also accessing the data in the dictionary
for stock in dp:
for dic in dp[stock]:
# print(stock, dic)
print(
f"For {stock} on {str(dic['date'])}, bought {dic['amount']} share(s)")
# -
# # Setting dates and downloading the data
# +
start = dt.datetime(2015, 1, 1)
end = dt.datetime.now()
df = yf.download(stocks,
start=start,
end=end,
progress=True)
# df.to_csv(f"Stocks_{'-'.join(stocks)}_{dt.date.today()}.csv")
# -
# # Exploratory plots
plot = True
plt.figure(figsize=(12,7))
if plot:
if len(stocks) == 1:
plt.plot(df.index, df['Adj Close'], label=stocks[0])
plt.plot(df.index, df['Adj Close'].rolling(window=14).mean(), '--k')
plt.legend(frameon=False)
plt.xlabel('Date')
plt.ylabel('Adj Close price ($)')
plt.show()
else:
for stock in stocks:
plt.plot(df.index, df['Adj Close'][stock], label=stock)
plt.plot(df.index, df['Adj Close'][stock].rolling(window=14).mean(), '--k')
plt.legend(frameon=False)
plt.xlabel('Date')
plt.ylabel('Adj Close price ($)')
plt.savefig(fname='Figure_1.png', bbox_tight=True, transparency=True, dpi=400)
plt.show()
# +
# fig = go.Figure()
# for stock in stocks:
# fig.add_trace(go.Scatter(x=df.index, y=df['Adj Close'][stock],
# mode='lines',
# name=stock))
# fig.add_trace(go.Scatter(x=df.index, y=df['Adj Close'][stock].rolling(window=14).mean(),
# line=dict(color='black', dash='dash'),
# name=f'{stock} 14 days moving average'))
# fig.update_layout(title=f'Adj Close price',
# xaxis_title='Date',
# yaxis_title='Price ($)')
# fig.show()
# -
URL = r'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
sp500 = pd.read_html(URL)[0]
print(sp500.shape)
sp500.head()
foo = yf.download(list(sp500['Symbol'].unique()),
start=start,
end=end,
progress=True)
foo.to_pickle('sp500_5y_data.pickle')
|
Stocks Data.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="ZCf4_UTUWYXt"
# ## Step 0: Delete related dependency
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 46822, "status": "ok", "timestamp": 1634113321074, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GiGMTOcDiDknof5dPIfslC7OyDBirpZc2iYp_BP=s64", "userId": "09493687449730268157"}, "user_tz": -480} id="gau1vo0_Vg40" outputId="cf390a50-5a37-4e25-b40d-c8be2219cc41"
# !pip uninstall tensorflow
# !pip uninstall tensorflow-gpu
# !pip uninstall keras
# !pip uninstall h5py
# + [markdown] id="u3z5zJW8WgMC"
# ## Step 0.5: Install designated version
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 52663, "status": "ok", "timestamp": 1634113377328, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GiGMTOcDiDknof5dPIfslC7OyDBirpZc2iYp_BP=s64", "userId": "09493687449730268157"}, "user_tz": -480} id="POALflCSVHZ8" outputId="f8587428-dfe1-48cb-9669-1147150ddbab"
# !pip install Keras==2.2.5
# !pip install tensorflow-gpu==1.14
# !pip install h5py==2.10.0
# + [markdown] id="R155-58KWmO3"
# ## Step 1: Enter directory
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 17565, "status": "ok", "timestamp": 1634113396812, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GiGMTOcDiDknof5dPIfslC7OyDBirpZc2iYp_BP=s64", "userId": "09493687449730268157"}, "user_tz": -480} id="d8-5BSrhQAUY" outputId="7ba21ab2-938c-4d56-e347-79404b66b44b"
import os
from google.colab import drive
drive.mount('/content/drive')
path = "/content/drive/My Drive/funcom_reproduction"
os.chdir(path)
os.listdir(path)
# + [markdown] id="FIevn48aWoxs"
# ## Step 2: Model training **( batch_size = 200 )**
# + colab={"base_uri": "https://localhost:8080/"} id="fOrWRB8dQumu" outputId="091638b9-6dda-4c01-a34f-1234bd4ba3a7"
# !python train.py --model-type=ast-attendgru --gpu=0
# + [markdown] id="oD5SXloheOgV"
# ## Step 3: Prediction and generating txt document
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 839937, "status": "ok", "timestamp": 1633812714199, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GiGMTOcDiDknof5dPIfslC7OyDBirpZc2iYp_BP=s64", "userId": "09493687449730268157"}, "user_tz": -480} id="Sr5FxBpTP5lD" outputId="dc6ffb74-d641-4a8f-ece6-585e11bdbc57"
# !python predict.py ./scratch/funcom/data/outdir/models/ast-attendgru_E03_1633784994.h5 --gpu=0
# + [markdown] id="3vTbqXmxedXj"
# ## Step 4: BLEU value calculation
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 35868, "status": "ok", "timestamp": 1633813169621, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GiGMTOcDiDknof5dPIfslC7OyDBirpZc2iYp_BP=s64", "userId": "09493687449730268157"}, "user_tz": -480} id="mb8czeyvecuY" outputId="3650ca62-e83e-4509-d6fb-9a57a76a1421"
# !python bleu.py ./scratch/funcom/data/outdir/predictions/predict-ast-attendgru_E03_1633784994.txt
|
ast-attendgru.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] tags=[]
# # SOP0124 - List Keys For Encryption At Rest.
#
# ## Description
#
# Use this notebook to connect to the `controller` database to list all
# keys which are used by the encryption at rest feature of SQL Server Big
# Data Cluster. These keys are used by HDFS encryption zone.
#
# Sample output: Name, Cipher, Bit Length, Master Key Version mykey1,
# AES/CTR/NoPadding, 256, hdfs-encryption-master-key@0 mykey2,
# AES/CTR/NoPadding, 128, hdfs-encryption-master-key@0 mykey3,
# AES/CTR/NoPadding, 192, hdfs-encryption-master-key@0 securelakekey,
# AES/CTR/NoPadding, 256, hdfs-encryption-master-key@0
#
# ## Steps
#
# ### Instantiate Kubernetes client
# + tags=["hide_input"]
# Instantiate the Python Kubernetes client into 'api' variable
import os
from IPython.display import Markdown
try:
from kubernetes import client, config
from kubernetes.stream import stream
except ImportError:
# Install the Kubernetes module
import sys
# !{sys.executable} -m pip install kubernetes
try:
from kubernetes import client, config
from kubernetes.stream import stream
except ImportError:
display(Markdown(f'HINT: Use [SOP059 - Install Kubernetes Python module](../install/sop059-install-kubernetes-module.ipynb) to resolve this issue.'))
raise
if "KUBERNETES_SERVICE_PORT" in os.environ and "KUBERNETES_SERVICE_HOST" in os.environ:
config.load_incluster_config()
else:
try:
config.load_kube_config()
except:
display(Markdown(f'HINT: Use [TSG118 - Configure Kubernetes config](../repair/tsg118-configure-kube-config.ipynb) to resolve this issue.'))
raise
api = client.CoreV1Api()
print('Kubernetes client instantiated')
# + [markdown] tags=[]
# ### Get the namespace for the big data cluster
#
# Get the namespace of the Big Data Cluster from the Kuberenetes API.
#
# **NOTE:**
#
# If there is more than one Big Data Cluster in the target Kubernetes
# cluster, then either:
#
# - set \[0\] to the correct value for the big data cluster.
# - set the environment variable AZDATA_NAMESPACE, before starting Azure
# Data Studio.
# + tags=["hide_input"]
# Place Kubernetes namespace name for BDC into 'namespace' variable
if "AZDATA_NAMESPACE" in os.environ:
namespace = os.environ["AZDATA_NAMESPACE"]
else:
try:
namespace = api.list_namespace(label_selector='MSSQL_CLUSTER').items[0].metadata.name
except IndexError:
from IPython.display import Markdown
display(Markdown(f'HINT: Use [TSG081 - Get namespaces (Kubernetes)](../monitor-k8s/tsg081-get-kubernetes-namespaces.ipynb) to resolve this issue.'))
display(Markdown(f'HINT: Use [TSG010 - Get configuration contexts](../monitor-k8s/tsg010-get-kubernetes-contexts.ipynb) to resolve this issue.'))
display(Markdown(f'HINT: Use [SOP011 - Set kubernetes configuration context](../common/sop011-set-kubernetes-context.ipynb) to resolve this issue.'))
raise
print('The kubernetes namespace for your big data cluster is: ' + namespace)
# + [markdown] tags=[]
# ### Python function queries `controller` database and return results.
# + tags=[]
try:
import pandas
except ModuleNotFoundError:
# !{sys.executable} -m pip install --user pandas
import pandas
from io import StringIO
pandas.set_option('display.max_colwidth', -1)
name = 'controldb-0'
container = 'mssql-server'
def get_dataframe(query):
command=f"""export SQLCMDPASSWORD=$(cat /var/run/secrets/credentials/mssql-sa-password/password);
/opt/mssql-tools/bin/sqlcmd -b -S . -U sa -Q "SET NOCOUNT ON;
{query}" -d controller -s"^" -W > /tmp/out.csv;
sed -i 2d /tmp/out.csv; cat /tmp/out.csv"""
output=stream(api.connect_get_namespaced_pod_exec, name, namespace, command=['/bin/sh', '-c', command], container=container, stderr=True, stdout=True)
return pandas.read_csv(StringIO(output), sep='^')
print("Function 'get_dataframe' defined")
# + [markdown] tags=[]
# ### List all keys for Hadoop encryption at rest.
# + tags=[]
import json
import base64
df = get_dataframe("select account_name, CAST(application_metadata AS NVARCHAR(4000)) from Credentials where application_metadata like '%hdfsvault-svc%' and type = '2'")
print("{:<20} {:<25} {:<20} {:<30}".format('Name', 'Cipher', 'Bit Length', 'Master Key Version'))
print("-------------------------------------------------------------------------------------------------")
for index, row in df.iterrows():
key_name = row[0]
applicationJson = json.loads(row[1])
cipher = applicationJson["cipher"]
bit_length = applicationJson["bitLength"]
originalUrl = base64.b64decode(applicationJson["master_key_version_name"]).decode()
splitItems = originalUrl.split("/")
master_key_version = splitItems[-2] + "@" + splitItems[-1]
print("{:<20} {:<25} {:<20} {:<30}".format(key_name, cipher, bit_length, master_key_version))
df = get_dataframe("select account_name, application_metadata from Credentials where application_metadata like '%hdfsvault-svc%' and type = '3'")
print("Encryption Key protector")
print("-------------------------")
for index, row in df.iterrows():
key_name = row[0]
print(key_name)
# + tags=[]
print("Notebook execution is complete.")
|
Big-Data-Clusters/CU9/public/content/tde/sop124-list-keys-encryption-at-rest.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Ex2 - Getting and Knowing your Data
# This time we are going to pull data directly from the internet.
# Special thanks to: https://github.com/justmarkham for sharing the dataset and materials.
#
# ### Step 1. Import the necessary libraries
import pandas as pd
# ### Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv).
# ### Step 3. Assign it to a variable called chipo.
chipo = pd.read_csv('chipotle.tsv', delimiter='\t')
# ### Step 4. See the first 10 entries
chipo.head(10)
# ### Step 5. What is the number of observations in the dataset?
# Solution 1
len(chipo)
# Solution 2
chipo.shape
# ### Step 6. What is the number of columns in the dataset?
len(chipo.columns)
# ### Step 7. Print the name of all the columns.
for col in chipo.columns:
print(col)
# ### Step 8. How is the dataset indexed?
chipo.index
# ### Step 9. Which was the most-ordered item?
chipo.groupby('item_name').mean().nlargest(5, 'quantity')
# ### Step 10. For the most-ordered item, how many items were ordered?
chipo.groupby('item_name')['quantity'].sum().nlargest(1)[0]
# ### Step 11. What was the most ordered item in the choice_description column?
chipo.groupby('choice_description')['quantity'].sum().nlargest(1)
# ### Step 12. How many items were orderd in total?
chipo['quantity'].sum()
# ### Step 13. Turn the item price into a float
# #### Step 13.a. Check the item price type
chipo['item_price'].dtype
# #### Step 13.b. Create a lambda function and change the type of item price
rem_sign = lambda x: float(x[1:])
chipo['item_price'] = chipo['item_price'].map(rem_sign)
# #### Step 13.c. Check the item price type
chipo['item_price'].dtype
# ### Step 14. How much was the revenue for the period in the dataset?
chipo['item_price'].sum()
# ### Step 15. How many orders were made in the period?
chipo['order_id'].nunique()
# ### Step 16. What is the average revenue amount per order?
# Solution 1
print(chipo['item_price'].sum()/chipo['order_id'].nunique())
# Solution 2
chipo.groupby('order_id')['item_price'].sum().mean()
# ### Step 17. How many different items are sold?
chipo['item_name'].nunique()
|
01_Getting_&_Knowing_Your_Data/Chipotle/Exercises.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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
dataset = tf.data.Dataset.from_tensor_slices(np.arange(10))
print(dataset)
for item in dataset:
print(item)
# 1. repeat epoch
# 2. get batch
dataset = dataset.repeat(3).batch(7)
for item in dataset:
print(item)
# interleave:
# case: 文件dataset -> 具体数据集
dataset2 = dataset.interleave(
lambda v: tf.data.Dataset.from_tensor_slices(v), # map fun
cycle_length=5, # cycle_length
block_length=5, # block_length
)
for item in dataset2:
print(item)
# +
x = np.array([[1, 2], [3, 4], [5, 6]])
y = np.array(['cat', 'dog', 'fox'])
dataset3 = tf.data.Dataset.from_tensor_slices((x, y))
print(dataset3)
for item_x, item_y in dataset3:
print(item_x.numpy(), item_y.numpy())
# -
dataset4 = tf.data.Dataset.from_tensor_slices({
"feature": x,
"label": y
})
for item in dataset4:
print(item['feature'].numpy(), item['label'].numpy())
|
TensorFlow-2.0/01-TensorFlow Base/06-Tensorflow-Dataset-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
# ---
# # Intro
#
# At the end of this lesson, you will understand how stochastic gradient descent and back-propagation are used to set the weights in a deep learning model. These topics are complex, but many experts view them as the most important ideas in deep learning.
#
# # Lesson
#
# + _kg_hide-input=true
from IPython.display import YouTubeVideo
YouTubeVideo('kQmHaI5Jw1c', width=800, height=450)
# -
# # Keep Going
# Now you are ready to **[train your own models from scratch](https://www.kaggle.com/dansbecker/deep-learning-from-scratch).**
#
# ---
# **Links Mentioned**
#
# [ReLU activation function](https://www.kaggle.com/dansbecker/rectified-linear-units-relu-in-deep-learning)
|
tensorflow_1_x/7_kaggle/notebooks/deep_learning/raw/tut6_deep_understanding.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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 cv2
import numpy as np
test_dirs = os.listdir("data/stage1_test")
test_filenames=["data/stage1_test/" + file_id + "/images/" + file_id + ".png" for file_id in test_dirs]
test_images=[cv2.imread(imagefile) for imagefile in test_filenames]
# -
def segment_mask(img_rgb):
# convert color image to gray scale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
# apply morphology transformation to open gaps between adjascent nuclei by suggesting shapes are ellipses
ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
img_open = cv2.morphologyEx(img_gray, cv2.MORPH_OPEN, ellipse)
# use OTSU method of threshholding for bimodal pixel intensity
img_th = cv2.threshold(img_open, 0, 255, cv2.THRESH_OTSU)[1]
# invert the image if nuclei are dark and background is light i.e. fluorescence microscopy image
if (np.sum(img_th == 255) > np.sum(img_th == 0)):
img_th = cv2.bitwise_not(img_th)
# perform morphological opening on binary image
img_mask_open = cv2.morphologyEx(img_th, cv2.MORPH_OPEN, ellipse)
# segment masked nuclei
seg_masks = cv2.connectedComponents(img_mask_open)[1]
return seg_masks
test_segmented_masks = [segment_mask(img) for img in test_images]
# +
def rle_encoding(segment_masks):
values = list(np.unique(segment_masks))
values.remove(0)
RLEs = []
for v in values:
dots = np.where(segment_masks.T.flatten() == v)[0]
run_lengths = []
prev = -2
for b in dots:
if (b > prev + 1):
run_lengths.extend((b + 1, 0))
run_lengths[-1] += 1
prev = b
RLEs.append(run_lengths)
return RLEs
test_RLEs = [rle_encoding(segmented_img) for segmented_img in test_segmented_masks]
# -
with open("benchmark_model.csv", "a") as myfile:
myfile.write("ImageId,EncodedPixels\n")
for i, RLEs in enumerate(test_RLEs):
for RLE in RLEs:
myfile.write(test_dirs[i] + "," + " ".join([str(i) for i in RLE]) + "\n")
|
capstone_benchmark.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.9.2 64-bit
# language: python
# name: python3
# ---
DATA_PATH = '../../data/Classification_2/raw/HAM10000_metadata.csv'
import pandas as pd
raw_df = pd.read_csv(DATA_PATH)
raw_df.shape
# Display random answer
raw_df.sample(1).iloc[0]
raw_df.info()
raw_df.describe()
print(raw_df['dx'].value_counts())
|
notebooks/Classification_2/00exploration.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: venv_explo_pysyft_ori
# language: python
# name: venv_explo_pysyft_ori
# ---
# # Syft Duet for Federated Learning - Data Owner (American Bank)
#
# ## Setup
#
# First we need to install syft 0.3.0 because for every other syft project in this repo we have used syft 0.2.9. However, a recent update has removed a lot of the old features and replaced them with this new 'Duet' function. To do this go into your terminal and cd into the repo directory and run:
#
# > pip uninstall syft
#
# Then confirm with 'y' and hit enter.
#
# > pip install syft==0.3.0
#
# NOTE: Make sure that you uninstall syft 0.3.0 and reinstall syft 0.2.9 if you want to run any of the other projects in this repo. Unfortunately when PySyft updated from 0.2.9 to 0.3.0 it removed all of the previous functionalities for the FL, DP, and HE that have previously been iplemented.
# +
# Double check you are using syft 0.3.0 not 0.2.9
# # !pip show syft
# -
import syft as sy
import torch as th
import pandas as pd
# ## Initialising Duet
#
# For each bank there will be this same initialisation step. Ensure that you run the below code. This should produce a Syft logo and some information. The important part is the lines of code;
# ```python
# import syft as sy
# duet = sy.duet("xxxxxxxxxxxxxxxxxxxxxxxxxxx")
# ```
# Where the x's are some combination of letters and numbers. You need to take this key and paste it in to the respective banks duet code in the central aggregator. This should be clear and detailed in the central aggregator notebook. In essence, this is similar to the specific banks generating a server and key, and sending the key to the aggregator to give them access to this joint, secure, server process.
#
# Once you have run the key in the code on the aggregator side, it will give you a similar key which it tells you to input on this side. There will be a box within the Syft logo/information output on this notebook to input the key. Once you enter it and hit enter then the connection for this bank should be established.
# +
# We now run the initialisation of the duet
# Note: this can be run with a specified network if required
# For exmaple, if you don't trust the netwrok provided by pysyft
# to not look at the data
duet = sy.duet()
sy.logging(file_path="./syft_do.log")
# -
# >If the connection is established then there should be a green message above saying 'CONNECTED!'. Similarly, there should also be a Live Status indicating the number of objects, requests, and messages on the duet.
# # Import American Bank Data
data = pd.read_csv('datasets/american-bank-data.csv', sep = ',')
target = pd.read_csv('datasets/american-bank-target.csv', sep = ',')
data.head()
data = th.tensor(data.values).float()
data
target = th.tensor(target.values).float()
target
# +
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
data = sc_X.fit_transform(data)
data = th.tensor(data).float()
data
# -
# ## Label and Send Data to Server
#
# Here we are tagging, and labeling the specific banks data. Although we are sending the data, this does not mean that it is accessible by the central aggregator. We are sending this data to a trusted network server - hence, the reason we can specify our own when establishing the duet, just in case we don't trust the default one. This specific network should reside in the country of the data, more specifically wihtin the banks own network, therefore adhering to all regulations where neccessary.
# +
data = data.tag("data")
data.describe("American Bank Training Data")
target = target.tag("target")
target.describe("American Bank Training Target")
# Once we have sent the data we are left with a pointer to the data
data_ptr = data.send(duet, searchable=True)
target_ptr = target.send(duet, searchable=True)
# -
# Detail what is stored
duet.store.pandas
# >NOTE: Although the data has been sent to this 'store' the other end of the connection cannot access/see the data without requesting it from you. However, from this side, because we sent the data, we can retrieve it whenever we want without rewuesting permission. Simply run the following code;
#
# ```python
# duet.store["tag"].get()
# ```
#
# >Where you replace the 'tag' with whatever the tag of the data you wish to get. Once you run this, the data will be removed from the store and brought back locally here.
# Detail any requests from client side. As mentioned above
# on the other end they need to request access to data/anything
# on duet server/store. This si where you can list any requests
# outstanding.
duet.requests.pandas
# +
# Because on the other end of the connection they/we plan on
# running a model (with lots of requests) we can set up some
# request handlers that will automatically accept/deny certain
# labeled requests.
# For example, lets assume that Portugal and Australia have similar
# rules on how much information can be shared - or even just the banks
# preferences. However, the American bank refuses to even show the models
# loss at each epoch. Then we can change the action to 'deny' instead of
# 'accept'. This will still perform computation but not allow the other
# end of the connection to see the computed data, i.e. loss value.
duet.requests.add_handler(
name="loss",
action="deny",
timeout_secs=-1, # no timeout
print_local=True # print the result in your notebook
)
duet.requests.add_handler(
name="model_download",
action="accept",
print_local=True # print the result in your notebook
)
# -
duet.requests.handlers
|
notebooks/eXate_samples/pysyft/duet_multi/3.0-mg-american-bank.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Integers
# *Question 1*
#
# Find the type of the value of the variables below.
#
# x = 1
#
# x = 1.5
x = 1
type(x)
x = 1.5
type(x)
# *Question 2*
#
# Divide 7 by 3.
print ( 7 / 3)
# *Question 3*
#
# Divide 7 by 3 but the answer should be in integer value.
print ( 7 // 3)
|
Lesson03/Integers.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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.ensemble import RandomForestRegressor
import pandas as pd
import numpy as np
import time
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
import matplotlib
from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
import random
# +
p_train = 0.01
p_test = 0.05
###############################
# THIS ONLY NEEDS TO RUN ONCE #
###############################
indexes = random.sample(range(1,68853600),int(68853600*(1-p_train)))
#LOADING TRAINING SET
start = time.time()
#Loading the inputs for the training set
train_inputs_thermal = pd.read_csv('..\\data2\\inputs\\inputs_thermal.csv')
input_vars = list(test_inputs_thermal.columns[1:])
X = np.array(train_inputs_thermal.loc[:,'G_Dh':].values)
area_envelope = np.multiply(np.array(train_inputs_thermal.loc[:,'perimeter'].values),np.array(train_inputs_thermal.loc[:,'height'].values)) + 2*np.array(train_inputs_thermal.loc[:,'area'].values)
train_inputs_thermal = None
#Loading the outputs or targets for the training set
train_outputs_thermal = pd.read_csv('..\\data2\\energy_demands\\thermal_losses.csv')
Y = np.array(train_outputs_thermal.loc[:,'Qs-Qi(Wh)'].values)
train_outputs_thermal = None
end = time.time()
print(str(end-start)+' seconds')
#SCALING TRAINING SET
start = time.time()
#Scaling the inputs and outputs (substracting mean and dividing by the standard deviation)
X_mean = X.mean(axis=0)
X_std = X.std(axis=0)
X = np.divide(X - X_mean, X_std)
#We use the area of the building enevelope to normalize the thermal losses (since we know that thermal losses are proportional to this area)
Y = np.divide(Y, area_envelope)
area_envelope = None
Y_mean = Y.mean(axis=0)
Y_std = Y.std(axis=0)
Y = np.divide(Y - Y_mean, Y_std)
end = time.time()
print(str(end-start)+' seconds')
#LOADING THE TEST SET
start = time.time()
indexes = random.sample(range(1,12299040),int(12299040*(1-p_test)))
test_inputs_thermal = pd.read_csv('..\\data2\\inputs\\inputs_thermal_testset.csv')
X_test = np.array(test_inputs_thermal.loc[:,'G_Dh':].values)
area_envelope_test = np.multiply(np.array(test_inputs_thermal.loc[:,'perimeter'].values),np.array(test_inputs_thermal.loc[:,'height'].values)) + 2*np.array(test_inputs_thermal.loc[:,'area'].values)
test_inputs_thermal = None
test_outputs_thermal = pd.read_csv('..\\data2\\energy_demands\\thermal_losses_testset.csv')
Y_test = np.array(test_outputs_thermal.loc[:,'Qs-Qi(Wh)'].values)
test_outputs_thermal = None
end = time.time()
print(str(end-start)+' seconds')
#SCALING TEST SET
X_test = np.divide(X_test - X_mean, X_std)
# +
##################################
# THIS IS THE CODE TO BE CHANGED #
##################################
start = time.time()
#TRAINING THE MACHINE LEARNING REGRESSOR
regr = RandomForestRegressor(max_depth=8, n_estimators=30)
regr.fit(X, Y)
end = time.time()
train_time = end-start
print(str(train_time)+' seconds')
# -
#We print the importances of the features we used for learning based on the information gain due to each of them (not all the regression algorithms allow this).
j = 0
for i in input_vars:
print(str(i)+': '+str(round(regr.feature_importances_[j]*100,2))+'%')
j += 1
# +
start = time.time()
#TESTING THE MACHINE LEARNING REGRESSOR
Y_pred = regr.predict(X_test)
end = time.time()
test_time = end-start
#Y_pred is normalized (since the regressor was trained using normalized targets). Now we de-normalize it a de-scale the predictions.
Y_pred = np.multiply(np.multiply(Y_pred, Y_std) + Y_mean, area_envelope_test)
print(str(test_time)+' seconds')
# -
#Calculating scores 0.6562254167979638
r2 = r2_score(Y_test,Y_pred)
mse = mean_squared_error(Y_test,Y_pred)
mae = mean_absolute_error(Y_test,Y_pred)
#Displaying results
print('Results for THERMAL LOSSES:')
print('R2: '+str(r2))
print('mse: '+str(mse))
print('mae: '+str(mae))
print('train_time: '+str(train_time))
print('test_time: '+str(test_time))
# +
figure(num=None, figsize=(16, 8), dpi=80, facecolor='w', edgecolor='k')
matplotlib.rc('xtick', labelsize=22)
matplotlib.rc('ytick', labelsize=22)
plt.plot(list(range(11000,11400)), Y_test[11000:11400],linewidth=3.0)
plt.plot(list(range(11000,11400)), Y_pred[11000:11400],linewidth=3.0)
plt.legend(['Simulation','Neural network prediction'], fontsize=20)
plt.xlabel('hours', fontsize=25)
plt.ylabel('Thermal losses (Wh)', fontsize=25)
# plt.savefig('thermal_losses.png', dpi=600)
# -
|
scripts/train_test_thermal.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 warnings
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
import re
import nltk
import string
import math
from matplotlib.colors import ListedColormap
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score, auc, ConfusionMatrixDisplay, classification_report
from sklearn.metrics import precision_score, recall_score, f1_score
# -
# # Phase 0 : Exploratory Data Analysis
df = pd.read_csv("spam.csv", encoding = "ISO-8859-1")
df.head()
# +
# We drop the redundent looking columns
unuseful = ["Unnamed: 2","Unnamed: 3","Unnamed: 4"]
df = df.drop(df[unuseful], axis=1)
# We rename the columns in order to make them more understandable
df.rename(columns = {"v1": "Target", "v2": "Text"}, inplace = True)
df.head()
# -
print(df['Text'][10])
print(df['Text'][8])
# Plot something useful. Taken from [here](https://www.kaggle.com/karnikakapoor/spam-or-ham-sms-classifier)
# +
sns.set_theme()
print('Ham:', len(df[df['Target'] == 'ham']), '\nSpam:', len(df[df['Target'] == 'spam']))
plt.figure(figsize=(12,8))
fg = sns.countplot(x = df["Target"])
fg.set_title("Count Plot of Classes", color="#58508d")
fg.set_xlabel("Classes", color="#58508d")
fg.set_ylabel("Number of Data points", color="#58508d")
# +
data = df
#Adding a column of numbers of charachters,words and sentences in each msg
data["No_of_Characters"] = data["Text"].apply(len)
data["No_of_Words"]=data.apply(lambda row: nltk.word_tokenize(row["Text"]), axis=1).apply(len)
data["No_of_sentence"]=data.apply(lambda row: nltk.sent_tokenize(row["Text"]), axis=1).apply(len)
data.describe().T
# -
plt.figure(figsize=(12,8))
fg = sns.pairplot(data=data, hue="Target")
plt.show(fg)
# # Phase 1: Data Preprocessing
#
# In order to further process the data, we need to make the data cleaner.
#
# In the first step we extract only the alphabetic characters, so we remove punctuation and numbers. Then we convert all the characters into lowercase.
nltk.download('wordnet')
# +
# pre-process a text : clean, tokenize and stem each word in text
def pre_processing(text):
# Initialize lemmatizer
lemmatizer = WordNetLemmatizer()
# Removing punctuation, lowercase the text, removing stopwords, map punctuation to space
translator = str.maketrans(string.punctuation, ' ' * len(string.punctuation))
p_text = text.translate(translator).lower()
ppt = ""
for word in p_text.split():
if word not in stopwords.words('english'):
ppt += word + " "
text = ppt.strip(" ")
token_words = word_tokenize(text)
lem_sentence = []
for word in token_words:
lem_sentence.append(lemmatizer.lemmatize(word, pos ='v'))
return ' '.join(lem_sentence)
df["Pre_processed_text"] = df["Text"].apply(pre_processing)
# +
# It creates a set for all the words
bag_words = set()
for sms in df["Pre_processed_text"]:
for w in sms.split(" "):
if w != "":
bag_words = bag_words.union({w})
# Create a list of the words <- our corpus of words
bag = list(bag_words)
# -
# # Phase 2: Extracting the Features
# It returns a list of words for each sms
def split_words(text, bag_words):
return text.split(" ")
df["Words"] = df["Pre_processed_text"].apply(split_words, args = (bag_words,))
# +
bag_len = len(bag) # Number of words in the bag # Size of the corpus
# Vectorize each sms, assign 1 every time a specific word is in the sms
def vectorize_sms(words):
vector = np.zeros(bag_len, dtype = "int64")
for i in range(bag_len):
if bag[i] in words:
vector[i] += words.count(bag[i])
return vector
# -
df["Vector"] = df["Words"].apply(vectorize_sms)
# Create a dataframe ready for the analysis. It has the sms (documents) on the row and the words (features) on the columns.
# This dataframe counts the words in the sms.
# +
# Initialize the dataframe
X = np.zeros((len(df), bag_len), dtype = "int64")
# For each sms consider its vectorized form
for i in range(len(df)):
X[i] += df.iloc[i, 7]
# Create a pandas Dataframe
pd.DataFrame(X, columns = bag)
# +
# Create the classes encoding the 'spam' and 'ham' information
'''
If a sms is ham == 0;
if a sms is spam == 1
'''
y = np.zeros(len(df), dtype="int64")
for i in range(len(df["Target"])):
if df.iloc[i,0] == "ham":
y[i] = 0
else:
y[i] = 1
# -
# # Phase 3: Model Building
# Splitting the test and training set
# We decided to consider the 20% of the dataset as test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)
X_train.shape, y_train.shape
N_yi = np.zeros((2, bag_len)) # feature count
N_y = np.zeros((2)) # total count
for i in range(len(y_train)):
# Compute N_y counting the features for each specific class
N_y[y_train[i]] += np.sum(X_train[i])
# Compute N_yi adding counting the specific words in each class
N_yi[y_train[i]] += (X_train[i])
print(N_yi)
# ## Prior
# +
P = np.zeros(2)
classes = np.unique(y_train)
# Implement Prior Probability P(A)
for j in classes:
P[j] = np.count_nonzero(y_train == j)/(len(y_train))
print(P)
# -
# ## Likelihood
# +
# The likelihood of each word to be in a ham or in a spam message
likelihood_matrix_words = np.zeros((2,bag_len))
for i in range(bag_len):
for j in range(2):
# NOTE: We implemented Laplace Smoothing
likelihood_matrix_words[j][i]=float((N_yi[j][i] + 1)/(N_y[j] + bag_len))
likelihood_matrix_words = pd.DataFrame(likelihood_matrix_words, columns = bag)
# -
likelihood_matrix_words
# + tags=[]
# Likelihood matrix for each sms
likelihood_matrix = np.zeros((len(X_train), 2))
for i in range(len(X_train)):
tmp_spam = []
tmp_ham = []
sms = X_train[i] #list of words
# NOTE: In order to have numerical stability, we opted for using the logarithms
# This way we convert all the products into sums
for index in range(len(sms)): #for each word in sms
if sms[index]!=0:
weight_ham, weight_spam = likelihood_matrix_words.iloc[:, index]
tmp_spam.append(math.log(weight_spam)**sms[index])
tmp_ham.append(math.log(weight_ham)**sms[index])
likelihood_matrix[i][0] = float(np.sum(tmp_ham))
likelihood_matrix[i][1] = float(np.sum(tmp_spam))
# -
likelihood_matrix_df = pd.DataFrame(likelihood_matrix, columns = ["ham", "spam"])
likelihood_matrix_df
# +
# Add the log of the prior probabilities
likelihood_final = np.zeros((len(X_train), 2))
for i in range(len(X_train)):
for j in range(2):
likelihood_final[i][j] = likelihood_matrix[i][j] + math.log(P[j])
likelihood_final = pd.DataFrame(likelihood_final, columns = ["ham", "spam"])
likelihood_final
# -
prob_spam = abs(likelihood_final['spam']) / (abs(likelihood_final['spam']) + abs(likelihood_final['ham']))
prob_spam
# +
# Take the max value between the two log-likelihoods to predict the label
res = likelihood_final.idxmax(axis = 1)
# Replace 'ham' with 0 and 'spam' with 1
res = res.replace("ham", 0)
res = res.replace("spam", 1)
res
# -
confusionMatrix=confusion_matrix(y_train, res)
print(c)
# +
true_positive=confusionMatrix[0,0]
false_negative=confusionMatrix[1,0]
false_positive=confusionMatrix[0,1]
true_negative=confusionMatrix[1,1]
true_positive_Rate=true_positive/(true_positive+false_negative)
false_positive_Rate=false_positive/(false_positive+true_negative)
print("true positive Rate",true_positive_Rate)
print("false positive Rate",false_positive_Rate)
# -
fpr, tpr, threshold = roc_curve(y_train, 1-prob_spam)
auc(fpr, tpr)
# plot the roc curve for the model
plt.plot([0,1], [0,1], linestyle='--', label='just tossing a coin')
plt.plot(fpr, tpr, marker='.', label='Naive Bayes')
# axis labels
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend()
# show the plot
plt.show()
# the optimal threshold is the treshold that create the greatest difference between the tpr and fpr
optimal_idx = np.argmax(tpr - fpr)
optimal_threshold = threshold[optimal_idx]
print("Threshold value is:", optimal_threshold)
print("TPR ",tpr[optimal_idx])
print("FPR ",fpr[optimal_idx])
# the threshold value is really near the default threshold
# ####
# Now, consider X_test, repeat the same steps as before
# +
likelihood_matrix_test = np.zeros((len(X_test), 2))
for i in range(len(X_test)):
tmp_spam = []
tmp_ham = []
sms = X_test[i] #list of sms in X_TEST
for index in range(len(sms)): #for each word in sms
if sms[index] != 0:
weight_ham, weight_spam = likelihood_matrix_words.iloc[:, index]
tmp_spam.append(math.log(weight_spam)**sms[index])
tmp_ham.append(math.log(weight_ham)**sms[index])
likelihood_matrix_test[i][0] = float(np.sum(tmp_ham))
likelihood_matrix_test[i][1] = float(np.sum(tmp_spam))
# -
likelihood_matrix_test_df = pd.DataFrame(likelihood_matrix_test, columns = ["ham", "spam"])
# +
# Add the log of the prior probabilities
likelihood_final_test = np.zeros((len(X_test), 2))
for i in range(len(X_test)):
for j in range(2):
likelihood_final_test[i][j] = likelihood_matrix_test[i][j] + math.log(P[j])
likelihood_final_test = pd.DataFrame(likelihood_final_test, columns = ["ham", "spam"])
likelihood_final_test
# -
prob_spam_test = abs(likelihood_final_test['spam']) / (abs(likelihood_final_test['spam']) + abs(likelihood_final_test['ham']))
prob_spam_test
# +
# Take the max value between the two log-likelihoods to predict the label
res_test = likelihood_final_test.idxmax(axis = 1)
# Replace 'ham' with 0 and 'spam' with 1
res_test = res_test.replace("ham", 0)
res_test = res_test.replace("spam", 1)
res_test
# -
cm = confusion_matrix(y_test, res_test)
cm
sns.set_theme(style="white")
disp = ConfusionMatrixDisplay(cm)
disp.plot()
plt.show()
print(classification_report(y_test, res_test))
# +
true_positive=cm[0,0]
false_negative=cm[1,0]
false_positive=cm[0,1]
true_negative=cm[1,1]
true_positive_Rate=true_positive/(true_positive+false_negative)
false_positive_Rate=false_positive/(false_positive+true_negative)
print("true positive Rate",true_positive_Rate)
print("false positive Rate",false_positive_Rate)
# -
fpr, tpr, threshold = roc_curve(y_test, 1-prob_spam_test)
# plot the roc curve for the model
plt.plot([0,1], [0,1], linestyle='--', label='just tossing a coin')
plt.plot(fpr, tpr, marker='.', label='Naive Bayes')
# axis labels
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend()
# show the plot
plt.show()
optimal_idx = np.argmax(tpr - fpr)
optimal_threshold = threshold[optimal_idx]
print("Threshold value is:", optimal_threshold)
print("TPR ",tpr[optimal_idx])
print("FPR ",fpr[optimal_idx])
# # Phase 4: Compare with other classifiers
# Including **MultinomialNB** from *sklearn*.
# +
#Testing on the following classifiers
classifiers = [MultinomialNB(),
KNeighborsClassifier(),
SVC(),
LogisticRegression()]
for cls in classifiers:
cls.fit(X_train, y_train)
# Dictionary of pipelines and model types for ease of reference
class_dict = {0: "NaiveBayes", 1: "KNeighbours", 2: "SVC", 3: "LogisticRegression"}
# -
# Cossvalidation
for i, model in enumerate(classifiers):
cv_score = cross_val_score(model, X_train, y_train, scoring = "accuracy")
print("%s: %f " % (class_dict[i], cv_score.mean()))
# ## Model evaluation
# +
# Model Evaluation
# creating lists of varios scores
precision =[]
recall =[]
f1_score = []
trainset_accuracy = []
testset_accuracy = []
for i in classifiers:
pred_train = i.predict(X_train)
pred_test = i.predict(X_test)
prec = precision_score(y_test, pred_test)
recal = recall_score(y_test, pred_test)
#f1_s = f1_score(y_test, pred_test)
train_accuracy = model.score(X_train, y_train)
test_accuracy = model.score(X_test, y_test)
#Appending scores
precision.append(prec)
recall.append(recal)
#f1_score.append(f1_s)
trainset_accuracy.append(train_accuracy)
testset_accuracy.append(test_accuracy)
# -
# initialise data of lists.
data = {'Precision':precision,
'Recall':recall,
#'F1score':f1_score,
'Accuracy on Testset':testset_accuracy,
'Accuracy on Trainset':trainset_accuracy}
# Creates pandas DataFrame.
Results = pd.DataFrame(data, index =["NaiveBayes", "KNeighbours", "SVC", "LogisticRegression"])
cmap2 = ListedColormap(["#E2CCFF", "#E598D8"])
Results.style.background_gradient(cmap = cmap2)
|
Davide_Simone2.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.7.4 64-bit
# name: python3
# ---
import cv2
# Reading Image
image = cv2.imread("download.jfif")
# Converting RGB image into Grayscale format
gray_image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
# Image Inversion
inverted_image = 255 - gray_image
blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0)
inverted_blurred = 255 - blurred
pencil_sketch = cv2.divide(gray_image, inverted_blurred, scale=256.0)
cv2.imshow("Original Image", image)
cv2.imshow("Pencil Sketch of Dog", pencil_sketch)
cv2.waitKey(0)
|
Python/Image_to_Sketch/main1.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# We use the Microsoft Azure Anomaly Detector service to identify potential anomalies as outliers in the dataset. A tutorial about this service can be found [here](https://docs.microsoft.com/en-us/learn/modules/identify-abnormal-time-series-data-anomaly-detector). Instructions on how to setup the service and install the Python package can be found [here](https://docs.microsoft.com/en-us/azure/cognitive-services/anomaly-detector/quickstarts/client-libraries?pivots=programming-language-python&tabs=windows).
# +
# # !pip install azure-ai-anomalydetector --upgrade
# -
# Import the necessary packages.
# +
import pandas as pd
import numpy as np
from azure.ai.anomalydetector import AnomalyDetectorClient
from azure.ai.anomalydetector.models import DetectRequest, TimeSeriesPoint, TimeGranularity, AnomalyDetectorError
from azure.core.credentials import AzureKeyCredential
import seaborn as sns
import matplotlib.pyplot as plt
# %matplotlib inline
# -
# Read in the data with input and output sensor measurements generated in the previous step.
# +
df_sensors = pd.read_parquet('./data_generated/raw_sensor_data.parquet')
df_sensors
# -
# Check the number of datapoints available for each sensor. Here we see the difference in counts for the time and value columns, corresponding to the missing values introduced for the input sensor measurements.
sensors_data_length = df_sensors.groupby('sensor').count()
sensors_data_length
# Here we have the core of our data preparation procedure. We start by running linear interpolation for all input sensors to impute missing values. Then we run the Azure Anomaly Detector service for all input and output sensors to flag anomalies and replace each anomalous data point by a missing value. Finally, we run a second pass of linear interpolation to impute those missing values. At the end of this process, we have our prepared dataset in wide format, indexed by time with measurements by minute.
# +
# %%capture --no-display
ANOMALY_DETECTOR_KEY = '<your anomaly detector key>'
ANOMALY_DETECTOR_ENDPOINT = '<your anomaly detector endpoint>'
client = AnomalyDetectorClient(AzureKeyCredential(ANOMALY_DETECTOR_KEY), ANOMALY_DETECTOR_ENDPOINT)
df_sensors_prepared = pd.DataFrame()
idx = pd.date_range(start=0, end=(sensors_data_length.max()['time'] - 1) * 60 * 1e9, freq='T', tz='UTC')
data_length = len(idx)
# max_data_points = 8640
# min_data_points = 12
for sensor in df_sensors['sensor'].unique():
df_sensor = df_sensors[df_sensors['sensor'] == sensor]
ts = pd.Series(df_sensor['value'])
ts.index = idx
ts = ts.interpolate(limit_direction='both')
batches = [ts[0:int(data_length/2)], ts[int(data_length/2):]]
responses = []
for batch in batches:
series = []
for index, value in zip(batch.index, batch):
series.append(TimeSeriesPoint(timestamp=index, value=value))
request = DetectRequest(series=series, granularity=TimeGranularity.PER_MINUTE, sensitivity=15)
response = client.detect_entire_series(request)
responses.append(response)
df_sensor['is_anomaly'] = responses[0].is_anomaly + responses[1].is_anomaly
df_sensor.reset_index(drop=True, inplace=True)
df_sensor['new_value'] = df_sensor['value']
df_sensor.loc[(df_sensor['is_anomaly'] == True), 'new_value'] = np.nan
ts = pd.Series(df_sensor['new_value'])
ts.index = idx
ts = ts.interpolate(limit_direction='both')
df_sensors_prepared[sensor] = ts
df_sensors_prepared
# -
# Here we plot a segment from the generated measurements for the input sensor IN2 plus its prepared data after missing value imputation and outlier replacement.
# +
sns.set(rc={'figure.figsize':(18, 8), 'figure.max_open_warning':0})
figure, axis = plt.subplots(2, 1)
plt.ylim(-0.9, 2.1)
axis[0].plot(df_sensors[df_sensors['sensor'] == 'IN2']['value'].reset_index(drop=True)[2000:6000])
axis[0].set_title('generated IN2 measurements')
axis[1].plot(df_sensors_prepared['IN2'].reset_index(drop=True)[2000:6000])
axis[1].set_title('prepared IN2 measurements')
# -
# Define a function to compute missing value ratios in a data frame.
def compute_missing_ratio(df):
df_missing = (df.isnull().sum() / len(df)) * 100
df_missing = df_missing.drop(df_missing[df_missing == 0].index).sort_values(ascending = False)
display(pd.DataFrame({'Missing Ratio' :df_missing}))
# Check for missing values in the prepared data frame.
compute_missing_ratio(df_sensors_prepared)
# Save the prepared dataset as a parquet file.
df_sensors_prepared.to_parquet('./data_prepared/prepared_sensor_data.parquet')
|
standalone/02_data_preparation.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] colab_type="text" gradient={"editing": false, "id": "176b6d57-9c9b-4220-afc4-59cee518ee7f", "kernelId": ""} id="view-in-github"
# <a href="https://colab.research.google.com/github/bengsoon/lstm_lord_of_the_rings/blob/main/LOTR_LSTM_Character_Level.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] gradient={"editing": false, "id": "78a50d87-f14f-458e-a5cc-b253e4980a76", "kernelId": ""} id="sBQN-dtIGzPk"
# ## Creating a Language Model with LSTM using Lord of The Rings Corpus
# In this notebook, we will create a character-level language language model using LSTM.
# + [markdown] gradient={"editing": false, "id": "59f1b821-f91c-49d6-b16b-f197ecbf79be", "kernelId": ""} id="BwvwLm9wnCwc"
# ### Imports
# + gradient={"editing": false, "execution_count": 42, "id": "f684ee60-982f-4b75-86c1-f693b9be6c0f", "kernelId": ""}
## for paperspace
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# # !pip install -r requirements.txt
# + gradient={"editing": false, "execution_count": 38, "id": "773c737a-b01a-4657-88cb-c37e1027ada4", "kernelId": ""} id="o75lMt9gIoRf"
import tensorflow as tf
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
from tensorflow.keras.layers import Embedding, Input, LSTM, Flatten, Dense, Dropout
from tensorflow.keras import Model
from tensorflow.keras.models import load_model
import numpy as np
from pprint import pprint as pp
from string import punctuation
import regex as re
import random
import os
from pathlib import Path
# + [markdown] gradient={"editing": false, "id": "05b0a9be-f651-4ef1-967d-3bdcc1fe0d92", "kernelId": ""} id="sMsUyeLHnFZC"
# ### Data Preprocessing & Pipeline
# + gradient={"editing": false, "execution_count": 2, "id": "1386aa19-e543-4fac-b7ea-edb3749341c4", "kernelId": ""} id="t4_puY1vH-Jv"
# get LOTR full text
# # !wget https://raw.githubusercontent.com/bengsoon/lstm_lord_of_the_rings/main/lotr_full.txt -P /content/drive/MyDrive/Colab\ Notebooks/LOTR_LSTM/data
# + [markdown] gradient={"editing": false, "id": "83cd9851-5afc-4ebf-ae8d-944baf3678bb", "kernelId": ""} id="s065iL9iBq_A"
# #### Loading Data
# + gradient={"editing": false, "execution_count": 6, "id": "8fd79a20-9a83-4fd7-8b0d-371e83c382e9", "kernelId": ""} id="SIYll8_1BycF"
path = Path("./")
# + colab={"base_uri": "https://localhost:8080/"} gradient={"editing": false, "execution_count": 7, "id": "e55354c5-aacc-456c-8a85-9db542b7e560", "kernelId": ""} id="8IVk7GxXn40r" outputId="7cffa039-02bb-4d40-ddec-92a0f2cff911"
with open(path / "data/lotr_full.txt", "r", encoding="utf-8") as f:
text = f.read()
print(text[:1000])
# + colab={"base_uri": "https://localhost:8080/"} gradient={"editing": false, "execution_count": 8, "id": "1069fe23-72ce-4f89-81ef-3aaaf082df18", "kernelId": ""} id="RjEFSBDEofqz" outputId="7b492d33-fb6e-4b3f-870f-9c9b025f7516"
print(f"Corpus length: {int(len(text)) / 1000 } K characters")
# + [markdown] gradient={"editing": false, "id": "20c107c1-53fa-4599-ac7c-a6c07169ad6e", "kernelId": ""} id="uhpey-V0ooM7"
# #### Unique Characters
# + gradient={"editing": false, "execution_count": 9, "id": "41392923-c71c-41c9-9e5c-08c2f68f926e", "kernelId": ""} id="wCcNzpC8o0rD"
chars = sorted(set(list(text)))
print("Total unique characters: %s" % (len(chars)))
# + gradient={"editing": false, "execution_count": 10, "id": "8519e226-ce2e-46f0-a964-8c3f0dccd5c3", "kernelId": ""} id="Lfip0JCRfrMT"
print(chars)
# + [markdown] id="XFvk_sHgpEbq"
# #### Preparing X & y Datasets
#
# We need to split the text into two sets of fixed-size character sequences (X & y)
# * The first sequence (`sentences`) is the input data where the model will receive a fixed-size (`MAX_SEQ_LEN`) character sequence
# * The second sequence (`next_chars`) is the output data, which is only 1 character.
# + gradient={"execution_count": 11, "id": "f7b0e649-e019-4b5d-918d-82d69eefd45e", "kernelId": ""} id="kzS0BUamA8_f"
# setting up model constants
MAX_SEQ_LEN = 20
MAX_FEATURES = len(chars)
step = 2
BATCH_SIZE = 64
EMBEDDING_DIM = 16
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 12, "id": "bbbded66-88b9-472d-a095-497a6d4678b5", "kernelId": ""} id="kfx1E_2-DNi4" outputId="d0fd4bf2-9d8b-472c-9d93-a8b2d63be711"
sentences = []
next_chars = []
for i in range(0, len(text) - MAX_SEQ_LEN, step):
sentences.append(text[i: i + MAX_SEQ_LEN])
next_chars.append(text[i + MAX_SEQ_LEN])
print("Total number of training examples:", len(sentences))
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 13, "id": "4962cae2-1362-4270-bda6-822be01d47d7", "kernelId": ""} id="1nm8ok_eFKp4" outputId="880af11d-8fd2-4303-c866-bf2d7d28f73c"
# randomly sample some of the input and output to visualize
for i in range(10):
ix = random.randint(0, len(sentences))
print(f"{sentences[ix]} ..... {next_chars[ix]}")
# + gradient={"execution_count": 14, "id": "b3d807b3-5e78-4f8d-bda3-ad9c20874c9e", "kernelId": ""} id="NttXyeNkmxBQ"
X_train_raw = tf.data.Dataset.from_tensor_slices(sentences)
y_train_raw = tf.data.Dataset.from_tensor_slices(next_chars)
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 15, "id": "a662c150-4346-4d82-9c66-54cb4d753401", "kernelId": ""} id="nS6ZY_vQnur9" outputId="32640daf-e86e-42a2-9f0e-243111bfc662"
for input, output in zip(X_train_raw.take(5), y_train_raw.take(5)):
print(f"{input.numpy().decode('utf-8')} ..... {output.numpy().decode('utf-8')}")
# + [markdown] id="b-RoO5g9oF11"
# #### Preprocessing with Keras `TextVectorization` layer
# [_doc_](https://www.tensorflow.org/api_docs/python/tf/keras/layers/TextVectorization)
#
# We will use the `TextVectorization` layer as the preprocessing pipeline for our data
# + gradient={"execution_count": 16, "id": "e44f62e7-fe35-4fac-aec0-e02e5ba7acc6", "kernelId": ""} id="CPkk5KYfpOGG"
def standardize_text(input):
"""
create a custom standardization that:
1. Fixes whitespaces
2. Removes punctuations & numbers
3. Sets all texts to lowercase
4. Preserves the Elvish characters
"""
input = tf.strings.regex_replace(input, r"[\s+]", " ")
input = tf.strings.regex_replace(input, r"[0-9]", "")
input = tf.strings.regex_replace(input, f"[{punctuation}–]", "")
return tf.strings.lower(input)
def char_split(input):
return tf.strings.unicode_split(input, 'UTF-8')
# + gradient={"execution_count": 17, "id": "a0e4373a-17f2-4e9a-9776-9516d663178b", "kernelId": ""} id="2YsTfuGvr1Yz"
# create text vectorization layer
vectorization_layer = TextVectorization(
max_tokens = MAX_FEATURES,
standardize = standardize_text,
split = char_split,
output_mode='int',
output_sequence_length=MAX_SEQ_LEN
)
# + gradient={"execution_count": 18, "id": "29cd6936-f807-453e-9fd9-6af8078b608d", "kernelId": ""} id="Av2-nTMwVg3i"
# create the vocabulary indexing with `adapt`
vectorization_layer.adapt(X_train_raw.batch(BATCH_SIZE))
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 19, "id": "fb3a892c-8cc8-4e89-9503-07020bf75395", "kernelId": ""} id="Ha0e8zdNZM9A" outputId="e1422f91-7b65-4537-9c8f-72e082582fc6"
print(f"Total unique characters: {len(vectorization_layer.get_vocabulary())}")
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 20, "id": "4973f32d-09ce-46d4-92f6-4448f7305677", "kernelId": ""} id="VfACnSAHcLo7" outputId="e606410c-9f70-44a0-e618-e40cf6d3fc90"
print(vectorization_layer.get_vocabulary())
# + gradient={"execution_count": 21, "id": "bcd25c53-7c94-4615-88b6-765e7c60b4f5", "kernelId": ""} id="UlqZ_iM2cQGT"
def vectorize_text(text):
""" Convert text into a Tensor using vectorization_layer"""
text = tf.expand_dims(text, -1)
return tf.squeeze(vectorization_layer(text))
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 22, "id": "be28aa20-e0ae-4268-a8a2-29c8f82837f3", "kernelId": ""} id="FNWzpoeyc9q9" outputId="24674c2c-ef3c-4566-9b1b-658d6d5d7da6"
test_text = "hello i am Hoaha"
vectorize_text(test_text)
# + [markdown] id="zbCiQhJpd5F-"
# #### Apply Text Vectorization to X & y datasets
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 23, "id": "1b4eb931-92d0-4b7c-801c-6fe8bcf3ae8e", "kernelId": ""} id="_yG2zJ-LdE8U" outputId="86a50c67-2810-4f86-c468-d343dd224c28"
# vectorize the dataset
X_train = X_train_raw.map(vectorize_text)
y_train = y_train_raw.map(vectorize_text)
X_train.element_spec, y_train.element_spec
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 24, "id": "e76873e0-5e5e-4a34-98dd-515ca639ed55", "kernelId": ""} id="g9Pj4qNKedwa" outputId="83d92ee7-0f57-408c-e319-92ee1224e315"
for elem in y_train.take(10):
print(elem)
# + gradient={"execution_count": 25, "id": "0d1be1a9-0bb8-4888-91da-ae9d13c25dd6", "kernelId": ""} id="UnWusGJVeuhK"
# we only one the first representation in the vector in the y_train dataset
y_train = y_train.map(lambda y: y[0])
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 26, "id": "735701a3-6097-4741-b15c-f8567755af70", "kernelId": ""} id="sJEa6PQvfbEU" outputId="47fcb6ed-ee19-42b6-c87b-c5350d207105"
for elem in y_train.take(5):
print(f"Shape: {elem.shape}")
print(f"Next Character: {elem.numpy()}")
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 27, "id": "48c6be67-452b-4d38-9826-c57e7391c344", "kernelId": ""} id="eBFi_L2lgL2R" outputId="f995db00-6073-484e-ce8a-f9b8f667c745"
# Check tensor dimensions to ensure we have MAX_SEQ_LEN-sized inputs and single output
X_train.take(1), y_train.take(1)
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 28, "id": "d9adef0f-856f-4fad-8ec2-6743d63b183a", "kernelId": ""} id="1Q7FdsXOg2XQ" outputId="24ea6572-7ff8-42f6-ee8b-6aca79ccd764"
for input, output in zip(X_train.take(5), y_train.take(5)):
print(f"{input.numpy()} ------------> {output.numpy()}")
# + [markdown] id="_8p3YiJRg_hP"
# #### Bringing the data pipeline together
# + [markdown] id="lRbr9Ub1hJ8K"
# **Joining the X and y into a dataset**
# + gradient={"execution_count": 29, "id": "3a46059d-5ee2-4c74-9fad-c51af7313b15", "kernelId": ""} id="M6G8kWIphMw-"
# joining X & y into a single dataset
train_dataset = tf.data.Dataset.zip((X_train, y_train))
# + [markdown] id="6N8Q5VeghVSa"
# **Setting data pipeline optimizations:**
# Perform async prefetching / buffering of data using AUTOTUNE
#
# + gradient={"execution_count": 30, "id": "4e44406e-1796-497e-855d-d0b3e7268d23", "kernelId": ""} id="PY_1f_H0hfXH"
AUTOTUNE = tf.data.AUTOTUNE
train_dataset = train_dataset.prefetch(buffer_size=512).batch(BATCH_SIZE, drop_remainder=True).cache().prefetch(buffer_size=AUTOTUNE)
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 31, "id": "bba515af-3a59-42f4-be39-3bd6848408da", "kernelId": ""} id="06t7wVLEhvBY" outputId="28b7317f-ecca-4ea2-975d-32c59f4abbf5"
print(f"Size of the dataset in batches: {train_dataset.cardinality().numpy()}")
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 32, "id": "c35d095c-46a9-404d-ad45-a2f96a53e97f", "kernelId": ""} id="J3LTZqwKh3Eg" outputId="a94c1d64-6027-4bb5-fd5f-8100f0bad166"
# check the tensor dimensions of X and y again
for sample in train_dataset.take(1):
print(f"Input (X) Dimension: {sample[0].numpy().shape}")
print(f"Output (y) Dimension: {sample[1].numpy().shape}")
# + [markdown] id="VCDje6OdiOBv"
# ### Build the LSTM Model!
# + gradient={"execution_count": 33, "id": "7ef0a756-2fa1-47d8-9a4f-418293cc9af6", "kernelId": ""} id="ff-C3pnnlR1D"
def char_LSTM_model(max_seq_len=MAX_SEQ_LEN, max_features=MAX_FEATURES, embedding_dim=EMBEDDING_DIM):
# Define input for the model (vocab indices)
inputs = tf.keras.Input(shape=(max_seq_len), dtype="int64")
# Add a layer to map the vocab indices into an embedding layer
X = Embedding(max_features, embedding_dim)(inputs)
X = Dropout(0.5)(X)
X = LSTM(128, return_sequences=True)(X)
X = Flatten()(X)
outputs = Dense(max_features, activation="softmax")(X)
model = Model(inputs, outputs, name="model_LSTM")
return model
# + colab={"base_uri": "https://localhost:8080/"} gradient={"execution_count": 34, "id": "685f775c-a5f3-4c30-a5f9-b7e5eec55cba", "kernelId": ""} id="gpI324yXrCCy" outputId="8ceaac43-e15e-4211-9efa-4ba6955078b9"
model = char_LSTM_model()
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001)
model.compile(loss="sparse_categorical_crossentropy", optimizer=optimizer, metrics=["accuracy"])
model.summary()
# + gradient={"execution_count": 35, "id": "75f802be-3d46-48df-9872-ef2e635ebd01", "kernelId": ""} id="Ing-AtSxllnH"
def sample(preds, temperature=0.2):
# helper function to sample an index from a probability array
preds=np.squeeze(preds)
preds = np.asarray(preds).astype("float64")
preds = np.log(preds) / temperature
exp_preds = np.exp(preds)
preds = exp_preds / np.sum(exp_preds)
probas = np.random.multinomial(1, preds, 1)
return np.argmax(probas)
def generate_text(model, seed_original, step, diversity):
seed=vectorize_text(seed_original)
# decode_sentence(seed.numpy().squeeze())
print(f"Starting the sentence with.... '{seed_original}'")
print("...Diversity:", diversity)
seed= vectorize_text(seed_original).numpy().reshape(1,-1)
generated = (seed)
for i in range(step):
predictions=model.predict(seed)
pred_max= np.argmax(predictions.squeeze())
next_index = sample(predictions, diversity)
generated = np.append(generated, next_index)
seed= generated[-MAX_SEQ_LEN:].reshape(1,MAX_SEQ_LEN)
return decode_sentence(generated)
def decode_sentence (encoded_sentence):
deceoded_sentence=[]
for word in encoded_sentence:
deceoded_sentence.append(vectorization_layer.get_vocabulary()[word])
sentence= ''.join(deceoded_sentence)
print(sentence)
return sentence
# + gradient={"id": "aa6f8b8e-0ace-4258-86ed-ec0be2aecead", "kernelId": ""} id="zSj2zhTQrTZe"
# Create a callback that saves the model's weights
checkpoint_path = path / "models/model_cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
save_weights_only=True,
verbose=1)
# Train the model
epochs = 30
BATCH_SIZE = 64
SAMPLING_STEPS = 100
for epoch in range(epochs):
print("-"*40 + f" Epoch: {epoch}/{epochs} " + "-"*40)
model.fit(train_dataset, batch_size=BATCH_SIZE, epochs=1, callbacks=[cp_callback])
print()
print("*"*30 + f" Generating text after epoch #{epoch} " + "*"*30)
start_index = random.randint(0, len(text) - MAX_SEQ_LEN - 1)
sentence = text[start_index : start_index + MAX_SEQ_LEN]
for diversity in [0.2, 0.5, 1.0, 1.2]:
generate_text(model, sentence, SAMPLING_STEPS, diversity)
print()
# + gradient={"id": "e3b76f5c-262e-43c8-a92b-4dcabd56c006", "kernelId": ""} id="CXRI53ovotoS"
model.save(path / "models/Char_LSTM_LOTR_20211112-1.h5" )
# + gradient={"execution_count": 40, "id": "9cbb9669-e6d4-44a3-ae79-88a8f3759e1a", "kernelId": ""}
model = load_model(path / "models/Char_LSTM_LOTR_20211112-1.h5")
# + gradient={"execution_count": 43, "id": "c35c4fe0-44bf-4d5c-9859-47cf5140c2bb", "kernelId": ""}
model.evaluate(train_dataset, batch_size = 64)
# + gradient={"id": "b4bfe53d-fb56-4b9a-8ccf-a1fb96adb0d2", "kernelId": ""}
|
LOTR_LSTM_Character_Level.ipynb
|
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# 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
# ---
# # Video Actor Synchroncy and Causality (VASC)
# ## RAEng: Measuring Responsive Caregiving Project
# ### <NAME>, 2020
# ### https://github.com/infantlab/VASC
#
# # Step 0 - Before we start
#
# Before anything else we need to install a few apps and libraries to make everything work. You should only have to do these steps once when you first install everything.
# ### 0.0 - Jupyter notebook environment
#
# *If you can read this you are probably already running Jupyter. Congratulations!*
#
# We recommend using the Anaconda Data Science platform (Python 3 version)
#
# https://www.anaconda.com/distribution/
#
# ### 0.1 - OpenPoseDemo application
#
# Next we need to download and install the [OpenPoseDemo](https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/doc/demo_overview.md) executable.
#
# Additionally, you need to download the trained neural-network models that OpenPose uses. To do this go to the `models` subdirectory of OpenPose directory, and double-click / run the `models.bat` script.
#
# The `openposedemo` bin/exe file can be run manually from the command line. It is worth trying this first so you understand what `openposedemo` is. See [this guide](https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/doc/demo_overview.md) or open a terminal app or Windows Powershell, navigate to the openpose installation folder and then try this command
#
# ```
# :: Windows
# bin\OpenPoseDemo.exe --video examples\media\video.avi --write_json output
# # Mac/Linux
# ./build/examples/openpose/openpose.bin --video examples/media/video.avi --write_json output
# ```
# ### 0.2 - Load python libraries
#
# There are a handful of python libraries that we use for things like image manipulation, file operations, maths and stats. Many are probably already installed by default such as `os, math, numpy, pandas, matplotlib`. Others need adding to our python environment.
#
# PyArrow is a useful extension for saving Pandas and NumPy data. We need it to move the large array created in Step 2 to Step 3.
#
# **If you are using conda then run the following command to install all the main libraries.**
# ```
# conda install glob2 opencv pyarrow xlrd openpyxl
# ```
# #### Troubleshooting
# If when you run the code in Steps 1, 2 & 3 you might see an error like `ModuleNotFoundError: No module named 'glob'` this is because that python module needs to be installed on your computer. If you use Anaconda, the missing module can usually be installed with the command `conda install glob`.
# ### 0.3 - iPyWidgets
#
# We also install `iPyWidgets` & `iPyCanvas` in order to use buttons and sliders and images in Jupyter notebooks (these are used in Step 2).
# ```
# conda install -c conda-forge ipywidgets
# conda install -c conda-forge ipycanvas
# ```
# To make these work with the newer Jupyter Lab we also need to install the widgets lab extension, like so:
#
# ```
# Jupyter 3.0 (current)
# conda install -c conda-forge jupyterlab_widgets
#
# Jupyter 2.0 (older)
# conda install -c conda-forge nodejs
# jupyter labextension install @jupyter-widgets/jupyterlab-manager
# jupyter labextension install @jupyter-widgets/jupyterlab-manager ipycanvas
# ```
#
# Documentation:
# + https://ipywidgets.readthedocs.io/en/latest/
# + https://ipycanvas.readthedocs.io/en/latest/
# + https://ipycanvas.readthedocs.io/en/latest/installation.html#jupyterlab-extension
#
# ### 0.4 - JupyText
#
# The standard ipython notebook format (`mynotebook.ipynb`) is a single file that mixes together code, formatting commands and outputs both as the results of running code and embedded binaries (images, graphs). This makes it non-human readable and very hard to tell what changes from one improvement to the next. `Jupytext` solves this by creating a synchronised plain text version of the file saved as a plain `.py` file (`mynotebook.py`). These are useful for developers (as it helps you track differences between versions more easily) but can mostly be ignored by users.
#
#
# Install JupyText by running
#
# ```conda install -c conda-forge jupytext```
# ### 0.6 Notebook extensions (optional)
# Installing Jupyter notebook extenstions provide some useful tools for navigating notebooks (e.g. table of contents) and other features.
#
# To install, run these commands in terminal window.
#
# ```conda install -c conda-forge jupyter_nbextensions_configurator```
#
# ```jupyter nbextensions_configurator enable --user```
#
# * https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/index.html
# * https://moonbooks.org/Articles/How-to-create-a-table-of-contents-in-a-jupyter-notebook-/
#
# ### 0.6 - Using Jupyter with network drives
#
# By default Jupyter launched from Anaconda Navigator will open it in your home directory. It then might not be possible to access files on a network drive you need. To get around this first launch a command window for the correct Jupyter environment. Then use this command to launch Jupyter itself (assuming you want to access the U:/ drive).
#
# ```jupyter lab --notebook-dir U:/```
|
analysis/Step0.GettingStarted.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
# ---
import pandas as pd
nba = pd.read_csv("nba.csv")
# ## Shared Methods and Attributes
nba = pd.read_csv("nba.csv")
nba.head(1)
nba.tail()
nba.index
nba.values
nba.shape
nba.dtypes
nba.head()
nba.columns
nba.axes
nba.info()
nba.get_dtype_counts()
rev = pd.read_csv("revenue.csv", index_col = "Date")
rev.head(3)
s = pd.Series([1, 2, 3])
s.sum()
rev.sum(axis = "columns")
# ## Select One Column from a `DataFrame`
nba = pd.read_csv("nba.csv")
nba.head(3)
# ## Select Two or More Columns from A `DataFrame`
nba = pd.read_csv("nba.csv")
nba.head(3)
nba[["Team", "Name"]].head(3)
nba[["Number", "College"]]
nba[["Salary", "Team", "Name"]].tail()
select = ["Salary", "Team", "Name"]
nba[select]
# ## Add New Column to `DataFrame`
# +
nba = pd.read_csv("nba.csv")
nba.head(3)
nba["Sport"] = "Basketball"
nba.head(3)
nba["League"] = "National Basketball Association"
nba.head(3)
nba = pd.read_csv("nba.csv")
nba.head(3)
nba.insert(3, column = "Sport", value = "Basketball")
nba.head(3)
nba.insert(7, column = "League", value = "National Basketball Association")
Output = None
# -
# ## Broadcasting Operations
nba = pd.read_csv("nba.csv")
nba.head(3)
# +
nba["Age"].add(5)
nba["Age"] + 5
nba["Salary"].sub(5000000)
nba["Salary"] - 5000000
nba["Weight"].mul(0.453592)
nba["Weight in Kilograms"] = nba["Weight"] * 0.453592
# -
nba.head(3)
nba["Salary"].div(1000000)
nba["Salary in Millions"] = nba["Salary"] / 1000000
nba.head(3)
# ## A Review of the `.value_counts()` Method
nba = pd.read_csv("nba.csv")
nba.head(3)
nba["Team"].value_counts()
nba["Position"].value_counts().head(1)
nba["Weight"].value_counts().tail()
nba["Salary"].value_counts()
# ## Drop Rows with Null Values
nba = pd.read_csv("nba.csv")
nba.head(3)
nba.tail(3)
nba.dropna(how = "all", inplace = True)
nba.tail(3)
nba.head(3)
nba.dropna(subset = ["Salary", "College"])
# ## Fill in Null Values with the `.fillna()` Method
nba = pd.read_csv("nba.csv")
nba.head(3)
nba.fillna(0)
nba["Salary"].fillna(0, inplace = True)
nba.head()
nba["College"].fillna("No College", inplace = True)
nba.head()
# ## The `.astype()` Method
nba = pd.read_csv("nba.csv").dropna(how = "all")
nba["Salary"].fillna(0, inplace = True)
nba["College"].fillna("None", inplace = True)
nba.head(6)
nba.dtypes
nba.info()
nba["Salary"] = nba["Salary"].astype("int")
nba.head(3)
nba["Number"] = nba["Number"].astype("int")
nba["Age"] = nba["Age"].astype("int")
nba.head(3)
nba["Age"].astype("float")
nba["Position"].nunique()
nba["Position"] = nba["Position"].astype("category")
nba["Team"] = nba["Team"].astype("category")
nba.head()
# ## Sort a `DataFrame` with the `.sort_values()` Method, Part I
nba = pd.read_csv("nba.csv")
nba.head(3)
# +
nba.sort_values("Name", ascending = False)
nba.sort_values("Age", ascending = False)
nba.sort_values("Salary", ascending = False, inplace = True)
nba.head(3)
# -
nba.sort_values("Salary", ascending = False, na_position = "first").tail()
# ## Sort a `DataFrame` with the `.sort_values()` Method, Part II
nba = pd.read_csv("nba.csv")
nba.head(3)
nba.sort_values(["Team", "Name"], ascending = [True, False], inplace = True)
nba.head(3)
# ## Sort `DataFrame` with the `.sort_index()` Method
nba = pd.read_csv("nba.csv")
nba.head(3)
nba.sort_values(["Number", "Salary", "Name"], inplace = True)
nba.tail(3)
nba.sort_index(ascending = False, inplace = True)
nba.head(3)
# ## Rank Values with the `.rank()` Method
nba = pd.read_csv("nba.csv").dropna(how = "all")
nba["Salary"] = nba["Salary"].fillna(0).astype("int")
nba.head(3)
nba["Salary Rank"] = nba["Salary"].rank(ascending = False).astype("int")
nba.head(3)
nba.sort_values(by = "Salary", ascending = False)
|
DataFrames 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
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/vitthal-bhandari/Detecting-Homophobia-and-Transphobia-2.0/blob/master/baselines/English/eng_mBERT_EDA.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="mUDmJgM7oyoo"
# # Initialize environment
# + colab={"base_uri": "https://localhost:8080/"} id="gESrFGwBowWQ" outputId="9246d656-d6ee-41a1-e9e9-38b7d4de8446"
#check gpu usage
# gpu_info = !nvidia-smi
gpu_info = '\n'.join(gpu_info)
if gpu_info.find('failed') >= 0:
print('Not connected to a GPU')
else:
print(gpu_info)
# + colab={"base_uri": "https://localhost:8080/"} id="gCHXWmroo694" outputId="db2174a3-e724-4e7c-b348-eb0db41ed3cc"
#check ram usage
from psutil import virtual_memory
ram_gb = virtual_memory().total / 1e9
print('Your runtime has {:.1f} gigabytes of available RAM\n'.format(ram_gb))
if ram_gb < 20:
print('Not using a high-RAM runtime')
else:
print('You are using a high-RAM runtime!')
# + colab={"base_uri": "https://localhost:8080/"} id="DOB8dMYvpkvP" outputId="9a5c4871-e2be-4b6e-b34e-80ef0a961ec1"
# !pip install datasets
# !pip install transformers
# ! pip install pyspellchecker
# ! pip install emoji --upgrade
# !sudo apt-get install git-lfs
# !pip3 install torch==1.10.2+cu102 torchvision==0.11.3+cu102 torchaudio===0.10.2+cu102 -f https://download.pytorch.org/whl/cu102/torch_stable.html
# + id="VOPu1DxOpox_"
from tensorflow.keras.preprocessing.text import Tokenizer
from huggingface_hub import notebook_login
from spellchecker import SpellChecker
from datasets import load_dataset
import tensorflow as tf
import pandas as pd
import numpy as np
import torch
import emoji
# + colab={"base_uri": "https://localhost:8080/", "height": 414, "referenced_widgets": ["b8a00f41f32e43d1b2e2e93ad5c3b677", "66b332353b8d4c7c9c6b4c1e60c354d8", "d029075b318847da8035f59ab657167f", "e54ecc1358644cd781453065a0afeb23", "55a0d05d85a547e993702cef5500a6da", "475602c524244a3e8d56e85662f8520a", "106548a88d2748f686fc0f56da7ba7bd", "d73af22415a34488bd074a23343519d0", "<KEY>", "<KEY>", "<KEY>", "065014e4d3774130b2387fa85b722e49", "<KEY>", "<KEY>", "785ef08c8ec34b0e95338d5f7a6555ad", "b07035b6ec8a4140a60dcc35c6ef63fb", "8f5fbd9c8ab6401eb53f210e26f4ba5f"]} id="PmYFTGLIYE-p" outputId="cc1f983d-b0e6-4d55-9475-07a1ca55089c"
notebook_login()
# + [markdown] id="tpJiHLVho8l3"
# # Data wrangling
# + [markdown] id="4ziOfe8nH_gK"
# ## Load data
# + colab={"base_uri": "https://localhost:8080/", "height": 254, "referenced_widgets": ["6d3514e857194498938261e4655d2745", "2e01a4d1152d486288484ff2ba234b2e", "605b5581ca4c4d9fbd68407d2b52dd48", "<KEY>", "7cc40e80f9424e819ead72a7a14bd06c", "3db17c182b784e268994a78c48ed7d1c", "<KEY>", "25f2833e1e494e0e9ca99709ad0b357d", "628b261eafdb4432aa1dabe95cbf5c38", "<KEY>", "2461d085e5594195bcba3764b9eab5d0", "3d023f1400e440ed8a60a57de7f5808f", "43f2eb310e1e4aae948f923a3cbb8203", "<KEY>", "<KEY>", "fc4ba4627237479dab411be5d28a116c", "dd6d7baf617d4848ab367e38e3cf60b1", "<KEY>", "<KEY>", "1972f8c5a7224c808edddd399c476896", "<KEY>", "<KEY>", "eadbe198ca824f9cbc66dd0b2e5b22b3", "<KEY>", "41fd623a118840b5b7447da53d95995a", "2b9ebb5d165f4eb781e56421d586d9a8", "<KEY>", "8e641d9bb6e248e281025549667f1fdb", "<KEY>", "<KEY>", "3caf33ea88824fcb9ccba12b3ede01c4", "<KEY>", "<KEY>"]} id="zhOmx0iWGHQu" outputId="7d369f55-b909-4805-9e55-d238de6a0623"
eng_train_dataset = load_dataset("csv", data_files="eng_3_train.tsv", sep="\t")
eng_train = eng_train_dataset["train"]
eng_dev_dataset = load_dataset("csv", data_files="eng_3_dev.tsv", sep="\t")
eng_dev = eng_dev_dataset["train"]
eng_test_dataset = load_dataset("csv", data_files="eng_3_test.tsv", sep="\t")
eng_test = eng_test_dataset["train"]
print(len(eng_train), len(eng_dev), len(eng_test))
# + colab={"base_uri": "https://localhost:8080/", "height": 254, "referenced_widgets": ["3a443cd0c1df404b846f70b08dc7f941", "b26d456eb1744872b617f293a9b90c98", "1916ecce3ad04df29915179c222b6795", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "9c182765b2274644ad88ca16177d4681", "<KEY>", "9eda97b9670346749d06000329385abd", "dd088f5e2b7f4f9eb395c0148f9a02dc", "0fbafbc7baa84424823b8c3b98fd4513", "3d934d43ad4e4e7182a4c8b4154de82b", "48b25e75f3cd42b58558472e0636b415", "<KEY>", "62b467705bda43418c23b7e6f6a47beb", "ac9a8d849111400fac5fddaa5638ea70", "8abe243d64de4dfeab0297959ce9866b", "0896b4a2b86f4a34960d627e677b5bca", "<KEY>", "e95ae1bf197a4c1baff374edbd904ba9", "<KEY>", "<KEY>", "69fcfe642379487dbe15d70822349e91", "<KEY>", "571af610e8d2481588080a505e035d65", "<KEY>", "1d2171eafeee4dfb98f0a76d36e817a8", "8903c5e5e8344cc1857a04e2a89f2ade", "5825de6af935454a87c42321da485d6b", "c2e48575fb094be5b50f6972df5ea51f", "41f21f067a3a4409a3e32403262ffb9e"]} id="UjIssYy4b7Qg" outputId="a6266583-0a07-423e-d471-a43bfb9b619a"
tam_train_dataset = load_dataset("csv", data_files="tam_3_train.tsv", sep="\t")
tam_train = tam_train_dataset["train"]
tam_dev_dataset = load_dataset("csv", data_files="tam_3_dev.tsv", sep="\t")
tam_dev = tam_dev_dataset["train"]
tam_test_dataset = load_dataset("csv", data_files="tam_3_test.tsv", sep="\t")
tam_test = tam_test_dataset["train"]
print(len(tam_train), len(tam_dev), len(tam_test))
# + colab={"base_uri": "https://localhost:8080/", "height": 254, "referenced_widgets": ["13921e075ddd41a69b8f32df6099e829", "1697ad260f8c450cb97757e42b07ec89", "58e7ae4bada54fb89c008372f4002d35", "e99d38924fe34bee8124ff8fe95d4890", "d86366bc6cb54c869b0a05ec6ff62860", "ff8a9cd1c94941c5a2763366bf8ea222", "<KEY>", "af9174785ed647efb7fe148f69352a6c", "<KEY>", "<KEY>", "<KEY>", "8921733db7eb4035aea34fa70ca57e9a", "6aea23c037164c1fa756754baaffa9d6", "<KEY>", "<KEY>", "df45891789de4e8e9c90c46abe2c19df", "<KEY>", "4f6c4a8389fb48e6bf13f60232d04db8", "9f8362a88cfa4b898ad6fc73b6189c8a", "<KEY>", "8ed99c5304ec4877ac9dcb813b9357e4", "36b4099e3f7b497aa9692b34475652d3", "<KEY>", "<KEY>", "6fd524b0925848138821a0cffeaf7d9a", "<KEY>", "8e723c094cc645eb997690ae49d43dbb", "41602a7d2d1844e29211d1c651c90ebc", "ad5c122a9fe943e1a4de5bfbbce9acec", "<KEY>", "f76e75ea39674867b4331a82a6f5b203", "1e2772c3a6864a88872c99cef71f4163", "e7d8bb660cc044c9a62317efcd1cfe3e"]} id="dw75tu8bcaq2" outputId="ec019cb3-2c14-401b-de3b-86fac0aba639"
eng_tam_train_dataset = load_dataset("csv", data_files="eng_tam_3_train.tsv", sep="\t")
eng_tam_train = eng_tam_train_dataset["train"]
eng_tam_dev_dataset = load_dataset("csv", data_files="eng_tam_3_dev.tsv", sep="\t")
eng_tam_dev = eng_tam_dev_dataset["train"]
eng_tam_test_dataset = load_dataset("csv", data_files="eng_tam_3_test.tsv", sep="\t")
eng_tam_test = eng_tam_test_dataset["train"]
print(len(eng_tam_train), len(eng_tam_dev), len(eng_tam_test))
# + colab={"base_uri": "https://localhost:8080/"} id="-un41vyLtHl_" outputId="1ba6abb2-37a9-48ce-91a4-05fad41c7c7a"
eng_train_dataset["train"] = eng_train_dataset["train"].remove_columns(column_names=['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4', 'Unnamed: 5', 'Unnamed: 6', 'Unnamed: 7', 'Unnamed: 8',
'Unnamed: 9', 'Unnamed: 10', 'Unnamed: 11', 'Unnamed: 12', 'Unnamed: 13', 'Unnamed: 14', 'Unnamed: 15'])
eng_train_dataset["train"] = eng_train_dataset["train"].rename_column(original_column_name= 'category', new_column_name= 'label')
eng_train_dataset["train"] = eng_train_dataset["train"].class_encode_column(column="label")
# + colab={"base_uri": "https://localhost:8080/"} id="90sevZgwqyUy" outputId="ec02a5c8-9f53-4fe4-d173-93b970730cb8"
eng_train = eng_train.remove_columns(column_names=['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4', 'Unnamed: 5', 'Unnamed: 6', 'Unnamed: 7', 'Unnamed: 8',
'Unnamed: 9', 'Unnamed: 10', 'Unnamed: 11', 'Unnamed: 12', 'Unnamed: 13', 'Unnamed: 14', 'Unnamed: 15'])
eng_train = eng_train.rename_column(original_column_name= 'category', new_column_name= 'label')
eng_train = eng_train.class_encode_column(column="label")
# + colab={"base_uri": "https://localhost:8080/"} id="8T-T8sUKhcH6" outputId="28a48277-0a7a-43df-e5c5-142639eb0648"
eng_dev = eng_dev.remove_columns(column_names=['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4', 'Unnamed: 5', 'Unnamed: 6', 'Unnamed: 7', 'Unnamed: 8',
'Unnamed: 9'])
eng_dev = eng_dev.rename_column(original_column_name= 'category', new_column_name= 'label')
eng_dev = eng_dev.class_encode_column(column="label")
# + colab={"base_uri": "https://localhost:8080/"} id="gVy7qOpIjU3r" outputId="375fb2a5-8f2a-49b9-bd8a-43c47be44049"
eng_test = eng_test.rename_column(original_column_name= 'category', new_column_name= 'label')
eng_test = eng_test.rename_column(original_column_name= 'text ', new_column_name= 'text')
eng_test = eng_test.class_encode_column(column="label")
# + colab={"base_uri": "https://localhost:8080/"} id="DN6bQTTw6TkI" outputId="350af664-1e18-44b1-9d24-8ad3c6512952"
eng_test
# + colab={"base_uri": "https://localhost:8080/"} id="H0TsZRPR4R2y" outputId="e7b53ae2-a1ad-4f39-89df-28c7313be646"
# remove NA rows in test set
eng_test = eng_test.filter(lambda example, indice: indice < 990, with_indices=True)
# + colab={"base_uri": "https://localhost:8080/"} id="OtY45-Ly6V7W" outputId="2c3980d9-6bd7-4db8-bd3a-24d4a2164afe"
eng_test
# + [markdown] id="SETpTBxYj4JF"
# **Converting Datasets to Datafrane**
# + id="GOza09Jfj123"
eng_train.set_format(type="pandas")
eng_dev.set_format(type="pandas")
eng_test.set_format(type="pandas")
# + colab={"base_uri": "https://localhost:8080/", "height": 423} id="VNlcuBFSkH5a" outputId="76bbf9e8-46b7-43e4-8bcf-16e248c4a59b"
df_eng_train = eng_train[:]
df_eng_dev = eng_dev[:]
df_eng_test = eng_test[:]
df_eng_test
# + id="41OUnVXcmJKT"
def label_int2str(row):
return eng_train.features['label'].int2str(row)
df_eng_train['label_name'] = df_eng_train['label'].apply(label_int2str)
# + id="VcstmkWRnU0K"
def label_int2str2(row):
return eng_dev.features['label'].int2str(row)
df_eng_dev['label_name'] = df_eng_dev['label'].apply(label_int2str2)
# + id="iLwKQU_Zn-hz"
def label_int2str3(row):
return eng_test.features['label'].int2str(row)
df_eng_test['label_name'] = df_eng_test['label'].apply(label_int2str3)
# + colab={"base_uri": "https://localhost:8080/", "height": 206} id="nTUyaaPRoN9b" outputId="c16d588b-7351-4762-b04a-449d555506a2"
df_eng_test.head()
# + [markdown] id="2iA2Ym9sFjb-"
# ## Drop empty rows
# + id="ColgQt3hzj1i"
df_eng_train = df_eng_train.dropna()
df_eng_dev = df_eng_dev.dropna()
df_eng_test = df_eng_test.dropna()
df_eng_train = df_eng_train.reset_index(drop=True)
df_eng_dev = df_eng_dev.reset_index(drop=True)
df_eng_test = df_eng_test.reset_index(drop=True)
# + [markdown] id="fcG4Uqzh5YsJ"
# ## Remove emojis
# + id="RAJAXLBy5eqR"
df_eng_train['text'] = df_eng_train['text'].apply(lambda x: emoji.demojize(x, delimiters=(" ", " ")))
df_eng_dev['text'] = df_eng_dev['text'].apply(lambda x: emoji.demojize(x, delimiters=(" ", " ")))
df_eng_test['text'] = df_eng_test['text'].apply(lambda x: emoji.demojize(x, delimiters=(" ", " ")))
# + [markdown] id="-Qz-nujG5bUu"
# ## Remove unnecessary puncutation
# + id="4fYlBj656BRT"
#keras tokenizer
train_text_tok = Tokenizer(split=' ', lower=True, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n')
train_text_tok.fit_on_texts(df_eng_train['text'])
dev_text_tok = Tokenizer(split=' ', lower=True, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n')
dev_text_tok.fit_on_texts(df_eng_dev['text'])
test_text_tok = Tokenizer(split=' ', lower=True, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n')
test_text_tok.fit_on_texts(df_eng_test['text'])
# + id="IHDnc5ag6WrV"
train_tok = train_text_tok.texts_to_sequences(df_eng_train['text'])
df_eng_train['text'] = df_eng_train.apply(lambda row: train_text_tok.sequences_to_texts([train_tok[row.name]])[0], axis=1)
# + id="_hIx-LeWHg9g"
dev_tok = dev_text_tok.texts_to_sequences(df_eng_dev['text'])
df_eng_dev['text'] = df_eng_dev.apply(lambda row: dev_text_tok.sequences_to_texts([dev_tok[row.name]])[0], axis=1)
# + id="-8znqdSyHsCb"
test_tok = test_text_tok.texts_to_sequences(df_eng_test['text'])
df_eng_test['text'] = df_eng_test.apply(lambda row: test_text_tok.sequences_to_texts([test_tok[row.name]])[0], axis=1)
# + [markdown] id="Jzzwmlj6KDm5"
# ## Run spell check
# + colab={"base_uri": "https://localhost:8080/"} id="K75pi376KjNv" outputId="e398e089-13f0-4c78-bf32-f1a58ec42412"
df_eng_train["text"].iloc[0:10]
# + id="QM9agVKrKJCR"
spell = SpellChecker()
spell.word_frequency.load_words(['lgbt', 'lgbtq', 'lgbtqia+', 'gay', 'lesbian', 'transgender', 'trans'])
# + id="LELCFpUnQsOg"
def spell_check(row):
correct_sent = []
misspelled = spell.unknown(row.split())
for word in row.split():
if word in misspelled:
correct_sent.append(spell.correction(word))
else:
correct_sent.append(word)
return " ".join(correct_sent)
# + id="4TLtZiCwQbNq"
df_eng_train['text'] = df_eng_train['text'].apply(spell_check)
df_eng_dev['text'] = df_eng_dev['text'].apply(spell_check)
df_eng_test['text'] = df_eng_test['text'].apply(spell_check)
# + colab={"base_uri": "https://localhost:8080/"} id="7yt_HapvRXy_" outputId="ca093ab9-175a-44e2-d3a9-06c5a993efe7"
df_eng_train["text"].iloc[0:10]
# + [markdown] id="dAT9UTv9K8At"
# ## Reset Dataset format
# + id="NtCT1RUCuvDG"
eng_train.reset_format()
eng_dev.reset_format()
eng_test.reset_format()
# + [markdown] id="ZR17qSI77zWN"
# # Tokenization
# + id="g-pdYG4y720n" colab={"base_uri": "https://localhost:8080/", "height": 0, "referenced_widgets": ["76c4f111199b4ca8bda229400acb27bf", "19925a8728ea43b1b37a73d8ee4feeca", "6029d70ee6764874991130376224cefe", "f911d0df51bd4031b73a2a2f895fcd94", "a77000aeaca0492e9cfef3036dce488a", "<KEY>", "4a84d9dd873a474cadd0e0fea5c60b9a", "0c858979106043d290bce10ddef5c2a1", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "a4f27c5dc4334488a8de22d7eb1914d7", "<KEY>", "580888e322b04e9abe2297682c64d281", "28f0b0507dd14781b353ba4463d69ec6", "<KEY>", "ca038e832c56467281afad08b9f56df9", "224e671cbe9543df8ec2263bd5078e28", "4e50954e64ff45b9a21f4960f6e69364", "a1fdd9ba0ba6484999c2f5ba5ed956c6", "<KEY>", "<KEY>", "3ee1cfce97d845839d86c6490d677ff3", "<KEY>", "<KEY>", "f9d74dca29e04c919e30c15edce2fd22", "<KEY>", "3e6fe6d3183940adb90c552650e68a68", "<KEY>", "ff74522d4e9f45dfac95f6648c59c846", "fd4e4a2315be4619a877425a4f519921", "e4a75e5a7697447db1805358aee9e193", "<KEY>", "d9796256358e4088a8d84ddda8ec20c2", "2979f7e2d9604113926062c94abc3f09", "013de32f01f948e4b76881a4e731593e", "<KEY>", "2aa0bb34dfb246389a7df784239a95d8", "f2eca339e7f349a998caa8331e3852c6", "2c82adf1a73f45ab82e78b42db94aec8", "<KEY>"]} outputId="4631e5c1-1e9f-495e-8f2b-25ad0436be23"
from transformers import AutoTokenizer
model_ckpt = "bert-base-multilingual-cased"
tokenizer = AutoTokenizer.from_pretrained(model_ckpt)
# + id="aisjWpBK9mJK"
def tokenize(batch):
return tokenizer(batch["text"], padding=True, truncation=True)
# + colab={"base_uri": "https://localhost:8080/", "height": 0, "referenced_widgets": ["c4c1871003fc40928607151c8068b6de", "36dfed12bc394dde8d01378b3154cf30", "23a2c839bbba4f65ad0e4c2ac914080b", "<KEY>", "<KEY>", "cced7242c5704fe9a26e59b29cb9b22d", "08eef52747b74efc9312c22f6845f864", "<KEY>", "<KEY>", "6f2fd5ef760e4db0aafd6188e5ba5bd4", "<KEY>", "4b2ca9240cab46b5aff0a128cfb4fac0", "<KEY>", "291b149d8e754d84b92fc01381853ca0", "8f3919f38ef34b79b03b1e48330fd480", "925d438686de4441ba6f860ce697a308", "ed5f3e4f0c5e4d9287ce88c4fc36a3ce", "085c026e73564ed5a1199096557c1d96", "<KEY>", "<KEY>", "143ed29560ff4187a2b93728e1f82857", "<KEY>", "638fe38d17f54d43920e108a7eaf2cc9", "<KEY>", "<KEY>", "<KEY>", "dd9dac7afc294c55b7a75fdd689c3032", "<KEY>", "7d5b53d800ba45b7a07b1fec4e4101d3", "94256caad0b74b77a77739856147486b", "<KEY>", "7b477e6f17344c69bef332ad0a39f4c1", "11bf017c55e44e16a9f5ea3d14844b46"]} id="PJhzXOA56xNq" outputId="c8bc71ad-2d29-4173-a4f3-b1631f29baec"
eng_train = eng_train.filter(lambda example: example['text'] is not None)
eng_dev = eng_dev.filter(lambda example: example['text'] is not None)
eng_test = eng_test.filter(lambda example: example['text'] is not None)
print( len(eng_train), len(eng_dev), len(eng_test) )
# + colab={"base_uri": "https://localhost:8080/", "height": 0, "referenced_widgets": ["64ec0dc156ca473795239e9a281b8d0d", "afdcd40e9c014331bb57c5d052897a5d", "<KEY>", "f749af8ba8374c29a95cbad5ae47b684", "eb56ed85ce404947b18bebefb8c014f5", "81f1e966673d429faa3611b654509916", "ea0ca26d0563430e866559092776daad", "7e8e49ee83044e62bb9be4688b5d4bba", "<KEY>", "2a5389962f264d6ba0dc90becd7406e8", "<KEY>", "2c283957e3ba4258a5ea0b3a76e1dc23", "<KEY>", "0e2392d996034d17a962e4c6609e5e4c", "b51a8484c35e4e3c9d1e652e28c5db9e", "35ed7cee9e9d436aab33581adeaf0dbe", "a6949164b01e4bb793e792e07d292cda", "<KEY>", "<KEY>", "<KEY>", "be89b6220e244336b4341744c6341cdd", "dc0ab63af4a64d2aa02d04e5c37cef7f", "<KEY>", "be577891a77845979ade3fd1f57b797a", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "8ad25eae54e9401ea45593840e620ea9", "695a008820674ff695029e57c169d843", "<KEY>", "<KEY>"]} id="mvycLxqK-Jww" outputId="970fda96-4152-4965-c839-a5bba9719a14"
#apply tokenizer across all splits in the corpus
eng_train_encoded = eng_train.map(tokenize, batched=True, batch_size=None)
eng_dev_encoded = eng_dev.map(tokenize, batched=True, batch_size=None)
eng_test_encoded = eng_test.map(tokenize, batched=True, batch_size=None)
# + id="Zp2cGC_k-zjZ" colab={"base_uri": "https://localhost:8080/"} outputId="24b9a1f5-e99b-48ea-d1c5-4bba7727c12e"
print(eng_train_encoded.column_names)
# + [markdown] id="C7a7GD2_GBhF"
# # Approach 1: Feature Extraction
# + colab={"base_uri": "https://localhost:8080/", "height": 121, "referenced_widgets": ["f4f989d6fcb74eaab04afd055665f4fe", "e30ab92b65d849f6a7daf2fc97b5439c", "6d20199bdbed401c90eb85c55c511941", "96bb3168152a48da9b0586e0e3d0bfca", "5fe22653f3f64028a4a9e796789048aa", "f91fc3d6190748f59cdb4a42723d6f4e", "897eaac4fb8d43e988d95005f5ab1957", "<KEY>", "a41eb9d9ad9b440385fbce045cd2a8d3", "9113dfa5755b4f6784b79479f3ab681f", "19696946fce74065a089bcbcd4720117"]} id="e6bldZhQFkWH" outputId="7147bc3f-3091-4a14-ab73-d1c33af012ab"
from transformers import AutoModel
model_ckpt = "bert-base-multilingual-cased"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = AutoModel.from_pretrained(model_ckpt).to(device)
# + colab={"base_uri": "https://localhost:8080/"} id="1QClD3V4M5Ne" outputId="2e9b6e57-edf4-4cb8-9710-f7b54d3377cb"
device
# + id="Bv1wutdyZCRR"
def extract_hidden_states(batch):
#Place model inputs on GPU
inputs = {k:v.to(device) for k, v in batch.items()
if k in tokenizer.model_input_names}
#Extract last hidden states
with torch.no_grad():
last_hidden_state = model(**inputs).last_hidden_state
#Return vector for [CLS] token
return {"hidden_state": last_hidden_state[:, 0].cpu().numpy()}
# + id="AbWrnNrKaHQD"
eng_train_encoded.set_format("torch", columns=["input_ids", "attention_mask", "label"])
# + id="PKdjVFRbdBfP"
eng_dev_encoded.set_format("torch", columns=["input_ids", "attention_mask", "label"])
# + colab={"base_uri": "https://localhost:8080/", "height": 81, "referenced_widgets": ["c0230aea6da844d2938de1a325014106", "b67b8feb4b32419ba1404b39f9f5d3f4", "<KEY>", "e9290378e4454700a8810e5dc468589a", "0bdc47e6d93540ad8e588af7c4bd5bd5", "2316bd2c4c334013b3deb3eee529c5ac", "d6de29b1e60d48f8bba9a86ca8fac371", "<KEY>", "<KEY>", "0c9e273c03054a088e68f9f0f5102f95", "c9c969e1f5ca4c97830ab2e63145c6b1", "<KEY>", "<KEY>", "d269548de7004ce18c58a6772db759ff", "d00088edfcb44e8499c72a62ad5b0fd2", "b3e2f0d372c64ab9ba58eae7968f6037", "9de2484ae2324c0194f27ec8cefd09c6", "4f0c35e804804817a9d517105c8b34de", "94c30307aa9842c3a893c295c3efa3f1", "<KEY>", "ce8dc97e3d8f410eb68fa6a6e1f3e0e3", "c496a3172a53472aa45557afbd694b03"]} id="RILhw15CaHGX" outputId="d26d7fb1-6331-4e47-afaf-4d8a620efda4"
eng_train_hidden = eng_train_encoded.map(extract_hidden_states, batched=True)
eng_dev_hidden = eng_dev_encoded.map(extract_hidden_states, batched=True)
# + colab={"base_uri": "https://localhost:8080/"} id="AW85j6qadWB-" outputId="a1ee8bd3-d18e-4449-835d-7145a1696e0a"
eng_train_hidden.column_names
# + colab={"base_uri": "https://localhost:8080/"} id="O5VdIZhbeRwJ" outputId="a866565d-d614-4a63-f13e-f28841d7b5c3"
X_eng_train = np.array(eng_train_hidden['hidden_state'])
X_eng_dev = np.array(eng_dev_hidden['hidden_state'])
Y_eng_train = np.array(eng_train_hidden['label'])
Y_eng_dev = np.array(eng_dev_hidden['label'])
print( X_eng_train.shape, X_eng_dev.shape, Y_eng_train.shape, Y_eng_dev.shape)
# + [markdown] id="5uswq6Edf2sE"
# ## Training an LR Classifier
# + colab={"base_uri": "https://localhost:8080/"} id="ttj9UvdPfepb" outputId="779a167a-debc-4f2e-94a2-425f090bac72"
from sklearn.linear_model import LogisticRegression
lr_clf = LogisticRegression(max_iter = 3000)
lr_clf.fit(X_eng_train, Y_eng_train)
# + colab={"base_uri": "https://localhost:8080/"} id="UwHYeXkWhm4Z" outputId="13c0b13d-f4f1-4c86-e5c5-b7f1fbc36531"
lr_clf.score(X_eng_dev, Y_eng_dev)
# + colab={"base_uri": "https://localhost:8080/"} id="lbJk9KO8h6ff" outputId="34a90695-6357-4a43-ce68-3620a25d5cfe"
#Evaluating a dummy classifier for comparison which always returns the majority class
from sklearn.dummy import DummyClassifier
dummy_clf = DummyClassifier(strategy="most_frequent")
dummy_clf.fit(X_eng_train, Y_eng_train)
dummy_clf.score(X_eng_dev, Y_eng_dev)
# + id="fSzzQAmPibsr"
Y_eng_preds = lr_clf.predict(X_eng_dev)
# + colab={"base_uri": "https://localhost:8080/"} id="QMuVn7wBls8a" outputId="e0ab6101-8e6b-46dc-a181-c76e6c44335e"
tf.math.confusion_matrix(Y_eng_dev, Y_eng_preds)
# + colab={"base_uri": "https://localhost:8080/"} id="NmtZwjjjmEtl" outputId="8d38738e-53a7-482a-f1cb-aa873b49b609"
from sklearn.metrics import classification_report
target_names = ['homophobic', 'Non-anti LGBTQIA+ content', 'transphobic']
print(classification_report(Y_eng_dev, Y_eng_preds, target_names=target_names))
# + [markdown] id="B_hBGa1yGHHO"
# # Approach 2: Fine Tuning
# + colab={"base_uri": "https://localhost:8080/"} id="zZ2Z4Fekp4kW" outputId="fed779c3-d746-4b5e-caa7-ecf7ab6e51f5"
from transformers import AutoModelForSequenceClassification
num_labels = 3
model = (AutoModelForSequenceClassification.from_pretrained(model_ckpt,
num_labels=num_labels)
.to(device))
# + id="OusitFBLu7cv"
#Define performance metrics
from sklearn.metrics import accuracy_score, f1_score
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
f1 = f1_score(labels, preds, average = "macro")
acc = accuracy_score(labels, preds)
return {"accuracy": acc, "f1": f1}
# + id="d1ZZ_l4YxH-G"
#Define hyperparameters
from transformers import Trainer, TrainingArguments
batch_size = 32
logging_steps = len(eng_train_encoded) // batch_size
model_name = f"{model_ckpt}-finetuned-emotion"
training_args = TrainingArguments(
output_dir = model_name,
num_train_epochs = 5,
learning_rate = 2e-5,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
weight_decay = 0.01,
evaluation_strategy = "epoch",
disable_tqdm = False,
logging_steps =logging_steps,
log_level = "error"
)
# + colab={"base_uri": "https://localhost:8080/", "height": 304} id="T3O2FBh2yYRP" outputId="eaef8df4-4e40-4ed7-fff6-b1fe3bf59995"
trainer = Trainer(
model = model,
args = training_args,
compute_metrics = compute_metrics,
train_dataset = eng_train_encoded,
eval_dataset = eng_dev_encoded,
tokenizer = tokenizer
)
trainer.train()
# + colab={"base_uri": "https://localhost:8080/", "height": 37} id="_KkykX0Ty1pm" outputId="d5334643-d2dc-4d7c-e83c-0fd02082f75b"
preds_output = trainer.predict(eng_dev_encoded)
# + colab={"base_uri": "https://localhost:8080/"} id="K-NHYssq6kBe" outputId="eb065dca-f797-432d-8b2f-62e39ed22200"
preds_output.metrics
# + id="UxgaCGpE6oGc"
y_preds = np.argmax(preds_output.predictions, axis=1)
# + colab={"base_uri": "https://localhost:8080/"} id="4SbjWhhW6vnO" outputId="62a04488-e27b-4add-affa-b47d8f6fcc00"
tf.math.confusion_matrix(Y_eng_dev, y_preds)
# + colab={"base_uri": "https://localhost:8080/"} id="chtZnvkd7FT9" outputId="6848e3d3-1113-4e6d-f294-350b09780a75"
print(classification_report(Y_eng_dev, y_preds, target_names=target_names))
# + [markdown] id="4FQK3LOE_nRC"
# # EDA
# + [markdown] id="7JUmSk-VB5lC"
# **Saving dataset in a csv format classwise separately**
# + id="3U4CDB8TA_KE"
eng_train.set_format(type="pandas")
eng_dev.set_format(type="pandas")
eng_test.set_format(type="pandas")
# + colab={"base_uri": "https://localhost:8080/", "height": 423} id="8wvlBBSiDFCr" outputId="2e1b087e-57d8-4efa-c844-7778974f27b7"
df_eng_train = eng_train[:]
df_eng_dev = eng_dev[:]
df_eng_test = eng_test[:]
df_eng_train
# + colab={"base_uri": "https://localhost:8080/", "height": 206} id="6EvcH-7LDE3p" outputId="b8b6f81b-dc15-4a41-84be-7f9aee2f3fbf"
df_homophobic=df_eng_train[df_eng_train.label == 0]
df_homophobic.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 206} id="aOsrwUKdEspO" outputId="be08298f-77d9-4b4f-c524-453c1ba40242"
df_transphobic=df_eng_train[df_eng_train.label == 2]
df_transphobic.head()
# + [markdown] id="nsljege1GEY8"
# **Applying EDA to homophobia and transphobia classes**
# + colab={"base_uri": "https://localhost:8080/"} id="_XvVwgQYFFpq" outputId="fec30c6d-8a8f-4b01-8dc6-a2d2a2e40d2b"
import nltk
nltk.download('wordnet')
# !git clone https://github.com/jasonwei20/eda_nlp.git
# %cd eda_nlp/code
# !ls
# + id="zMwnlFOBE_5L"
df_homophobic.to_csv('homophobic.txt', sep="\t", header=False, index=False)
df_transphobic.to_csv('transphobic.txt', sep="\t", header=False, index=False)
# + colab={"base_uri": "https://localhost:8080/"} id="UXT5KjETHXeZ" outputId="65a76ff1-649f-46bf-b6b0-5a16765a605f"
# ! python augment.py --input=transphobic.txt --num_aug=32
# + colab={"base_uri": "https://localhost:8080/"} id="abDpvUlGGia6" outputId="70aaf4ba-215d-442a-8eb9-685f87e2035e"
# ! python augment.py --input=homophobic.txt --num_aug=16
# + [markdown] id="AH4jcCcBI6Um"
# **Combine augmented data with existing data**
# + id="KFoyQpf1JA7h"
df_homophobic_aug=pd.read_csv('eda_homophobic.txt', sep="\t", names=["label", "text"])
df_transphobic_aug=pd.read_csv('eda_transphobic.txt', sep="\t", names=["label", "text"])
# + colab={"base_uri": "https://localhost:8080/", "height": 300} id="rY92Tt5zJFu6" outputId="552fe0a1-1208-4e45-cb2d-1c9aca26391b"
df_homophobic_aug.describe()
# + colab={"base_uri": "https://localhost:8080/", "height": 300} id="OIq24ju5JFdL" outputId="76678211-a7de-408c-f418-51afa15dae29"
df_ally=df_eng_train[df_eng_train.label == 1]
df_ally.describe()
# + id="X_-xQjycJ5E1"
frames = [df_ally, df_homophobic, df_transphobic, df_homophobic_aug, df_transphobic_aug]
df_aug = pd.concat(frames)
# + colab={"base_uri": "https://localhost:8080/"} id="8vAoO8tvKEu2" outputId="22f57f45-b694-4605-f204-d097d3ef4078"
# re shuffling dataframe
df_aug_shuffled = df_aug.sample(frac=1).reset_index(drop=True)
df_aug_shuffled.info
# + colab={"base_uri": "https://localhost:8080/"} id="oTiur68vKKus" outputId="af1784d4-c5ab-4fa7-aeaf-e4ed490ed95a"
df_aug_shuffled['label'].value_counts()
# + id="Z4IAhI3pKl3v"
df_aug_shuffled.to_csv('augmented_data.csv')
# + [markdown] id="jB15jQ7Z_hkN"
# # Approach 3: Fine Tuning with EDA
# + [markdown] id="5nqwElS7K2y2"
# **We convert augmented dataset back to a Datasets object and run tokenization again, before fine-tuning it**
# + id="b9vi609w7bmG"
from datasets import Dataset
eng_train_aug = Dataset.from_pandas(df = df_aug_shuffled)
# + colab={"base_uri": "https://localhost:8080/"} id="kzmr-gOxNGVS" outputId="9034c54a-a3cd-4ce7-9e02-f155c66abc91"
eng_train_aug
# + colab={"base_uri": "https://localhost:8080/", "height": 49, "referenced_widgets": ["a08b178e859a49e492e5edda2e03f8d6", "3af2d0b43d0046aab1b99fc5af500fdc", "<KEY>", "<KEY>", "a5b2a623b2374e3f8504e674af579e67", "<KEY>", "e0bb784edc644b338eadab80b7a06206", "<KEY>", "<KEY>", "061627db11984acd9c8b34a762f8f08a", "302f12b388ec420ba6b465d7741e71a8"]} id="Wr6YT2a2OpgT" outputId="0b08858c-a5c5-4b25-814c-92d442f3c307"
eng_train_aug_encoded = eng_train_aug.map(tokenize, batched=True, batch_size=None)
# + colab={"base_uri": "https://localhost:8080/"} id="rEKDqtawO5xS" outputId="48edc60a-ca0d-44ef-8cbb-c5b73b1aa852"
eng_train_aug_encoded.column_names
# + id="JVaGKdqicsXl"
#Define hyperparameters
from transformers import Trainer, TrainingArguments
batch_size = 32
logging_steps = len(eng_train_encoded) // batch_size
model_name = f"Homophobia-Transphobia-v2-mBERT-EDA"
training_args = TrainingArguments(
output_dir = model_name,
num_train_epochs = 5,
learning_rate = 2e-5,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
weight_decay = 0.01,
evaluation_strategy = "epoch",
disable_tqdm = False,
logging_steps =logging_steps,
push_to_hub=True,
log_level = "error"
)
# + colab={"base_uri": "https://localhost:8080/", "height": 322} id="V5hiP6reO8GK" outputId="d5a68d1b-a2e4-473d-cb9e-28abe8b6caee"
trainer = Trainer(
model = model,
args = training_args,
compute_metrics = compute_metrics,
train_dataset = eng_train_aug_encoded,
eval_dataset = eng_dev_encoded,
tokenizer = tokenizer
)
trainer.train()
# + colab={"base_uri": "https://localhost:8080/", "height": 37} id="GvAgT18yPQ5i" outputId="ef66c9b8-cd1d-49e3-ee09-63b1acfc859f"
preds_output = trainer.predict(eng_dev_encoded)
# + id="ofkVb7SbPYMN"
y_preds_aug = np.argmax(preds_output.predictions, axis=1)
# + colab={"base_uri": "https://localhost:8080/"} id="QLJnzQHRPeoT" outputId="ec78c7e9-4355-48c3-a305-c9b1795a2123"
tf.math.confusion_matrix(Y_eng_dev, y_preds_aug)
# + colab={"base_uri": "https://localhost:8080/"} id="hWPfjrPHPhnW" outputId="028b9c20-8be2-4b15-a7ae-be7d2efe1fcc"
print(classification_report(Y_eng_dev, y_preds_aug, target_names=target_names))
# + colab={"base_uri": "https://localhost:8080/", "height": 266, "referenced_widgets": ["5e8b295a60ad441a803486b8b0c460de", "a0096f028e034d288d05e6c8c0224e19", "884117267bd5437891c8ec8c963533e1", "6894e571f0cc4f7890ad640bfbff6599", "e3b78c4882404b8b83ef3f05ce0b0302", "0c86270ea36141168deec68075cb31aa", "42d7ca3c501f4976b8c0f58ce349517c", "156f4214a3974dd6854b0a5d6d59179e", "d652bf61948f44f6a8598126fb6a94b8", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "ee4aa45c5aeb44138975936a5424cffe", "7f41ea35dbcd4eb39f9428ad7394da95", "ee69de151b75454e9b596d8699d01959", "bb226357eec64caeb3f857811a364843", "<KEY>", "<KEY>"]} id="7aKNnLZkmQxJ" outputId="6934ab1a-48e4-49d1-ac93-02f19d66eec1"
trainer.push_to_hub(commit_message="Training completed!")
# + id="daz5VKbhmRbb"
|
baselines/English/eng_mBERT_EDA.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="ICGQy3wfzynE"
# <div align="center">
# <h1><img width="30" src="https://madewithml.com/static/images/rounded_logo.png"> <a href="https://madewithml.com/">Made With ML</a></h1>
# Applied ML · MLOps · Production
# <br>
# Join 20K+ developers in learning how to responsibly <a href="https://madewithml.com/about/">deliver value</a> with ML.
# </div>
#
# <br>
#
# <div align="center">
# <a target="_blank" href="https://newsletter.madewithml.com"><img src="https://img.shields.io/badge/Subscribe-20K-brightgreen"></a>
# <a target="_blank" href="https://github.com/GokuMohandas/madewithml"><img src="https://img.shields.io/github/stars/GokuMohandas/madewithml.svg?style=social&label=Star"></a>
# <a target="_blank" href="https://www.linkedin.com/in/goku"><img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social"></a>
# <a target="_blank" href="https://twitter.com/GokuMohandas"><img src="https://img.shields.io/twitter/follow/GokuMohandas.svg?label=Follow&style=social"></a>
# <p>🔥 Among the <a href="https://github.com/topics/deep-learning" target="_blank">top ML</a> repositories on GitHub</p>
# </div>
#
# <br>
# <hr>
# + [markdown] id="RvwFrkzSPbw7"
# # PyTorch
#
# In this notebook, we'll learn the basics of [PyTorch](https://pytorch.org), which is a machine learning library used to build dynamic neural networks. We'll learn about the basics, like creating and using Tensors.
# + [markdown] id="0aqN-ffaP4t1"
# <div align="left">
# <a target="_blank" href="https://madewithml.com/courses/ml-foundations/pytorch/"><img src="https://img.shields.io/badge/📖 Read-blog post-9cf"></a>
# <a href="https://github.com/GokuMohandas/madewithml/blob/main/notebooks/05_PyTorch.ipynb" role="button"><img src="https://img.shields.io/static/v1?label=&message=View%20On%20GitHub&color=586069&logo=github&labelColor=2f363d"></a>
# <a href="https://colab.research.google.com/github/GokuMohandas/madewithml/blob/main/notebooks/05_PyTorch.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
# </div>
# + [markdown] id="SFa_PSr2tvaC"
# # Set up
# + id="eLAkqoRKtyFD"
import numpy as np
import torch
# + id="l9krh147uJOV"
SEED = 1234
# + id="1uLEnBgft22Y" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406979, "user_tz": 420, "elapsed": 3568, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="3c7e21d3-af74-4450-b1ed-c5aeb3d8f4af"
# Set seed for reproducibility
np.random.seed(seed=SEED)
torch.manual_seed(SEED)
# + [markdown] id="08AUKP9xu8YQ"
# # Basics
# + id="o3jBRfYZuNqF" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406980, "user_tz": 420, "elapsed": 3562, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="c7406f7f-5be9-4c02-db94-d3297ddf2a85"
# Creating a random tensor
x = torch.randn(2, 3) # normal distribution (rand(2,3) -> uniform distribution)
print(f"Type: {x.type()}")
print(f"Size: {x.shape}")
print(f"Values: \n{x}")
# + id="Pho5A7JluNvj" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406980, "user_tz": 420, "elapsed": 3555, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="ae06f332-b1cf-49f3-e34e-e01ac75783f1"
# Zero and Ones tensor
x = torch.zeros(2, 3)
print (x)
x = torch.ones(2, 3)
print (x)
# + id="UTecl1RduNtL" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406981, "user_tz": 420, "elapsed": 3549, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="2267a8e7-d01b-4f94-c56f-ce3c093a11df"
# List → Tensor
x = torch.Tensor([[1, 2, 3],[4, 5, 6]])
print(f"Size: {x.shape}")
print(f"Values: \n{x}")
# + id="2OQTnxWOuNnY" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406982, "user_tz": 420, "elapsed": 3543, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="a85f4944-8763-4d50-cf08-26452665348f"
# NumPy array → Tensor
x = torch.Tensor(np.random.rand(2, 3))
print(f"Size: {x.shape}")
print(f"Values: \n{x}")
# + id="8K2kWrkZuilf" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406982, "user_tz": 420, "elapsed": 3536, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="3b729f58-af24-4363-a929-9b7d89cbd269"
# Changing tensor type
x = torch.Tensor(3, 4)
print(f"Type: {x.type()}")
x = x.long()
print(f"Type: {x.type()}")
# + [markdown] id="6LxCmxqFu6sq"
# # Operations
# + id="yfYLm_1Buixy" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406983, "user_tz": 420, "elapsed": 3530, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="b2d54c35-43cc-4ea9-ce90-d43d0c8071a4"
# Addition
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = x + y
print(f"Size: {z.shape}")
print(f"Values: \n{z}")
# + id="22abfI18uiuw" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406983, "user_tz": 420, "elapsed": 3523, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="18704267-01a7-4ded-dcf7-50ca42d95d21"
# Dot product
x = torch.randn(2, 3)
y = torch.randn(3, 2)
z = torch.mm(x, y)
print(f"Size: {z.shape}")
print(f"Values: \n{z}")
# + id="p1ztJNrruiqv" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406984, "user_tz": 420, "elapsed": 3517, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="7db463f1-de7f-4184-c82c-8b4a8198de93"
# Transpose
x = torch.randn(2, 3)
print(f"Size: {x.shape}")
print(f"Values: \n{x}")
y = torch.t(x)
print(f"Size: {y.shape}")
print(f"Values: \n{y}")
# + id="zoLDryFYuioF" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406984, "user_tz": 420, "elapsed": 3510, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="2098360d-6350-49be-8a67-8725e29d1df0"
# Reshape
x = torch.randn(2, 3)
z = x.view(3, 2)
print(f"Size: {z.shape}")
print(f"Values: \n{z}")
# + id="2fdNmFu3vlE7" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406985, "user_tz": 420, "elapsed": 3505, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="8a2f4a47-8e14-4834-f27b-11b50b148cf4"
# Dangers of reshaping (unintended consequences)
x = torch.tensor([
[[1,1,1,1], [2,2,2,2], [3,3,3,3]],
[[10,10,10,10], [20,20,20,20], [30,30,30,30]]
])
print(f"Size: {x.shape}")
print(f"x: \n{x}\n")
a = x.view(x.size(1), -1)
print(f"\nSize: {a.shape}")
print(f"a: \n{a}\n")
b = x.transpose(0,1).contiguous()
print(f"\nSize: {b.shape}")
print(f"b: \n{b}\n")
c = b.view(b.size(0), -1)
print(f"\nSize: {c.shape}")
print(f"c: \n{c}")
# + id="HcW6i9xJwU2Q" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406986, "user_tz": 420, "elapsed": 3499, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="8adac0f4-2222-4dfa-d9a7-f8498fd0e18f"
# Dimensional operations
x = torch.randn(2, 3)
print(f"Values: \n{x}")
y = torch.sum(x, dim=0) # add each row's value for every column
print(f"Values: \n{y}")
z = torch.sum(x, dim=1) # add each columns's value for every row
print(f"Values: \n{z}")
# + [markdown] id="kqxljkudzH0M"
# # Indexing, Splicing and Joining
# + id="Q8-w1Cb3wsj0" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406986, "user_tz": 420, "elapsed": 3492, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="9eb663da-9490-45d3-a1b6-6f88fa77b578"
x = torch.randn(3, 4)
print (f"x: \n{x}")
print (f"x[:1]: \n{x[:1]}")
print (f"x[:1, 1:3]: \n{x[:1, 1:3]}")
# + id="jBGk_740wsm3" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406987, "user_tz": 420, "elapsed": 3486, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="55b9e49a-2917-4add-c803-886c0454883f"
# Select with dimensional indicies
x = torch.randn(2, 3)
print(f"Values: \n{x}")
col_indices = torch.LongTensor([0, 2])
chosen = torch.index_select(x, dim=1, index=col_indices) # values from column 0 & 2
print(f"Values: \n{chosen}")
row_indices = torch.LongTensor([0, 1])
col_indices = torch.LongTensor([0, 2])
chosen = x[row_indices, col_indices] # values from (0, 0) & (2, 1)
print(f"Values: \n{chosen}")
# + id="UI_hboLNwsqQ" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406987, "user_tz": 420, "elapsed": 3480, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="d9226710-baed-4ca2-a5ca-0f6c68a7e319"
# Concatenation
x = torch.randn(2, 3)
print(f"Values: \n{x}")
y = torch.cat([x, x], dim=0) # stack by rows (dim=1 to stack by columns)
print(f"Values: \n{y}")
# + [markdown] id="lK1OQUYL1bE3"
# # Gradients
# + [markdown] id="VF5Q5kfs1rXZ"
# * $ y = 3x + 2 $
# * $ z = \sum{y}/N $
# * $ \frac{\partial(z)}{\partial(x)} = \frac{\partial(z)}{\partial(y)} \frac{\partial(y)}{\partial(x)} = \frac{1}{N} * 3 = \frac{1}{12} * 3 = 0.25 $
# + id="9Ft6PAeW0WCe" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406988, "user_tz": 420, "elapsed": 3474, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="4b2dd20e-2c64-4e4c-a1e9-772a8b2dca6f"
# Tensors with gradient bookkeeping
x = torch.rand(3, 4, requires_grad=True)
y = 3*x + 2
z = y.mean()
z.backward() # z has to be scalar
print(f"x: \n{x}")
print(f"x.grad: \n{x.grad}")
# + [markdown] id="kseQSKj72H8S"
# # CUDA tensors
# + id="ZE-ZyECv0WOX" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607980406988, "user_tz": 420, "elapsed": 3467, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="b430b0a1-a7b4-4db4-99a0-761e4bb239cf"
# Is CUDA available?
print (torch.cuda.is_available())
# + [markdown] id="n5sWo3Yv2MxO"
# If False (CUDA is not available), let's change that by following these steps: Go to *Runtime* > *Change runtime type* > Change *Hardware accelertor* to *GPU* > Click *Save*
# + id="ewamITzX2W-B"
import torch
# + id="IwsrvGad2NDO" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607981870584, "user_tz": 420, "elapsed": 656, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjMIOf3R_zwS_zZx4ZyPMtQe0lOkGpPOEUEKWpM7g=s64", "userId": "00378334517810298963"}} outputId="63324f49-3195-49ec-a680-8801eb74d158"
# Is CUDA available now?
print (torch.cuda.is_available())
# + id="50ewrqUVCRHg" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607981870585, "user_tz": 420, "elapsed": 648, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/<KEY>g=s64", "userId": "00378334517810298963"}} outputId="f179b5e5-b13d-4fae-9827-90a1b8198cde"
# Set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print (device)
# + id="s12ivWJZCLq7" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1607981881034, "user_tz": 420, "elapsed": 11089, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/<KEY>", "userId": "00378334517810298963"}} outputId="1d1443e4-ad3d-4c8d-d220-0ac10e726339"
x = torch.rand(2,3)
print (x.is_cuda)
x = torch.rand(2,3).to(device) # sTensor is stored on the GPU
print (x.is_cuda)
|
notebooks/05_PyTorch.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
import mlflow.sklearn
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import os
experiment_name="BCA_experiment4"
# + pycharm={"name": "#%%\n"}
data = pd.read_csv("Data/data.csv")
data.head()
# + pycharm={"name": "#%%\n"}
data.drop(["id"],axis=1, inplace = True)
# + pycharm={"name": "#%%\n"}
data.head()
# + pycharm={"name": "#%%\n"}
data["Unnamed: 32"].unique()
data.drop(["Unnamed: 32"], axis=1, inplace = True)
# + pycharm={"name": "#%%\n"}
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
data["diagnosis"] = le.fit_transform(data["diagnosis"])
# + pycharm={"name": "#%%\n"}
data["diagnosis"].unique()
# + pycharm={"name": "#%%\n"}
data.info()
# +
import mlflow
from azureml.core import Workspace
# + pycharm={"name": "#%%\n"}
# I needed to create my own custom config.json file that included my tenant_id and interactive login
# If you system is working you shouldn't need this added step
from azureml.core.authentication import InteractiveLoginAuthentication
import json
with open("config/config.json") as file:
config = json.load(file)
interactive_auth=InteractiveLoginAuthentication(tenant_id=config["tenant_id"])
ws = Workspace(subscription_id=config["subscription_id"],
resource_group=config["resource_group"],
workspace_name=config["workspace_name"],
auth=interactive_auth)
mlflow.set_tracking_uri(ws.get_mlflow_tracking_uri())
# +
#mlflow.set_tracking_uri("http://localhost:5001")
mlflow.set_experiment(experiment_name)
# + pycharm={"name": "#%%\n"}
try:
os.mkdir(f"deployments/{experiment_name}")
os.mkdir(f"deployments/{experiment_name}/api")
print(f"deployments/{experiment_name} created")
except FileExistsError:
print(f"deployments/{experiment_name} exists")
# + pycharm={"name": "#%%\n"}
sns.heatmap(data.corr())
plt.show()
# + pycharm={"name": "#%%\n"}
corr_cutoff = .7
top_corrs = list(data.corr()[(data.corr()>corr_cutoff) | (data.corr()<-corr_cutoff)].diagnosis.dropna().index)
top_corrs
# + pycharm={"name": "#%%\n"}
sns.heatmap(data[top_corrs].corr(),vmin=0)
# + pycharm={"name": "#%%\n"}
from sklearn.model_selection import train_test_split
#top_corrs.remove("diagnosis")
X = data[top_corrs].drop("diagnosis",axis=1)
y = data["diagnosis"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)
# + pycharm={"name": "#%%\n"}
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# + pycharm={"name": "#%%\n"}
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, accuracy_score
test_models = [LogisticRegression(random_state = 0),
KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2),
SVC(kernel = 'rbf', random_state = 0),
GaussianNB(),
DecisionTreeClassifier(criterion="entropy", random_state=0),
RandomForestClassifier(n_estimators=100, criterion="entropy", random_state=0)]
# + pycharm={"name": "#%%\n"}
def model_test(Model):
model_type = type(Model).__name__
print(model_type)
Model.fit(X_train, y_train)
run_name = "Basic " + model_type + " Experiment"
print(run_name)
with mlflow.start_run(run_name=run_name) as run:
Model.fit(X_train, y_train)
y_pred = Model.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print(cm)
df_cm = pd.DataFrame(cm, index = ["T", "F"],
columns = ["T", "F"])
plt.figure(figsize = (5,5))
sns.heatmap(df_cm, annot=True)
figname = "Confusion_Matrix_" + model_type
# Log CM
plt.savefig(figname)
mlflow.log_artifact(figname+".png")
score = accuracy_score(y_test, y_pred)
# Log model
mlflow.sklearn.log_model(Model, model_type+"-model")
# Create metrics
print(f"score: {score}")
# Log metrics
mlflow.log_metric("score", score)
runID = run.info.run_uuid
experimentID = run.info.experiment_id
print(f"Inside MLflow Run with run_id `{runID}` and experiment_id `{experimentID}`")
# + pycharm={"name": "#%%\n"}
for model in test_models:
model_test(model)
# + [markdown] pycharm={"name": "#%% md\n"}
# ## Stage 2: Download Model
#
#
# + pycharm={"name": "#%%\n"}
exp = ws.experiments[experiment_name]
runs = list(exp.get_runs())
high_score = [0, "run"]
for run in runs:
try:
print(run.get_metrics("score"))
tmp = run.get_metrics("score")["score"]
if tmp > high_score[0]:
high_score = [tmp, run]
except KeyError:
pass
print(high_score[0],"\n",high_score[1])
# + pycharm={"name": "#%%\n"}
high_score[1].download_files(output_directory=f"deployments/{experiment_name}")
filenames = high_score[1].get_file_names()
filenames
# + pycharm={"name": "#%%\n"}
for file in filenames:
if ".pkl" in file:
file = file.split(r"/")
dir_name = "/".join(file[:-1])
print(dir_name)
# + pycharm={"name": "#%%\n"}
model_config_json = {"experiment_name":experiment_name,
"model_directory":dir_name}
with open(f"deployments/{experiment_name}/api/model_config.json", "w") as f:
f.write(json.dumps(model_config_json))
# -
# ## Stage 3: Create Flask app
# See deployments/rfbca-container/api/FlaskAPI.py
# + pycharm={"name": "#%%\n"}
from shutil import copyfile
copyfile("template/FlaskAPI.py", f"deployments/{experiment_name}/api/FlaskAPI.py")
# -
# ## Stage 4: Create Flask API as Docker Container
#
# Created deployments/rfbca-containter/Dockerfile and deployments/rfbca-container/api/requirements.txt
# DockerFile:
#
# FROM python:3.7.8
# MAINTAINER <NAME>, Northwestern Student
# COPY ./api /usr/local/python/api
# COPY ./random_forest_model /usr/local/python/random_forest_model/
# EXPOSE 5010
# WORKDIR /usr/local/python/api/
# RUN pip install -r requirements.txt
# CMD python FlaskAPI.py
#
# requirements.txt:
#
# flask
# flasgger
# scikit-learn
# pandas
# cloudpickle
#
#
# + pycharm={"name": "#%%\n"}
dir = "./"+dir_name
dir2 = "/usr/local/python/" +dir_name
text = """FROM python:3.7.8
MAINTAINER <NAME>, Northwestern Student
COPY ./api /usr/local/python/api
COPY {} {}
EXPOSE 5010
WORKDIR /usr/local/python/api/
RUN pip install -r requirements.txt
CMD python FlaskAPI.py
""".format(dir, dir2)
print(text)
# + pycharm={"name": "#%%\n"}
with open(f"deployments/{experiment_name}/Dockerfile","w") as f:
f.write(text)
# + pycharm={"name": "#%%\n"}
os.chdir(f"deployments/{experiment_name}")
# +
text ="""flask
flasgger
scikit-learn
pandas
pickle5"""
with open("api/requirements.txt","w") as f:
f.write(text)
# + pycharm={"name": "#%%\n"}
container_name = experiment_name.lower().replace("_","")
# !docker build -t $container_name:latest -f Dockerfile .
# + pycharm={"name": "#%%\n"}
# !docker run -d --rm -p5010:5010 --name $container_name $container_name:latest
# + pycharm={"name": "#%%\n"}
# !docker ps
# -
# !docker stop $container_name
# + pycharm={"name": "#%%\n"}
os.chdir("../..")
# + [markdown] pycharm={"name": "#%% md\n"}
# ## Step 5: send to container registry
# + pycharm={"name": "#%%\n"}
# !az login
# + pycharm={"name": "#%%\n"}
# !az acr login --name cisfinalcr
# + pycharm={"name": "#%%\n"}
# build and push to acr
import os
os.chdir(f"deployments/{experiment_name}")
# !az acr build --image $container_name:latest --registry cisfinalcr --file Dockerfile .
# + pycharm={"name": "#%%\n"}
os.chdir("../..")
# + pycharm={"name": "#%%\n"}
# !az acr repository list --name cisfinalcr
# + [markdown] pycharm={"name": "#%% md\n"}
# ## Step 6: Configure kuber cluster
#
# Created yaml file deployments/rfbca-container/kuber.yaml:
#
# apiVersion: apps/v1
# kind: Deployment
# metadata:
# name: bca-api-prediction
# spec:
# replicas: 1
# selector:
# matchLabels:
# app: bca-api-prediction
# strategy:
# rollingUpdate:
# maxSurge: 1
# maxUnavailable: 1
# minReadySeconds: 5
# template:
# metadata:
# labels:
# app: bca-api-prediction
# spec:
# nodeSelector:
# "beta.kubernetes.io/os": linux
# containers:
# - name: bca-api-prediction
# image: cisfinalcr.azurecr.io/bca-api
# ports:
# - containerPort: 5010
# resources:
# requests:
# cpu: 250m
# limits:
# cpu: 500m
# ---
# apiVersion: v1
# kind: Service
# metadata:
# name: bca-api-prediction
# spec:
# type: LoadBalancer
# ports:
# - port: 5010
# selector:
# app: bca-api-prediction
#
# +
kuber_text = """apiVersion: apps/v1
kind: Deployment
metadata:
name: {}-prediction
spec:
replicas: 1
selector:
matchLabels:
app: {}-prediction
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
minReadySeconds: 5
template:
metadata:
labels:
app: {}-prediction
spec:
nodeSelector:
"beta.kubernetes.io/os": linux
containers:
- name: {}-prediction
image: cisfinalcr.azurecr.io/{}
ports:
- containerPort: 5010
resources:
requests:
cpu: 250m
limits:
cpu: 500m
---
apiVersion: v1
kind: Service
metadata:
name: {}-prediction
spec:
type: LoadBalancer
ports:
- port: 5010
selector:
app: {}-prediction""".format(container_name,container_name,container_name,container_name,container_name,container_name,container_name)
print(kuber_text)
with open(f"deployments/{experiment_name}/kuber.yaml","w") as file:
file.write(kuber_text)
# + pycharm={"name": "#%%\n"}
# !az aks get-credentials --resource-group CISFinalRG --name CISFinalKS
# + pycharm={"name": "#%%\n"}
# !kubectl apply -f deployments/$experiment_name/kuber.yaml
# + pycharm={"name": "#%%\n"}
# !kubectl get service bca-api-prediction --watch
# + pycharm={"name": "#%%\n"}
|
Data_Review_Experimentation2.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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 data_validator_pkg.dataV import transform
# +
import pandas as pd
df = pd.DataFrame({'num' : [1, 2, 2, 3] , 'str' : ['a', 'a', 'b', None]})
df2 = pd.DataFrame({'num' : [2, 3, 3, 4] , 'str' : ['a', 'a', 'b', None]})
# -
transform([{'name': 'test', 'table': df}, {'name': 'test2', 'table': df2}])
from DataVisualization.src.data_visualization import data_visualize
pip list
|
jupyterlab-data-validator/.ipynb_checkpoints/Untitled-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
# ---
# # CSV command-line kung fu
#
# You might be surprised how much data slicing and dicing you can do from the command line using some simple tools and I/O redirection + piping. (See [A Quick Introduction to Pipes and Redirection](http://bconnelly.net/working-with-csvs-on-the-command-line/#a-quick-introduction-to-pipes-and-redirection)).
#
# To motivate the use of command line, rather than just reading everything into Python, commandline tools will often process data much faster. (Although, In this case, we are using a Python based commandline tool.) Most importantly, you can launch many of these commands simultaneously from the commandline, computing everything in parallel using the multiple CPU core you have in your computer. If you have 4 core, you have the potential to process the data four times faster than a single-threaded Python program.
# ## Stripping char beyond 255 from commandline
#
# If there are characters within the file that are non-ASCII and larger than 255, we can convert the file using the command line. Here's a simple version of the problem I put into file `/tmp/foo.html`:
#
# ```html
# <html>
# <body>
# གྷ
# </body>
# </html>
# ```
#
# I deliberately injected a Unicode code point > 255, which requires two bytes to store. Most of the characters require just one byte. Here is first part of file:
#
# ```bash
# $ od -c -t xC /tmp/t.html
# 0000000 < h t m l > \n < b o d y > \n གྷ **
# 3c 68 74 6d 6c 3e 0a 3c 62 6f 64 79 3e 0a e0 bd
# ...
# ```
#
# Here is how you could strip any non-one-byte characters from the file before processing:
#
# ```bash
# $ iconv -c -f utf-8 -t ascii /tmp/foo.html
# <html>
# <body>
#
# </body>
# </html>
# ```
#
# We've already seen I/O redirection where we took the output of a command and wrote it to a file. We can do the same here:
#
# ```bash
# $ iconv -c -f utf-8 -t ascii /tmp/foo.html > /tmp/foo2.html
# ```
# ## Set up for CSV on commandline
#
# ```bash
# pip install csvkit
# ```
#
# ## Extracting rows with grep
#
# Now, let me introduce you to the `grep` command that lets us filter the lines in a file according to a regular expression. Here's how to find all rows that contain `<NAME>`:
# ! grep '<NAME>' data/SampleSuperstoreSales.csv | head -3
# We didn't have to write any code. We didn't have to jump into a development environment or editor. We just asked for the sales for Annie. If we want to write the data to a file, we simply redirect it:
# ! grep '<NAME>' data/SampleSuperstoreSales.csv > /tmp/Annie.csv
# ! head -3 /tmp/Annie.csv # show first 3 lines of that new file
# ## Filtering with csvgrep
#
# [csvkit](https://csvkit.readthedocs.io/en/1.0.3/) is an amazing package with lots of cool CSV utilities for use on the command line. `csvgrep` is one of them.
#
# If we want a specific row ID, then we need to use the more powerful `csvgrep` not just `grep`. We use a different regular expression that looks for a specific string at the left edge of a line (`^` means the beginning of a line, `$` means end of line or end of record):
# ! csvgrep -c 1 -r '^80$' -e latin1 data/SampleSuperstoreSales.csv
# What if you want, say, two different rows?
# ! csvgrep -c 1 -r '^(80|160)$' -e latin1 data/SampleSuperstoreSales.csv
# ## Beginning, end of files
# If we'd like to see just the header row, we can use `head`:
# ! head -1 data/SampleSuperstoreSales.csv
# If, on the other hand, we want to see everything but that row, we can use `tail` (which I pipe to `head` so then I see only the first two lines of output):
# ! tail +2 data/SampleSuperstoreSales.csv | head -2
# The output would normally be many thousands of lines here so I have *piped* the output to the `head` command to print just the first two rows. We can pipe many commands together, sending the output of one command as input to the next command.
# ### Exercise
#
# Count how many sales items there are in the `Technology` product category that are also `High` order priorities? Hint: `wc -l` counts the number of lines.
# ! grep Technology, data/SampleSuperstoreSales.csv | grep High, | wc -l
# ## Extracting columns with csvcut
#
# Extracting columns is also pretty easy with `csvcut`. For example, let's say we wanted to get the customer name column (which is 12th by my count).
# ! csvcut -c 12 -e latin1 data/SampleSuperstoreSales.csv | head -10
# Actually, hang on a second. We don't want the `Customer Name` header to appear in the list so we combine with the `tail` we just saw to strip the header.
# ! csvcut -c 12 -e latin1 data/SampleSuperstoreSales.csv | tail +2 | head -10
# What if we want a unique list? All we have to do is sort and then call `uniq`:
# ! csvcut -c 12 -e latin1 data/SampleSuperstoreSales.csv | tail +2 | sort | uniq | head -10
# You can get multiple columns at once in the order specified. For example, here is how to get the sales ID and the customer name together (name first then ID):
# ! csvcut -c 12,2 -e latin1 data/SampleSuperstoreSales.csv |head -10
# Naturally, we can write any of this output to a file using the `>` redirection operator. Let's do that and put each of those columns into a separate file and then `paste` them back with the customer name first.
# ! csvcut -c 2 -e latin1 data/SampleSuperstoreSales.csv > /tmp/IDs
# ! csvcut -c 12 -e latin1 data/SampleSuperstoreSales.csv > /tmp/names
# ! paste /tmp/names /tmp/IDs | head -10
# Amazing, right?! This is often a very efficient means of manipulating data files because you are directly talking to the operating system instead of through Python libraries. We also don't have to write any code, we just have to know some syntax for terminal commands.
#
# Not impressed yet? Ok, how about creating a histogram indicating the number of sales per customer sorted in reverse numerical order? We've already got the list of customers and we can use an argument on `uniq` to get the count instead of just making a unique set. Then, we can use a second `sort` with arguments to reverse sort and use numeric rather than text-based sorting. This gives us a histogram:
# ! csvcut -c 12 -e latin1 data/SampleSuperstoreSales.csv | tail +2 | sort | uniq -c | sort -r -n | head -10
# ### Exercise
#
# Modify the command so that you get a histogram of the shipping mode.
# ! csvcut -c 8 -e latin1 data/SampleSuperstoreSales.csv | tail +2 | sort | uniq -c | sort -r -n | head -10
|
notes/bashcsv.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .jl
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Julia 1.4.2
# language: julia
# name: julia-1.4
# ---
using DrWatson
@quickactivate "MEngProject"
using MEngProject, CUDA, DifferentialEquations, PyPlot, NNlib, ImageFiltering, Images, MEngProject, MEngProject.LamKernels, MEngProject.Laminart, MEngProject.Utils, BenchmarkTools, Test
using OrdinaryDiffEq, ParameterizedFunctions, LSODA, Sundials, DiffEqDevTools
function reshape2d_4d(img::AbstractArray)
reshape(img, size(img)[1], size(img)[2], 1, 1)
end
# +
img = convert(Array{Float32,2}, load(datadir("temp_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
# -
Utils.plot_rb(img[:,:,1,1])
tspan = (0.0f0, 500f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob)
Utils.plot_rb(sol[end][:,:,11,1])
Utils.plot_rb(sol[end][:,:,7,1])
out = sol[end][:,:,7,1] .+ sol[end][:,:,8,1] .-sol[end][:,:,11,1] .- sol[end][:,:,12,1];
Utils.plot_rb(out)
iimg = img .* 2;
out = sol[end][:,:,7,1] .+ sol[end][:,:,8,1] .- iimg[:,:,1,1];
Utils.plot_rb(out, axMin=-2.0)
# +
img = convert(Array{Float32,2}, load(datadir("temp1_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
# -
Utils.plot_rb(img[:,:,1,1])
tspan = (0.0f0, 500f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob)
Utils.plot_rb(sol[end][:,:,11,1])
Utils.plot_rb(sol[end][:,:,7,1])
out = sol[end][:,:,7,1] .+ sol[end][:,:,8,1] .-sol[end][:,:,11,1] .- sol[end][:,:,12,1];
Utils.plot_rb(out)
iimg = img .* 2;
out = sol[end][:,:,7,1] .+ sol[end][:,:,8,1] .- iimg[:,:,1,1];
Utils.plot_rb(out, axMin=-2.0)
out = sol[end][:,:,1,1] .+ sol[end][:,:,2,1] .- iimg[:,:,1,1];
Utils.plot_rb(out, axMin=-2.0)
out = sol[end][:,:,3,1] .+ sol[end][:,:,4,1] .- iimg[:,:,1,1];
Utils.plot_rb(out, axMin=-2.0)
out = sol[end][:,:,5,1] .+ sol[end][:,:,6,1] .- iimg[:,:,1,1];
Utils.plot_rb(out, axMin=-2.0)
out = sol[end][:,:,9,1] .+ sol[end][:,:,10,1] .- iimg[:,:,1,1];
Utils.plot_rb(out, axMin=-2.0)
out = sol[end][:,:,11,1] .+ sol[end][:,:,12,1] .- iimg[:,:,1,1];
Utils.plot_rb(out, axMin=-2.04)
out = sol[end][:,:,7,1] .- iimg[:,:,1,1];
Utils.plot_rb(out, axMin=-2.0)
img = convert(Array{Float32,2}, load(datadir("temp1_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
img = img .* 0.2f0
# +
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
# -
# +
tspan = (0.0f0, 500f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob)
# -
iimg = img .* 5;
out = sol[end][:,:,7,1] .- iimg[:,:,1,1];
outmx = findmax(out)
outmn = findmin(out)
Utils.plot_rb(out, axMax=findmax(out)[1], axMin=findmin(out)[1])
findmax(sol[end][:,:,7,1])
# +
img = convert(Array{Float32,2}, load(datadir("temp2_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
tspan = (0.0f0, 500f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob);
# +
# iimg = img .* 5;
# out = sol[end][:,:,7,1] .- iimg[:,:,1,1];
# outmx = findmax(out)
# outmn = findmin(out)
# Utils.plot_rb(out, axMax=findmax(out)[1], axMin=findmin(out)[1])
# -
Utils.plot_gs(sol[end][:,:,7,1], axMax=findmax(sol[end][:,:,7,1])[1], axMin=findmin(sol[end][:,:,7,1])[1])
# +
img = convert(Array{Float32,2}, load(datadir("temp3_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
tspan = (0.0f0, 500f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob);
# +
# iimg = img .* 5;
# out = sol[end][:,:,7,1] .- iimg[:,:,1,1];
# outmx = findmax(out)
# outmn = findmin(out)
# Utils.plot_rb(out, axMax=findmax(out)[1], axMin=findmin(out)[1])
# -
Utils.plot_gs(sol[end][:,:,7,1], axMax=findmax(sol[end][:,:,7,1])[1], axMin=findmin(sol[end][:,:,7,1])[1])
Utils.plot_gs(sol[end][:,:,7,1] .+ sol[end][:,:,8,1], axMax=findmax(sol[end][:,:,7,1] .+ sol[end][:,:,8,1])[1], axMin=findmin(sol[end][:,:,7,1] .+ sol[end][:,:,8,1])[1])
# +
img = convert(Array{Float32,2}, load(datadir("temp4_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
tspan = (0.0f0, 500f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob);
# +
# iimg = img .* 5;
# # out = sol[end][:,:,7,1] .- iimg[:,:,1,1];
# # outmx = findmax(out)
# # outmn = findmin(out)
# # Utils.plot_rb(out, axMax=findmax(out)[1], axMin=findmin(out)[1])
# -
Utils.plot_gs(sol[end][:,:,7,1], axMax=findmax(sol[end][:,:,7,1])[1], axMin=findmin(sol[end][:,:,7,1])[1])
Utils.plot_gs(sol[end][:,:,7,1] .+ sol[end][:,:,8,1], axMax=findmax(sol[end][:,:,7,1] .+ sol[end][:,:,8,1])[1], axMin=findmin(sol[end][:,:,7,1] .+ sol[end][:,:,8,1])[1])
# +
img = convert(Array{Float32,2}, load(datadir("temp5_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
tspan = (0.0f0, 1000f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob);
# -
Utils.plot_gs(sol[end][:,:,7,1], axMax=findmax(sol[end][:,:,7,1])[1], axMin=findmin(sol[end][:,:,7,1])[1])
Utils.plot_gs(sol[end][:,:,7,1] .+ sol[end][:,:,8,1], axMax=findmax(sol[end][:,:,7,1] .+ sol[end][:,:,8,1])[1], axMin=findmin(sol[end][:,:,7,1] .+ sol[end][:,:,8,1])[1])
# +
iimg = img .* 5;
out = sol[end][:,:,7,1] .- iimg[:,:,1,1];
# Utils.plot_gs(out, axMax=findmax(out)[1], axMin=findmin(out)[1])
# +
img = convert(Array{Float32,2}, load(datadir("temp3_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
tspan = (0.0f0, 500f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob);
# +
# iimg = img .* 5;
# out = sol[end][:,:,7,1] .- iimg[:,:,1,1];
# outmx = findmax(out)
# outmn = findmin(out)
# Utils.plot_rb(out, axMax=findmax(out)[1], axMin=findmin(out)[1])
# -
Utils.plot_gs(sol[end][:,:,7,1], axMax=findmax(sol[end][:,:,7,1])[1], axMin=findmin(sol[end][:,:,7,1])[1])
# +
img = convert(Array{Float32,2}, load(datadir("temp3_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
tspan = (0.0f0, 500f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob);
# -
iimg = img .* 5;
out = sol[end][:,:,7,1] .- iimg[:,:,1,1];
outmx = findmax(out)
outmn = findmin(out)
Utils.plot_rb(out, axMax=findmax(out)[1], axMin=findmin(out)[1])
# +
img = convert(Array{Float32,2}, load(datadir("temp5_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
tspan = (0.0f0, 1000f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob)
# -
Utils.plot_gs(sol[end][:,:,7,1], axMax=findmax(sol[end][:,:,7,1])[1], axMin=findmin(sol[end][:,:,7,1])[1])
findmax(sol[end][:,:,7,1])
findmax(sol[35,45,7,1,:])
plot(sol[35,45,7,1,:])
plot(sol[35,45,7,1,150:end])
plot(sol[35,45,5,1,:])
plot(sol[35,45,7,1,150:250])
plot(sol[35,45,7,1,1:00])
# +
img = convert(Array{Float32,2}, load(datadir("temp5_100_100_gs.png")));
img = reshape2d_4d(img)
img = cu(img)
r = similar(img)
p = LaminartGPU.kernels(img, Parameters.parameters);
LaminartGPU.I_u!(r, img, p)
temp_out = (I = img, r = r)
p = merge(p, temp_out);
tspan = (0.0f0, 5f0)
u0 = cu(reshape(zeros(Float32, p.dim_i, p.dim_j*(5*p.K+2)), p.dim_i, p.dim_j, 5*p.K+2,1));
arr1 = u0[:, :, 1:p.K,:]
arr2 = u0[:, :, 1:1,:];
f = LaminartGPU.LamFunction(
similar(arr1), #x
similar(arr1), #m
similar(arr1), #s
similar(arr2), #x_lgn,
similar(arr1), #C,
similar(arr1), #H_z,
similar(arr1), # dy_temp,
similar(arr1), # dm_temp,
similar(arr1), # dz_temp,
similar(arr1), # ds_temp,
similar(arr2), # dv_temp,
similar(arr1), # H_z_temp,
similar(arr2), # V_temp_1,
similar(arr2), # V_temp_2,
similar(arr1), # Q_temp,
similar(arr1), # P_temp
);
prob = ODEProblem(f, u0, tspan, p);
@time sol = solve(prob);
# -
Utils.plot_gs(sol[end][:,:,7,1], axMax=findmax(sol[end][:,:,7,1])[1], axMin=findmin(sol[end][:,:,7,1])[1])
plot(sol[findmax(sol[:,:,7,1,end])[2][1],findmax(sol[:,:,7,1,end])[2][2],7,1,:])
|
notebooks/dev/.ipynb_checkpoints/test_img_dev-checkpoint.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 AlGDock.BindingPMF_plots
from AlGDock.BindingPMF_plots import *
import os, shutil, glob
phases = ['NAMD_Gas', 'NAMD_OBC']
self = AlGDock.BindingPMF_plots.BPMF_plots(\
dir_dock='dock', dir_cool='cool',\
ligand_database='prmtopcrd/ligand.db', \
forcefield='prmtopcrd/gaff2.dat', \
ligand_prmtop='prmtopcrd/ligand.prmtop', \
ligand_inpcrd='prmtopcrd/ligand.trans.inpcrd', \
ligand_mol2='prmtopcrd/ligand.mol2', \
ligand_rb='prmtopcrd/ligand.rb', \
receptor_prmtop='prmtopcrd/receptor.prmtop', \
receptor_inpcrd='prmtopcrd/receptor.trans.inpcrd', \
receptor_fixed_atoms='prmtopcrd/receptor.pdb', \
complex_prmtop='prmtopcrd/complex.prmtop', \
complex_inpcrd='prmtopcrd/complex.trans.inpcrd', \
complex_fixed_atoms='prmtopcrd/complex.pdb', \
score = 'prmtopcrd/anchor_and_grow_scored.mol2', \
pose=-1, \
rmsd=True, \
dir_grid='grids', \
protocol='Adaptive', cool_therm_speed=5.0, dock_therm_speed=0.5, \
T_HIGH=600.0, T_SIMMIN=300.0, T_TARGET=300.0, \
sampler='HMC', \
MCMC_moves=1, \
sampling_importance_resampling = True, \
solvation = 'Fractional', \
seeds_per_state=10, steps_per_seed=200, darts_per_seed=0, \
sweeps_per_cycle=25, attempts_per_sweep=100, \
steps_per_sweep=100, darts_per_sweep=0, \
cool_repX_cycles=3, dock_repX_cycles=4, \
site='Sphere', site_center=[1.7416, 1.7416, 1.7416], \
site_max_R=0.6, \
site_density=10., \
phases=phases, \
cores=-1, \
random_seed=-1, \
max_time=240, \
keep_intermediate=True)
# -
self.universe.setConfiguration(Configuration(self.universe,self.confs['ligand']))
self._set_universe_evaluator(self._lambda(1.0, 'dock'))
self.universe.energyTerms()
# Before the unit fix, OBC_desolv is -358.92191041097993
print self._forceFields['OBC'].desolvationGridFN
# +
# First goal: Get GB radii for ligand.
# Second goal: Load receptor
# Third goal: Get GB radii for ligand with receptor present
# +
# This is to test the gradients, which do not work
# from AlGDock.ForceFields.OBC.OBC import OBCForceField
# FF_desolv = OBCForceField(desolvationGridFN=self._FNs['grids']['desolv'])
# self.universe.setForceField(FF_desolv)
# from MMTK.ForceFields.ForceFieldTest import gradientTest
#
# gradientTest(self.universe)
# +
# This is the receptor without the ligand
self.receptor_R = MMTK.Molecule('receptor.db')
self.universe_R = MMTK.Universe.InfiniteUniverse()
self.universe_R.addObject(self.receptor_R)
# Getting the AMBER energy appears to work
# from MMTK.ForceFields import Amber12SBForceField
# self._forceFields['AMBER'] = \
# Amber12SBForceField(\
# mod_files=['/Users/dminh/Installers/AlGDock-0.0.1/Data/frcmod.ff14SB',
# '/Users/dminh/Installers/AlGDock-0.0.1/Example/prmtopcrd/R2773.frcmod',
# '/Users/dminh/Installers/AlGDock-0.0.1/Example/prmtopcrd/R2777.frcmod'])
# Specifying the main force field file seems to make the energy calculation crash
# '/Users/dminh/Installers/AlGDock-0.0.1/Data/parm10_gaff2.dat',
# self.universe_R.setForceField(self._forceFields['AMBER'])
# print self.universe_R.energyTerms()
from AlGDock.ForceFields.OBC.OBC import OBCForceField
self.universe_R.setForceField(OBCForceField())
print self.universe_R.energyTerms()
# +
# This is the protein alone
# import MMTK
# universe = MMTK.Universe.InfiniteUniverse()
# from MMTK.Proteins import Protein
# protein = Protein('/Users/dminh/Installers/AlGDock-0.0.1/Example/prmtopcrd/receptor.pdb')
# universe.addObject(protein)
# from MMTK.ForceFields import Amber12SBForceField
# forcefield = Amber12SBForceField(mod_files=['/Users/dminh/Installers/AlGDock-0.0.1/Data/frcmod.ff14SB'])
# # '/Users/dminh/Installers/AlGDock-0.0.1/Data/parm10.dat',
# # mod_files=['/Users/dminh/Installers/AlGDock-0.0.1/Data/frcmod.ff14SB'])
# universe.setForceField(forcefield)
# universe.energyTerms()
# +
self.receptor_RL = MMTK.Molecule('receptor.db')
self.molecule_RL = MMTK.Molecule(os.path.basename(self._FNs['ligand_database']))
for (atom,pos) in zip(self.molecule_RL.atomList(),self.confs['ligand']):
atom.setPosition(pos)
self.universe_RL = MMTK.Universe.InfiniteUniverse()
self.universe_RL.addObject(self.receptor_RL)
self.universe_RL.addObject(self.molecule_RL)
self.universe_RL.configuration().array[-len(self.universe.configuration().array):,:] = self.universe.configuration().array
from AlGDock.ForceFields.OBC.OBC import OBCForceField
self.universe_RL.setForceField(OBCForceField())
print self.universe_RL.energyTerms()
# -
# The columns are before and after fractional desolvation and in the complex
I = np.array(
[( 1.55022, 1.66261, 2.90035 ),
( 1.56983, 1.68106, 2.82747 ),
( 1.41972, 1.53815, 2.8298 ),
( 1.45936, 1.58425, 2.84062 ),
( 2.05316, 2.15476, 3.24919 ),
( 1.5354, 1.65705, 2.93556 ),
( 1.43417, 1.56071, 3.04796 ),
( 1.85508, 1.9636 , 3.13083 ),
( 2.06909, 2.17661, 3.35871 ),
( 2.4237, 2.57502 , 4.41055 ),
( 1.9603, 2.16599 , 4.35363 ),
( 2.18017, 2.32447, 3.89703 ),
( 2.19774, 2.32646, 3.68217 ),
( 2.02152, 2.16213, 3.76695 ),
( 2.05662, 2.21947, 3.8166 ),
( 2.65659, 2.79067, 4.25442 ),
( 2.81839, 2.9631 , 4.4784 ),
( 2.90653, 3.02582, 4.34538 ),
( 2.37779, 2.5372 , 4.38744 ),
( 2.17795, 2.32426, 4.23382 ),
( 1.77652, 1.89423, 3.35642 ),
( 1.22359, 1.38423, 3.22575 ),
( 1.2336, 1.40284 , 3.49822 ),
( 1.21771, 1.37135, 3.07989 )])
# %matplotlib inline
import matplotlib.pyplot as plt
# +
# This is the different between the quantity added by fractional desolvation and by the full complex
diff_frac = I[:,1]-I[:,0]
diff_real = I[:,2]-I[:,0]
plt.plot(diff_frac, diff_real,'.')
A = np.vstack([diff_frac, np.ones(len(diff_frac))]).T
m,c = np.linalg.lstsq(A, diff_real)[0]
plt.plot(diff_frac, m*diff_frac + c, 'r')
print 'The correlation is', np.corrcoef(diff_frac,diff_real)[0,1]
print 'The linear least squares regression slope is', m, 'and intercept is', c
# -
# ## Igrid[atomI] appears to be off by a factor of 12.6!
# +
# This is probably due to a unit conversion in a multiplicative prefactor
# This multiplicative prefactor is based on nanometers
r_min = 0.14
r_max = 1.0
print (1/r_min - 1/r_max)
# This multiplicative prefactor is based on angstroms
r_min = 1.4
r_max = 10.0
print (1/r_min - 1/r_max)
# -
# ## Switching from nanometers to angstroms makes the multiplicative prefactor smaller, which is opposite of the desired effect!
4*np.pi
# ## Igrid[atomI] appears to be off by a factor of 4*pi!
# +
# This is after multiplication by 4*pi
# Sum for atom 0: 1.55022, 2.96246
# Sum for atom 1: 1.56983, 2.96756
# Sum for atom 2: 1.41972, 2.90796
# Sum for atom 3: 1.45936, 3.02879
# Sum for atom 4: 2.05316, 3.32989
# Sum for atom 5: 1.5354, 3.06405
# Sum for atom 6: 1.43417, 3.02438
# Sum for atom 7: 1.85508, 3.21875
# Sum for atom 8: 2.06909, 3.42013
# Sum for atom 9: 2.4237, 4.32524
# Sum for atom 10: 1.9603, 4.54512
# Sum for atom 11: 2.18017, 3.99349
# Sum for atom 12: 2.19774, 3.8152
# Sum for atom 13: 2.02152, 3.7884
# Sum for atom 14: 2.05662, 4.10305
# Sum for atom 15: 2.65659, 4.34157
# Sum for atom 16: 2.81839, 4.63688
# Sum for atom 17: 2.90653, 4.40561
# Sum for atom 18: 2.37779, 4.38092
# Sum for atom 19: 2.17795, 4.01659
# Sum for atom 20: 1.77652, 3.25573
# Sum for atom 21: 1.22359, 3.24223
# Sum for atom 22: 1.2336, 3.3604
# Sum for atom 23: 1.21771, 3.1483
|
Example/test_GB.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
# ---
# +
from pyspark.sql import SparkSession
from operator import add
# New API
spark_session = SparkSession\
.builder\
.master("spark://192.168.2.119:7077") \
.appName("TianruZ_lecture1_hdfs_example")\
.config("spark.executor.cores",2)\
.config("spark.dynamicAllocation.enabled", True)\
.config("spark.dynamicAllocation.shuffleTracking.enabled", True)\
.config("spark.shuffle.service.enabled", False)\
.config("spark.dynamicAllocation.executorIdleTimeout","30s")\
.config("spark.driver.port",9998)\
.config("spark.blockManager.port",10005)\
.getOrCreate()
# Old API (RDD)
spark_context = spark_session.sparkContext
spark_context.setLogLevel("ERROR")
# +
# The same example, this time using map and reduce from the Spark API, and loading the text file from HDFS.
lines = spark_context.textFile("hdfs://192.168.2.119:9000/i_have_a_dream.txt")
print(lines.first())
words = lines.map(lambda line: line.split(' '))
word_counts = words.map(lambda w: len(w))
total_words = word_counts.reduce(add)
print(f'total words= {total_words}')
# ... the same number of words?
# -
lines.take(10)
lines_splitted = lines.map(lambda line: line.split(' '))
print(lines_splitted.first())
# +
# Note, we're in Python, but using Java naming conventions!
all_words = lines.flatMap(lambda line: line.split(' '))
all_words.take(100)
# -
all_words.filter(lambda word: word.startswith('d'))\
.take(20)
# release the cores for another application!
spark_context.stop()
|
de1-2022/Lecture1_Example0_with_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.6 (wustl)
# language: python
# name: wustl
# ---
# # T81-558: Applications of Deep Neural Networks
# **Module 13: Advanced/Other Topics**
# * Instructor: [<NAME>](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)
# * For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/).
# # Module 13 Video Material
#
# Main video lecture:
#
# * Part 13.1: Deploying a Model to AWS [[Video]]() [[Notebook]](t81_558_class_13_01_flask.ipynb)
# * **Part 13.2: Flask and Deep Learning Web Services** [[Video]]() [[Notebook]](t81_558_class_13_02_cloud.ipynb)
# * Part 13.3: AI at the Edge: Using Keras on a Mobile Device [[Video]]() [[Notebook]](t81_558_class_13_03_web.ipynb)
# * Part 13.4: When to Retrain Your Neural Network [[Video]]() [[Notebook]](t81_558_class_13_04_edge.ipynb)
# * Part 13.5: Using a Keras Deep Neural Network with a Web Application [[Video]]() [[Notebook]](t81_558_class_13_05_retrain.ipynb)
#
# +
# COMING SOON
# -
|
t81_558_class_13_02_cloud.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="VAYu3ISwwGks"
import numpy as np
import pandas as pd
import torch
import torchvision
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from matplotlib import pyplot as plt
# %matplotlib inline
# + colab={"base_uri": "https://localhost:8080/"} id="yuUQrW3FPToA" outputId="db80183a-24ba-48a4-b38a-92e68e16eb1c"
from google.colab import drive
drive.mount('/content/drive')
# + id="_S8jVM83Pl6F"
path="/content/drive/MyDrive/Research/alternate_minimisation/type4_data/"
# + [markdown] id="DOcT9MVdvXAE"
# #data creation
# + id="V0-L-CdcyMrM"
# y = np.random.randint(0,10,5000)
# idx= []
# for i in range(10):
# print(i,sum(y==i))
# idx.append(y==i)
# + id="xzNbHl8pujas"
# x = np.zeros((5000,2))
# x[idx[0],:] = np.random.multivariate_normal(mean = [4,6.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[0]))
# x[idx[1],:] = np.random.multivariate_normal(mean = [5.5,6],cov=[[0.01,0],[0,0.01]],size=sum(idx[1]))
# x[idx[2],:] = np.random.multivariate_normal(mean = [4.5,4.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[2]))
# x[idx[3],:] = np.random.multivariate_normal(mean = [3,3.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[3]))
# x[idx[4],:] = np.random.multivariate_normal(mean = [2.5,5.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[4]))
# x[idx[5],:] = np.random.multivariate_normal(mean = [3.5,8],cov=[[0.01,0],[0,0.01]],size=sum(idx[5]))
# x[idx[6],:] = np.random.multivariate_normal(mean = [5.5,8],cov=[[0.01,0],[0,0.01]],size=sum(idx[6]))
# x[idx[7],:] = np.random.multivariate_normal(mean = [7,6.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[7]))
# x[idx[8],:] = np.random.multivariate_normal(mean = [6.5,4.5],cov=[[0.01,0],[0,0.01]],size=sum(idx[8]))
# x[idx[9],:] = np.random.multivariate_normal(mean = [5,3],cov=[[0.01,0],[0,0.01]],size=sum(idx[9]))
# + id="cq08aajNulXM"
# plt.figure(figsize=(6,6))
# for i in range(10):
# plt.scatter(x[idx[i],0],x[idx[i],1],label="class_"+str(i))
# plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
# + id="mCpHrpYhulTE"
# class SyntheticDataset(Dataset):
# """MosaicDataset dataset."""
# def __init__(self, x, y):
# """
# Args:
# csv_file (string): Path to the csv file with annotations.
# root_dir (string): Directory with all the images.
# transform (callable, optional): Optional transform to be applied
# on a sample.
# """
# self.x = x
# self.y = y
# #self.fore_idx = fore_idx
# def __len__(self):
# return len(self.y)
# def __getitem__(self, idx):
# return self.x[idx] , self.y[idx] #, self.fore_idx[idx]
# + id="sb7du8wMulF0"
# trainset = SyntheticDataset(x,y)
# trainloader = torch.utils.data.DataLoader(trainset, batch_size=100, shuffle=True)
# classes = ('zero','one','two','three','four','five','six','seven','eight','nine')
# foreground_classes = {'zero','one','two'}
# fg_used = '012'
# fg1, fg2, fg3 = 0,1,2
# all_classes = {'zero','one','two','three','four','five','six','seven','eight','nine'}
# background_classes = all_classes - foreground_classes
# background_classes
# + id="xPlROVpyutDc"
# dataiter = iter(trainloader)
# background_data=[]
# background_label=[]
# foreground_data=[]
# foreground_label=[]
# batch_size=100
# for i in range(50):
# images, labels = dataiter.next()
# for j in range(batch_size):
# if(classes[labels[j]] in background_classes):
# img = images[j].tolist()
# background_data.append(img)
# background_label.append(labels[j])
# else:
# img = images[j].tolist()
# foreground_data.append(img)
# foreground_label.append(labels[j])
# foreground_data = torch.tensor(foreground_data)
# foreground_label = torch.tensor(foreground_label)
# background_data = torch.tensor(background_data)
# background_label = torch.tensor(background_label)
# + id="mhP1Eo_aus_s"
# def create_mosaic_img(bg_idx,fg_idx,fg):
# """
# bg_idx : list of indexes of background_data[] to be used as background images in mosaic
# fg_idx : index of image to be used as foreground image from foreground data
# fg : at what position/index foreground image has to be stored out of 0-8
# """
# image_list=[]
# j=0
# for i in range(9):
# if i != fg:
# image_list.append(background_data[bg_idx[j]])
# j+=1
# else:
# image_list.append(foreground_data[fg_idx])
# label = foreground_label[fg_idx] - fg1 # minus fg1 because our fore ground classes are fg1,fg2,fg3 but we have to store it as 0,1,2
# #image_list = np.concatenate(image_list ,axis=0)
# image_list = torch.stack(image_list)
# return image_list,label
# + id="dBbTrz2WuzUs"
# # number of data points in bg class and fg class
# nbg = sum(idx[3]) + sum(idx[4]) + sum(idx[5]) + sum(idx[6]) + sum(idx[7]) + sum(idx[8]) + sum(idx[9])
# nfg = sum(idx[0]) + sum(idx[1]) + sum(idx[2])
# print(nbg, nfg, nbg+nfg)
# + id="PaMrJLbduzSO"
# desired_num = 3000
# mosaic_list_of_images =[] # list of mosaic images, each mosaic image is saved as list of 9 images
# fore_idx =[] # list of indexes at which foreground image is present in a mosaic image i.e from 0 to 9
# mosaic_label=[] # label of mosaic image = foreground class present in that mosaic
# list_set_labels = []
# for i in range(desired_num):
# set_idx = set()
# np.random.seed(i)
# bg_idx = np.random.randint(0,nbg,8)
# set_idx = set(background_label[bg_idx].tolist())
# fg_idx = np.random.randint(0,nfg)
# set_idx.add(foreground_label[fg_idx].item())
# fg = np.random.randint(0,9)
# fore_idx.append(fg)
# image_list,label = create_mosaic_img(bg_idx,fg_idx,fg)
# mosaic_list_of_images.append(image_list)
# mosaic_label.append(label)
# list_set_labels.append(set_idx)
# + id="emY8ogVJuzPF"
# desired_num = 2000
# test_mosaic_list_of_images =[] # list of mosaic images, each mosaic image is saved as list of 9 images
# test_fore_idx =[] # list of indexes at which foreground image is present in a mosaic image i.e from 0 to 9
# test_mosaic_label=[] # label of mosaic image = foreground class present in that mosaic
# test_list_set_labels = []
# for i in range(desired_num):
# set_idx = set()
# np.random.seed(i+3000)
# bg_idx = np.random.randint(0,nbg,8)
# set_idx = set(background_label[bg_idx].tolist())
# fg_idx = np.random.randint(0,nfg)
# set_idx.add(foreground_label[fg_idx].item())
# fg = np.random.randint(0,9)
# test_fore_idx.append(fg)
# test_image_list,test_label = create_mosaic_img(bg_idx,fg_idx,fg)
# test_mosaic_list_of_images.append(test_image_list)
# test_mosaic_label.append(test_label)
# test_list_set_labels.append(set_idx)
# + id="yD8U0GO4u7lc"
# data = [{"mosaic_list":mosaic_list_of_images, "mosaic_label": mosaic_label, "fore_idx":fore_idx}]
# np.save(path+"train_type4_data.npy",data)
# + id="kO5a7347u7i8"
# data = [{"mosaic_list":test_mosaic_list_of_images, "mosaic_label": test_mosaic_label, "fore_idx":test_fore_idx}]
# np.save(path+"test_type4_data.npy",data)
# + id="KxV2mSymu7gL"
# data = [{"X":x,"Y":y}]
# np.save(path+"type_4_data.npy",data)
# + [markdown] id="kQqboQsTvTrc"
# # Data loading
# + id="M-0Scwk6vdIT"
class MosaicDataset1(Dataset):
"""MosaicDataset dataset."""
def __init__(self, mosaic_list, mosaic_label,fore_idx):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.mosaic = mosaic_list
self.label = mosaic_label
self.fore_idx = fore_idx
def __len__(self):
return len(self.label)
def __getitem__(self, idx):
return self.mosaic[idx] , self.label[idx] , self.fore_idx[idx]
# + id="eLwbmDwPvdBL"
class SyntheticDataset(Dataset):
"""MosaicDataset dataset."""
def __init__(self, x, y):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.x = x
self.y = y
#self.fore_idx = fore_idx
def __len__(self):
return len(self.y)
def __getitem__(self, idx):
return self.x[idx] , self.y[idx] #, self.fore_idx[idx]
# + id="1A7jpjpMt-cu"
train_data = np.load(path+"train_type4_data.npy",allow_pickle=True)
test_data = np.load(path+"test_type4_data.npy",allow_pickle=True)
data = np.load(path+"type_4_data.npy",allow_pickle=True)
# + id="xeH1Aekrt_QU"
train_mosaic_list_of_images = train_data[0]["mosaic_list"]
train_mosaic_label = train_data[0]["mosaic_label"]
train_fore_idx = train_data[0]["fore_idx"]
test_mosaic_list_of_images = test_data[0]["mosaic_list"]
test_mosaic_label = test_data[0]["mosaic_label"]
test_fore_idx = test_data[0]["fore_idx"]
X = data[0]["X"]
Y = data[0]["Y"]
# + id="JonzP2VfvpS0"
batch = 250
tr_msd = MosaicDataset1(train_mosaic_list_of_images, train_mosaic_label, train_fore_idx)
train_loader = DataLoader( tr_msd,batch_size= batch ,shuffle=True)
# + id="9JJvOp_9v4qE"
batch = 250
tst_msd = MosaicDataset1(test_mosaic_list_of_images, test_mosaic_label, test_fore_idx)
test_loader = DataLoader( tst_msd,batch_size= batch ,shuffle=True)
# + id="eWVGP1ffv4mk"
dset = SyntheticDataset(X,Y)
dtloader = DataLoader(dset,batch_size =batch,shuffle=True )
# + id="zgF90qBIt8yN"
def calculate_loss(dataloader,model,criter):
model.eval()
r_loss = 0
with torch.no_grad():
for i, data in enumerate(dataloader, 0):
inputs, labels = data
inputs, labels = inputs.to("cuda"),labels.to("cuda")
outputs = model(inputs)
loss = criter(outputs, labels)
r_loss += loss.item()
return r_loss/i
# + [markdown] id="ilzPfrih82Bg"
# **Focus Net**
# + id="KzN3Bbs8c0fA"
class Module1(nn.Module):
def __init__(self):
super(Module1, self).__init__()
self.fc1 = nn.Linear(2, 100)
self.fc2 = nn.Linear(100, 1)
def forward(self, z):
x = torch.zeros([batch,9],dtype=torch.float64)
y = torch.zeros([batch,2], dtype=torch.float64)
x,y = x.to("cuda"),y.to("cuda")
for i in range(9):
x[:,i] = self.helper(z[:,i])[:,0]
x = F.softmax(x,dim=1) # alphas
for i in range(9):
x1 = x[:,i]
y = y + torch.mul(x1[:,None],z[:,i])
return y , x
def helper(self,x):
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
# + [markdown] id="EjrL0Zb484KO"
# **Classification Net**
# + id="w0W0oKcClFZY"
class Module2(nn.Module):
def __init__(self):
super(Module2, self).__init__()
self.fc1 = nn.Linear(2, 100)
self.fc2 = nn.Linear(100, 3)
def forward(self,y):
y = F.relu(self.fc1(y))
y = self.fc2(y)
return y
# + id="ehAfQnNwgFYX"
def calculate_attn_loss(dataloader,what,where,criter):
what.eval()
where.eval()
r_loss = 0
alphas = []
lbls = []
pred = []
fidices = []
with torch.no_grad():
for i, data in enumerate(dataloader, 0):
inputs, labels,fidx = data
lbls.append(labels)
fidices.append(fidx)
inputs = inputs.double()
inputs, labels = inputs.to("cuda"),labels.to("cuda")
avg,alpha = where(inputs)
outputs = what(avg)
_, predicted = torch.max(outputs.data, 1)
pred.append(predicted.cpu().numpy())
alphas.append(alpha.cpu().numpy())
loss = criter(outputs, labels)
r_loss += loss.item()
alphas = np.concatenate(alphas,axis=0)
pred = np.concatenate(pred,axis=0)
lbls = np.concatenate(lbls,axis=0)
fidices = np.concatenate(fidices,axis=0)
#print(alphas.shape,pred.shape,lbls.shape,fidices.shape)
analysis = analyse_data(alphas,lbls,pred,fidices)
return r_loss/i,analysis
# + id="6e9HQJMzxBhp"
def analyse_data(alphas,lbls,predicted,f_idx):
'''
analysis data is created here
'''
batch = len(predicted)
amth,alth,ftpt,ffpt,ftpf,ffpf = 0,0,0,0,0,0
for j in range (batch):
focus = np.argmax(alphas[j])
if(alphas[j][focus] >= 0.5):
amth +=1
else:
alth +=1
if(focus == f_idx[j] and predicted[j] == lbls[j]):
ftpt += 1
elif(focus != f_idx[j] and predicted[j] == lbls[j]):
ffpt +=1
elif(focus == f_idx[j] and predicted[j] != lbls[j]):
ftpf +=1
elif(focus != f_idx[j] and predicted[j] != lbls[j]):
ffpf +=1
#print(sum(predicted==lbls),ftpt+ffpt)
return [ftpt,ffpt,ftpf,ffpf,amth,alth]
# + colab={"base_uri": "https://localhost:8080/"} id="DTBDprf17TMN" outputId="03b7ad04-88f0-4e5a-b794-c8586a1fc780"
number_runs = 10
full_analysis =[]
FTPT_analysis = pd.DataFrame(columns = ["FTPT","FFPT", "FTPF","FFPF"])
every_what_epoch = 5 #to change
for n in range(number_runs):
print("--"*40)
# instantiate focus and classification Model
torch.manual_seed(n)
where = Module1().double()
torch.manual_seed(n)
what = Module2().double()
where = where.to("cuda")
what = what.to("cuda")
# instantiate optimizer
optimizer_where = optim.Adam(where.parameters(),lr =0.001)
optimizer_what = optim.Adam(what.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()
acti = []
analysis_data = []
loss_curi = []
epochs = 1000
# calculate zeroth epoch loss and FTPT values
running_loss,anlys_data = calculate_attn_loss(train_loader,what,where,criterion)
loss_curi.append(running_loss)
analysis_data.append(anlys_data)
print('epoch: [%d ] loss: %.3f' %(0,running_loss))
# training starts
for epoch in range(epochs): # loop over the dataset multiple times
ep_lossi = []
running_loss = 0.0
what.train()
where.train()
if ((epoch) % (every_what_epoch*2) ) <= every_what_epoch-1 :
print(epoch+1,"updating what_net, where_net is freezed")
print("--"*40)
elif ((epoch) % (every_what_epoch*2)) > every_what_epoch-1 :
print(epoch+1,"updating where_net, what_net is freezed")
print("--"*40)
for i, data in enumerate(train_loader, 0):
# get the inputs
inputs, labels,_ = data
inputs = inputs.double()
inputs, labels = inputs.to("cuda"),labels.to("cuda")
# zero the parameter gradients
optimizer_where.zero_grad()
optimizer_what.zero_grad()
# forward + backward + optimize
avg, alpha = where(inputs)
outputs = what(avg)
loss = criterion(outputs, labels)
# print statistics
running_loss += loss.item()
loss.backward()
if ((epoch) % (every_what_epoch*2) ) <= every_what_epoch-1 :
optimizer_what.step()
elif ( (epoch) % (every_what_epoch*2)) > every_what_epoch-1 :
optimizer_where.step()
# optimizer_where.step()
# optimizer_what.step()
running_loss,anls_data = calculate_attn_loss(train_loader,what,where,criterion)
analysis_data.append(anls_data)
print('epoch: [%d] loss: %.3f' %(epoch + 1,running_loss))
loss_curi.append(running_loss) #loss per epoch
if running_loss<=0.01:
break
print('Finished Training run ' +str(n))
analysis_data = np.array(analysis_data)
FTPT_analysis.loc[n] = analysis_data[-1,:4]/30
full_analysis.append((epoch, analysis_data))
correct = 0
total = 0
with torch.no_grad():
for data in train_loader:
images, labels,_ = data
images = images.double()
images, labels = images.to("cuda"), labels.to("cuda")
avg, alpha = where(images)
outputs = what(avg)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 3000 train images: %d %%' % ( 100 * correct / total))
# + colab={"base_uri": "https://localhost:8080/"} id="tqSMmYwp8QYT" outputId="6d744c97-25a5-47c7-a728-05cf68a01afe"
a,b= full_analysis[0]
print(a)
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="L31RVViMkYM-" outputId="74ca7f47-b191-4bb7-c419-771cbdf119a6"
cnt=1
for epoch, analysis_data in full_analysis:
analysis_data = np.array(analysis_data)
# print("="*20+"run ",cnt,"="*20)
plt.figure(figsize=(6,6))
plt.plot(np.arange(0,epoch+2,1),analysis_data[:,0],label="ftpt")
plt.plot(np.arange(0,epoch+2,1),analysis_data[:,1],label="ffpt")
plt.plot(np.arange(0,epoch+2,1),analysis_data[:,2],label="ftpf")
plt.plot(np.arange(0,epoch+2,1),analysis_data[:,3],label="ffpf")
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.title("Training trends for run "+str(cnt))
plt.savefig(path+"what_where/every5/run"+str(cnt)+".png",bbox_inches="tight")
plt.savefig(path+"what_where/every5/run"+str(cnt)+".pdf",bbox_inches="tight")
cnt+=1
# + id="_ZSZor21zD_f" colab={"base_uri": "https://localhost:8080/"} outputId="21a52fec-8583-4d01-af7f-b10dc48d5545"
np.mean(np.array(FTPT_analysis),axis=0) # [9.08933333e+01, 9.08333333e+00, 2.33333333e-02, 0.00000000e+00]
# + id="O2hM_iKJPQMt"
FTPT_analysis.to_csv(path+"what_where/FTPT_analysis_every5"+".csv",index=False)
# + colab={"base_uri": "https://localhost:8080/", "height": 363} id="1sboJVYXS7Lq" outputId="80d52562-6635-4135-d813-ab4d42074beb"
FTPT_analysis
# + id="R2Fh3DbcS7lW"
|
1_mosaic_data_attention_experiments/3_stage_wise_training/alternate_minimization/effect on interpretability/type4_without_sparse_regulariser/10runs_every5_what_where.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <h2>Creazione serie storica decessi COVID-19 confermati delle province complete dal 22 marzo al 22 maggio 2020
import pandas as pd
df = pd.read_csv('csv/decessi_covid_province.csv')
df.head()
df['data'] = pd.to_datetime(df['data'], format='%Y-%m-%d')
df['decessi'] = pd.to_numeric(df['decessi'])
df.info()
df=df.groupby('data').sum()
df.head()
# Il campo <b>decessi</b> è riportato per incremento, per il numero effettivo di decessi avvenuti in un giorno è necessario applicarvi l'operazione di differenza.
# +
import numpy as np
df_diff = df.diff()
df_diff = df_diff.dropna()
df_diff.head()
# -
ts = df_diff.decessi
ts
df_diff.to_csv('csv/decessi_covid19_8province.csv')
|
Modulo 3 - Analisi dati province complete/Creazione serie storica decessi COVID-19 confermati province complete.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Occupation
# ### Introduction:
#
# Special thanks to: https://github.com/justmarkham for sharing the dataset and materials.
#
# ### Step 1. Import the necessary libraries
import pyspark
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("occupation").getOrCreate()
spark
# ### Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user).
# ### Step 3. Assign it to a variable called users.
from pyspark import SparkFiles
url = "https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user"
spark.sparkContext.addFile(url)
users = spark.read.csv(SparkFiles.get("u.user"), header=True, inferSchema=True, sep='|')
users.show(5)
# ### Step 4. Discover what is the mean age per occupation
users.groupBy("occupation").mean().select("occupation","avg(age)").show(5)
# ### Step 5. Discover the Male ratio per occupation and sort it from the most to the least
from pyspark.sql.functions import *
from pyspark.sql.types import *
def gender_num(x):
if x == "M":
return int(1)
if x == "F":
return int(0)
udf_gender_num = udf(lambda x: gender_num(x),IntegerType())
users_df = users.withColumn("gender_num", udf_gender_num(col("gender")))
users_df.show(5)
users_df.printSchema()
users_male = users_df.filter(users_df.gender == "M").groupBy("occupation").count()
users_male = users_male.withColumnRenamed("count", "male_count")
users_male.show(5)
users_male.printSchema()
users_all = users_df.groupBy("occupation").count()
users_all = users_all.withColumnRenamed("count","occ_total")
users_all.show(5)
users_all.printSchema()
# +
# result = users_male.join(users_all, users_male["occupation"] == users_all["occupation"])
#produces duplicate column "occupation"
#produces no duplicate columns
result = users_male.join(users_all, ["occupation"])
result.show(5)
# -
result_male_ratio = result.withColumn("male_ratio",(result['male_count']/result['occ_total'])*100 )
result_male_ratio.orderBy("male_ratio", ascending=0).show(5)
# result_male_ratio.show(5)
# ### Step 6. For each occupation, calculate the minimum and maximum ages
# +
# users.groupBy("occupation").agg({"age":"min", "age":"max"}).show(5)
#performs the last agg in the dict
#from pyspark.sql.functions import *
# min & max must be already imported from pyspark.sql.functions
users.groupBy("occupation").agg(min('age'), max('age')).show(5)
# -
# ### Step 7. For each combination of occupation and gender, calculate the mean age
users.groupBy("occupation","gender").agg(mean('age')).orderBy("occupation").show(5)
# ### Step 8. For each occupation present the percentage of women and men
# create a data frame and apply count to gender
# gender_ocup = users.groupby(['occupation', 'gender']).agg({'gender': 'count'})
gender_ocup = users.groupBy("occupation","gender").agg({"gender": "count"})
gender_ocup = gender_ocup.withColumnRenamed("count(gender)", "gender_count")
gender_ocup.show(5)
# create a DataFrame and apply count for each occupation
# occup_count = users.groupby(['occupation']).agg('count')
occup_count = users.groupBy("occupation").count()
occup_count = occup_count.withColumnRenamed("count","occup_count")
occup_count.show(5)
# divide the gender_ocup per the occup_count and multiply per 100
# occup_gender = gender_ocup.div(occup_count, level = "occupation") * 100
occup_gender = gender_ocup.join(occup_count,['occupation'])
occup_gender.show(5)
occup_gender = occup_gender.withColumn("percent_presence", (occup_gender['gender_count']/occup_gender['occup_count'])*100)
occup_gender.orderBy(["occupation","gender"], ascending=1).show(5)
|
03_Grouping/Occupation/PySparkSolution.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# bestChiSq > 100 and ngoodobs > 100
import matplotlib.pyplot as plt
# %matplotlib notebook
import numpy as np
from astropy.table import Table as tbl
source = tbl.read('allsky4.tbl', format = 'ipac')
ret = plt.hist(source['bestmeanmag'], range = (12,27), bins = 50)
plt.xlabel('Mean Mag')
plt.ylabel('Counts')
# This is showing the best mean magnitude observed for all sources. There appears to be a linear trend for the counts between ~14 and ~18.5 magnitude stars. Then, the distrubtion turns into a more typical Gaussian-like shape. However, this may be a exponential trend upward that just falls off at higher magnitudes because of the telescope being used and the time it takes to observe fainter stars. The latter seems like a more probable explanation as the number of stars increases at higher magnitudes. Additionally, I am somewhat concerned about the area surrounding the 26th magnitude as this seems fainter than what could be measured, and there is a broad area in which very few observations were made. These seem to be extraneous points due to some unknown source.
#
# Below are the counts and cent
print(ret)
|
LSST/VariableStarClassification/All_sky_histogram.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Elimination with Matrices (18.06_L2)
# > Linear Algebra - An introduction to Elimination (solving systems of equations)
#
# - toc: true
# - badges: true
# - comments: true
# - author: <NAME>
# - categories: [Linear Algebra]
# # Motivation
#
# One of my goals is to understand more deeply what Neural Networks are doing. Another is to have an easier time understanding and implementing cutting edge academic papers. In order to work toward those goals, I am revisiting the Math behind Neural Networks. This time my goal is to understand intuitively every piece of the material forward and backward - rather than to pass a course on a deadline.
#
# This blog post will be my notes about Lecture 2 from the following course:
#
# <NAME>. 18.06 Linear Algebra. Spring 2010. Massachusetts Institute of Technology: MIT OpenCourseWare, https://ocw.mit.edu. License: Creative Commons BY-NC-SA.
# # Goal
#
# The goal is to solve N equations with N unknowns, just like it was with lecture 1. In the first Lecture it was about understanding how to solve them intuitively with linear combinations and matrix multiplication. In reality, that is not a scalable choice when you get to higher and higher dimensions. We need to be able to express these concepts in matrices and be more comfortable with that language and operations..
# # Matrix Form
#
# As a recap, we can express a system of equations by listing the equations. x
#
# $x+2y+z=2$
#
# $3x+8y+z=12$
#
# $4y+z=2$
#
# We can write the same thing in matrix form using the formula $Ax=b$. The matrix A is from the system of equation above.
#
# $A = \begin{bmatrix}1&2&1\\3&8&1\\0&4&1\end{bmatrix}$
#
#
# # Elimination
#
# The general idea in elimination is to isolate variables so we can solve the equation. For example, if we have 0x + 0y + 1z = 10, it is very easy to solve for z. We can then plug it into another equation in the series that has z and 1 other unknown to get another value, and so on and so forth.
# ## $E_{21}$
#
# We are going to start by eliminating the first variable in the second row. Row 2, column 1. This would leave the second row with only 2 unknowns.
#
# The way we do this is we subtract row 1 from row 2. If we substract 3 * 1 from 3, we get 0, so 3 will be the multiplier.
#
# $\begin{bmatrix}1&0&0\\-3&1&0\\0&0&1\end{bmatrix}
# \begin{bmatrix}1&2&1\\3&8&1\\0&4&1\end{bmatrix}
# =\begin{bmatrix}1&2&1\\0&2&-2\\0&4&1\end{bmatrix}$
#
# ## $E_{31}$
#
# We then move on to row 3, column 1. Lucky for us it's already 0 so we can skip this step
# ## $E_{32}$
#
# We now move on to row 3, column 2. If we can get this to 0, then we have 1 unknown in that column. That's what we want as that's easily solvable.
#
# $\begin{bmatrix}1&0&0\\0&1&0\\0&-2&1\end{bmatrix}
# \begin{bmatrix}1&2&1\\0&2&-2\\0&4&1\end{bmatrix}
# =\begin{bmatrix}1&2&1\\0&2&-2\\0&0&5\end{bmatrix}$
# ## How can this fail?
#
# A 0 cannot be in one of the pivot spots. The pivot positions are the diagonals. If that happens, elimination will fail. If you think about it, a 0 being in the pivot spot means that the left side of the equation is 0. Either the right side is also 0 and it gives you no information, or the right side is not 0 and there is no solution (ie 2 = 0 is False).
#
# Of course, there are some tricks that can be added to minimize failures. The most common of these are row exchanges. By swapping the order of the rows, you can potentially solve an equation that would have failed in the original order.
#
# For example, if I were to exchange the 2nd and 3rd rows I would multiply by the following matrix.
#
# $\begin{bmatrix}1&0&0\\0&0&1\\0&1&0\end{bmatrix}$
#
#
# # Back Substitution
#
# Let's recap the steps that were taken. We started with A and through elimination in 2 steps we ended with a new matrix.
#
# $A => \begin{bmatrix}1&2&1\\3&8&1\\0&4&1\end{bmatrix} => \begin{bmatrix}1&2&1\\0&2&-2\\0&4&1\end{bmatrix} => \begin{bmatrix}1&2&1\\0&2&-2\\0&0&5\end{bmatrix} => U$
#
#
# ## Finish the Equation
#
# You may have realized these matrices represented the left side of the equation. You may have wondered how we can modify the left side of the equation while leaving the right side alone? The answer is that we cannot. What is done on the left side must be applied to the right side. Let's do that now.
# We have done 2 transformations.
#
# 1. The first transformation was subtracting 3 of the first row from the second.
# 1. The second transformation was subracting 2 of the second row from the third.
#
# Let's do that to the the right side
#
# b => $\begin{bmatrix}2\\12\\2\end{bmatrix} => \begin{bmatrix}2\\6\\2\end{bmatrix} =>
# \begin{bmatrix}2\\6\\-10\end{bmatrix} => c$
# Let's put the left and right side of the equations together to see what it looks like.
#
# $Ux = C$
#
# $\begin{bmatrix}1&2&1\\0&2&-2\\0&0&5\end{bmatrix}\begin{bmatrix}x\\y\\z\end{bmatrix}=\begin{bmatrix}2\\6\\-10\end{bmatrix}$
# # Final Solution
# ## Intuitive Solution
# Great! Let's translate the $Ux=C$ matrix above back to our systems of equations view just to see if we can see how this transformation helps us.
#
# $x + 2y + z = 2$
#
# $2y - 2z = 6$
#
# $5z = -10$
# When we look at it here, we can solve them with some simple algebra starting from the bottom equation.
#
# $5z = -10 \;\;\;\mathbf{=>}\;\;\; z = -10/5 \;\;\;\mathbf{=>}\;\;\; z = -2$
#
# $2y - 2z = 6 \;\;\;\mathbf{=>}\;\;\; 2y - 2(-2) = 6 \;\;\;\mathbf{=>}\;\;\; 2y + 4 = 6 \;\;\;\mathbf{=>}\;\;\; 2y = 2 \;\;\;\mathbf{=>}\;\;\; y = 1$
#
# $x+2y+z=2 \;\;\;\mathbf{=>}\;\;\;x+2-2=2$$x+2y+z=2 \;\;\;\mathbf{=>}\;\;\;x=2$
# ## Matrix Solution
#
# So first we should ask if we have an intuitive solution, why bother with doing the whole thing in matrix format? Isn't it the same thing?
#
# And yes, we will be doing the same thing. The reason is scalability and ability to transfer to N equation and N unknowns. There's a limit to what can be done by hand, and matrix form allows for easier scalability.
# ### Recap
#
# We did several steps intuitively. Let's recap our elimination steps from above
#
#
# $E_{21}$ step
# $\begin{bmatrix}1&0&0\\-3&1&0\\0&0&1\end{bmatrix}
# \begin{bmatrix}1&2&1\\3&8&1\\0&4&1\end{bmatrix}
# =\begin{bmatrix}1&2&1\\0&2&-2\\0&4&1\end{bmatrix}$
#
# $E_{32}$ step
# $\begin{bmatrix}1&0&0\\0&1&0\\0&-2&1\end{bmatrix}
# \begin{bmatrix}1&2&1\\0&2&-2\\0&4&1\end{bmatrix}
# =\begin{bmatrix}1&2&1\\0&2&-2\\0&0&5\end{bmatrix}$
# ### Simplify into 1 step
#
# Great! Now let's just combine these so we only have 1 equation.
#
# $E_{21}E_{32}A=U$
# $\begin{bmatrix}1&0&0\\0&1&0\\0&-2&1\end{bmatrix}
# \begin{bmatrix}1&0&0\\-3&1&0\\0&0&1\end{bmatrix}
# \begin{bmatrix}1&2&1\\3&8&1\\0&4&1\end{bmatrix}=
# \begin{bmatrix}1&2&1\\0&2&-2\\0&0&5\end{bmatrix}
# $
#
# Now let's simplify this by multiplying and combining my $E_{21}$ and $E_{31}$ matrices together. We will call the result $E$
# $E_{21}E_{32}=E$
# $\begin{bmatrix}1&0&0\\0&1&0\\0&-2&1\end{bmatrix}
# \begin{bmatrix}1&0&0\\-3&1&0\\0&0&1\end{bmatrix} =
# \begin{bmatrix}1&0&0\\-3&1&0\\6&-2&1\end{bmatrix}$
#
# Great! Now we can use this to simplify our formula.
#
# $EA=U$
# $\begin{bmatrix}1&0&0\\-3&1&0\\6&-2&1\end{bmatrix}
# \begin{bmatrix}1&2&1\\3&8&1\\0&4&1\end{bmatrix}=
# \begin{bmatrix}1&2&1\\0&2&-2\\0&0&5\end{bmatrix}$
|
_notebooks/2020-05-10-18.06_2_EliminationWithMatrices.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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
#
# Neural Transfer Using PyTorch
# =============================
#
#
# **Author**: `<NAME> <https://alexis-jacq.github.io>`_
#
# **Edited by**: `<NAME> <https://github.com/winston6>`_
#
# Introduction
# ------------
#
# This tutorial explains how to implement the `Neural-Style algorithm <https://arxiv.org/abs/1508.06576>`__
# developed by <NAME>, <NAME> and <NAME>.
# Neural-Style, or Neural-Transfer, allows you to take an image and
# reproduce it with a new artistic style. The algorithm takes three images,
# an input image, a content-image, and a style-image, and changes the input
# to resemble the content of the content-image and the artistic style of the style-image.
#
#
# .. figure:: /_static/img/neural-style/neuralstyle.png
# :alt: content1
#
#
# Underlying Principle
# --------------------
#
# The principle is simple: we define two distances, one for the content
# ($D_C$) and one for the style ($D_S$). $D_C$ measures how different the content
# is between two images while $D_S$ measures how different the style is
# between two images. Then, we take a third image, the input, and
# transform it to minimize both its content-distance with the
# content-image and its style-distance with the style-image. Now we can
# import the necessary packages and begin the neural transfer.
#
# Importing Packages and Selecting a Device
# -----------------------------------------
# Below is a list of the packages needed to implement the neural transfer.
#
# - ``torch``, ``torch.nn``, ``numpy`` (indispensables packages for
# neural networks with PyTorch)
# - ``torch.optim`` (efficient gradient descents)
# - ``PIL``, ``PIL.Image``, ``matplotlib.pyplot`` (load and display
# images)
# - ``torchvision.transforms`` (transform PIL images into tensors)
# - ``torchvision.models`` (train or load pre-trained models)
# - ``copy`` (to deep copy the models; system package)
#
#
# +
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
import copy
# -
# Next, we need to choose which device to run the network on and import the
# content and style images. Running the neural transfer algorithm on large
# images takes longer and will go much faster when running on a GPU. We can
# use ``torch.cuda.is_available()`` to detect if there is a GPU available.
# Next, we set the ``torch.device`` for use throughout the tutorial. Also the ``.to(device)``
# method is used to move tensors or modules to a desired device.
#
#
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Loading the Images
# ------------------
#
# Now we will import the style and content images. The original PIL images have values between 0 and 255, but when
# transformed into torch tensors, their values are converted to be between
# 0 and 1. The images also need to be resized to have the same dimensions.
# An important detail to note is that neural networks from the
# torch library are trained with tensor values ranging from 0 to 1. If you
# try to feed the networks with 0 to 255 tensor images, then the activated
# feature maps will be unable sense the intended content and style.
# However, pre-trained networks from the Caffe library are trained with 0
# to 255 tensor images.
#
#
# .. Note::
# Here are links to download the images required to run the tutorial:
# `picasso.jpg <https://pytorch.org/tutorials/_static/img/neural-style/picasso.jpg>`__ and
# `dancing.jpg <https://pytorch.org/tutorials/_static/img/neural-style/dancing.jpg>`__.
# Download these two images and add them to a directory
# with name ``images`` in your current working directory.
#
#
# +
# desired size of the output image
imsize = 512 if torch.cuda.is_available() else 128 # use small size if no gpu
loader = transforms.Compose([
transforms.Resize(imsize), # scale imported image
transforms.ToTensor()]) # transform it into a torch tensor
def image_loader(image_name):
image = Image.open(image_name)
# fake batch dimension required to fit network's input dimensions
image = loader(image).unsqueeze(0)
return image.to(device, torch.float)
style_img = image_loader("./data/images/neural-style/picasso.jpg")
content_img = image_loader("./data/images/neural-style/dancing.jpg")
assert style_img.size() == content_img.size(), \
"we need to import style and content images of the same size"
# -
# Now, let's create a function that displays an image by reconverting a
# # copy of it to PIL format and displaying the copy using
# ``plt.imshow``. We will try displaying the content and style images
# to ensure they were imported correctly.
#
#
# +
unloader = transforms.ToPILImage() # reconvert into PIL image
plt.ion()
def imshow(tensor, title=None):
image = tensor.cpu().clone() # we clone the tensor to not do changes on it
image = image.squeeze(0) # remove the fake batch dimension
image = unloader(image)
plt.imshow(image)
if title is not None:
plt.title(title)
plt.pause(0.001) # pause a bit so that plots are updated
plt.figure()
imshow(style_img, title='Style Image')
plt.figure()
imshow(content_img, title='Content Image')
# -
# Loss Functions
# --------------
# Content Loss
# ~~~~~~~~~~~~
#
# The content loss is a function that represents a weighted version of the
# content distance for an individual layer. The function takes the feature
# maps $F_{XL}$ of a layer $L$ in a network processing input $X$ and returns the
# weighted content distance $w_{CL}.D_C^L(X,C)$ between the image $X$ and the
# content image $C$. The feature maps of the content image($F_{CL}$) must be
# known by the function in order to calculate the content distance. We
# implement this function as a torch module with a constructor that takes
# $F_{CL}$ as an input. The distance $\|F_{XL} - F_{CL}\|^2$ is the mean square error
# between the two sets of feature maps, and can be computed using ``nn.MSELoss``.
#
# We will add this content loss module directly after the convolution
# layer(s) that are being used to compute the content distance. This way
# each time the network is fed an input image the content losses will be
# computed at the desired layers and because of auto grad, all the
# gradients will be computed. Now, in order to make the content loss layer
# transparent we must define a ``forward`` method that computes the content
# loss and then returns the layer’s input. The computed loss is saved as a
# parameter of the module.
#
#
#
class ContentLoss(nn.Module):
def __init__(self, target,):
super(ContentLoss, self).__init__()
# we 'detach' the target content from the tree used
# to dynamically compute the gradient: this is a stated value,
# not a variable. Otherwise the forward method of the criterion
# will throw an error.
self.target = target.detach()
def forward(self, input):
self.loss = F.mse_loss(input, self.target)
return input
# .. Note::
# **Important detail**: although this module is named ``ContentLoss``, it
# is not a true PyTorch Loss function. If you want to define your content
# loss as a PyTorch Loss function, you have to create a PyTorch autograd function
# to recompute/implement the gradient manually in the ``backward``
# method.
#
#
# Style Loss
# ~~~~~~~~~~
#
# The style loss module is implemented similarly to the content loss
# module. It will act as a transparent layer in a
# network that computes the style loss of that layer. In order to
# calculate the style loss, we need to compute the gram matrix $G_{XL}$. A gram
# matrix is the result of multiplying a given matrix by its transposed
# matrix. In this application the given matrix is a reshaped version of
# the feature maps $F_{XL}$ of a layer $L$. $F_{XL}$ is reshaped to form $\hat{F}_{XL}$, a $K$\ x\ $N$
# matrix, where $K$ is the number of feature maps at layer $L$ and $N$ is the
# length of any vectorized feature map $F_{XL}^k$. For example, the first line
# of $\hat{F}_{XL}$ corresponds to the first vectorized feature map $F_{XL}^1$.
#
# Finally, the gram matrix must be normalized by dividing each element by
# the total number of elements in the matrix. This normalization is to
# counteract the fact that $\hat{F}_{XL}$ matrices with a large $N$ dimension yield
# larger values in the Gram matrix. These larger values will cause the
# first layers (before pooling layers) to have a larger impact during the
# gradient descent. Style features tend to be in the deeper layers of the
# network so this normalization step is crucial.
#
#
#
def gram_matrix(input):
a, b, c, d = input.size() # a=batch size(=1)
# b=number of feature maps
# (c,d)=dimensions of a f. map (N=c*d)
features = input.view(a * b, c * d) # resise F_XL into \hat F_XL
G = torch.mm(features, features.t()) # compute the gram product
# we 'normalize' the values of the gram matrix
# by dividing by the number of element in each feature maps.
return G.div(a * b * c * d)
# Now the style loss module looks almost exactly like the content loss
# module. The style distance is also computed using the mean square
# error between $G_{XL}$ and $G_{SL}$.
#
#
#
class StyleLoss(nn.Module):
def __init__(self, target_feature):
super(StyleLoss, self).__init__()
self.target = gram_matrix(target_feature).detach()
def forward(self, input):
G = gram_matrix(input)
self.loss = F.mse_loss(G, self.target)
return input
# Importing the Model
# -------------------
#
# Now we need to import a pre-trained neural network. We will use a 19
# layer VGG network like the one used in the paper.
#
# PyTorch’s implementation of VGG is a module divided into two child
# ``Sequential`` modules: ``features`` (containing convolution and pooling layers),
# and ``classifier`` (containing fully connected layers). We will use the
# ``features`` module because we need the output of the individual
# convolution layers to measure content and style loss. Some layers have
# different behavior during training than evaluation, so we must set the
# network to evaluation mode using ``.eval()``.
#
#
#
cnn = models.vgg19(pretrained=True).features.to(device).eval()
# Additionally, VGG networks are trained on images with each channel
# normalized by mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225].
# We will use them to normalize the image before sending it into the network.
#
#
#
# +
cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)
# create a module to normalize input image so we can easily put it in a
# nn.Sequential
class Normalization(nn.Module):
def __init__(self, mean, std):
super(Normalization, self).__init__()
# .view the mean and std to make them [C x 1 x 1] so that they can
# directly work with image Tensor of shape [B x C x H x W].
# B is batch size. C is number of channels. H is height and W is width.
self.mean = torch.tensor(mean).view(-1, 1, 1)
self.std = torch.tensor(std).view(-1, 1, 1)
def forward(self, img):
# normalize img
return (img - self.mean) / self.std
# -
# A ``Sequential`` module contains an ordered list of child modules. For
# instance, ``vgg19.features`` contains a sequence (Conv2d, ReLU, MaxPool2d,
# Conv2d, ReLU…) aligned in the right order of depth. We need to add our
# content loss and style loss layers immediately after the convolution
# layer they are detecting. To do this we must create a new ``Sequential``
# module that has content loss and style loss modules correctly inserted.
#
#
#
# +
# desired depth layers to compute style/content losses :
content_layers_default = ['conv_4']
style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']
def get_style_model_and_losses(cnn, normalization_mean, normalization_std,
style_img, content_img,
content_layers=content_layers_default,
style_layers=style_layers_default):
cnn = copy.deepcopy(cnn)
# normalization module
normalization = Normalization(normalization_mean, normalization_std).to(device)
# just in order to have an iterable access to or list of content/syle
# losses
content_losses = []
style_losses = []
# assuming that cnn is a nn.Sequential, so we make a new nn.Sequential
# to put in modules that are supposed to be activated sequentially
model = nn.Sequential(normalization)
i = 0 # increment every time we see a conv
for layer in cnn.children():
if isinstance(layer, nn.Conv2d):
i += 1
name = 'conv_{}'.format(i)
elif isinstance(layer, nn.ReLU):
name = 'relu_{}'.format(i)
# The in-place version doesn't play very nicely with the ContentLoss
# and StyleLoss we insert below. So we replace with out-of-place
# ones here.
layer = nn.ReLU(inplace=False)
elif isinstance(layer, nn.MaxPool2d):
name = 'pool_{}'.format(i)
elif isinstance(layer, nn.BatchNorm2d):
name = 'bn_{}'.format(i)
else:
raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))
model.add_module(name, layer)
if name in content_layers:
# add content loss:
target = model(content_img).detach()
content_loss = ContentLoss(target)
model.add_module("content_loss_{}".format(i), content_loss)
content_losses.append(content_loss)
if name in style_layers:
# add style loss:
target_feature = model(style_img).detach()
style_loss = StyleLoss(target_feature)
model.add_module("style_loss_{}".format(i), style_loss)
style_losses.append(style_loss)
# now we trim off the layers after the last content and style losses
for i in range(len(model) - 1, -1, -1):
if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):
break
model = model[:(i + 1)]
return model, style_losses, content_losses
# -
# Next, we select the input image. You can use a copy of the content image
# or white noise.
#
#
#
# +
input_img = content_img.clone()
# if you want to use white noise instead uncomment the below line:
# input_img = torch.randn(content_img.data.size(), device=device)
# add the original input image to the figure:
plt.figure()
imshow(input_img, title='Input Image')
# -
# Gradient Descent
# ----------------
#
# As <NAME>, the author of the algorithm, suggested `here <https://discuss.pytorch.org/t/pytorch-tutorial-for-neural-transfert-of-artistic-style/336/20?u=alexis-jacq>`__, we will use
# L-BFGS algorithm to run our gradient descent. Unlike training a network,
# we want to train the input image in order to minimise the content/style
# losses. We will create a PyTorch L-BFGS optimizer ``optim.LBFGS`` and pass
# our image to it as the tensor to optimize.
#
#
#
def get_input_optimizer(input_img):
# this line to show that input is a parameter that requires a gradient
optimizer = optim.LBFGS([input_img.requires_grad_()])
return optimizer
# Finally, we must define a function that performs the neural transfer. For
# each iteration of the networks, it is fed an updated input and computes
# new losses. We will run the ``backward`` methods of each loss module to
# dynamicaly compute their gradients. The optimizer requires a “closure”
# function, which reevaluates the modul and returns the loss.
#
# We still have one final constraint to address. The network may try to
# optimize the input with values that exceed the 0 to 1 tensor range for
# the image. We can address this by correcting the input values to be
# between 0 to 1 each time the network is run.
#
#
#
def run_style_transfer(cnn, normalization_mean, normalization_std,
content_img, style_img, input_img, num_steps=300,
style_weight=1000000, content_weight=1):
"""Run the style transfer."""
print('Building the style transfer model..')
model, style_losses, content_losses = get_style_model_and_losses(cnn,
normalization_mean, normalization_std, style_img, content_img)
optimizer = get_input_optimizer(input_img)
print('Optimizing..')
run = [0]
while run[0] <= num_steps:
def closure():
# correct the values of updated input image
input_img.data.clamp_(0, 1)
optimizer.zero_grad()
model(input_img)
style_score = 0
content_score = 0
for sl in style_losses:
style_score += sl.loss
for cl in content_losses:
content_score += cl.loss
style_score *= style_weight
content_score *= content_weight
loss = style_score + content_score
loss.backward()
run[0] += 1
if run[0] % 50 == 0:
print("run {}:".format(run))
print('Style Loss : {:4f} Content Loss: {:4f}'.format(
style_score.item(), content_score.item()))
print()
return style_score + content_score
optimizer.step(closure)
# a last correction...
input_img.data.clamp_(0, 1)
return input_img
# Finally, we can run the algorithm.
#
#
#
# +
output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,
content_img, style_img, input_img)
plt.figure()
imshow(output, title='Output Image')
# sphinx_gallery_thumbnail_number = 4
plt.ioff()
plt.show()
|
deepml/pytorch-tutorial01/neural_style_tutorial.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Introducing the Keras Sequential API
#
# **Learning Objectives**
# 1. Learn how to use feature columns in a Keras model
# 1. Build a DNN model using the Keras Sequential API
# 1. Learn how to train a model with Keras
# 1. Learn how to save/load, and deploy a Keras model on GCP
# 1. Learn how to deploy and make predictions with at Keras model
#
# ## Introduction
#
# The [Keras sequential API](https://keras.io/models/sequential/) allows you to create Tensorflow models layer-by-layer. This is useful for building most kinds of machine learning models but it does not allow you to create models that share layers, re-use layers or have multiple inputs or outputs.
#
# In this lab, we'll see how to build a simple deep neural network model using the keras sequential api and feature columns. Once we have trained our model, we will deploy it using AI Platform and see how to call our model for online prediciton.
#
# Each learning objective will correspond to a __#TODO__ in this student lab notebook -- try to complete this notebook first and then review the [solution notebook](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/3_keras_sequential_api.ipynb)
#
# !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Please ignore any incompatibility warnings and errors and re-run the cell to view the installed tensorflow version.
#
# Start by importing the necessary libraries for this lab.
# +
import datetime
import os
import shutil
import numpy as np
import pandas as pd
import tensorflow as tf
from matplotlib import pyplot as plt
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, DenseFeatures
from tensorflow.keras.callbacks import TensorBoard
print(tf.__version__)
# %matplotlib inline
# -
# ## Load raw data
#
# We will use the taxifare dataset, using the CSV files that we created in the first notebook of this sequence. Those files have been saved into `../data`.
# !ls -l ../data/*.csv
# !head ../data/taxi*.csv
# ## Use tf.data to read the CSV files
#
# We wrote these functions for reading data from the csv files above in the [previous notebook](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/deepdive2/introduction_to_tensorflow/labs/2_dataset_api.ipynb).
# +
CSV_COLUMNS = [
'fare_amount',
'pickup_datetime',
'pickup_longitude',
'pickup_latitude',
'dropoff_longitude',
'dropoff_latitude',
'passenger_count',
'key'
]
LABEL_COLUMN = 'fare_amount'
DEFAULTS = [[0.0], ['na'], [0.0], [0.0], [0.0], [0.0], [0.0], ['na']]
UNWANTED_COLS = ['pickup_datetime', 'key']
def features_and_labels(row_data):
label = row_data.pop(LABEL_COLUMN)
features = row_data
for unwanted_col in UNWANTED_COLS:
features.pop(unwanted_col)
return features, label
def create_dataset(pattern, batch_size=1, mode='eval'):
dataset = tf.data.experimental.make_csv_dataset(
pattern, batch_size, CSV_COLUMNS, DEFAULTS)
dataset = dataset.map(features_and_labels)
if mode == 'train':
dataset = dataset.shuffle(buffer_size=1000).repeat()
# take advantage of multi-threading; 1=AUTOTUNE
dataset = dataset.prefetch(1)
return dataset
# -
# ## Build a simple keras DNN model
#
# We will use feature columns to connect our raw data to our keras DNN model. Feature columns make it easy to perform common types of feature engineering on your raw data. For example, you can one-hot encode categorical data, create feature crosses, embeddings and more. We'll cover these in more detail later in the course, but if you want to a sneak peak browse the official TensorFlow [feature columns guide](https://www.tensorflow.org/api_docs/python/tf/feature_column).
#
# In our case we won't do any feature engineering. However, we still need to create a list of feature columns to specify the numeric values which will be passed on to our model. To do this, we use `tf.feature_column.numeric_column()`
#
# We use a python dictionary comprehension to create the feature columns for our model, which is just an elegant alternative to a for loop.
# **Lab Task #1:** Create a feature column dictionary that we will use when building our deep neural network below. The keys should be the element of the `INPUT_COLS` list, while the values should be numeric feature columns.
# +
INPUT_COLS = [
'pickup_longitude',
'pickup_latitude',
'dropoff_longitude',
'dropoff_latitude',
'passenger_count',
]
# Create input layer of feature columns
# TODO 1
feature_columns = {
colname: tf.feature_column.numeric_column(colname)
for colname in INPUT_COLS
}
# -
# Next, we create the DNN model. The Sequential model is a linear stack of layers and when building a model using the Sequential API, you configure each layer of the model in turn. Once all the layers have been added, you compile the model.
# **Lab Task #2a:** Create a deep neural network using Keras's Sequential API. In the cell below, use the `tf.keras.layers` library to create all the layers for your deep neural network.
# Build a keras DNN model using Sequential API
# TODO 2a
model = Sequential([
DenseFeatures(feature_columns=feature_columns.values()),
Dense(units=32, activation="relu", name="h1"),
Dense(units=8, activation="relu", name="h2"),
Dense(units=1, activation="linear", name="output")
])
# Next, to prepare the model for training, you must configure the learning process. This is done using the compile method. The compile method takes three arguments:
#
# * An optimizer. This could be the string identifier of an existing optimizer (such as `rmsprop` or `adagrad`), or an instance of the [Optimizer class](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/optimizers).
# * A loss function. This is the objective that the model will try to minimize. It can be the string identifier of an existing loss function from the [Losses class](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/losses) (such as categorical_crossentropy or mse), or it can be a custom objective function.
# * A list of metrics. For any machine learning problem you will want a set of metrics to evaluate your model. A metric could be the string identifier of an existing metric or a custom metric function.
#
# We will add an additional custom metric called `rmse` to our list of metrics which will return the root mean square error.
# **Lab Task #2b:** Compile the model you created above. Create a custom loss function called `rmse` which computes the root mean squared error between `y_true` and `y_pred`. Pass this function to the model as an evaluation metric.
# +
# TODO 2b
# Create a custom evalution metric
def rmse(y_true, y_pred):
return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true)))
# Compile the keras model
model.compile(optimizer="adam", loss="mse", metrics=[rmse, "mse"])
# -
# ## Train the model
#
# To train your model, Keras provides three functions that can be used:
# 1. `.fit()` for training a model for a fixed number of epochs (iterations on a dataset).
# 2. `.fit_generator()` for training a model on data yielded batch-by-batch by a generator
# 3. `.train_on_batch()` runs a single gradient update on a single batch of data.
#
# The `.fit()` function works well for small datasets which can fit entirely in memory. However, for large datasets (or if you need to manipulate the training data on the fly via data augmentation, etc) you will need to use `.fit_generator()` instead. The `.train_on_batch()` method is for more fine-grained control over training and accepts only a single batch of data.
#
# The taxifare dataset we sampled is small enough to fit in memory, so can we could use `.fit` to train our model. Our `create_dataset` function above generates batches of training examples, so we could also use `.fit_generator`. In fact, when calling `.fit` the method inspects the data, and if it's a generator (as our dataset is) it will invoke automatically `.fit_generator` for training.
#
# We start by setting up some parameters for our training job and create the data generators for the training and validation data.
#
# We refer you the the blog post [ML Design Pattern #3: Virtual Epochs](https://medium.com/google-cloud/ml-design-pattern-3-virtual-epochs-f842296de730) for further details on why express the training in terms of `NUM_TRAIN_EXAMPLES` and `NUM_EVALS` and why, in this training code, the number of epochs is really equal to the number of evaluations we perform.
# +
TRAIN_BATCH_SIZE = 1000
NUM_TRAIN_EXAMPLES = 10000 * 5 # training dataset will repeat, wrap around
NUM_EVALS = 50 # how many times to evaluate
NUM_EVAL_EXAMPLES = 10000 # enough to get a reasonable sample
trainds = create_dataset(
pattern='../data/taxi-train*',
batch_size=TRAIN_BATCH_SIZE,
mode='train')
evalds = create_dataset(
pattern='../data/taxi-valid*',
batch_size=1000,
mode='eval').take(NUM_EVAL_EXAMPLES//1000)
# -
# There are various arguments you can set when calling the [.fit method](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/Model#fit). Here `x` specifies the input data which in our case is a `tf.data` dataset returning a tuple of (inputs, targets). The `steps_per_epoch` parameter is used to mark the end of training for a single epoch. Here we are training for NUM_EVALS epochs. Lastly, for the `callback` argument we specify a Tensorboard callback so we can inspect Tensorboard after training.
# **Lab Task #3:** In the cell below, you will train your model. First, define the `steps_per_epoch` then train your model using `.fit()`, saving the model training output to a variable called `history`.
# +
# %time
# TODO 3
steps_per_epoch = NUM_TRAIN_EXAMPLES // (TRAIN_BATCH_SIZE * NUM_EVALS)
LOGDIR = "./taxi_trained"
# Train the sequential model
history = model.fit(x=trainds,
steps_per_epoch=steps_per_epoch,
epochs=NUM_EVALS,
validation_data=evalds,
callbacks=[TensorBoard(LOGDIR)])
# -
# ### High-level model evaluation
#
# Once we've run data through the model, we can call `.summary()` on the model to get a high-level summary of our network. We can also plot the training and evaluation curves for the metrics we computed above.
model.summary()
# Running `.fit` (or `.fit_generator`) returns a History object which collects all the events recorded during training. Similar to Tensorboard, we can plot the training and validation curves for the model loss and rmse by accessing these elements of the History object.
# +
RMSE_COLS = ['rmse', 'val_rmse']
pd.DataFrame(history.history)[RMSE_COLS].plot()
# +
LOSS_COLS = ['loss', 'val_loss']
pd.DataFrame(history.history)[LOSS_COLS].plot()
# -
# # Making predictions with our model
#
# To make predictions with our trained model, we can call the [predict method](https://www.tensorflow.org/api_docs/python/tf/keras/Model#predict), passing to it a dictionary of values. The `steps` parameter determines the total number of steps before declaring the prediction round finished. Here since we have just one example, we set `steps=1` (setting `steps=None` would also work). Note, however, that if x is a `tf.data` dataset or a dataset iterator, and steps is set to None, predict will run until the input dataset is exhausted.
model.predict(x={"pickup_longitude": tf.convert_to_tensor([-73.982683]),
"pickup_latitude": tf.convert_to_tensor([40.742104]),
"dropoff_longitude": tf.convert_to_tensor([-73.983766]),
"dropoff_latitude": tf.convert_to_tensor([40.755174]),
"passenger_count": tf.convert_to_tensor([3.0])},
steps=1)
# # Export and deploy our model
#
# Of course, making individual predictions is not realistic, because we can't expect client code to have a model object in memory. For others to use our trained model, we'll have to export our model to a file, and expect client code to instantiate the model from that exported file.
#
# We'll export the model to a TensorFlow SavedModel format. Once we have a model in this format, we have lots of ways to "serve" the model, from a web application, from JavaScript, from mobile applications, etc.
# **Lab Task #4:** Use `tf.saved_model.save` to export the trained model to a Tensorflow SavedModel format. Reference the [documentation for `tf.saved_model.save`](https://www.tensorflow.org/api_docs/python/tf/saved_model/save) as you fill in the code for the cell below.
#
# Next, print the signature of your saved model using the SavedModel Command Line Interface command `saved_model_cli`. You can read more about the command line interface and the `show` and `run` commands it supports in the [documentation here](https://www.tensorflow.org/guide/saved_model#overview_of_commands).
# TODO 4a
OUTPUT_DIR = "./export/savedmodel"
shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
# The join() method takes all items in an iterable and joins them into one string.
EXPORT_PATH = os.path.join(OUTPUT_DIR,
datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
tf.saved_model.save(model, EXPORT_PATH) # with default serving function
# Export the model to a TensorFlow SavedModel format
# TODO 4b
# !saved_model_cli show \
# --tag_set serve \
# --signature_def serving_default \
# --dir {EXPORT_PATH}
# !find {EXPORT_PATH}
os.environ['EXPORT_PATH'] = EXPORT_PATH
# ### Deploy our model to AI Platform
#
# Finally, we will deploy our trained model to AI Platform and see how we can make online predicitons.
# **Lab Task #5a:** Complete the code in the cell below to deploy your trained model to AI Platform using the `gcloud ai-platform versions create` command. Have a look at [the documentation for how to create model version with gcloud](https://cloud.google.com/sdk/gcloud/reference/ai-platform/versions/create).
# + language="bash"
# gcloud config set compute/region us-east1
#
# -
# **Below cell will take around 10 minutes to complete.**
# + language="bash"
#
# # TODO 5a
#
# PROJECT= # TODO: Change this to your PROJECT
# BUCKET=${PROJECT}
# REGION=us-east1
# MODEL_NAME=taxifare
# VERSION_NAME=dnn
#
# # Create GCS bucket if it doesn't exist already...
# exists=$(gsutil ls -d | grep -w gs://${BUCKET}/)
#
# if [ -n "$exists" ]; then
# echo -e "Bucket exists, let's not recreate it."
# else
# echo "Creating a new GCS bucket."
# gsutil mb -l ${REGION} gs://${BUCKET}
# echo "Here are your current buckets:"
# gsutil ls
# fi
#
# if [[ $(gcloud ai-platform models list --format='value(name)' --region=$REGION | grep $MODEL_NAME) ]]; then
# echo "$MODEL_NAME already exists"
# else
# echo "Creating $MODEL_NAME"
# gcloud ai-platform models create --region=$REGION $MODEL_NAME
# fi
#
# if [[ $(gcloud ai-platform versions list --model $MODEL_NAME --region=$REGION --format='value(name)' | grep $VERSION_NAME) ]]; then
# echo "Deleting already existing $MODEL_NAME:$VERSION_NAME ... "
# echo yes | gcloud ai-platform versions delete --model=$MODEL_NAME $VERSION_NAME --region=$REGION
# echo "Please run this cell again if you don't see a Creating message ... "
# sleep 2
# fi
#
# echo "Creating $MODEL_NAME:$VERSION_NAME"
# gcloud ai-platform versions create --model=$MODEL_NAME $VERSION_NAME \
# --framework=tensorflow --python-version=3.7 --runtime-version=2.1 \
# --origin=$EXPORT_PATH --staging-bucket=gs://$BUCKET --region=$REGION
# -
# %%writefile input.json
{"pickup_longitude": -73.982683, "pickup_latitude": 40.742104,"dropoff_longitude": -73.983766,"dropoff_latitude": 40.755174,"passenger_count": 3.0}
# **Lab Task #5b:** Complete the code in the cell below to call prediction on your deployed model for the example you just created in the `input.json` file above.
# The `gcloud ai-platform predict` sends a prediction request to AI Platform for the given instances.
# TODO 5b
# !gcloud ai-platform predict --model taxifare --json-instances input.json --version dnn --region us-east1
# Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
|
preparing-gcp-ml-engineer/introduction-to-tensorflow/3_keras_sequential_api.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
# ---
# +
from arcgis.gis import GIS
from arcgis.mapping import WebMap, WebScene
from arcgis.widgets import FeatureSet, Layer, MapView
from arcgis.features import summarize_data, FeatureLayer, manage_data
from IPython.display import display
import pandas as pd
import json
import requests
'''
main fields:
------------
Client ID
- 3hEOA0ytHFO2XH3w
Client Secret:
- <KEY>
Temporary Token
- <KEY>
Service Details:
----------------
Geocoding and Place Search
- https://utility.arcgis.com/usrsvcs/appservices/z2N0LuaQIPTYndoo/rest/services/World/GeocodeServer/findAddressCandidates
TODO
HANDLE UPDATE on feature layers
'''
from data.geographic import gisConn, gisUser, gisPass
gis = GIS(gisConn, gisUser, gisPass)
# +
def get_token():
params = {
'client_id': "3hEOA0ytHFO2XH3w",
'client_secret': "<KEY>",
'grant_type': "client_credentials"
}
request = requests.get('https://www.arcgis.com/sharing/oauth2/token',
params=params)
response = request.json()
token = response["access_token"]
return token
#token = get_token()
#token
# +
def token(token, url):
'''
- https://utility.arcgis.com/usrsvcs/appservices/PaxuIDwgHm34KeUH/rest/services/World/GeoenrichmentServer/GeoEnrichment/enrich
'''
params = {
'f': 'json',
'token': token,
'studyAreas': '[{"geometry":{"x":-117.1956,"y":34.0572}}]'
}
url = 'https://utility.arcgis.com/usrsvcs/appservices/PaxuIDwgHm34KeUH/rest/services/World/GeoenrichmentServer/GeoEnrichment/enrich'
data = requests.post(url, params=params)
return data.json(), data
dataJson, data = token(get_token, 'https://utility.arcgis.com/usrsvcs/appservices/PaxuIDwgHm34KeUH/rest/services/World/GeoenrichmentServer/GeoEnrichment/enrich')
data
# +
def searchGis(gis, key = 'world'):
items = gis.content.search(key)
for item in items:
display(item)
def getFeatureLayers(item):
'''
stockTest = company performance
cityToCompanyTest = company to city comparison
'''
layers = item.layers
fset = layers[0].query()
# display(fset.df)
return fset
search_result = gis.content.search('city')
display(search_result)
item = search_result[1]
cityToCompany_fset = getFeatureLayers(item)
search_result = gis.content.search('stock')
display(search_result)
item = search_result[3]
companyStat_fset = getFeatureLayers(item)
# -
|
arcgis_service.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="b_5p1xg77ilg" outputId="8fd65e50-f800-40f7-d812-71336035c7be"
from google.colab import drive
drive.mount('/content/drive/')
# + [markdown] id="25hfAPB9DCEu"
# # Exploring Datasets
# + id="5eN_iWveU7P2"
import pandas as pd
import numpy as np
# + id="wUdHyrEvVEW2"
# + colab={"base_uri": "https://localhost:8080/"} id="OFONGPW-VLao" outputId="3e2dd795-e127-496e-8e6f-7df1849139fe"
# %%time
train = pd.read_csv('/content/drive/MyDrive/Amazon Datasets/train.csv',escapechar = "\\" ,quoting = 3)
# + id="QNreCpIjWG2k"
test = pd.read_csv('/content/drive/MyDrive/Amazon Datasets/test.csv',escapechar = "\\" ,quoting = 3)
# + id="34mKWqV7WWd9"
train.head()
# + id="ciNakH16WWhI"
train.BROWSE_NODE_ID.value_counts()
# + id="5RSZW4pQXLwE"
train.isnull().sum()
# + id="U9WU6XdEXOJS"
test.isnull().sum()
# + id="-F0m5swFWWkm"
train[train['TITLE'].isnull() &train['DESCRIPTION'].isnull()& train['BULLET_POINTS'].isnull()].shape
# + id="eE-819WaWWnQ"
print(train.shape)
train = train[~(train['TITLE'].isnull() &train['DESCRIPTION'].isnull()& train['BULLET_POINTS'].isnull())]
print(train.shape)
# + id="PlWOIkZcWWqA"
train.head(10)
# + id="ev34H8kg2EZL"
train[train['BULLET_POINTS'].isnull()]
# + id="wSDKli_tWWsS"
train['DESCRIPTION'][6]
# + id="yY3sd6tHrkYH"
train['TITLE'][8]
# + id="80tHv7dlyAYq"
train['BULLET_POINTS'][8]
# + [markdown] id="EfV4QQEXBzeX"
# # Text summarizer
# + id="gL3682-OYV7i"
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize,sent_tokenize
# + id="cK3TUqQLYV-b"
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
# !pip install -q wordcloud
import wordcloud
# + id="e85YzKXNYWBE"
text = train['DESCRIPTION'][6]
# + id="Y_BqADtLYWDK"
##Tokenizing the text
stopWords=stopwords.words('english')
words=word_tokenize(text)
# + id="uxJAUrKaYWFj"
##creating freq table for each word
freqTable = dict()
for word in words:
word=word.lower()
if word in stopWords:
continue
if word in freqTable:
freqTable[word]+=1
else:
freqTable[word]=1
##creating dict to keep score of each sentence
sentenceValue = dict()
sentences = sent_tokenize(text)
for sentence in sentences:
for word,freq in freqTable.items():
if word in sentence.lower():
if sentence in sentenceValue:
sentenceValue[sentence]+=freq
else:
sentenceValue[sentence]=freq
# + id="Qqz1enS_xb1o"
sentences
# + id="UIORwTOrYWJ9"
freqTable,sentenceValue
# + id="l-lviMLqmGVn"
sumvalues=0
for sentence in sentenceValue:
sumvalues+=sentenceValue[sentence]
# + id="IWZ3mVW7qIPu"
##Avg value of sentence from og text
avg = int(sumvalues/len(sentenceValue)-1)
# + id="1f9VRhPxqxWy"
avg
# + id="qBzOipY1qKOY"
##storing sentence in summary
summary=''
for sentence in sentences:
if (sentence in sentenceValue) and (sentenceValue[sentence]>(1.2*avg)):
summary=summary +" " +sentence
# + id="pTRmHJI_qYrU"
train['TITLE'][8]+','+summary
# + [markdown] id="CQJwMUzuBdjR"
# # Final Packing into Functions
#
# + id="w6IR13VH2wMd"
def text_summarizer(text):
##Tokenizing the text
stopWords=stopwords.words('english')
words=word_tokenize(text)
##creating freq table for each word
freqTable = dict()
for word in words:
word=word.lower()
if word in stopWords:
continue
if word in freqTable:
freqTable[word]+=1
else:
freqTable[word]=1
##creating dict to keep score of each sentence
sentenceValue = dict()
sentences = sent_tokenize(text)
if len(sentences)==1:
return sentences[0]
else:
for sentence in sentences:
for word,freq in freqTable.items():
if word in sentence.lower():
if sentence in sentenceValue:
sentenceValue[sentence]+=freq
else:
sentenceValue[sentence]=freq
sumvalues=0
for sentence in sentenceValue:
sumvalues+=sentenceValue[sentence]
##Avg value of sentence from og text
avg = int(sumvalues/len(sentenceValue))
##storing sentence in summary
summary=''
for sentence in sentences:
if (sentence in sentenceValue) and (sentenceValue[sentence]>(1.2*avg)):
summary=summary +" " +sentence
return summary
# + id="zJxu7aqprX5-"
def bullet_points_generator(data):
data1= data[data['BULLET_POINTS'].isnull()]
data1_index = list(data1.index)
for index in data1_index:
if (data1['DESCRIPTION'].isnull()[index]==False) and (data1['TITLE'].isnull()[index]==False) :#if none are null value
data1.at[index,'BULLET_POINTS']=[data1['TITLE'].loc[index]+','+ text_summarizer(data1['DESCRIPTION'].loc[index])]
elif (data1['DESCRIPTION'].isnull()[index]==False) and (data1['TITLE'].isnull()[index]==True):#if TITLE is null
data1.at[index,'BULLET_POINTS']=[text_summarizer(data1['DESCRIPTION'].loc[index])]
elif (data1['DESCRIPTION'].isnull()[index]==True) and (data1['TITLE'].isnull()[index]==False):#if DESCRIPTION is null
data1.at[index,'BULLET_POINTS']= [data1['TITLE'].loc[index]]
else:
continue
##assuming that in test data all three won't be null at the same time and removed such rows from train data
data.drop(data1_index,axis=0,inplace=True)
final_data = pd.concat([data,data1])
final_data = final_data.reset_index().iloc[:,1:]
return final_data
# + id="F6QsHSoSvpKj"
train
# + [markdown] id="RYWdh5pmCiMj"
# ### Getting Final Dataaset - Beware of the below cell, as this took 2:30 hr to execute
# + id="el0cDoVKtQzs"
#train_final = bullet_points_generator(train)
# + id="jdNP5sS2YZjr"
#train_final
# + id="uPNp3f8a6kAO"
# + id="SoKKTYebYZlv"
#train_final.to_csv('final_train.csv',index=False)
# + id="66R2jkAx7HSa"
# + id="Rsc3Wi35F1qr"
#test_final = bullet_points_generator(test)
# + id="mzvtAHQCGtBZ"
#test_final.to_csv('final_test.csv',index=False)
# + id="jCLdR2ByHKvb"
#test_final
# + id="h-ZYXCclHMP9"
test.isnull().sum()
# + id="EDGodG9UHP1j"
#test_final.isnull().sum()
# + [markdown] id="IIunS6R8pcgy"
# # Upto POS tagger pipeline
# + id="Jj-TPE0LHbEg"
import nltk
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
from nltk.corpus import stopwords
stop = stopwords.words('english')
from nltk import word_tokenize, pos_tag, pos_tag_sents
from sklearn.pipeline import Pipeline
pd.options.display.max_colwidth = 10000000
pd.options.mode.chained_assignment = None
# + id="ArtjVtN8J2xp"
from string import punctuation
Sp_C = list(punctuation)
ord = ['FW','NN','NNP','NNS',"JJ",'JJr','JJS']
# + id="HIFjTZayJ25i"
train.drop(['TITLE', 'DESCRIPTION','BRAND'], axis=1,inplace=True)
train.dropna(inplace=True)
# + id="BoO_LtLWJ26J"
class DataframeFunctionTransformer():
def __init__(self, func):
self.func = func
def transform(self, input_df, **transform_params):
return self.func(input_df)
def fit(self, X, y=None, **fit_params):
return self
# + id="yznJhBR2J265"
VSize = []
# + id="eSI1OrpSJ27p"
def upeer_dataframe(input_df):
input_df["BULLET_POINTS"] = input_df["BULLET_POINTS"].map(lambda t: t.lower())
return input_df
def Stopword_dataframe(input_df):
input_df["BULLET_POINTS"] = input_df["BULLET_POINTS"].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))
return input_df
def Clean(input_df):
input_df["BULLET_POINTS"] = input_df["BULLET_POINTS"].apply(lambda x: x.encode('ascii', 'ignore').decode('ascii'))
input_df["BULLET_POINTS"] = input_df["BULLET_POINTS"].replace(r'http\S+', '', regex=True).replace(r'www\S+', '', regex=True)
return input_df
def PosTag_dataframe(input_df):
for row in input_df.iterrows():
print(row[0])
# print(row[1]['BULLET_POINTS'])
texts = row[1]['BULLET_POINTS'].split(',')
# print(texts)
tagged_texts = pos_tag_sents(map(word_tokenize, texts))
req = []
for i in tagged_texts:
for j in i:
if(j[0] not in Sp_C and j[1] in ord):
if(j[0] not in req):
req.append(j[0])
if(j[0] not in VSize):
VSize.append(j[0])
sent = ""
Max_Len = 512;
for i in range(len(req)):
if(i<len(req)-1 and req[i].isdigit() and req[i+1].isdigit()):
sent += req[i] + "."
else:
sent += req[i] +' '
if(i>Max_Len):
break;
input_df['BULLET_POINTS'].loc[row[0]]= sent
return input_df
# + id="u4B19cNFJ28Y"
# The pipeline
pipeline = Pipeline([
("lowercase", DataframeFunctionTransformer(upeer_dataframe)),
("Stopword",DataframeFunctionTransformer(Stopword_dataframe)),
("Clean",DataframeFunctionTransformer(Clean)),
("Pos_Tag",DataframeFunctionTransformer(PosTag_dataframe))
])
# + id="syxKTzh-J29E"
# apply the pipeline to the input dataframe
pipeline.fit_transform(train.loc[0:10000])
# + [markdown] id="Ioj1Ay6wpldS"
# # Models
# + id="GqnhQ7loJ292"
from tensorflow.keras.layers import Embedding
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import one_hot
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dense
# + id="iFIq1j0OJ2-h"
Courpus = list(train['BULLET_POINTS'].loc[0:10000])
Vcab = len(VSize)
Vcab
# + id="9KEwrA1TJ2_P"
train[0:23387]
# + id="gwXv_ehqJ3AB"
Y = list(train['BROWSE_NODE_ID'].loc[0:10000])
print("MAX = " ,max(Y))
print("MIN = " ,min(Y))
# + id="3yEFz_Z0J3Av"
One_Hot = [one_hot(words,Vcab)for words in Courpus]
# + id="Q5sUypcsJ3Bd"
One_Hot
# + id="nXmOF9ubJ3CJ"
sent_length = 512
Padded = pad_sequences(One_Hot,padding='pre',maxlen=sent_length)
# + id="s9sibGgsJ3C1"
import numpy as np
X_final=np.array(Padded)
y_final=np.array(Y)
X_final.shape,y_final.shape
# + id="fSW-1yeEJ3De"
from sklearn.svm import SVC,SVR
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.tree import DecisionTreeClassifier,DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor,RandomForestClassifier,ExtraTreesRegressor,ExtraTreesClassifier,VotingRegressor,VotingClassifier,AdaBoostRegressor,AdaBoostClassifier
from xgboost import XGBClassifier,XGBRegressor
# + id="TuZPXPiGJ3EG"
std_scaler = StandardScaler()
##model1_pipeline = Pipeline([('scaler',std_scaler),('svc',SVC())])
svr=SVR()
svc=SVC()
# decision = DecisionTreeRegressor()
# random_forest = RandomForestRegressor(n_estimators=200)
# extra_trees = ExtraTreesRegressor(n_estimators=200)
# adaboost = AdaBoostRegressor(n_estimators=100)
# xg= XGBRegressor()
decision = DecisionTreeClassifier()
random_forest = RandomForestClassifier(n_estimators=200)
extra_trees = ExtraTreesClassifier(n_estimators=200)
adaboost = AdaBoostClassifier(n_estimators=100)
xg= XGBClassifier()
# + id="azj_3YDNJ3Et"
# + id="Vk0Z4pG8J3Gb"
#test_final.shape
# + id="XpiV0IdGl22W"
X_final
# + id="x4tWNXgJr1Bf"
train
# + [markdown] id="SzFRMMUIqXfo"
# # validation set
# + id="np_Hyy9eqaGP"
X_vali,y_vali= train.loc[10001:11000],train['BROWSE_NODE_ID'].loc[10001:11000]
# + id="uc5uetFWztJ6"
len(y_vali)
# + id="IaMiJwxhtsvL"
y_vali = list(y_vali)
# + id="0riNRfo3uJZN"
pipeline.fit_transform(X_vali)
# + id="j5_kQ-q8uJ-t"
Courpus = list(train['BULLET_POINTS'].loc[10001:11000])
Vcab = len(VSize)
One_Hot = [one_hot(words,Vcab)for words in Courpus]
sent_length = 512
Padded = pad_sequences(One_Hot,padding='pre',maxlen=sent_length)
X_vali_final=np.array(Padded)
X_vali_final.shape
# + id="Xi5JKBBCuKBO"
#predictions = model1_pipeline.predict(X_vali_final)
# + id="wKHeOH2PuKEj"
#len(predictions),len(y_vali)
# + id="sxNmaAnLuKGQ"
#min(y_vali),max(y_vali)
# + id="lU_mrB_8zOWI"
#m#in(predictions),max(predictions)
# + id="PGfRDx6QdqPk"
#new_test = test_final.drop(['PRODUCT_ID','TITLE','DESCRIPTION','BRAND'],axis=1)
# + id="eapDa2bEkIyv"
#Ptest = new_test.loc[0:10000]
# + id="7jJU-ySvdqSS"
#pipeline.fit_transform(Ptest)
# + id="Iy8-B6TedqVY"
# Courpus = list(Ptest['BULLET_POINTS'])
# One_Hot = [one_hot(words,Vcab)for words in Courpus]
# sent_length = 512
# Padded = pad_sequences(One_Hot,padding='pre',maxlen=sent_length)
# test_pred = np.array(Padded)
# + id="sLqBwlGOdqXp"
from sklearn.metrics import accuracy_score,mean_squared_error,r2_score
for model in [extra_trees,adaboost,xg]:
model.fit(X_final,y_final)
prediction = model.predict(X_vali_final)
prediction=np.ceil(prediction)
# if model==svc:
# print('Model= ','svc')
# print('accuracy= ', accuracy_score(y_vali,prediction))
# elif model==decision:
# print('Model= ','Decision Tree Regressor')
# print('accuracy= ', accuracy_score(y_vali,prediction))
# elif model==random_forest:
# print('Model= ','Random Forest Regressor')
# print('accuracy= ', accuracy_score(y_vali,prediction))
if model==extra_trees:
print('Model= ','Extra Tree Regressor')
print('accuracy= ', accuracy_score(y_vali,prediction))
elif model==adaboost:
print('Model= ','Adaboost Regressor')
print('accuracy= ', accuracy_score(y_vali,prediction))
else:
print('Model= ','XG boost Regressor')
print('accuracy= ', accuracy_score(y_vali,prediction))
# + id="6AlIaxYkn_0f"
#predictions = np.floor(predictions)
# + id="rwdGt4-YoBfm"
# + id="G722r_BkdqZ0"
# + id="EwPJYVPylIeo"
# + id="FrLlBPHklZU-"
# + [markdown] id="2Z9Mz1PBp7Lx"
# # Models
# + id="YB1hOeC5p8Ew"
import pandas as pd
import numpy as np
# + id="2drlC3sJqHdK"
df= pd.read_csv('cluster18.csv')
# + id="TRkp-7gcqHiM" colab={"base_uri": "https://localhost:8080/", "height": 203} outputId="e022f767-d89c-43bf-ea14-05862f2635cf"
df.head()
# + id="OJ7X3TEgqHkC" colab={"base_uri": "https://localhost:8080/"} outputId="352d975d-2f46-424b-fbe7-396ea5bd26f8"
for row in df.iterrows():
print(row[1][2])
print('*********************************')
# + [markdown] id="hPJROVAU7sMs"
# ## TFIDF
# + id="o1U8UqSxqHr5"
from sklearn.feature_extraction.text import TfidfVectorizer
# + id="IWV2mtTgqHsj"
sentences = []
for i in range(df.shape[0]):
sentences.append(df.iloc[i]['BULLET_POINTS'])
# + id="_Y7dOml7qHtb" colab={"base_uri": "https://localhost:8080/"} outputId="8a006d24-bdb1-445b-f140-4e4c0253c579"
sentences
# + id="imiRUY2qqHuK"
vectorizer = TfidfVectorizer()
sentences_vectorized = vectorizer.fit_transform(sentences)
# + id="fCBZlKQRqHu7" colab={"base_uri": "https://localhost:8080/"} outputId="bf9eac65-e329-4004-8180-c7195503a016"
sentences_vectorized.toarray()
# + [markdown] id="8mj9i1ie7nsI"
# ## Word2vec
# + id="VeLdq5otqHvp"
from gensim.models import word2vec
# + id="isrCRxa8qHwX"
model = word2vec.Word2Vec(sentences)
# + id="CdypWC5sqHx6" colab={"base_uri": "https://localhost:8080/"} outputId="c4710d35-a8d1-4850-9332-441bcce364bc"
model.wv.vocab.keys()
# + id="pFnLUWTAqHym"
for i, sentence in enumerate(sentences):
tokenized=[]
for word in sentence.split(' '):
if word=='':
continue
tokenized.append(word)
sentences[i] = tokenized
# + colab={"base_uri": "https://localhost:8080/"} id="mVQZ93h6x74A" outputId="160b0146-e1d3-49ee-a1db-ee2ce9e5701c"
sentences
# + id="9Ly5XXEw0reU"
model = word2vec.Word2Vec(sentences,window=10,max_vocab_size=100,iter=100)
# + colab={"base_uri": "https://localhost:8080/"} id="-W4e76EH0vb7" outputId="f90139fb-e5b6-4c0d-dd08-59ac764adb2e"
model.wv.vocab
# + colab={"base_uri": "https://localhost:8080/"} id="Ivhd4v2H0vj3" outputId="c43b0a0f-65af-47bb-c2cb-30271f3acdc1"
model.wv['j7']
# + id="j5FzP-il0voM"
# + [markdown] id="OLhHaNBY7xGu"
# ## DOC2VEC
# + colab={"base_uri": "https://localhost:8080/"} id="hlUrPWgw7xcK" outputId="8fe7b6d7-dfea-4d6f-b2ad-5482ad079be9"
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
tagged_data = [TaggedDocument(d, [i]) for i, d in enumerate(sentences)]
tagged_data
# + colab={"base_uri": "https://localhost:8080/"} id="Hk2jObky8f6o" outputId="1cd8882b-aff0-4646-e6ab-f51678f1a88b"
model = Doc2Vec(tagged_data, vector_size = 20, window = 2, min_count = 1,, epochs = 100)
'''
vector_size = Dimensionality of the feature vectors.
window = The maximum distance between the current and predicted word within a sentence.
min_count = Ignores all words with total frequency lower than this.
alpha = The initial learning rate.
'''
## Print model vocabulary
model.wv.vocab
# + colab={"base_uri": "https://localhost:8080/"} id="XoojSVoD9aD0" outputId="7b0f7158-e6fc-407d-d89b-db5157db8f06"
len(model.wv.vocab)
# + colab={"base_uri": "https://localhost:8080/"} id="3oQX7zcd8iLR" outputId="44b95667-54af-4e68-ee31-442b26f967e7"
list(model.docvecs[12])
# + colab={"base_uri": "https://localhost:8080/"} id="XP1x20CJafma" outputId="a6482195-37e2-406f-8769-7e79358fffe5"
list(model.docvecs[12])
# + [markdown] id="UYY9BtPEaf_T"
# # Applying doc2vec on train dataset
# + id="ZhZxiEpa83Rq"
import pandas as pd
import numpy as np
# + id="82lO7S8A83UG"
def reading_data(name):
df = pd.read_csv(name)
return df
# + id="REV8bW5-83We"
train1 = reading_data('/content/drive/MyDrive/Amazon Challenge/Train_Clusters/1.csv')
test1 = reading_data('/content/drive/MyDrive/Amazon Challenge/Test_Clusters/1.csv')
# + id="5P9DOrDN8iN2"
train1 = train1.iloc[:,2:]
test1 = test1.iloc[:,1:]
# + colab={"base_uri": "https://localhost:8080/"} id="a2e6W6Aqan_J" outputId="9fdc00b6-b45d-46d1-bd47-38375ef5d24b"
train1.shape,test1.shape
# + colab={"base_uri": "https://localhost:8080/"} id="djSBu4C_aoF1" outputId="64864d54-b399-49b3-aaed-4a8507f36b0a"
train1.BROWSE_NODE_ID.value_counts()
# + colab={"base_uri": "https://localhost:8080/"} id="7M4mPh5gs4Z9" outputId="e70d06b8-1f65-41dd-8db9-567622d37ee0"
from google.colab import drive
drive.mount('/content/drive')
# + colab={"base_uri": "https://localhost:8080/", "height": 203} id="_G7vsxMfaoOQ" outputId="4f09db50-d6e6-4277-e544-5d380cc1251a"
train1.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 203} id="NY_1VreqaoTA" outputId="79c99a86-9f0a-4b96-b1bb-ba4cc5e19b49"
test1.head()
# + id="pv55P4Z18iQV"
def df_tokenizer(df):
sentences = []
for i in range(df.shape[0]):
sentences.append(df.iloc[i]['BULLET_POINTS'])
for i, sentence in enumerate(sentences):
tokenized=[]
for word in sentence.split(' '):
if word=='':
continue
tokenized.append(word)
sentences[i] = tokenized
return sentences
# + id="KlETt7ME8iSo"
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
# + colab={"base_uri": "https://localhost:8080/"} id="3yByw5p6hwGz" outputId="af5090be-85b2-45a1-b37c-254ff60a8949"
Doc2Vec()
# + id="_TgoybjAa2CJ"
def df_doc2vec(df,s):
tagged_data = [TaggedDocument(d, [i]) for i, d in enumerate(s)]
model = Doc2Vec(tagged_data, vector_size = 100, window = 2, min_count = 1, epochs = 10)
'''
vector_size = Dimensionality of the feature vectors.
window = The maximum distance between the current and predicted word within a sentence.
min_count = Ignores all words with total frequency lower than this.
alpha = The initial learning rate.
'''
word_embedding_size= model.wv.vector_size
vector_list = []
for i in range(df.shape[0]):
vector_list.append(list(model.docvecs[i]))
print('The word embedding vector size is {}'.format(word_embedding_size))
return vector_list
# + id="pnz9mpYIa2Et"
sentence_train1= df_tokenizer(train1)
# + colab={"base_uri": "https://localhost:8080/"} id="UCZjjYyRa2G4" outputId="684bdec5-6dd4-4bdb-eb23-c41c11153c73"
final_vector_train1 = df_doc2vec(train1,sentence_train1)
# + id="3Cuyp-X5a2JB"
y_train = np.array(train1.BROWSE_NODE_ID)
# + colab={"base_uri": "https://localhost:8080/"} id="KBHWQ0hwdD4S" outputId="c67c8605-db45-411e-9620-9c365b49ae0b"
sentence_test1 = df_tokenizer(test1)
final_vector_test1 = df_doc2vec(test1,sentence_test1) ##We want to find prediction for these test vectors
# + id="Z-YrJoFsdD9I"
from sklearn.decomposition import PCA
# + id="JjOYImChdD_6"
final_vector_train1=np.array(final_vector_train1)
final_vector_test1=np.array(final_vector_test1)
# + id="By1GHt1fdECJ"
pca = PCA(n_components=2)
# + id="UeGg7bfMdEDn"
from sklearn.model_selection import train_test_split
# + id="CierqBOxntyb"
X_train, X_test, y_train, y_test = train_test_split(final_vector_train1,y_train,test_size=0.25)
# + id="JVsHau6wnt3g"
from sklearn.svm import SVC,SVR
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.tree import DecisionTreeClassifier,DecisionTreeRegressor
from sklearn.linear_model import LogisticRegression,SGDClassifier
from sklearn.ensemble import RandomForestRegressor,RandomForestClassifier,ExtraTreesRegressor,ExtraTreesClassifier,VotingRegressor,VotingClassifier,AdaBoostRegressor,AdaBoostClassifier
from xgboost import XGBClassifier,XGBRegressor
from sklearn.metrics import mean_squared_error,r2_score,accuracy_score
# + id="ykzbqrMMnt58"
def Fitting_models_with_evaluation(x_train,y_train,x_test):
model = LogisticRegression(n_jobs=-1,max_iter=1)
model.fit(x_train,y_train)
predictions = model.predict(x_test)
return predictions
# + id="GZoBqCutjOas"
test_finally =pd.DataFrame({'PRODUCT_ID':[],'BROWSE_NODE_ID':[]})
# + id="V7AEEaGdjlvr"
# + colab={"base_uri": "https://localhost:8080/", "height": 387} id="AdvtvGAOnt7m" outputId="fbedc6b1-0453-499d-d7ef-eac00fca6880"
for i in range(50):
train = reading_data('/content/drive/MyDrive/Amazon Challenge/Train_Clusters/{}.csv'.format(i))
test = reading_data('/content/drive/MyDrive/Amazon Challenge/Test_Clusters/{}.csv'.format(i))
train = train.iloc[:,2:]
test = test.iloc[:,1:]
product_id = list(test['PRODUCT_ID'])
sentence_train = df_tokenizer(train)
final_vector_train = df_doc2vec(train,sentence_train)
y_train = np.array(train.BROWSE_NODE_ID)
sentence_test = df_tokenizer(test)
final_vector_test = df_doc2vec(test,sentence_test1)
final_vector_train =np.array(final_vector_train)
final_vector_test =np.array(final_vector_test)
prediction = Fitting_models_with_evaluation(final_vector_train,y_train,final_vector_test)
df=pd.DataFrame({'PRODUCT_ID':product_id,'BROWSE_NODE_ID':prediction})
test_finally.append(df)
# + id="y5NNqNrvmwWb"
# + id="IAUAJms6d6I1"
# + id="Fayk7Ai-d6LH"
# + id="8yr_DwyBl54K"
# + id="bTgjmFiql-Ab"
# + id="xllqhk7Kl6hQ"
# + colab={"base_uri": "https://localhost:8080/"} id="zJ_7TPXdnt9h" outputId="3515f6b9-1f5a-4ea7-c442-a123b607f8f8"
X_train.shape,y_train.shape
# + id="08t4wwg84p82"
#temp = pca.fit_transform(X_train)
# + colab={"base_uri": "https://localhost:8080/"} id="JzwO_vyc5EgG" outputId="b8250f4b-682b-482b-d04d-6b7943629d61"
#temp.shape
# + id="TzsPLv1Ua2Lh"
svr=SVR()
svr.fit(X=temp,y= y_train)
pred = svr.predict(X_test)
print(mean_squared_error(y_test,pred))
# + colab={"base_uri": "https://localhost:8080/"} id="oER7WzK2tRWp" outputId="853da8b3-0955-490e-d7e8-77b0d460e8d1"
decision =DecisionTreeRegressor()
decision.fit(temp,y_train)
# + id="1_YJ5yVpJhCF"
# + id="JGZiEsUxJV3L"
pred = decision.predict(pca.fit_transform(X_test))
# + colab={"base_uri": "https://localhost:8080/"} id="_Y8aFL89JbSI" outputId="cecf8adf-5d1f-48fe-c4de-e1a95d09bd49"
print(mean_squared_error(y_test,np.ceil(pred)))
# + id="9KiOe6OeJntc"
rf = RandomForestClassifier(n_estimators=100)
rf.fit(X_train,y_train)
pred=rf.predict(X_test)
# + id="2xJPuLqhKA4q"
accuracy_score(y_test,pred)
# + colab={"base_uri": "https://localhost:8080/"} id="99nlqBmtKLF7" outputId="fc60a074-0665-4084-a6b5-969986c85c1e"
logit = LogisticRegression(n_jobs=-1,max_iter=5)
logit.fit(X_train,y_train)
pred=logit.predict(X_test)
accuracy_score(y_test,pred)
# + colab={"base_uri": "https://localhost:8080/"} id="zi2vTJwicZkR" outputId="e7eaf85f-ee57-4cbd-982c-e5163e911352"
# logit = SGDClassifier()
# logit.fit(temp,y_train)
# pred=logit.predict(pca.fit_transform(X_test))
# accuracy_score(y_test,pred)
# + colab={"base_uri": "https://localhost:8080/"} id="BWpApJuCeOh-" outputId="36111873-ecd7-48a4-c88a-08092acacce9"
logit.predict(final_vector_test1)
# + colab={"base_uri": "https://localhost:8080/"} id="ynhJ5EdHZGh4" outputId="d8e4cccd-d7a3-49e5-d6be-8673aa28d1fd"
# from keras.models import Sequential
# from keras.layers import Dense
# from keras.layers import Flatten
# from keras.layers.embeddings import Embedding
# # define problem
# vocab_size = 100
# max_length = 2
# # define the model
# model = Sequential()
# model.add(Embedding(vocab_size, 8, input_length=max_length))
# model.add(Flatten())
# model.add(Dense(1, activation='sigmoid'))
# # compile the model
# model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# # summarize the model
# print(model.summary())
# + colab={"base_uri": "https://localhost:8080/"} id="7gVvaDtqbVkc" outputId="47efc3f4-0d72-47f4-f546-af83ea463b18"
model.fit(temp,y_train)
# + colab={"base_uri": "https://localhost:8080/"} id="QOccHLShc89K" outputId="f395f64a-a899-4b9c-a894-55db50b8216c"
print(model.summary())
# + id="IFkIUAaedNHr"
|
Amazon_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
# ---
# + id="QUKJvStgL4b2"
# Importing the libraries here
import pandas as pd
import numpy as np
import ast
import json
from operator import add
from operator import truediv
import re
# import swifter
from tqdm import tqdm
# -
#data with TECH removed or non master removed and tech removed
# summary = pd.read_csv("BERT_Pred_189_FULL_with_eng.csv")
# summary = pd.read_csv("BERT_Pred_189_FULL_without_MASTER.csv")
summary = pd.read_csv("Bert_Preds_EXP_Summary_ENG_only.csv")
# summary = pd.read_csv("BERT_Pred_500_without_MASTER_ENG+TECH_ROW_WISE.csv")
summary.head()
summary.columns = ['id','summaries','exact_matched_patt_contextual','BERT_Tags']
# +
dataa = summary[['id','summaries','exact_matched_patt_contextual','BERT_Tags']]
# dataa = summary[['ID','summaries','exact_matched_patt_contextual','string_matched']]
# -
summary=dataa
# + id="urN31hx3L4b6"
summary = summary.sort_values(by=['id'], ascending=False)
summary.reset_index(inplace = True, drop = True)
# -
col_name_op = "BERT_Tags"
# col_name_op = "string_matched"
# +
# Pass the matched technology column that we got
def convert_data_format(df,column_name):
for i in range(0, len(df)):
if df[column_name][i][0] == '[':
res = ast.literal_eval(df[column_name][i])
df[column_name][i] = res
else:
x = []
x.insert(0, df[column_name][i])
df[column_name][i] = x
return df
df_cm = summary
# + id="HmN4Ivz3L4b8"
df_cm = convert_data_format(df_cm, col_name_op)
# -
df_cm = convert_data_format(df_cm, "exact_matched_patt_contextual")
df_cm[col_name_op][12]
df_cm["exact_matched_patt_contextual"][12]
# +
count_context_technologies = []
for i in range(0, len(df_cm)):
count_context_technologies.extend(df_cm["exact_matched_patt_contextual"][i])
d = list(set(count_context_technologies))
len(d)
# + [markdown] id="nB5FwA4kL4b9"
# # Converting into dataformat to compare two strings
# + id="royjvg14L4b9"
# TP: present in both sheet i==j
# TN: not in both (insignificant)
# FP: in extracted sheet but not in manual tagging i!=j
# FN: in manual tagging and is not in extracted tagging j
# + id="PK5FRNxTL4b_"
tp = []
tn = []
fp = []
fn = []
# + id="W-XM1LmCL4b_"
TP = TN = FP = FN = 0
# TP + FP calculation
# op_string = exact_matched_patt
# , manual_tagged_string = Actual/Actual(NER)
df_cm.head()
# + id="nJisBsXOL4b_"
df_cm["exact_matched_patt_contextual"] = df_cm["exact_matched_patt_contextual"].fillna('[]')
# reading
tech = pd.read_csv("/Users/mohitbagaria/Downloads/spacy_string_match/Eng_pydictionary_2.csv")
# tech = pd.read_csv("Tech_pydictionary_2.csv")
tech.columns = ["index", "title"]
tech.drop(columns = ["index"], axis =1 , inplace = True)
tech.reset_index(inplace = True, drop = True)
# -
tech.head()
tech_list = tech["title"].tolist()
tech_list = list(set(tech_list))
len(tech_list)
for i in range(0, len(tech_list)):
tech_list[i] = tech_list[i].lower()
# +
# tech_list
# -
df_cm['Eng_Label']=df_cm["exact_matched_patt_contextual"].copy()
# +
tech_tag_list = []
def get_tech_tagged_data(manually_tagged, tech_list):
keep=[]
for word in manually_tagged:
if word in tech_list:
keep.append(word)
return keep
# -
df_cm.head(20)
# df_cm['Tech_Label'] = df_cm.apply(lambda x: get_tech_tagged_data(x["MANUAL_TAG"], tech_list), axis = 1)
df_cm['Eng_Label'] = df_cm.apply(lambda x: get_tech_tagged_data(x["Eng_Label"], tech_list), axis = 1)
df_cm.head(20)
# +
# df_cm.to_csv("technology_dataset_with_taggging.csv", index= False)
# df_cm.to_csv("non_technology_dataset_with_taggging.csv", index= False)
# -
list_tech_dataset = []
# fill with
for i in range(0, len(df_cm)):
list_tech_dataset.extend(df_cm["Eng_Label"][i])
len(list_tech_dataset)
set_tech = set(list_tech_dataset)
len(set_tech)
for i in range(0, len(df_cm)):
l = df_cm[col_name_op][i]
df_cm[col_name_op][i] = [0 if element == '0' else element for element in l]
for i in range(0, len(df_cm)):
words = df_cm[col_name_op][i]
stopwords = [0]
for word in list(words):
if word in stopwords:
words.remove(word)
def Diff(li1, li2): #FP entries
return list(set(li2)-set(li1))
def Same(lis1,lis2): #TP entries
return list(set(lis1).intersection(lis2))
def Common(lis1,lis2):
return list(set(lis1)-(set(lis2)))
# list of technologies which are not in extracted list but are in tagged list i.e. FN entries
df_cm['FP_entries_eng'] = df_cm.apply(lambda x: Diff(x["Eng_Label"], x[col_name_op]), axis = 1)
# list of technologies which are in extracted list and are in tagged list i.e. TP entries
df_cm['TP_entries_eng'] = df_cm.apply(lambda x: Same(x["Eng_Label"], x[col_name_op]), axis = 1)
# list of technologies which are NOT extracted list and are in tagged list i.e. FN entries
df_cm['FN_entries_eng'] = df_cm.apply(lambda x: Common(x["Eng_Label"], x[col_name_op]), axis = 1)
df_cm.head(15)
# +
# df_cm.to_csv("bert_eng_accuracy_M1_with_entries.csv", index = False)
# + id="iktQD7-SL4cA"
def get_TP(df,manual_tagged_string,op_string):
for ind in df.index:
TP = FP = 0
for i in range(0, len(df[op_string][ind])):
if df[op_string][ind][i] in df[manual_tagged_string][ind]:
TP = TP + 1
else:
pass
tp.append(TP)
return tp
# -
fp_entry =[]
# fn_entry = []
# + id="5zJ2Qy8pL4cA"
# import numpy as np
# list_1 = ["a", "b", "c", "d", "e"]
# list_2 = ["a", "f", "c", "m"]
# # yields the elements in `list_2` that are NOT in `list_1`
# main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`
def get_FP(df,manual_tagged_string, op_string):
for ind in df.index:
main_list = np.setdiff1d(df[op_string][ind],df[manual_tagged_string][ind])
fp.append(len(main_list))
fp_entry.append(main_list)
return fp, fp_entry
# + id="BMn9F9K2L4cA"
# ORIGINAL
# def get_FN(df,manual_tagged_string, op_string):
# for ind in df.index:
# main_list = np.setdiff1d(df[manual_tagged_string][ind], df[op_string][ind])
# fn.append(len(main_list))
# return fn
# -
def get_FN(df,manual_tagged_string, op_string):
for ind in df.index:
main_list = np.setdiff1d(df[manual_tagged_string][ind], df[op_string][ind])
if df[manual_tagged_string][ind]=='[]':
fn.append(0)
else:
fn.append(len(main_list))
return fn
# entry like Empty|list of technology output
# +
# def get_FN(df,manual_tagged_string, op_string):
# for ind in df.index:
# main_list = np.setdiff1d(df[manual_tagged_string][ind], df[op_string][ind])
# if (manual_tagged_string[ind] == "[]"or manual_tagged_string[ind] == ""):
# fn.append(0)
# else:
# fn.append(len(main_list))
# return fn
# + id="jq8qjL0lL4cA"
# function call
tp = get_TP(df_cm, "Eng_Label", col_name_op)
fp, fp_entry_names = get_FP(df_cm, "Eng_Label", col_name_op)
fn = get_FN(df_cm, "Eng_Label", col_name_op)
# tp = get_TP(df_cm, "Tech_Label", col_name_op)
# fp, fp_entry_names = get_FP(df_cm, "Tech_Label", col_name_op)
# fn = get_FN(df_cm, "Tech_Label", col_name_op)
# tp = get_TP(df_cm, "Technology", col_name_op)
# fp = get_FP(df_cm, "Technology", col_name_op)
# fn = get_FN(df_cm, "Technology", col_name_op)
# +
# tp
# + colab={"base_uri": "https://localhost:8080/"} id="pK2mL9yOL4cB" outputId="020334f1-19f7-4300-d4e6-12a3476dcf1f"
print(len(tp), len(fp), len(fn))
# -
len(fp_entry_names)
type(fp_entry_names)
dict_fp = {}
for i in range(0, len(fp_entry_names)):
fp_entry_names[i] = fp_entry_names[i].tolist()
dict_fp[i] = fp_entry_names[i]
# +
# dict_fp
# +
# for i in range(0, len(fn_entry_names)):
# # fn_entry_names[i] = fn_entry_names[i].tolist()
# dict_fn[i] = fn_entry_names[i]
# +
# dict_fn
# +
# len(dict_fp)
# +
# df_fp = pd.DataFrame(dict_fp.items(), columns=['index', 'FP_entries_string'])
# df_fn = pd.DataFrame(dict_fp.items(), columns=['index', 'FN_entries_combined'])
# +
# len(df_fp)
# +
# df_fp_fn = pd.concat([df_fp, df_cm], axis = 1)
# +
# df_fp_fn.head()
# +
# df_fp_fn.to_csv("FP_combined.csv", index = False)
# + colab={"base_uri": "https://localhost:8080/", "height": 419} id="mJJ4g_rxL4cB" outputId="77b2e10f-c14c-40de-c8fb-0727ba08fca5"
# creating a dataframe
df_matrix = pd.DataFrame(list(zip(tp, fp, fn)),
columns =['TP', 'FP', "FN"])
df_matrix.head(-1)
# + id="v2EqX-TlL4cB"
def get_precision(tp,fp):
if tp+fp ==0:
precision = 0
else:
precision = tp/(tp+fp)
return precision
# + id="QZySAZqbL4cB"
def get_recall(tp,fn):
if tp+fn ==0:
recall = 0
else:
recall = tp/(tp+fn)
return recall
# + id="GvUg2Wf-L4cC"
def get_f_score(precision, recall):
if precision+recall == 0:
f_score = 0
else:
f_score = 2*(precision*recall)/(precision+recall)
return f_score
# + id="lZ75jArPL4cC"
df_matrix['Precision'] = df_matrix.apply(lambda x: get_precision(x["TP"], x["FP"]), axis = 1)
# + id="gI_MseILL4cC"
df_matrix["Recall"] = df_matrix.apply(lambda x: get_recall(x["TP"], x["FN"]), axis = 1)
# + id="TvnAn8oNL4cC"
df_matrix["f_score"] = df_matrix.apply(lambda x: get_f_score(x["Precision"], x["Recall"]), axis = 1)
# + colab={"base_uri": "https://localhost:8080/", "height": 204} id="3woo4j7CL4cC" outputId="a23454ec-d9b1-4620-e995-ddc312348831"
df_matrix.head()
# + id="wdpYNTxBL4cD"
# df_matrix.to_csv("Train_Data/Accuracy_Data/Dataset_to_run_on_all/Output/Accuracy_Sheet_ner_en_large_flair_100_tagged.csv", index = False)
# df_matrix.to_csv("Train_Data/Accuracy_Data/Dataset_to_run_on_all/Output/Accuracy_Sheet_spacy_adding_more_tags.csv", index = False)
# df_matrix.to_csv("Train_Data/Accuracy_Data/Dataset_to_run_on_all/Output/Accuracy_Sheet_String_Match_non_context.csv", index = False)
# df_matrix.to_csv("189_BERT_tags_SPACY_TEST_DATA_M1_12_Jun_21.csv", index = False)
# df_matrix.to_csv("Train_Data/Accuracy_Data/Dataset_to_run_on_all/Output/Accuracy_Sheet_lg__moreTAGS_tagged_100_more_ENTS.csv", index = False)
# df_matrix.to_csv("Train_Data/Accuracy_Data/Dataset_to_run_on_all/Output/Accuracy_Sheet_lg_100_simple_spacy.csv", index = False)
# -
final_data = df_cm.join(df_matrix)
final_data.to_csv("ACC-ENG_BERT_pred_ENG_SUM_EXP.csv")
# final_data.to_csv("1190_spacy_pred_tech_match.csv")
|
accuracy_matrix_bert_2500-ENG.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Split Dataset
#
# This notebook shows how to split dataset into train, validation and test sub set.
# ## Read data
# Use numpy and pandas to read data file list.
import numpy as np
import pandas as pd
np.random.seed(1)
# Tell pandas where the csv file is:
csv_file_url = "data/data.csv"
# Check the data.
full_data = pd.read_csv(csv_file_url)
total_file_number = len(full_data)
print("There are total {} examples in this dataset.".format(total_file_number))
full_data.head()
# ## Split files
# There will be three groups: train, validation and test.
#
# Tell notebook number of samples for each group in the following cell.
num_train = 200000
num_validation = 11565
num_test = 10000
# Make sure there are enough example for your choice.
assert num_train + num_validation + num_test <= total_file_number, "Not enough examples for your choice."
print("Looks good! {} for train, {} for validation and {} for test.".format(num_train, num_validation, num_test))
# Random spliting files.
index_train = np.random.choice(total_file_number, size=num_train, replace=False)
index_validation_test = np.setdiff1d(list(range(total_file_number)), index_train)
index_validation = np.random.choice(index_validation_test, size=num_validation, replace=False)
index_test = np.setdiff1d(index_validation_test, index_validation)
# Merge them into sub datasets.
train = full_data.iloc[index_train]
validation = full_data.iloc[index_validation]
test = full_data.iloc[index_test]
# ## Write to files
train.to_csv('data/data_train.csv', index=None)
validation.to_csv("data/data_validation.csv", index=None)
test.to_csv('data/data_test.csv', index=None)
print("All done!")
|
split_data.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] slideshow={"slide_type": "slide"}
# # Vector-space models: dimensionality reduction
# -
__author__ = "<NAME>"
__version__ = "CS224u, Stanford, Spring 2019"
# + [markdown] slideshow={"slide_type": "slide"}
# ## Contents
#
# 1. [Overview](#Overview)
# 1. [Set-up](#Set-up)
# 1. [Latent Semantic Analysis](#Latent-Semantic-Analysis)
# 1. [Overview of the LSA method](#Overview-of-the-LSA-method)
# 1. [Motivating example for LSA](#Motivating-example-for-LSA)
# 1. [Applying LSA to real VSMs](#Applying-LSA-to-real-VSMs)
# 1. [Other resources for matrix factorization](#Other-resources-for-matrix-factorization)
# 1. [GloVe](#GloVe)
# 1. [Overview of the GloVe method](#Overview-of-the-GloVe-method)
# 1. [GloVe implementation notes](#GloVe-implementation-notes)
# 1. [Applying GloVe to our motivating example](#Applying-GloVe-to-our-motivating-example)
# 1. [Testing the GloVe implementation](#Testing-the-GloVe-implementation)
# 1. [Applying GloVe to real VSMs](#Applying-GloVe-to-real-VSMs)
# 1. [Autoencoders](#Autoencoders)
# 1. [Overview of the autoencoder method](#Overview-of-the-autoencoder-method)
# 1. [Testing the autoencoder implementation](#Testing-the-autoencoder-implementation)
# 1. [Applying autoencoders to real VSMs](#Applying-autoencoders-to-real-VSMs)
# 1. [word2vec](#word2vec)
# 1. [Training data](#Training-data)
# 1. [Basic skip-gram](#Basic-skip-gram)
# 1. [Skip-gram with noise contrastive estimation ](#Skip-gram-with-noise-contrastive-estimation-)
# 1. [word2vec resources](#word2vec-resources)
# 1. [Other methods](#Other-methods)
# 1. [Exploratory exercises](#Exploratory-exercises)
# + [markdown] slideshow={"slide_type": "slide"}
# ## Overview
#
# The matrix weighting schemes reviewed in the first notebook for this unit deliver solid results. However, they are not capable of capturing higher-order associations in the data.
#
# With dimensionality reduction, the goal is to eliminate correlations in the input VSM and capture such higher-order notions of co-occurrence, thereby improving the overall space.
#
# As a motivating example, consider the adjectives _gnarly_ and _wicked_ used as slang positive adjectives. Since both are positive, we expect them to be similar in a good VSM. However, at least stereotypically, _gnarly_ is Californian and _wicked_ is Bostonian. Thus, they are unlikely to occur often in the same texts, and so the methods we've reviewed so far will not be able to model their similarity.
#
# Dimensionality reduction techniques are often capable of capturing such semantic similarities (and have the added advantage of shrinking the size of our data structures).
# + [markdown] slideshow={"slide_type": "slide"}
# ## Set-up
#
# * Make sure your environment meets all the requirements for [the cs224u repository](https://github.com/cgpotts/cs224u/). For help getting set-up, see [setup.ipynb](setup.ipynb).
#
# * Make sure you've downloaded [the data distribution for this course](http://web.stanford.edu/class/cs224u/data/data.zip), unpacked it, and placed it in the current directory (or wherever you point `DATA_HOME` to below).
# -
from mittens import GloVe
import numpy as np
import os
import pandas as pd
import scipy.stats
from torch_autoencoder import TorchAutoencoder
import utils
import vsm
DATA_HOME = os.path.join('data', 'vsmdata')
imdb5 = pd.read_csv(
os.path.join(DATA_HOME, 'imdb_window5-scaled.csv.gz'), index_col=0)
imdb20 = pd.read_csv(
os.path.join(DATA_HOME, 'imdb_window20-flat.csv.gz'), index_col=0)
giga5 = pd.read_csv(
os.path.join(DATA_HOME, 'giga_window5-scaled.csv.gz'), index_col=0)
giga20 = pd.read_csv(
os.path.join(DATA_HOME, 'giga_window20-flat.csv.gz'), index_col=0)
# + [markdown] slideshow={"slide_type": "slide"}
# ## Latent Semantic Analysis
#
# Latent Semantic Analysis (LSA) is a prominent dimensionality reduction technique. It is an application of __truncated singular value decomposition__ (SVD) and so uses only techniques from linear algebra (no machine learning needed).
# + [markdown] slideshow={"slide_type": "slide"}
# ### Overview of the LSA method
#
# The central mathematical result is that, for any matrix of real numbers $X$ of dimension $m \times n$, there is a factorization of $X$ into matrices $T$, $S$, and $D$ such that
#
# $$X_{m \times n} = T_{m \times m}S_{m\times m}D_{n \times m}^{\top}$$
#
# The matrices $T$ and $D$ are __orthonormal__ – their columns are length-normalized and orthogonal to one another (that is, they each have cosine distance of $1$ from each other). The singular-value matrix $S$ is a diagonal matrix arranged by size, so that the first dimension corresponds to the greatest source of variability in the data, followed by the second, and so on.
#
# Of course, we don't want to factorize and rebuild the original matrix, as that wouldn't get us anywhere. The __truncation__ part means that we include only the top $k$ dimensions of $S$. Given our row-oriented perspective on these matrices, this means using
#
# $$T[1{:}m, 1{:}k]S[1{:}k, 1{:}k]$$
#
# which gives us a version of $T$ that includes only the top $k$ dimensions of variation.
#
# To build up intuitions, imagine that everyone on the Stanford campus is associated with a 3d point representing their position: $x$ is east–west, $y$ is north–south, and $z$ is zenith–nadir. Since the campus is spread out and has relatively few deep basements and tall buildings, the top two dimensions of variation will be $x$ and $y$, and the 2d truncated SVD of this space will leave $z$ out. This will, for example, capture the sense in which someone at the top of Hoover Tower is close to someone at its base.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Motivating example for LSA
#
# We can also return to our original motivating example of _wicked_ and _gnarly_. Here is a matrix reflecting those assumptions:
# +
gnarly_df = pd.DataFrame(
np.array([
[1,0,1,0,0,0],
[0,1,0,1,0,0],
[1,1,1,1,0,0],
[0,0,0,0,1,1],
[0,0,0,0,0,1]], dtype='float64'),
index=['gnarly', 'wicked', 'awesome', 'lame', 'terrible'])
gnarly_df
# -
# No column context includes both _gnarly_ and _wicked_ together so our count matrix places them far apart:
vsm.neighbors('gnarly', gnarly_df)
# Reweighting doesn't help. For example, here is the attempt with Positive PMI:
vsm.neighbors('gnarly', vsm.pmi(gnarly_df))
# However, both words tend to occur with _awesome_ and not with _lame_ or _terrible_, so there is an important sense in which they are similar. LSA to the rescue:
gnarly_lsa_df = vsm.lsa(gnarly_df, k=2)
vsm.neighbors('gnarly', gnarly_lsa_df)
# + [markdown] slideshow={"slide_type": "slide"}
# ### Applying LSA to real VSMs
#
# Here's an example that begins to convey the effect that this can have empirically.
#
# First, the original count matrix:
# -
vsm.neighbors('superb', imdb5).head()
# And then LSA with $k=100$:
imdb5_svd = vsm.lsa(imdb5, k=100)
vsm.neighbors('superb', imdb5_svd).head()
# + [markdown] slideshow={"slide_type": "slide"}
# A common pattern in the literature is to apply PMI first. The PMI values tend to give the count matrix a normal (Gaussian) distribution that better satisfies the assumptions underlying SVD:
# -
imdb5_pmi = vsm.pmi(imdb5, positive=False)
imdb5_pmi_svd = vsm.lsa(imdb5_pmi, k=100)
vsm.neighbors('superb', imdb5_pmi_svd).head()
# + [markdown] slideshow={"slide_type": "slide"}
# ### Other resources for matrix factorization
#
# The [sklearn.decomposition](http://scikit-learn.org/stable/modules/classes.html#module-sklearn.decomposition) module contains an implementation of LSA ([TruncatedSVD](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html#sklearn.decomposition.TruncatedSVD)) that you might want to switch to for real experiments:
#
# * The `sklearn` version is more flexible than the above in that it can operate on both dense matrices (Numpy arrays) and sparse matrices (from Scipy).
#
# * The `sklearn` version will make it easy to try out other dimensionality reduction methods in your own code; [Principal Component Analysis (PCA)](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA) and [Non-Negative Matrix Factorization (NMF)](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.NMF.html#sklearn.decomposition.NMF) are closely related methods that are worth a look.
# + [markdown] slideshow={"slide_type": "slide"}
# ## GloVe
#
# ### Overview of the GloVe method
#
# [Pennington et al. (2014)](http://www.aclweb.org/anthology/D/D14/D14-1162.pdf) introduce an objective function for semantic word representations. Roughly speaking, the objective is to learn vectors for words $w_{i}$ and $w_{j}$ such that their dot product is proportional to their probability of co-occurrence:
#
# $$w_{i}^{\top}\widetilde{w}_{k} + b_{i} + \widetilde{b}_{k} = \log(X_{ik})$$
#
# The paper is exceptionally good at motivating this objective from first principles. In their equation (6), they define
#
# $$w_{i}^{\top}\widetilde{w}_{k} = \log(P_{ik}) = \log(X_{ik}) - \log(X_{i})$$
#
# If we allow that the rows and columns can be different, then we would do
#
# $$w_{i}^{\top}\widetilde{w}_{k} = \log(P_{ik}) = \log(X_{ik}) - \log(X_{i} \cdot X_{*k})$$
#
# where, as in the paper, $X_{i}$ is the sum of the values in row $i$, and $X_{*k}$ is the sum of the values in column $k$.
#
# The rightmost expression is PMI by the equivalence $\log(\frac{x}{y}) = \log(x) - \log(y)$, and hence we can see GloVe as aiming to make the dot product of two learned vectors equal to the PMI!
#
# The full model is a weighting of this objective:
#
# $$\sum_{i, j=1}^{|V|} f\left(X_{ij}\right)
# \left(w_i^\top \widetilde{w}_j + b_i + \widetilde{b}_j - \log X_{ij}\right)^2$$
#
# where $V$ is the vocabulary and $f$ is a scaling factor designed to diminish the impact of very large co-occurrence counts:
#
# $$f(x)
# \begin{cases}
# (x/x_{\max})^{\alpha} & \textrm{if } x < x_{\max} \\
# 1 & \textrm{otherwise}
# \end{cases}$$
#
# Typically, $\alpha$ is set to $0.75$ and $x_{\max}$ to $100$ (though it is worth assessing how many of your non-zero counts are above this; in dense word $\times$ word matrices, you could be flattening more than you want to).
# + [markdown] slideshow={"slide_type": "slide"}
# ### GloVe implementation notes
#
# * The implementation in `vsm.glove` is the most stripped-down, bare-bones version of the GloVe method I could think of. As such, it is quite slow.
#
# * The required [mittens](https://github.com/roamanalytics/mittens) package includes a vectorized implementation that is much, much faster, so we'll mainly use that.
#
# * For really large jobs, [the official C implementation released by the GloVe team](http://nlp.stanford.edu/projects/glove/) is probably the best choice.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Applying GloVe to our motivating example
#
# GloVe should do well on our _gnarly_/_wicked_ evaluation, though you will see a lot variation due to the small size of this VSM:
# -
gnarly_glove = vsm.glove(gnarly_df, n=5, max_iter=1000)
vsm.neighbors('gnarly', gnarly_glove)
# + [markdown] slideshow={"slide_type": "slide"}
# ### Testing the GloVe implementation
#
# It is not easy analyze GloVe values derived from real data, but the following little simulation suggests that `vsm.glove` is working as advertised: it does seem to reliably deliver vectors whose dot products are proportional to the co-occurrence probability:
# -
glove_test_count_df = pd.DataFrame(
np.array([
[10.0, 2.0, 3.0, 4.0],
[ 2.0, 10.0, 4.0, 1.0],
[ 3.0, 4.0, 10.0, 2.0],
[ 4.0, 1.0, 2.0, 10.0]]),
index=['A', 'B', 'C', 'D'],
columns=['A', 'B', 'C', 'D'])
glove_test_df = vsm.glove(glove_test_count_df, max_iter=1000, n=4)
glove_test_df
def correlation_test(true, pred):
mask = true > 0
M = pred.dot(pred.T)
with np.errstate(divide='ignore'):
log_cooccur = np.log(true)
log_cooccur[np.isinf(log_cooccur)] = 0.0
row_prob = np.log(true.sum(axis=1))
row_log_prob = np.outer(row_prob, np.ones(true.shape[1]))
prob = log_cooccur - row_log_prob
return np.corrcoef(prob[mask], M[mask])[0, 1]
correlation_test(glove_test_count_df.values, glove_test_df.values)
# + [markdown] slideshow={"slide_type": "slide"}
# ### Applying GloVe to real VSMs
# -
# The `vsm.glove` implementation is too slow to use on real matrices. The distribution in the `mittens` package is significantly faster, making its use possible even without a GPU (and it will be very fast indeed on a GPU machine):
# +
glove_model = GloVe()
imdb5_glv = glove_model.fit(imdb5.values)
imdb5_glv = pd.DataFrame(imdb5_glv, index=imdb5.index)
# -
vsm.neighbors('superb', imdb5_glv).head()
# + [markdown] slideshow={"slide_type": "slide"}
# ## Autoencoders
#
# An autoencoder is a machine learning model that seeks to learn parameters that predict its own input. This is meaningful when there are intermediate representations that have lower dimensionality than the inputs. These provide a reduced-dimensional view of the data akin to those learned by LSA, but now we have a lot more design choices and a lot more potential to learn higher-order associations in the underyling data.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Overview of the autoencoder method
#
# The module `torch_autoencoder` uses PyToch to implement a simple one-layer autoencoder:
#
# $$
# \begin{align}
# h &= \mathbf{f}(xW + b_{h}) \\
# \widehat{x} &= hW^{\top} + b_{x}
# \end{align}$$
#
# Here, we assume that the hidden representation $h$ has a low dimensionality like 100, and that $\mathbf{f}$ is a non-linear activation function (the default for `TorchAutoencoder` is `tanh`). These are the major design choices internal to the network. It might also be meaningful to assume that there are two matrices of weights $W_{xh}$ and $W_{hx}$, rather than using $W^{\top}$ for the output step.
#
# The objective function for autoencoders will implement some kind of assessment of the distance between the inputs and their predicted outputs. For example, one could use the one-half mean squared error:
#
# $$\frac{1}{m}\sum_{i=1}^{m} \frac{1}{2}(\widehat{X[i]} - X[i])^{2}$$
#
# where $X$ is the input matrix of examples (dimension $m \times n$) and $X[i]$ corresponds to the $i$th example.
#
# When you call the `fit` method of `TorchAutoencoder`, it returns the matrix of hidden representations $h$, which is the new embedding space: same row count as the input, but with the column count set by the `hidden_dim` parameter.
#
# For much more on autoencoders, see the 'Autoencoders' chapter of [Goodfellow et al. 2016](http://www.deeplearningbook.org).
# + [markdown] slideshow={"slide_type": "slide"}
# ### Testing the autoencoder implementation
#
# Here's an evaluation that is meant to test the autoencoder implementation – we expect it to be able to full encode the input matrix because we know its rank is equal to the dimensionality of the hidden representation.
# +
def randmatrix(m, n, sigma=0.1, mu=0):
return sigma * np.random.randn(m, n) + mu
def autoencoder_evaluation(nrow=1000, ncol=100, rank=20, max_iter=20000):
"""This an evaluation in which `TfAutoencoder` should be able
to perfectly reconstruct the input data, because the
hidden representations have the same dimensionality as
the rank of the input matrix.
"""
X = randmatrix(nrow, rank).dot(randmatrix(rank, ncol))
ae = TorchAutoencoder(hidden_dim=rank, max_iter=max_iter)
ae.fit(X)
X_pred = ae.predict(X)
mse = (0.5 * (X_pred - X)**2).mean()
return(X, X_pred, mse)
# +
ae_max_iter = 100
_, _, ae = autoencoder_evaluation(max_iter=ae_max_iter)
print("Autoencoder evaluation MSE after {0} evaluations: {1:0.04f}".format(ae_max_iter, ae))
# + [markdown] slideshow={"slide_type": "slide"}
# ### Applying autoencoders to real VSMs
#
# You can apply the autoencoder directly to the count matrix, but this could interact very badly with the internal activation function: if the counts are all very high or very low, then everything might get pushed irrevocably towards the extreme values of the activation.
#
# Thus, it's a good idea to first normalize the values somehow. Here, I use `vsm.length_norm`:
# -
imdb5.shape
imdb5_l2 = imdb5.apply(vsm.length_norm, axis=1)
imdb5_l2.shape
imdb5_l2_ae = TorchAutoencoder(
max_iter=100, hidden_dim=50, eta=0.001).fit(imdb5_l2)
imdb5_l2_ae.shape
vsm.neighbors('superb', imdb5_l2_ae).head()
# This is very slow and seems not to work all that well. To speed things up, one can first apply LSA or similar:
imdb5_l2_svd100 = vsm.lsa(imdb5_l2, k=100)
imdb_l2_svd100_ae = TorchAutoencoder(
max_iter=1000, hidden_dim=50, eta=0.01).fit(imdb5_l2_svd100)
vsm.neighbors('superb', imdb_l2_svd100_ae).head()
# + [markdown] slideshow={"slide_type": "slide"}
# ## word2vec
#
# The label __word2vec__ picks out a family of models in which the embedding for a word $w$ is trained to predict the words that co-occur with $w$. This intuition can be cashed out in numerous ways. Here, we review just the __skip-gram model__, due to [Mikolov et al. 2013](https://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality).
# + [markdown] slideshow={"slide_type": "slide"}
# ### Training data
#
# The most natural starting point is to transform a corpus into a supervised data set by mapping each word to a subset (maybe all) of the words that it occurs with in a given window. Schematically:
#
# __Corpus__: `it was the best of times, it was the worst of times, ...`
#
# With window size 2:
#
# ```
# (it, was)
# (it, the)
# (was, it)
# (was, the)
# (was, best)
# (the, was)
# (the, it)
# (the, best)
# (the, of)
# ...
# ```
# + [markdown] slideshow={"slide_type": "slide"}
# ### Basic skip-gram
#
# The basic skip-gram model estimates the probability of an input–output pair $(a, b)$ as
#
# $$P(b \mid a) = \frac{\exp(x_{a}w_{b})}{\sum_{b'\in V}\exp(x_{a}w_{b'})}$$
#
# where $x_{a}$ is the row-vector representation of word $a$ and $w_{b}$ is the column vector representation of word $b$. The objective is to minimize the following quantity:
#
# $$
# -\sum_{i=1}^{m}\sum_{k=1}^{|V|}
# \textbf{1}\{c_{i}=k\}
# \log
# \frac{
# \exp(x_{i}w_{k})
# }{
# \sum_{j=1}^{|V|}\exp(x_{i}w_{j})
# }$$
#
# where $V$ is the vocabulary.
#
# The inputs $x_{i}$ are the word representations, which get updated during training, and the outputs are one-hot vectors $c$. For example, if `was` is the 560th element in the vocab, then the output $c$ for the first example in the corpus above would be a vector of all $0$s except for a $1$ in the 560th position. $x$ would be the representation of `it` in the embedding space.
#
# The distribution over the entire output space for a given input word $a$ is thus a standard softmax classifier; here we add a bias term for good measure:
#
# $$c = \textbf{softmax}(x_{a}W + b)$$
#
# If we think of this model as taking the entire matrix $X$ as input all at once, then it becomes
#
# $$c = \textbf{softmax}(XW + b)$$
#
# and it is now very clear that we are back to the core insight that runs through all of our reweighting and dimensionality reduction methods: we have a word matrix $X$ and a context matrix $W$, and we are trying to push the dot products of these two embeddings in a specific direction: here, to maximize the likelihood of the observed co-occurrences in the corpus.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Skip-gram with noise contrastive estimation
#
# Training the basic skip-gram model directly is extremely expensive for large vocabularies, because $W$, $b$, and the outputs $c$ get so large.
#
# A straightforward way to address this is to change the objective to use __noise contrastive estimation__ (negative sampling). Where $\mathcal{D}$ is the original training corpus and $\mathcal{D}'$ is a sample of pairs not in the corpus, we minimize
#
# $$\sum_{a, b \in \mathcal{D}}-\log\sigma(x_{a}w_{b}) + \sum_{a, b \in \mathcal{D}'}\log\sigma(x_{a}w_{b})$$
#
# with $\sigma$ the sigmoid activation function $\frac{1}{1 + \exp(-x)}$.
#
# The advice of Mikolov et al. is to sample $\mathcal{D}'$ proportional to a scaling of the frequency distribution of the underlying vocabulary in the corpus:
#
# $$P(w) = \frac{\textbf{count}(w)^{0.75}}{\sum_{w'\in V} \textbf{count}(w')}$$
#
# where $V$ is the vocabulary.
#
# Although this new objective function is a substantively different objective than the previous one, Mikolov et al. (2013) say that it should approximate it, and it is building on the same insight about words and their contexts. See [Levy and Golberg 2014](http://papers.nips.cc/paper/5477-neural-word-embedding-as-implicit-matrix-factorization) for a proof that this objective reduces to PMI shifted by a constant value. See also [Cotterell et al. 2017](https://aclanthology.coli.uni-saarland.de/papers/E17-2028/e17-2028) for an interpretation of this model as a variant of PCA.
# + [markdown] slideshow={"slide_type": "slide"}
# ### word2vec resources
#
# * In the usual presentation, word2vec training involves looping repeatedly over the sequence of tokens in the corpus, sampling from the context window from each word to create the positive training pairs. I assume that this same process could be modeled by sampling (row, column) index pairs from our count matrices proportional to their cell values. However, I couldn't get this to work well. I'd be grateful if someone got it work or figured out why it won't!
#
# * Luckily, there are numerous excellent resources for word2vec. [The TensorFlow tutorial Vector representations of words](https://www.tensorflow.org/tutorials/word2vec) is very clear and links to code that is easy to work with. Because TensorFlow has a built in loss function called `tf.nn.nce_loss`, it is especially simple to define these models – one pretty much just sets up an embedding $X$, a context matrix $W$, and a bias $b$, and then feeds them plus a training batch to the loss function.
#
# * The excellent [Gensim package](https://radimrehurek.com/gensim/) has an implementation that handles the scalability issues related to word2vec.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Other methods
#
# Learning word representations is one of the most active areas in NLP right now, so I can't hope to offer a comprehensive summary. I'll settle instead for identifying some overall trends and methods:
#
# * The LexVec model of [Salle et al. 2016](https://aclanthology.coli.uni-saarland.de/papers/P16-2068/p16-2068) combines the core insight of GloVe (learn vectors that approximate PMI) with the insight from word2vec that we should additionally try to push words that don't appear together farther apart in the VSM. (GloVe simply ignores 0 count cells and so can't do this.)
#
# * There is growing awareness that many apparently diverse models can be expressed as matrix factorization methods like SVD/LSA. See especially
# [Singh and Gordon 2008](http://www.cs.cmu.edu/~ggordon/singh-gordon-unified-factorization-ecml.pdf),
# [Levy and Golberg 2014](http://papers.nips.cc/paper/5477-neural-word-embedding-as-implicit-matrix-factorization), [Cotterell et al.](https://aclanthology.coli.uni-saarland.de/papers/E17-2028/e17-2028). Also <NAME> tweeted [this very helpful annotated chart](https://twitter.com/_shrdlu_/status/927278909040873472).
#
# * Subword modeling ([reviewed briefly in the previous notebook](vsm_01_distributional.ipynb#Subword-information)) is increasingly yielding dividends. (It would already be central if most of NLP focused on languages with complex morphology!) Check out the papers at the Subword and Character-Level Models for NLP Workshops: [SCLeM 2017](https://sites.google.com/view/sclem2017/home), [SCLeM 2018](https://sites.google.com/view/sclem2018/home).
#
# * Contextualized word representations have proven valuable in many contexts. These methods do not provide representations for individual words, but rather represent them in their linguistic context. This creates space for modeling how word senses vary depending on their context of use. We will study these methods later in the quarter, mainly in the context of identifying ways that might achieve better results on your projects.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Exploratory exercises
#
# These are largely meant to give you a feel for the material, but some of them could lead to projects and help you with future work for the course. These are not for credit.
#
# 1. Try out some pipelines of reweighting, `vsm.lsa` at various dimensions, and `TorchAutoencoder` to see which seems best according to your sampling around with `vsm.neighbors` and high-level visualization with `vsm.tsne_viz`. Feel free to use other factorization methods defined in [sklearn.decomposition](http://scikit-learn.org/stable/modules/classes.html#module-sklearn.decomposition) as well.
#
# 1. What happens if you set `k=1` using `vsm.lsa`? What do the results look like then? What do you think this first (and now only) dimension is capturing?
#
# 1. Modify `vsm.glove` so that it uses [the AdaGrad optimization method](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf) as in the original paper. It's fine to use [the authors' implementation](http://nlp.stanford.edu/projects/glove/), [<NAME>'s implementation](http://www.foldl.me/2014/glove-python/), or the [mittens Numpy implementation](https://github.com/roamanalytics/mittens/blob/master/mittens/np_mittens.py) as references, but you might enjoy the challenge of doing this with no peeking at their code.
|
vsm_02_dimreduce.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Get sorta big data
#
# ## Medicare Part B Payment Data
#
# For calendar year 2015: https://www.cms.gov/Research-Statistics-Data-and-Systems/Statistics-Trends-and-Reports/Medicare-Provider-Charge-Data/Physician-and-Other-Supplier2015.html
#
#
# NOTE: this file is >400MB zipped and 2GB unzipped
#
# This file outlines all procedures paid by Medicare Part B, aggregated by physician (NPI) and procedure (HCPCS code)
#
# * NPI: https://en.wikipedia.org/wiki/National_Provider_Identifier
# * HCPCS: https://en.wikipedia.org/wiki/Healthcare_Common_Procedure_Coding_System
# !curl http://www.cms.gov/apps/ama/license.asp?file=http://download.cms.gov/Research-Statistics-Data-and-Systems/Statistics-Trends-and-Reports/Medicare-Provider-Charge-Data/Downloads/Medicare_Provider_Util_Payment_PUF_CY2015.zip > 2015_partB.zip
# !unzip 2015_partB.zip
# First trick, use grep to reduce our huge file down to something manageable for a tutorial.
# !grep -e FL -e MIAMI 2015_partB.txt > 2015_partB_miami.txt
# If you're impatient, just download it from S3
# !aws s3 cp s3://rikturr/2015_partB_miami.txt 2015_partB_miami.txt
# +
import pandas as pd
import numpy as np
df = pd.read_csv('2015_partB_miami.txt', sep='\t')
df.head()
# -
# # File formats are key
# !ls -alh 2015_partB_miami.txt
df = pd.read_csv('2015_partB_miami.txt', sep='\t')
df.to_parquet('2015_partB_miami.parquet')
# !ls -alh 2015_partB_miami.parquet
# # Use your cores
indexes = list(df.index)
len(indexes)
# Oh no! A for loop 😱
def super_complex_function(x):
return len(df.loc[x]['hcpcs_code'])
# %%time
out = []
for i in indexes:
out.append(super_complex_function(i))
# Let's try using multiple threads
# +
import multiprocessing as mp
num_chunks = 10
num_threads = 4
# -
# %%time
pool = mp.Pool(num_threads)
fast_out = pool.map(super_complex_function, indexes)
set(out) == set(fast_out)
# # Sparse matrices
one_hot = (df
.pivot_table(index=['npi'], columns='hcpcs_code', values='line_srvc_cnt')
.reset_index()
.fillna(0)
.values)
one_hot
one_hot.shape, one_hot.shape[0] * one_hot.shape[1]
np.count_nonzero(one_hot)
# +
import scipy.sparse as sp
one_hot_sparse = sp.csc_matrix(one_hot)
one_hot_sparse
# -
np.save('dense.npy', one_hot)
sp.save_npz('sparse.npz', one_hot_sparse)
# !ls -alh dense.npy
# !ls -alh sparse.npz
|
code.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # NS delayes notification
#
# NS API address: https://www.ns.nl/en/travel-information/ns-api
#
# credentials management: https://dev.to/jamestimmins/django-cheat-sheet-keep-credentials-secure-with-environment-variables-2ah5
# https://pypi.org/project/python-dotenv/
#
# +
# #!pip install python-dotenvb
# #!pip install osa
# +
#pip install jupyter_helpers
# +
import http.client, urllib.request, urllib.parse, urllib.error, base64, pandas as pd
import json
import os
from pandas.io.json import json_normalize
import numpy as np
from jupyter_helpers.namespace import NeatNamespace
import datetime
import time
import requests
import re
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from collections import defaultdict
pd.set_option('display.max_columns', 300) # display 300 columns without shrinking
pd.set_option('display.max_rows', 100) # Show more rows
# -
from dotenv import load_dotenv
load_dotenv(override=True)
# from pathlib import Path # python3 only using specific path
# env_path = Path('.') / '.env'
# load_dotenv(dotenv_path=env_path)
# ## Manual data insert
user_data=defaultdict()
user_data['daily_work_leave'] = {'from_uic': 8400061, 'to_uic': 8400319, 'h':6, 'm':26, 'enabled':True}
user_data['daily_work_return'] = {'from_uic': 8400319, 'to_uic': 8400061, 'h':16, 'm':8, 'enabled':True}
df_user_data = pd.DataFrame(user_data).T
df_user_data[df_user_data['enabled']==True]
df_user_data['search_date_time'] = df_user_data.apply(lambda row: datetime.datetime.today().replace(hour=row.h, minute=row.m, second =0).strftime('%Y-%m-%dT%T%z') ,axis=1)
df_user_data['current_date_time'] = datetime.datetime.today()
df_user_data['diff'] = pd.to_datetime(df_user_data['search_date_time']) - pd.to_datetime(df_user_data['current_date_time'])
df_user_data_input = df_user_data[df_user_data['diff']>pd.Timedelta(0, unit='s')].sort_values(by='diff').head(1).to_dict(orient='records')
# +
# len(df_user_data_input)
# -
# # Logic
# ## Calculation
# 1. check if train is canceled
# * Canceled train return next earliest available one
# * And calculate waiting time
# 2. check if train is delayed
# * Calculate
# +
# #Set UIC code, stations code can be googled with universal destinations.
# denbosch = 8400319
# amszuid = 8400061
# search_date_time_leave = datetime.datetime.today().replace(hour=6, minute=26, second =0).strftime('%Y-%m-%dT%T%z')
# search_date_time_return = datetime.datetime.today().replace(hour=16, minute=8, second =0).strftime('%Y-%m-%dT%T%z')
# from_uic = amszuid
# to_uic = denbosch
# email_sent = False
#train_id = 'IC 3519 ' # Return 3556
#ctx_Reconn_amsz_to_denbosch = 'arnu|fromStation=8400061|toStation=8400319|plannedFromTime=2019-12-23T06:26:00+01:00|plannedArrivalTime=2019-12-23T07:21:00+01:00|yearCard=false|excludeHighSpeedTrains=false'
# +
def get_data_from_ns(from_uic, to_uic, search_date_time, email_sent, **kwargs):
# all ride information
# # https://apiportal.ns.nl/docs/services/public-reisinformatie-api/operations/ApiV3TripsGet?
key = os.getenv("NS_KEY")
headers = {
# Request headers
'Accept': '',
'X-Request-ID': '',
'X-Caller-ID': '',
'x-api-key': '',
'Authorization': '',
'Ocp-Apim-Subscription-Key': '%s' % key,
}
params = urllib.parse.urlencode({
# Request parameters
'originUicCode': '%s' % from_uic,
'destinationUicCode': '%s' % to_uic,
'dateTime': '%s' % search_date_time,
'previousAdvices': 2,
'nextAdvices': 8 ,
})
try:
conn = http.client.HTTPSConnection('gateway.apiportal.ns.nl')
conn.request("GET", "/public-reisinformatie/api/v3/trips?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
#print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
def date_time_column(x):
date_time_col=[]
l = list(x.columns)
for i in l:
if i.find('DateTime')==-1:
continue
else:
date_time_col.append(i)
x[i] = pd.to_datetime(x[i])
return x
d = json.loads(data)
lenghth = len(d)
if lenghth >0:
print(f'Data successfully got from NS. len={lenghth}')
df_unpack = json_normalize(data=d['trips'], record_path=['legs'], meta=['ctxRecon','status','transfers','plannedDurationInMinutes','actualDurationInMinutes','punctuality'
, 'realtime','optimal','shareUrl'], errors='ignore',meta_prefix='meta_' , sep='_')
#print(type(df_unpack['origin_plannedDateTime']))
date_time_column(df_unpack)
df_unpack['time_to_target'] = df_unpack['origin_plannedDateTime'].apply(lambda x: abs(x - pd.Timestamp(search_date_time+'+0100') ) )
#print(df_unpack['time_to_target'])
#target_train = df_unpack.copy()[df_unpack['origin_plannedDateTime']==search_date_time+'+0100'].head(1)
target_train = df_unpack.copy().sort_values(by='time_to_target', ascending =True).head(1)
selected_len = len(target_train)
#date_time_column(target_train)
def status(target_train):
status='normal'
delayed_min = 0
url_to_html = target_train['meta_shareUrl'].values.item()['uri']
if target_train['cancelled'].bool() == True:
status = 'cancelled'
else:
try:
diff = target_train['origin_actualDateTime'] - target_train['origin_plannedDateTime']
delayed_min = diff.values.item()/60000000000
if delayed_min > 5 :
status = 'delayed > 5 mins'
else:
status = 'delayed <= 5 mins'
except:
if target_train['meta_status'].values.item() != 'NORMAL':
status = target_train['meta_status'].values.item()
else:
status = 'normal'
pass
return status, int(delayed_min), url_to_html
if selected_len>0:
print(f'Target time selected. Time={search_date_time}')
status, delayed_min, url_to_html = status(target_train)
print(f'Status {status}; Delayed {delayed_min} mins.')
else:
print(f'No train selected for time {search_date_time}')
def send_email(status, delayed_min, url_to_html ):
sender_email = os.getenv('GMAIL_USER')
receiver_email = [i.strip() for i in list(os.getenv("SEND_TO").split(";"))][1]
password = os.<PASSWORD>('<PASSWORD>')
message = MIMEMultipart("alternative")
message["Subject"] = 'Train '+status+'!'
message["From"] = sender_email
message["To"] = receiver_email
# Create the plain-text and HTML version of your message
text = """\
Hi,
""" + url_to_html
html = '' #requests.get(url_to_html).text
# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)
# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
if status == 'normal':
pass
else:
try:
send_email(status, delayed_min, url_to_html)
email_sent = True
except:
email_sent = False
return email_sent
# -
def check_which_job_to_run(df_user_data_input):
if len(df_user_data_input)>0:
try:
email_sent = get_data_from_ns( email_sent=email_sent, **df_user_data_input[0])
except:
print('error: email not sent')
# +
# email_sent = get_data_from_ns( to_uic, from_uic, search_date_time_return, email_sent)
# +
# search_date_time_return
# time.strptime(search_date_time_return, '%Y-%m-%dT%H:%M:%S')
#pd.Timestamp(search_date_time_return)
# +
#d
# +
#NeatNamespace(d['trips'][0])
# +
#df_trips.columns
# +
#df_trips.info()
# +
# df_unpack = json_normalize(data=d['trips'], record_path=['legs'], meta=['ctxRecon','status','transfers','plannedDurationInMinutes','actualDurationInMinutes','punctuality'
# , 'realtime','optimal','shareUrl'], errors='ignore',meta_prefix='meta_' , sep='_')
# +
#df_unpack.head()
# +
#df_unpack['meta_shareUrl'][0]['uri']
# +
#df_unpack[df_unpack['cancelled']==False]
# +
# target_train = df_unpack.copy()[df_unpack['origin_plannedDateTime']==search_date_time+'+0100'].head(1)
# +
#target_train = df_unpack.copy().head(1)
# +
# def date_time_column(x):
# date_time_col=[]
# l = list(x.columns)
# for i in l:
# if i.find('DateTime')==-1:
# continue
# else:
# date_time_col.append(i)
# x[i] = pd.to_datetime(x[i])
# return x
# +
# date_time_column(target_train)
# +
#diff = target_train['origin_actualDateTime'] - target_train['origin_plannedDateTime']
# +
# diff.values.item()/60000000000
# +
# def status(target_train):
# status='normal'
# delayed_min = 0
# url_to_html = target_train['meta_shareUrl'].values.item()['uri']
# if target_train['cancelled'].bool() == True:
# status = 'cancelled'
# else:
# try:
# diff = target_train['origin_actualDateTime'] - target_train['origin_plannedDateTime']
# delayed_min = diff.values.item()/60000000000
# if delayed_min > 5 :
# status = 'delayed > 5 mins'
# else:
# status = 'delayed <= 5 mins'
# except:
# if target_train['meta_status'].values.item() != 'NORMAL':
# status = target_train['meta_status'].values.item()
# else:
# status = 'normal'
# pass
# return status, int(delayed_min), url_to_html
# +
# status, delayed_min, url_to_html = status(target_train)
# +
# status
# +
# delayed_min
# +
# url_to_html
# -
# ## Notification
# +
# import smtplib
# gmail_user = os.getenv('GMAIL_USER')
# gmail_password = os.getenv('GMAIL_PWD')
# server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
# server.ehlo()
# server.login(gmail_user, gmail_password)
# +
#txt_html = requests.get(url_to_html).text
#urllib.request.urlopen(url_to_html).read().decode("utf-8")
# +
#<div class="rp-reisadvies"></reisadvies>
# +
# import smtplib, ssl
# from email.mime.text import MIMEText
# from email.mime.multipart import MIMEMultipart
# def send_email(status, delayed_min, url_to_html ):
# sender_email = os.getenv('GMAIL_USER')
# receiver_email = [i.strip() for i in list(os.getenv("SEND_TO").split(";"))][1]
# password = os.getenv('GMAIL_PWD')
# message = MIMEMultipart("alternative")
# message["Subject"] = 'Train '+status+'!'
# message["From"] = sender_email
# message["To"] = receiver_email
# # Create the plain-text and HTML version of your message
# text = """\
# Hi,
# """ + url_to_html
# html = '' #requests.get(url_to_html).text
# # Turn these into plain/html MIMEText objects
# part1 = MIMEText(text, "plain")
# part2 = MIMEText(html, "html")
# # Add HTML/plain-text parts to MIMEMultipart message
# # The email client will try to render the last part first
# message.attach(part1)
# message.attach(part2)
# # Create secure connection with server and send email
# context = ssl.create_default_context()
# with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
# server.login(sender_email, password)
# server.sendmail(
# sender_email, receiver_email, message.as_string()
# )
# +
# def notification():
# message = ''
# if
# elif 'origin.actualDateTime' in intersection:
# m = 'Delayed by' +
# #print('Delayed')
# else:
# m = 'OK'
# #print('OK')
# return m
# +
# notification()
# m
# -
# ## Save to S3
# +
# def df_to_s3(df, table_name, schema, dtype=None, sep='\t', delete_first=False, clean_df=False, keep_csv=True, chunksize=10000, if_exists="fail", redshift_str=None, bucket=None):
# """Copies a dataframe inside a Redshift schema.table
# using the bulk upload via this process:
# df -> local csv -> s3 csv -> redshift table
# NOTE: currently this function performs a delete * in
# the target table, append is in TODO list, also we
# need to add a timestamp column
# COLUMN TYPES: right now you need to do a DROP TABLE to
# change the column type, this needs to be changed TODO
# Parameters
# ----------
# keep_csv : bool, optional
# Whether to keep the local csv copy after uploading it to Amazon S3, by default True
# redshift_str : str, optional
# Redshift engine string, if None then 'mssql+pyodbc://Redshift'
# bucket : str, optional
# Bucket name, if None then 'teis-data'
# """
# ACCESS_KEY = os.getenv('AWS_ACCESS')
# SECRET_KEY = os.getenv('AWS_SECRET')
# REGION = os.getenv('AWS_REGION')
# redshift_str = redshift_str if redshift_str else 'mssql+pyodbc://Redshift'
# bucket_name = bucket if bucket else 'bing'
# engine = create_engine(redshift_str, encoding='utf8', poolclass=NullPool)
# s3 = boto3.resource('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=REGION)
# bucket = s3.Bucket(bucket_name)
# filename = table_name + '.csv'
# filepath = os.path.join(os.getcwd(), filename)
# if delete_first:
# remove_from_s3(table_name)
# s3_file = s3.Object(bucket_name, filename)
# s3_file.delete()
# if clean_df:
# df = df_clean(df)
# df = clean_colnames(df)
# df.columns = df.columns.str.strip().str.replace(" ", "_") # Redshift won't accept column names with spaces
# df.to_csv(filepath, sep="\t", encoding="utf-8", index=False, chunksize=chunksize)
# print(f'{filename} created in {filepath}')
# bucket.upload_file(filepath, f"bulk/{filename}")
# print(f'bulk/{filename} file uploaded to s3')
# if check_if_exists(table_name, schema, redshift_str=redshift_str):
# if if_exists == 'fail':
# raise ValueError(f"Table {table_name} already exists")
# elif if_exists == 'replace':
# sql = f"DELETE FROM {schema}.{table_name}"
# engine.execute(sql)
# print('SQL table has been cleaned up successfully.')
# else:
# pass
# else:
# df.head(1).to_sql(table_name, schema=schema, index=False, con=engine, dtype=dtype)
# if not keep_csv:
# os.remove(filepath)
# +
#dateTime (optional)string
#Format - date-time (as date-time in RFC3339). Departure date / time for the search. defaults to server time (Europe/Amsterdam)
# -
# # Appendix
# ## Other APIs
# +
# #disruptions
# headers = {
# # Request headers
# 'Ocp-Apim-Subscription-Key': '%s' % key ,
# }
# params = urllib.parse.urlencode({
# # Request parameters
# 'type': '{string}',
# 'actual': '{boolean}',
# 'lang': 'en',
# })
# try:
# conn = http.client.HTTPSConnection('gateway.apiportal.ns.nl')
# conn.request("GET", "/public-reisinformatie/api/v2/disruptions?%s" % params, "{body}", headers)
# response = conn.getresponse()
# disruption = response.read()
# #print(data)
# conn.close()
# except Exception as e:
# print("[Errno {0}] {1}".format(e.errno, e.strerror))
# +
# station = "amsterdamzuid"
# +
# #Disruption station
# headers = {
# # Request headers
# 'Ocp-Apim-Subscription-Key': '%s' % key ,
# }
# params = urllib.parse.urlencode({
# })
# try:
# conn = http.client.HTTPSConnection('gateway.apiportal.ns.nl')
# conn.request("GET", "/public-reisinformatie/api/v2/disruptions/station/%s" % station, "{body}", headers)
# response = conn.getresponse()
# disrupt_station = response.read()
# #print(data)
# conn.close()
# except Exception as e:
# print("[Errno {0}] {1}".format(e.errno, e.strerror))
# +
# # This doesn't work yet
# uid_add = "http://webservices.ns.nl/ns-api-stations-v2?_ga=2.141585782.518451146.1577077875-2005063189.1572857950"
# key = os.getenv("NS_KEY")
# headers = {
# # Request headers
# 'Ocp-Apim-Subscription-Key': '%s' % key,
# }
# try:
# conn = http.client.HTTPSConnection('gateway.apiportal.ns.nl')
# conn.request("GET", uid_add, "{body}", headers)
# response = conn.getresponse()
# uid = response.read()
# #print(data)
# conn.close()
# except Exception as e:
# print("[Errno {0}] {1}".format(e.errno, e.strerror))
# -
# ## Code used to explore json file
# +
# NeatNamespace(d)
# +
# trips = d['trips'][0]
# -
# # NeatNamespace(trips)
# legs = d['trips'][0]['legs'][0]
# len(legs)
# NeatNamespace(legs)
# len(legs)
# #d
# ## Explore dictionary in old way
# df = df.reset_index()
# df_lcopy = df['legs'].copy()
# df_lcopy
# frames = []
# for i in range(len(df_lcopy)):
# frames.append(json_normalize(df_lcopy[i]))
# df_leg = pd.concat(frames, sort='True')
# df_leg
# #df_unpack[df_unpack['name']==train_id]
# #df_unpack.info()
# #df_trips.query('transfers == 0')
# #df_leg['destination.notes'].values
# #df_leg['notes'].values
# columns_select = ['destination.prognosisType', 'origin.name','destination.name', 'cancelled','origin.plannedDateTime', 'origin.actualDateTime', 'destination.plannedDateTime','punctuality']
# all_columns = df_leg.columns
# intersection = set(columns_select) & set(all_columns)
# df_an = df_leg[intersection]
# date_time_col = intersection.islike('%Date%')
# df_an
# df_an = pd.to_datetime(df_an['origin.plannedDateTime'])
#
# # import smtplib
#
# # def send_email(status, delayed_min, url_to_html ):
# # gmail_user = os.getenv('GMAIL_USER')
# # gmail_password = os.getenv('GMAIL_PWD')
# # send_to = [i.strip() for i in list(os.getenv("SEND_TO").split(";"))]
#
# # sent_from = gmail_user
# # to = send_to
# # subject = 'Train '+status+'!'
# # body = 'test'
#
# # email_text = """\
# # From: %s
# # To: %s
# # Subject: %s
# # Body:
# # %s
# # """ % (sent_from,'<EMAIL>' , subject, body) # "; ".join(to)
# # server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
# # server.ehlo()
# # server.login(gmail_user, gmail_password)
# # server.sendmail(sent_from, to, email_text)
# # server.close()
#
# # # try:
# # # server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
# # # server.ehlo()
# # # server.login(gmail_user, gmail_password)
# # # server.sendmail(sent_from, to, email_text)
# # # server.close()
#
# # # print('Email sent!')
# # # except:
# # # print('Something went wrong...')
|
ns_train_defact_notification/Archive/ns_train_defact_notification.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
# ---
# +
# #!/usr/bin/python3
# +
#from collections import Counter
#import re
#import os
#import time
#from collections import defaultdict
#from collections import deque
# -
# Day 2, https://adventofcode.com/2021/day/2
date = 2
dev = 0 # extra prints
part = 2 # 1,2, or 3 for both
# 0 or 1:
samp = 0
# + [markdown] tags=[]
# ## Read the input data
# +
#time0 = time.time()
if samp == 1:
filename = "/sample.txt"
else:
filename = "/input.txt"
try:
with open(str(date) + filename,"r") as f:
t = f.readlines()
except FileNotFoundError:
with open("." + filename,"r") as f:
t = f.readlines()
t = [(x.strip().replace(' ',' ')) for x in t]
#t = [int(x) for x in t]
# +
## Run the program
if 0:
if part == 1:
print("Part 1: ", day(t))
elif part == 2:
print("Part 2: ", day2(t))
elif part == 3:
pass
#run both
#print("Part 1: ", day(t))
#print("Part 2: ", day2(t))
#tdif = time.time() - time0
#print("Elapsed time: {:.4f} s".format(tdif))
# -
# ## Part one
class Submarine:
def __init__(self, name, depth, position):
self.name = name
self.depth = depth
self.position = position
self.aim = 0
def getDepth(self):
return self.depth
def getPosition(self):
return self.position
def up(self, steps):
self.depth -= steps
if self.depth < 0:
self.depth = 0
def down(self, steps):
self.depth += steps
def forward(self, steps):
self.position += steps
def back(self, steps):
self.position -= steps
# + tags=[]
def day(te):
part = 1
sub = Submarine("one", 0, 0)
for t in te:
row = t.split()
task = row[0]
number = int(row[1])
if task == "forward":
sub.forward(number)
elif task == "back":
sub.back(number)
elif task == "up":
sub.up(number)
elif task == "down":
sub.down(number)
else:
print("ERROR: ", task, number)
#print(row, "---", sub.getDepth(), sub.getPosition())
print(sub.getDepth(), sub.getPosition())
return sub.getDepth() * sub.getPosition()
day(t) # 1250395
# -
# ## Part two
class Submarine:
def __init__(self, name):
self.name = name
self.depth = 0
self.position = 0
self.aim = 0
def getDepth(self):
return self.depth
def getPosition(self):
return self.position
def getAim(self):
return self.aim
def up(self, steps):
self.aim -= steps
if self.aim < 0:
self.aim = 0
def down(self, steps):
self.aim += steps
def forward(self, steps):
self.position += steps
self.depth += steps * self.aim
def back(self, steps):
self.position -= steps
# + tags=[]
def day2(te):
part = 2
sub = Submarine("one")
for t in te:
row = t.split()
task = row[0]
number = int(row[1])
if task == "forward":
sub.forward(number)
elif task == "back":
sub.back(number)
elif task == "up":
sub.up(number)
elif task == "down":
sub.down(number)
else:
print("ERROR: ", task, number)
if samp:
print(row, "---", sub.getDepth(), sub.getPosition(), sub.getAim())
print(sub.getDepth(), sub.getPosition())
return sub.getDepth() * sub.getPosition()
day2(t) # 1451210346
|
2/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
# ---
# <a id='topcell'></a>
# <h1> An Introduction to Python for Physics Students </h1><hr>
# This notebook is for students in the physical sciences who are seeking to learn about scripting for scientific purposes. The language of choice will be Python as it is the easiest language to work with and requires the least amount of knowledge of computer science fundamentals in order to use effectively.
#
# Questions can be sent to the below contacts: <br>
# <EMAIL> (may be inactive past Summer 2023, if that is the case, refer to the github link which has an updated address).<br>
# https://github.com/JoeyTurn
# <br>
#
# Some parts of this notebook will not be all that applicable to physics-based projects, I'll mark these by having a <b>NP</b> (non-physics) tag in front of them. They'll still be included in the case they are necessary to a project or to those who are more curious about the more programming-heavy aspects.
# <a id="classes"></a>
# <h2>Classes and Objects</h2>
# Classes and Objects are, perhaps, the most fundamental ideas and structures used in programming, though their implementation can take quite a bit more work than other fundamental coding tools such as variables and functions. Now that imports have been introduced and looked at, I believe it's an appropriate time to finally introduce classes and objects.<br><br>
# As an overview, objects are made of classes, in the exact same way that a phone may be made out of a phone blueprint: each individual phone (object) may have different apps, texts, and other media inside the phone, but the specification for what a phone of this model consists of will be contained inside a blueprint (class). Since we can't mass produce something without a blueprint, let's first look at classes, then move to objects.<br><br>
# As a quick reminder, <b>NP</b> is the tag for sections that aren't heavily used in physics (that I know of).
# <h3> Classes and Objects Topics </h3>
#
# 1: [Classes](#class)<br>
#   1.1 [Class Methods](#classmethods)<br>
#   1.2 <b>NP</b> [Attributes Setters and Getters](#attributes)<br>
#   1.3 <b>NP</b> [Dunder Methods](#dunder)<br>
# 2: [Inheritance and Polymorphism](#inheritance)<br>
# 3: [Objects](#objects)<br>
# 4: <b>NP</b> [Abstract Base and Data Classes](#data)<br>
# 5: [Classes and Objects Example Solutions](#classessol)
# <a id="class"></a>
# <h3>Classes</h3>
# Classes are essentially generalizations of functions; knowing how important functions were, it should be somewhat self-evident that classes are also highly used. Classes allow programmers to group specific functionality of an object, which will be gone over later, into one chunk of code (typically in a program alone) that allows us to access its contents of variables and functions, along with their interaction. If this sounds somewhat familiar, that's good: classes were actually what we were importing in the previous section! With this, let's jump right into setting up a class. I'll set up a class that doesn't do much, but should help to get the basic syntax across.
class Basic_Class:
"""Just a simple basic class"""
def __init__(self):
self._class_variable = True
@property
def class_variable(self) -> bool:
return self._class_variable
@class_variable.setter
def set_class_variable(self, new_variable: bool):
self._class_variable = new_variable
def random_method(self):
return (not self.class_variable)
# The first thing to note is the triple quotes <code>""" """</code> on either side of a string under the class declaration, this acts as the comment for classes, and needs to go under the class declaration. The actual implementation of this isn't important to understand quite yet, it was simply to introduce the structure of a class. We can see from the cell that a <code>class</code> is defined by <code>class Class_Name</code>, which is <b>always</b> specified without the parantheses <code>()</code> that we use in functions, as well as having the name of the class having capatalized first letters (something else that differentiates classes and functions).<br><br>
# The other things to initially note before getting into the bulk of classes are the <code>\__init__()</code> method and the <code>self</code> tag. To start with the <code>\__init__()</code> method, all classes need to have this line in order to properly set up the class. Like the name of the method suggests, the contents of this function will setup the rest of what will be used throughout the class. We can pass inputs into the <code>\__init__()</code> method in the typical function way by having <code>\__init__(self, variable_1, variable_2, ...)</code>, but we will also then <b>need</b> to put them into the class itself:
class Basic_Class_2:
def __init__(self, input_variable, test_variable):
self.my_variable = input_variable
self.test_variable = test_variable
# The above code should look somewhat silly, since why would we need to have lines putting the value of a variable into the same variable with the same name but <code>self.</code> attached? We'll get into what the <code>self</code> tag does shortly, but in this context, what the <code>\__init__(...)</code> method does is it asks us to put in some paramaters when creating an object out of the class, which we'll get into in a few sections, and allows us to use these inputs throughout the entire class, which wouldn't be possible otherwise (since Classes are generally meant to be in their own programs without knowing another program's variables).<br><br>
# As for the <code>self</code> tag, this is what tells our class that a variable belongs to the class. It is extremely important to remember that inside the functions we define, we write <code>self</code>, and for the actual items we want to use, we write <code>self.</code>, as writing <code>self variable_name</code> or <code>\__init__(self.)</code> will give an error, but you should be fairly used to this convention with time. Looking in terms of the code block above, the <code>self.my_variable = input_variable</code> is telling the class that it has access to a variable <code>self.my_variable</code> and that this variable is set equal to our input of <code>input_variable</code>. The following line of code simply shows that the variable name inside the code with the <code>self.</code> tag can be exactly the same as the variable we use as an input, something that's actually standard practice. (Technically Python will put a <code>self.</code> tag before any class variables even if we as the coders don't, so the <code>self.</code> are not absolutely required, but doing this is <b>highly</b> discouraged).
# [Return to Classes and Objects](#classes)
# <a id="classmethods"></a>
# <h4>Class Methods</h4>
# Class methods are the class version of functions. That's about all the text that you need to read in order to understand them, but let's quickly look at how to implement them.
class Basic_Class_3:
def __init__(self, input_int_1, input_int_2):
self.input_int_1 = input_int_1
self.input_int_2 = input_int_2
def multiply_ints(self):
return self.input_int_1*self.input_int_2
# Where we can see here that they're defined in the exact same way as they would be outside of a class, except for the inclusion of the class-specific <code>self</code> tag. As such, everything that can be said about functions can also be said about class methods, which makes everyone's job easier!
# [Return to Classes and Objects](#classes)
# <a id="attributes"></a>
# <h4>Attributes Setters and Getters (NP)</h4>
# Setter and getter methods allow for the manipulation/reading of class attributes. This may sound strange, since we can just set any attributes outside of the class anyway. Setters and getters are only for when we want a specific way to modify attributes; for instance, if we had made a bank account attribute, we would want users to get their balance but not set it, and if we had a secret list that only one person could see, we would want the majority of users only to set something into the list but not get the list. I couldn't think of a physics-based use of these, so that's the best you'll get as for motivation for now.<br><br>
# As for class attributes, they're always specified with <code>_</code> underscores before their name (ie <code>_mass</code>, and the distinction between attributes and typical variables used in classes comes down to use cases. With the <code>_</code>, the variable is specified for internal use, hence not being able to change it without a setter method. There are also some attributes with two <code>__</code> underscores before their name, and honestly I have no clue what they're used for if they're not dunder methods (which we'll get to in the next section). As a little note, I believe attributes as I have defined them can be changed/gotten without setter/getter methods, that might come down to Python being less object-oriented than other languages or my lack of deep coding knowledge, but either way, it shouldn't affect your code.<br><br>
# To make attributes, like stated earlier, just put a <code>_</code> underscore before the actual name you mean to use. Then, to make a getter, we need to write a method with a line above it reading <code>@property</code>, and the code inside the getter method simply returning <code>self._variable</code>. As for setters, we again need a line above the method, this time reading <code>@class_variable.setter</code>, and the code inside the method (which takes a new variable as an input) being the standard variable setting of <code>self._variable = variable</code>. (Technically, the <code>@</code> lines above the definitions aren't needed, but that's something for the computer scientists to look over). To see this in use, let's look at the following example:
class Basic_Class_Again:
def __init__(self):
self._class_variable = 10
@property
def class_variable(self) -> int:
return self._class_variable
@class_variable.setter
def set_class_variable(self, new_variable: int):
self._class_variable = new_variable
# As attributes, setters, and getters aren't really used for physics, I'll stop the discussion of them here.
# [Return to Classes and Objects](#classes)
# <a id="dunder"></a>
# <h4>Dunder Methods (NP)</h4>
# Double underscore methods, known as dunder methods are inherent properties of the class you make, and broadly specify how Python interacts with classes and their objects. As dunder methods are not much of our concerns, I won't go too much into them, but the one dunder method that I've said before must be included in every class is the <code>\__init__(self)</code> method. If you wanted to have a specific output when printing an object, that would also be a dunder method (<code>\_\_str()\_\_</code> in this case). They would also be used if you wanted to add (<code>\_\_add()\_\_</code>), subtract (<code>\_\_sub()\_\_</code>), and compare (<code>\_\_eq()\_\_</code>) two objects, to name a few.<br><br>
# As a quick example, say you had a class of non-relativistic particles and wanted to have the addition operator give a new particle with their combinded mass and velocity, which is possible with the following code:
# +
class Non_Relativistic_Particle:
# mass in kg, velocity in m/s
def __init__(self, mass = 1, velocity = 1):
self._mass = mass
self._velocity = velocity
@property
def get_mass(self):
return self._mass
@property
def get_velocity(self):
return self._velocity
#dunder method we want
def __add__(self, particle_2):
return Non_Relativistic_Particle(self._mass+particle_2.get_mass, self._velocity+particle_2.get_velocity)
#now to put them to use
particle_1 = Non_Relativistic_Particle()
particle_2 = Non_Relativistic_Particle(2, 5)
particle_12 = particle_1+particle_2
print(particle_12._mass, particle_12._velocity)
# -
# Try not to worry about the lines under the dunder method, we'll go over those shortly.
# <a id="inheritance"></a>
# <h3>Inheritance and Polymorphism</h3>
# Inheritance is how we can write one class and have subclasses which take its attributes and methods. Essentially, if you were wanting to make a general <code>Particle</code> class and have other classes for types of elementary particles, you would want to use inheritance and have <code>Particle</code> have some general mass, spin, charge attributes which can be tuned by the specific subclasses of the general <code>Particle</code> class. In addition, these subclasses can have attributes and methods of their own (ie if only <code>Charm</code> needed the charm attribute, that would not go under <code>Particle</code>).
# +
class Particle:
def __init__(self, mass, energy):
self._mass = mass
self._energy = energy
def random_function(self):
return energy^2
class Charm(Particle):
def __init__(self, mass, energy, charm):
super().__init__(mass, energy)
self._charm = charm
charm_1 = Charm(1, 1, -1)
print(charm_1._mass, charm_1._energy, charm_1._charm)
# -
# Polymorphism is something I will get back to eventually.
# [Return to Classes and Objects](#classes)
# <a id="objects"></a>
# <h3>Objects</h3>
# Objects are where the usefulness of classes really start to factor in; objects are the basis of a way of programming (object-oriented programming) and, in fact, almost everything used thus far has been an object: the things we got from imports (besides attributes), basic Python units like strings/integers, and the functions Python gives.<br><br>
# Objects are also really what differentiates classes from a simple program with functions; say we had some system to calculate an equation of motion, depending only on the potential <code>V(r)</code>, and we wanted to use some various functions for multiple potentials, we can do this through objects.<br><br>
# To set up our own objects, we first need to <code>import</code> the class if it's in a seperate file, then we can use the line <code>variable_name = Class_name(input_1, input_2, ...)</code> like the following:
# #random class, not to be interpreted
# class Basic_Class:
#
# def __init__(self, input_int_1, input_int_2):
# self.input_int_1 = input_int_1
# self.input_int_2 = input_int_2
#
# def multiply_ints(self):
# return self.input_int_1*self.input_int_2
#
# @property
# def class_variable(self) -> bool:
# return self._class_variable
#
# @class_variable.setter
# def set_class_variable(self, new_variable: bool):
# self._class_variable = new_variable
#
# def random_method(self):
# return (not self.class_variable)
#
# #focus on this part
# #if needed, import:
# #import Basic_Class
#
# basic_object_1 = Basic_Class(1, 2)
# basic_object_2 = Basic_Class(2, 5)
# print(basic_object_1.multiply_ints())
# print(basic_object_2.multiply_ints())
# As noted, the actual class isn't really important, just note that we can have multiple objects from the same class along with the general notation of how to make an object.
# [Return to Classes and Objects](#classes)
# <a id="data"></a>
# <h3>Abstract Base and Data Classes (NP)</h3>
# I don't imagine either of these specific type of classes would be too useful for physics-related tasks in Python, so feel free to skip this section if desired. This well primarily, then, serve as a reference in case you need to use them. For both data classes and abstract base classes, we need to import them first.<br><br>
# To start with data classes, we need to import from <code>dataclasses</code>, and we specify a data class with the <code>@dataclass</code> marker above the class (like we did for setter/getter methods inside a class). I don't really remember what dataclasses give the user the ability to do (might have to ask the internet/a computer scientist for that), so I won't spend much more time than providing a reference on how to implement them.
# +
from dataclasses import dataclass
@dataclass
class Inventory:
name: str
mass: float
number_density: int = 0
# -
# Where (I don't believe) we need a dunder init method anymore to quantify our attributes as those are automatically set up by the import.<br><br>
# In a similar vein, we get abstract base classes from the <code>abc</code> import (an unfortunate name for those in atomic/bio/condensed matter), and specify them in a similar way,
# I wish I could say more on these two class generalizations, but they aren't very important to the physics programs I've seen, and so I never had quite the motivation to learn them fully. For those who do want to learn more, the documentation for ABC is here: https://docs.python.org/3/library/abc.html.
# [Return to Classes and Objects](#classes)
# <a id="classessol"></a>
# <h3>Classes and Object Example Solutions</h3>
# No examples for now! Come back when the other sections of the notebook are complete!
|
Python for Physics Classes and Objects.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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['PYWIKIBOT_DIR'] = './wiki_reader/'
# +
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.sql.functions import udf
from pyspark.sql import SparkSession
from pyspark.sql.types import StringType, StructField, StructType, ArrayType, LongType, DoubleType
from spark_app.scorers import score_text, vader_scorer
from spark_app.spark_tools import SparkSentimentStreamer
from pathlib import Path
from ml.OutputProcessing import process_output_files
# -
# ## Input
# +
request = 'peano'
is_category = False # Set it to True if you want to switch search mode from "containing word" to "all pages in category"
batch_size = 50 # Amount of pages in one batch
limit = 1000 # Maximum amount of pages to process, set to None if unlimited
debug_info = False # Set it to True if you want
wiki_page_dir = 'requests/'
spark_results_dir = 'responses/'
# -
# ## Processing
def cleanup(path):
path = Path(path)
path.mkdir(parents=True, exist_ok=True)
for x in path.iterdir():
if x.is_file():
x.unlink()
else:
cleanup(x)
x.rmdir()
def spark_process(request, score_func, size):
data_in = wiki_page_dir + request
data_out = spark_results_dir + request
cleanup(data_out)
spark = SparkSession.builder\
.master("local[*]")\
.appName("NetworkWordCount")\
.getOrCreate()
sc = spark.sparkContext
ssc = StreamingContext(sc, 1)
streamer = SparkSentimentStreamer(sc,
ssc,
spark,
score_func,
data_in,
data_out,
size,
debug_info=debug_info)
streamer.run()
# +
from concurrent.futures import ThreadPoolExecutor
import wiki_reader.reader as reader
query_size = reader.query_size(request, limit)
preload_content = query_size <= 1500 # Set it True when you processing up to ~1500 pages to speed up process
wiki_wrapper = lambda r,b,l,cat,cont: reader.query(r,out_dir=wiki_page_dir,batch_size=b,debug_info=debug_info,
limit=l,is_category=cat,preload_content=cont)
# -
with ThreadPoolExecutor(max_workers=4) as e:
e.submit(wiki_wrapper, request, batch_size, limit, is_category, preload_content)
e.submit(spark_process, request, vader_scorer, query_size)
e.submit(process_output_files, spark_results_dir, query_size)
|
main.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: transformers
# language: python
# name: transformers
# ---
from collections import defaultdict
import re
import pickle
import os
import random
import numpy as np
# ## Shard doordash data by category
#
# This is basically a manual map-reduce. First for each shard, we separate by the category name, then we gather entries across shards by category.
def get_by_category(shard):
datafile = '/home/doordash/doordash_{}.pkl'.format(shard)
with open(datafile, 'rb') as f:
print("Opened {}".format(datafile))
json = pickle.load(f)
all_entries = []
for entry in json:
title = entry['title']
section = entry['metadata']['section']
description = entry['metadata']['description']
category = entry['metadata'].get('restaurant_category', None)
all_entries.append((title, description, section, category))
print("Loaded all entries")
category_to_entries = defaultdict(list)
for entry in all_entries:
og_category = entry[3]
if og_category is None:
og_category = 'None'
if og_category == '':
og_category = 'blank'
format_category = re.sub(r"\s+", '-', og_category)
format_category = re.sub(r"\&", "and", format_category)
format_category = format_category.lower()
# (title, description) in a list
category_to_entries[format_category].append((entry[0], entry[1]))
print("Made dictionary")
for category, entries in category_to_entries.items():
print(category, len(entries))
with open(
'/home/doordash-sharded/doordash_{}_{}'.format(category, shard), 'wb') as f:
pickle.dump(entries, f)
for i in range(0, 16):
get_by_category(i)
# +
category_to_filenames = defaultdict(list)
rootdir = '/home/doordash-sharded'
for filename in os.listdir(rootdir):
_, category, shard = filename.split("_")
category_to_filenames[category].append(
os.path.join(rootdir, filename))
for category, filenames in category_to_filenames.items():
all_items = []
for filename in filenames:
with open(filename, 'rb') as f:
all_items.extend(pickle.load(f))
with open('/home/doordash-by-category/{}'.format(category), 'wb') as f:
pickle.dump(all_items, f)
# -
from collections import Counter
category_items_counter = Counter()
for filename in os.listdir('/home/doordash-by-category'):
with open(os.path.join('/home/doordash-by-category', filename),
'rb') as f:
all_items = pickle.load(f)
category_items_counter[filename] = len(all_items)
print(category_items_counter.most_common())
# # Take sharded data and clean
cuisine = 'other'
with open(os.path.join('/home/doordash-by-dish', cuisine),
'rb') as f:
all_items = pickle.load(f)
all_titles = [e[0] for e in all_items]
re.sub("[\(\[].*?[\)\]]", "", 'Bacon & Sausage (2 Each)')
re.sub(r"\&", "and", "Bacon & Sausage (2 Each)")
random.choices(all_items, k=10)
def check_valid(title):
check = "".join(title.split()) # remove whitespace
check = check.replace("-", "") # remove -, allowed
return check.isalpha()
def format_valid(title):
title = " ".join(title.split()) # whitespace to " "
title = title.rstrip().lstrip()
title = title.replace("-", " ")
return title
letter_items = [format_valid(x[0]) for x in all_items if check_valid(x[0])]
len([x for x in letter_items if x==" "])
len(letter_items), len(all_items)
random.choices(letter_items, k=10)
# ## Take sharded data and tokenize
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained(
'bert-base-multilingual-cased',
do_lower_case=True)
# ##### Demonstrate with particular cuisine
cuisine = 'soup'
with open(os.path.join('/home/doordash-by-dish', cuisine),
'rb') as f:
all_items = pickle.load(f)
titles = [(e[0], e[1]) for e in all_items]
print(titles[:100])
max_seq_length=64
tokenized_output = tokenizer.batch_encode_plus(
titles[:5], max_length=max_seq_length,
pad_to_max_length=False)
print(tokenized_output)
# ###### Getting max seq length
cuisine_to_lens = {}
for cuisine in os.listdir('/home/doordash-by-category'):
if os.path.isdir('/home/doordash-by-category/{}'.format(cuisine)):
continue
print(cuisine)
with open(os.path.join('/home/doordash-by-category', cuisine),
'rb') as f:
all_items = pickle.load(f)
# titles = [e[0] for e in all_items]
titles = all_items
random.shuffle(titles)
tokenized_output = tokenizer.batch_encode_plus(
titles[:1000], max_seq_length=128,
pad_to_max_length=False)
lens = [len(input_ids) for input_ids in tokenized_output['input_ids']]
cuisine_to_lens[cuisine] = lens
{c: (max(l), np.mean(l)) for c, l in cuisine_to_lens.items()}
# ### Saving tokenization
rootdir = '/home/doordash-by-dish-no-and/title-tokenized/bert-base-multilingual-cased'
max_seq_length = 64
assert os.path.exists(rootdir)
file_pattern = "titles_{cuisine}_{max_seq_len}_{input_key}"
# +
do_clean = True
def format_valid(title):
title = " ".join(title.split()) # whitespace to " "
title = title.rstrip().lstrip()
title = title.replace("-", " ")
return title
def check_valid(title):
check = "".join(title.split()) # remove whitespace
check = check.replace("-", "") # remove -, allowed
return check.isalpha()
# -
targets_to_categories = {
# Label to list of filenames corresponding to that label
'mexican': ['mexican'],
'chinese': ['chinese'],
'american': ['american', 'burgers'],
'italian': ['italian', 'pasta'],
'thai': ['thai'],
'indian': ['indian'],
'japanese': ['japanese', 'ramen', 'sushi'],
'other': ['african', 'alcohol', 'argentine', 'australian',
'bakery', 'belgian', 'brazilian', 'burmese', 'desserts',
'drinks', 'ethiopian', 'filipino', 'french',
'german', 'greek', 'korean', 'vietnamese', 'poke']
}
all_categories = [item for sublist in targets_to_categories.values() for item in sublist]
all_categories = [
'burger', 'other', 'pizza', 'salad', 'sandwich', 'soup', 'sushi']
print(max_seq_length)
file_pattern = "titles_{cuisine}_{max_seq_len}_{input_key}"
lens = {}
for cuisine in all_categories:# os.listdir('/home/doordash-by-category'):
if os.path.isdir('/home/doordash-by-dish-no-and/{}'.format(cuisine)):
# Not a real cuisine, for example bert-base-multilingual-cased is a folder containing tokenizations
continue
with open(os.path.join('/home/doordash-by-dish-no-and', cuisine), 'rb') as f:
all_items = pickle.load(f)
titles = [e[0] for e in all_items]
if do_clean:
titles = [format_valid(t) for t in titles if check_valid(t)]
# titles = [(format_valid(t[0]), t[1]) for t in titles if check_valid(t[0])]
lens[cuisine] = len(titles)
# if os.path.exists(os.path.join(
# rootdir, file_pattern.format(
# cuisine=cuisine, max_seq_len=max_seq_length,
# input_key="input_ids"))):
# # Tokenziation already exists in the given folder
# continue
print(cuisine, len(titles))
tokenized_output = tokenizer.batch_encode_plus(
titles,
max_length=max_seq_length,
pad_to_max_length=True)
print("Done tokenizing")
for input_key, arr in tokenized_output.items():
filename = os.path.join(rootdir,
file_pattern.format(cuisine=cuisine,
max_seq_len=max_seq_length,
input_key=input_key))
arr = np.array(arr)
assert arr.shape == (len(titles), max_seq_length)
fp = np.memmap(filename, dtype='int64', mode='w+',
shape=arr.shape)
fp[:] = arr[:]
del fp
with open(os.path.join(rootdir, 'lens.pkl'), 'wb') as f:
# Keep lens which is needed for loading a memmap
pickle.dump(lens, f)
# # Dataloader
import torch
import itertools
from collections import Counter, OrderedDict, defaultdict
from torch.utils.data import DataLoader
# +
class IterableTitles(torch.utils.data.IterableDataset):
def __init__(self, cuisine, root_dir, max_seq_length, len_dict):
super(IterableTitles).__init__()
self.cuisine = cuisine
self.max_seq_length = max_seq_length
self.datafile_pattern = os.path.join(
root_dir,
'titles_{}_{}_{{}}'.format(cuisine, max_seq_length))
self.shape = (len_dict[cuisine], max_seq_length)
self.length = len_dict[cuisine]
def __len__(self):
return self.length
def __iter__(self):
input_key_to_memmap = {}
for input_key in ['input_ids',
'attention_mask',
'token_type_ids']:
datafile = self.datafile_pattern.format(input_key)
fp = np.memmap(
datafile, dtype='int64', mode='r+',
shape=self.shape)
input_key_to_memmap[input_key] = fp
while True:
i = random.choice(range(self.shape[0]))
#for i in itertools.cycle(range(self.shape[0])):
yield (
input_key_to_memmap['input_ids'][i],
input_key_to_memmap['token_type_ids'][i],
input_key_to_memmap['attention_mask'][i])
class MultiStreamDataLoader:
def __init__(self, targets_to_categories, batch_size, rootdir):
self.targets = list(sorted(targets_to_categories.keys()))
self.targets_to_categories = targets_to_categories
self.categories_to_target = OrderedDict()
self.targets_to_categories_weights= {}
self.categories_to_dataset = {}
self.categories_to_dataset_iter = {}
with open(os.path.join(rootdir, 'lens.pkl'), 'rb') as f:
self.categories_to_len = pickle.load(f)
for t, list_of_c in targets_to_categories.items():
for c in list_of_c:
self.categories_to_target[c] = t
dataset = IterableTitles(c, rootdir, 64, self.categories_to_len)
self.categories_to_dataset[c] = dataset
self.categories_to_dataset_iter[c] = iter(DataLoader(dataset, batch_size=None))
for t, c_list in self.targets_to_categories.items():
self.targets_to_categories_weights[t] = [self.categories_to_len[c] for c in c_list]
self.batch_size = batch_size
self.total_samples = sum(self.categories_to_len.values())
def __len__(self):
return self.total_samples//self.batch_size
def __iter__(self):
while True:
buffer = []
labels = []
target_choices = random.choices(self.targets, k=self.batch_size)
category_choices = []
for t in target_choices:
category_choices.append(random.choices(
self.targets_to_categories[t],
weights=self.targets_to_categories_weights[t],
k=1)[0])
category_counter = Counter(category_choices)
category_labels = []
for category, num_sample in category_counter.items():
category_labels.extend([category for _ in range(num_sample)])
l_num = self.targets.index(self.categories_to_target[category])
labels.extend([l_num for _ in range(num_sample)])
buffer.extend(
[next(self.categories_to_dataset_iter[category]) for _ in range(num_sample)]
)
yield (torch.stack([b[0] for b in buffer]),
torch.stack([b[1] for b in buffer]),
torch.stack([b[2] for b in buffer]),
torch.tensor(labels),
category_labels
)
# +
# rootdir = '/home/doordash-by-category/cleaned-tokenized/bert-base-multilingual-cased/'
# rootdir = '/home/doordash-by-category/title-desc-tokenized/bert-base-multilingual-cased/'
rootdir = '/home/doordash-by-dish-no-and/title-tokenized/bert-base-multilingual-cased'
# -
targets_to_categories = {
# Label to list of filenames corresponding to that label
'mexican': ['mexican'],
'chinese': ['chinese'],
'american': ['american', 'burgers'],
'italian': ['italian', 'pasta'],
'thai': ['thai'],
'indian': ['indian'],
'japanese': ['japanese', 'ramen', 'sushi'],
'other': ['african', 'argentine', 'australian',
'bakery', 'belgian', 'brazilian', 'burmese', # 'desserts',
'drinks', 'ethiopian', 'filipino', 'french', # 'alcohol'
'german', 'greek', 'korean', 'vietnamese', 'poke']
}
targets_to_categories = {
'burger': ['burger'],
'other': ['other'],
'pizza': ['pizza'],
'salad': ['salad'],
'sandwich': ['sandwich'],
'soup': ['soup'],
'sushi': ['sushi']
}
ds = MultiStreamDataLoader(targets_to_categories,
batch_size=800,
rootdir=rootdir)
ds.targets
# +
# ds.targets_to_categories_weights
# -
[(t, sum(w)) for t, w in ds.targets_to_categories_weights.items()]
for batch_num, batch in enumerate(ds):
if batch_num == 5:
break
print(Counter(batch[3].numpy()))
input_ids = batch[0]
labels = batch[3]
categories = batch[4]
for i, ids in enumerate(input_ids):
print(
ds.targets[labels[i]], "({})".format(categories[i]),
":",
tokenizer.convert_tokens_to_string(
tokenizer.convert_ids_to_tokens(ids, skip_special_tokens=True)),
# "\n",
# ids
)
print("=====")
|
notebooks/Doordash data preprocessing.ipynb
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Q_learning
# +
import gym
import math
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as T
# Create the Cart-Pole game environment
env = gym.make('CartPole-v1')
# Number of possible actions
print('Number of possible actions:', env.action_space.n)
# -
# action: 2
#
# left and right
# +
# set up matplotlib
is_ipython = 'inline' in matplotlib.get_backend()
if is_ipython:
from IPython import display
plt.ion()
# if gpu is to be used
if torch.cuda.is_available():
print('>>> use cuda to train')
device = torch.device('cuda')
else:
print('>>> use cpu to train')
device = torch.device('cpu')
# -
|
reinforcement_learning/Q_learning/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
# ---
# # Example 8.1: Piston Exergy Analysis
#
# *<NAME>, Ph.D., P.E.<br>
# University of Kentucky - Paducah Campus<br>
# ME 321: Engineering Thermodynamics II<br>*
# ## Problem Statement
# The piston cylinder shown below is initially at a state of $T_1=60^\circ\text{C}$, $P_1=200\,\text{kPa}$. Heat is added to the system from a $500^\circ\text{C}$ reservoir until the final pressure is $400\,\text{kPa}$. The mass of the air is $2\,\text{kg}$, the spring constant is $1000\,\text{kN/m}$, and the cross sectional area of the piston is $A_p=0.1\,\mathrm{m^2}$. The piston moves $0.1\,\text{m}$ before contacting the linear spring.
# * (a) How much work is done by the air in the cylinder?
# * (b) How much heat transfer took place?
# * (c) What is the entropy generation, $S_{gen}$?
# * (d) Sketch and label a $T$-$s$ diagram of the air.
# * (e) How much exergy is stored in the system at the and at the end of the process
# * (f) What is the change in exergy for the process?
# * (g) How much exergy was destroyed during the process?
# * (f) What is the second law efficiency of the process, $\eta_{II}$?
# ## Solution
#
# __[Video Explanation](https://uky.yuja.com/V/Video?v=3071305&node=10458695&a=1201605425&autoplay=1)__
# ### Python Initialization
# We'll start by importing the libraries we will use for our analysis and initializing dictionaries to hold the properties we will be usings.
# + jupyter={"outputs_hidden": false}
from kilojoule.templates.kSI_C import *
air = idealgas.Properties('Air')
# -
# ### Given Parameters
# We now define variables to hold our known values.
# + jupyter={"outputs_hidden": false}
T[0] = Quantity(20,'degC') # dead state temperature
p[0] = Quantity(1,'bar') # dead state pressure
T[1] = Quantity(60,'degC') # initial temperature
p[1] = Quantity(200,'kPa') # initial pressure
p_final = Quantity(400,'kPa') # final pressure
A_p = Quantity(0.1,'m^2') # piston area
Delta_x = Quantity(0.1,'m') # distance between initial state and spring
m = Quantity(2,'kg') # mass
T_R = Quantity(500,'degC') # temperature of heat reservoir
k = Quantity(1000,'kN/m') # spring constant
Summary();
# -
# ### Assumptions
# - Negligible changes in kinetic energy
# - Negligible changes in potential energy
# - Isobaric from 1-2
# - Spring restrained from 2-3
# - Treat air as ideal gas
# + jupyter={"outputs_hidden": false}
# %%showcalc
p[2] = p[1]
p[3] = p_final
R = air.R
# -
# ### (a) How much work is done by the air in the cylinder?
# Since we are treating air as in ideal gas and we know both the temperature and the pressure at state 1, we can determine the specific volume at state 1. To do this we can either solve the ideal gas law for $v$ or we can use the `air` property tables we imported above.
# + jupyter={"outputs_hidden": false}
# %%showcalc
v_tables = air.v(T[1], p[1])
v_ig = R*T[1].to('K')/p[1]
v[1] = v_ig
# -
# The initial volume can then be found with the mass and the specific volume
# + jupyter={"outputs_hidden": false}
# %%showcalc
Vol[1] = m*v[1]
# -
# The change in volume for 1 to 2 due to the expansion of the fluid can be calculated with the cross-sectional area of the piston and the space between the piston and the spring
# + jupyter={"outputs_hidden": false}
# %%showcalc
Vol[2] = Vol[1] + Delta_x*A_p
# -
# The process from 1 to 2 is isobaric so the boundary work, $W_{1\to2}=\int_1^2p\ dv$, can be evaluated by pulling the pressure (constant) out of the integral
# + jupyter={"outputs_hidden": false}
# %%showcalc
W_1_to_2 = p[1]*(Vol[2]-Vol[1])
W_1_to_2.ito('kJ')
# -
# The spring must provide enough force to support the change in pressure. So the spring relations can be used to determine the necessary change in volume by solving the following equation for $\Delta V$
# $$\Delta p=\frac{k}{A^2}\Delta V$$
# + jupyter={"outputs_hidden": false}
# %%showcalc
Vol[3] = Vol[2] + (p[3]-p[2])*A_p**2/k
# -
# The work from 2 to 3 is most easily calculated by looking at the area under the curve on the $p$-$V$ diagram. Recall that the pressure varies linearly with the change in volume for a piston in contact with an ideal spring
# + jupyter={"outputs_hidden": false}
# %%showcalc
W_2_to_3 = (p[3]+p[2])/2*(Vol[3]-Vol[2])
W_2_to_3.ito('kJ')
# -
# The total work is then the summation the two processes
# + jupyter={"outputs_hidden": false}
# %%showcalc
# Work from 1 to 3
W_1_to_3 = W_1_to_2 + W_2_to_3
W_tot = W_1_to_3
# -
# #### (b) How much heat transfer took place?
# We need two independent properties at state 3. We know the pressure and we can find the specific volume from the mass and total volume
# + jupyter={"outputs_hidden": false}
# %%showcalc
v[3] = Vol[3]/m
# -
# We now have enough information to look up the final temperature and the internal energy at the beginning and the end
# + jupyter={"outputs_hidden": false}
# %%showcalc
T[3] = air.T(p[3],v[3])
u[1] = air.u(T[1],p[1])
u[3] = air.u(T[3],p[3])
# -
# The first law can be applied from state 1 to state 3 to determine the total heat transfer for the process
# + jupyter={"outputs_hidden": false}
# %%showcalc
# 1st Law
Q_1_to_3 = m*(u[3]-u[1]) + W_1_to_3
# -
# #### (c) What is the entropy generation, $S_{gen}$?
# To apply the 2nd law from 1 to 3, we will need the specific entropies, which we can look up with the same two independent intensive properties as the other properties
# + jupyter={"outputs_hidden": false}
# %%showcalc
# Entropies from property tables
s[1] = air.s(T[1],p[1])
s[3] = air.s(T[3],p[3])
# -
# The 2nd law can then be solved for the entropy generation.
# + jupyter={"outputs_hidden": false}
# %%showcalc
# 2nd Law
S_gen = m*(s[3]-s[1]) - Q_1_to_3/T_R.to('K')
# -
# #### (d) Sketch a $T$-$s$ diagram of the air
# + jupyter={"outputs_hidden": false}
# Still need to find T[2] and s[2]
v[2] = Vol[2]/m
T[2] = air.T(p[2], v[2])
s[2] = air.s(p[2], v[2])
# Plot T-s diagram
Ts = air.Ts_diagram(unit_system='SI_K')
Ts.plot_state(states[1])
Ts.plot_state(states[2])
Ts.plot_state(states[3])
Ts.plot_process(states[1],states[2],path='isobaric')
Ts.plot_process(states[2],states[3],path='unknown');
# -
# We can also visualize the process on a $p$-$v$ diagram
# + jupyter={"outputs_hidden": false}
# Plot p-v diagram
pv = air.pv_diagram(unit_system='SI_K')
pv.plot_state(states[1])
pv.plot_state(states[2],label_loc='north west')
pv.plot_state(states[3])
pv.plot_process(states[1],states[2],path='isobaric')
pv.plot_process(states[2],states[3],path='straight');
# -
# #### (e) How much exergy is stored in the system at the end of the process?
# The dead state properties are the properties the fluid would have if it were allowed to reach equilibrium with the surroundings, i.e. $T_0$ and $p_0$
# + jupyter={"outputs_hidden": false}
# %%showcalc
# Need dead state properties
v[0] = air.v(T[0], p[0])
Vol[0] = m*v[0]
u[0] = air.u(T[0], p[0])
s[0] = air.s(T[0], p[0])
# -
# The exergy at state 3 is then defined as the potential for the fluid to do work relative to the dead state
# + jupyter={"outputs_hidden": false}
# %%showcalc
# Exergy at 3
X[3] = m*(u[3]-u[0]) + p[0]*(Vol[3]-Vol[0]) - T[0].to('K')*m*(s[3]-s[0])
# -
# #### (f) What is the change in exergy for the process
# We can use the same method to caluclate the exergy at the beginning of the process
# + jupyter={"outputs_hidden": false}
# %%showcalc
# Exergy at 1
X[1] = m*(u[1]-u[0]) + p[0]*(Vol[1]-Vol[0]) - T[0].to('K')*m*(s[1]-s[0])
# -
# Then the change in exergy of the process is simply the difference between the two states
# + jupyter={"outputs_hidden": false}
# %%showcalc
# Change in Exergy
Delta_X_1_to_3 = X[3]-X[1]
# -
# #### (g) How much exergy was destroyed during the process?
# The exergy destruction can always be calculated as $T_0\cdot S_{gen}$
# + jupyter={"outputs_hidden": false}
# %%showcalc
# Exergy destruction
X_d = T[0].to('K')*S_gen
# -
# #### (f) Second Law Efficiency
# The second law efficiency is defined as the ratio of the recovered exergy to the expended exergy,
# \[\eta_{II} = \frac{X_{recovered}}{X_{expended}}=1-\frac{X_{destroyed}}{X_{expended}}\]
# We already know the exergy destruction, so we just need to find the expended exergy.
#
# In this case, the heat that was transferred to the system from the hot reservoir could have been used for some other purpose, such as to power a heat engine. So the expended exergy for this process is the decrease in potential of the reservoir. Since we are treating the reservoir as being constant temperature, we can't calculate a change in property of the reservoir, but we can calculate the amount of exergy the left the reservior through heat transfer.
# + jupyter={"outputs_hidden": false}
# %%showcalc
# Exergy expended is due to heat transfer from the high temperature reservoir
X_exp = (1 - T[0].to('K')/T_R.to('K'))*Q_1_to_3
# -
# Finally then second law efficiency can be calculated
# + jupyter={"outputs_hidden": false}
# %%showcalc
# Second Law Efficiency
eta_II = 1 - X_d/X_exp
# -
# #### Summary of Results
# + jupyter={"outputs_hidden": false}
Summary();
|
examples/ME321-Thermodynamics_II/01 - Chapter 8 Exergy/Ex8.1 Piston Exergy 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
# ---
import matplotlib.pyplot as plt
import numpy as np
# +
x = np.arange(-10, 2.1, 0.1)
y = (np.e)**x
plt.plot(x, y)
#x軸とy軸を同じスケールで
plt.axis('scaled')
#目盛りを刻む間隔を調整(1刻みならlist(range(...))で十分ですが、
#対数目盛りにしたいときなどラムダ式をいじってください)
plt.xticks(list(map(lambda x: x, np.arange(-10,3))))
plt.yticks(list(map(lambda y: y, np.arange(0, 8))))
#グリッド表示
plt.grid(linewidth=0.5)
#外枠をすべて非表示
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['bottom'].set_visible(False)
plt.gca().spines['left'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
#目盛りの表示設定
plt.tick_params(
axis='both',
which='both',
left=False, #外枠目盛りを非表示
bottom=False,
labelleft=False, #外枠目盛りの数字を非表示
labelbottom=False
)
#各形式で出力
#plt.savefig("expgraph.png", format="png", dpi=400, transparent=True)
#plt.savefig("expgraph.svg", format="svg", transparent=True)
#plt.savefig("expgraph.eps", format="eps", transparent=True)
#plt.savefig("expgraph.pdf", format="pdf", transparent=True)
plt.show()
# -
|
Graph of exponential function.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
# language: python
# name: python3
# ---
import matplotlib.pyplot as plt
# +
lux_train_rmse = [0.354708, 0.254875, 0.187462, 0.143280, 0.115620, 0.099290, 0.090214, 0.085400, 0.082946, 0.081716, 0.081096, 0.080789, 0.080636, 0.080560, 0.080524, 0.080505, 0.080494, 0.080489, 0.080486, 0.080484, 0.080483, 0.080482, 0.080481, 0.080481, 0.080481, 0.080481, 0.080481, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480, 0.080480]
lux_test_rmse = [ 0.354471, 0.254307, 0.186431, 0.141691, 0.113432, 0.096561, 0.087071, 0.082011, 0.079382, 0.078044, 0.077395, 0.077083, 0.076936, 0.076873, 0.076828, 0.076816, 0.076824, 0.076837, 0.076833, 0.076848, 0.076861, 0.076873, 0.076884, 0.076884, 0.076894, 0.076902, 0.076902, 0.076910, 0.076910, 0.076917, 0.076922, 0.076927, 0.076931, 0.076935, 0.076935, 0.076935, 0.076938, 0.076940, 0.076940, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942, 0.076942]
cora_pure_train_rmse = [ 0.432090, 0.392018, 0.367898, 0.349618, 0.340519, 0.333002, 0.326937, 0.323394, 0.320868, 0.318008, 0.314157, 0.313384, 0.310861, 0.308803, 0.306869, 0.302689, 0.301620, 0.299791, 0.295778, 0.294170, 0.290438, 0.287817, 0.284779, 0.281942, 0.280407, 0.277237, 0.276564, 0.275966, 0.274699, 0.272834, 0.271861, 0.271264, 0.269087, 0.268329, 0.265994, 0.265418, 0.264088, 0.263056, 0.261636, 0.261055, 0.260383, 0.259968, 0.259569, 0.258852, 0.257159, 0.256523, 0.255499, 0.255098, 0.253867, 0.252693, 0.250441, 0.249350, 0.248418, 0.247532, 0.247276, 0.245794, 0.245153, 0.244991, 0.244054, 0.242979, 0.241695, 0.241502, 0.240921, 0.240657, 0.240016, 0.238984, 0.238474, 0.237556, 0.236406, 0.235723, 0.235457, 0.235254, 0.234830, 0.233756, 0.232996, 0.231683, 0.230502, 0.229328, 0.228450, 0.228057, 0.227617, 0.227322, 0.227126, 0.226802, 0.225877, 0.225589, 0.224237, 0.223272, 0.222802, 0.222149, 0.221365, 0.220512, 0.219545, 0.219273, 0.218703, 0.218580, 0.218047, 0.217897, 0.217560, 0.217072]
cora_pure_test_rmse = [ 0.440070, 0.405776, 0.390287, 0.381504, 0.378461, 0.375217, 0.373769, 0.372908, 0.372518, 0.372961, 0.372598, 0.372650, 0.372665, 0.372680, 0.373379, 0.374072, 0.374624, 0.375155, 0.375248, 0.375917, 0.377324, 0.378189, 0.377435, 0.378346, 0.378431, 0.378903, 0.378869, 0.379433, 0.379746, 0.379594, 0.379803, 0.380014, 0.381218, 0.381313, 0.381157, 0.381469, 0.381337, 0.381946, 0.382452, 0.382552, 0.382854, 0.382834, 0.382921, 0.383377, 0.383977, 0.383900, 0.383785, 0.383791, 0.383795, 0.384224, 0.384869, 0.385062, 0.385424, 0.385597, 0.385636, 0.385759, 0.385895, 0.386108, 0.386217, 0.386781, 0.387715, 0.387711, 0.387834, 0.387847, 0.388070, 0.388415, 0.388629, 0.388858, 0.389134, 0.389385, 0.389736, 0.389808, 0.389835, 0.389639, 0.389874, 0.389957, 0.391317, 0.391137, 0.391509, 0.391989, 0.392469, 0.392614, 0.392635, 0.392734, 0.393202, 0.393475, 0.393947, 0.394419, 0.394629, 0.394731, 0.394894, 0.395034, 0.395227, 0.395131, 0.395358, 0.395353, 0.395697, 0.395750, 0.395767, 0.395921]
cora_purged_train_rmse = [ 0.232830, 0.226757, 0.221622, 0.217448, 0.214847, 0.212295, 0.207033, 0.204920, 0.202150, 0.199644, 0.195659, 0.191685, 0.189960, 0.187028, 0.183938, 0.181473, 0.178882, 0.176723, 0.174792, 0.173395, 0.171891, 0.168841, 0.168450, 0.164870, 0.161430, 0.159869, 0.158250, 0.157020, 0.155574, 0.152644, 0.151001, 0.148553, 0.147592, 0.146530, 0.144846, 0.144430, 0.142863, 0.142259, 0.140942, 0.139994, 0.138404, 0.136631, 0.134595, 0.133863, 0.132215, 0.131196, 0.130777, 0.130342, 0.129397, 0.129101, 0.127121, 0.126712, 0.124736, 0.123392, 0.122190, 0.121083, 0.119904, 0.119527, 0.117712, 0.116598, 0.116434, 0.116010, 0.114914, 0.114791, 0.113538, 0.112062, 0.111481, 0.110043, 0.108504, 0.106386, 0.104649, 0.103829, 0.102232, 0.100902, 0.099108, 0.098725, 0.096515, 0.094461, 0.093998, 0.092970, 0.090993, 0.090529, 0.089539, 0.088987, 0.088841, 0.088015, 0.087153, 0.085877, 0.085390, 0.084949, 0.083427, 0.083345, 0.083221, 0.081994, 0.081226, 0.080995, 0.080643, 0.079933, 0.079542, 0.078420]
cora_purged_test_rmse = [ 0.254183,0.255058,0.256574,0.257267,0.257720,0.258277,0.260088,0.260276,0.261661,0.262496,0.262833,0.264492,0.264454,0.265813,0.265785,0.266318,0.266525,0.266934,0.267978,0.268153,0.268549,0.268268,0.268340,0.268977,0.270257,0.270788,0.271319,0.271888,0.272242,0.272574,0.272841,0.273130,0.273247,0.273699,0.274152,0.274219,0.274797,0.275233,0.275507,0.275417,0.275210,0.275608,0.276248,0.276957,0.277409,0.277504,0.277436,0.277459,0.277720,0.277822,0.278057,0.278273,0.279135,0.279970,0.279899,0.279905,0.280132,0.280304,0.281040,0.281551,0.281712,0.281680,0.282211,0.282261,0.282259,0.282878,0.282989,0.282958,0.283156,0.283607,0.284525,0.284676,0.284772,0.285152,0.285236,0.285530,0.285594,0.286653,0.286747,0.287140,0.287475,0.287572,0.287649,0.287721,0.287771,0.287823,0.287939,0.288282,0.288313,0.288553,0.288656,0.288613,0.288634,0.288852,0.288994,0.289011,0.289161,0.289339,0.289493,0.289912 ]
# -
plt.title('luxembourg vs cora')
plt.plot(lux_train_rmse, label='training rmse')
plt.plot(lux_test_rmse, label='test rmse')
plt.plot(cora_pure_train_rmse, label='cora training rmse')
plt.plot(cora_pure_test_rmse, label='cora training rmse')
plt.legend(loc='lower center',bbox_to_anchor=(1.5, 0.5))
plt.show()
# +
plt.title('cora cleanup (removing all conflicting edges)')
plt.plot(cora_pure_train_rmse, label='pure training rmse')
plt.plot(cora_pure_test_rmse, label='pure training rmse')
plt.plot(cora_purged_train_rmse, label='cleaned train rmse')
plt.plot(cora_purged_test_rmse, label='cleaned test rmse')
plt.legend(loc='lower center', bbox_to_anchor=(1.25, 0.7))
plt.show()
# -
sp_train_rmse = [ 0.354517, 0.254493, 0.186864, 0.142450, 0.114565, 0.098048, 0.088840, 0.083960, 0.081462, 0.080210, 0.079589, 0.079282, 0.079132, 0.079058, 0.079022, 0.079004, 0.078995, 0.078990, 0.078988, 0.078987, 0.078987, 0.078986, 0.078986, 0.078986, 0.078986, 0.078986, 0.078986, 0.078986, 0.078986, 0.078986, 0.078986, 0.078986, 0.078986, 0.078986 ]
sp_test_rmse = [ 0.354542, 0.254551, 0.186965, 0.142604, 0.114775, 0.098308, 0.089139, 0.084285, 0.081804, 0.080561, 0.079946, 0.079644, 0.079496, 0.079424, 0.079389, 0.079372, 0.079364, 0.079360, 0.079358, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357, 0.079357 ]
plt.title('333SP vs cora')
plt.plot(sp_train_rmse, label='training rmse')
plt.plot(sp_test_rmse, label='test rmse')
plt.plot(cora_pure_train_rmse, label='cora training rmse')
plt.plot(cora_pure_test_rmse, label='cora training rmse')
plt.legend(loc='lower center', bbox_to_anchor=(1.25, 0.7))
plt.show()
rgg_train_rmse = [ 0.358520,0.262695,0.199550,0.159693,0.135931,0.122573,0.115418,0.111690,0.109778,0.108747,0.108168,0.107882,0.107646,0.107531,0.107410,0.107336,0.107249,0.107194,0.107128,0.107091,0.107030,0.106956,0.106913,0.106880,0.106832,0.106758,0.106647,0.106628,0.106568,0.106482,0.106401,0.106311,0.106218,0.106123,0.106064,0.106038,0.105941,0.105893,0.105831,0.105764,0.105755,0.105672,0.105599,0.105553,0.105512,0.105413,0.105351,0.105294,0.105237,0.105180,0.105135,0.105070,0.105000,0.104927,0.104890,0.104816,0.104758,0.104719,0.104686,0.104626,0.104588,0.104514,0.104438,0.104387,0.104332,0.104284,0.104261,0.104216,0.104165,0.104096,0.104046,0.103988,0.103941,0.103930,0.103877,0.103853]
rgg_test_rmse = [ 0.358685,0.263088,0.200275,0.160795,0.137361,0.124322,0.117407,0.113861,0.112087,0.111228,0.110786,0.110559,0.110488,0.110445,0.110408,0.110375,0.110380,0.110379,0.110377,0.110378,0.110375,0.110381,0.110371,0.110375,0.110388,0.110385,0.110411,0.110416,0.110410,0.110421,0.110406,0.110451,0.110459,0.110451,0.110482,0.110478,0.110487,0.110492,0.110504,0.110509,0.110509,0.110500,0.110517,0.110530,0.110537,0.110563,0.110570,0.110587,0.110595,0.110607,0.110633,0.110639,0.110652,0.110661,0.110663,0.110673,0.110678,0.110675,0.110672,0.110695,0.110695,0.110697,0.110694,0.110719,0.110725,0.110714,0.110719,0.110716,0.110740,0.110781,0.110780,0.110791,0.110803,0.110807,0.110820,0.110833]
plt.title('rgg_17 vs luxembourg')
plt.plot(lux_train_rmse, label='luxembourg training rmse')
plt.plot(lux_test_rmse, label='luxembourg test rmse')
plt.plot(rgg_train_rmse, label='rgg training rmse')
plt.plot(rgg_test_rmse, label='rgg training rmse')
plt.legend(loc='lower center',bbox_to_anchor=(1.3, 0.5))
plt.show()
# +
import igraph
edges = []
with open('../data/3-cluster.metis') as file:
line = file.readline()
nodecount, edgecount = [int(number) for number in line.split(' ')]
for i, line in enumerate(file):
for edge in [[i, int(node) - 1] for node in line.split(' ') if i < int(node) - 1]:
edges.append(edge)
print(edges)
graph = igraph.Graph(edges=edges)
graph.vs['label'] = range(1, graph.vcount() + 1)
graph.vs['color'] = [*(['green'] * 7), *(['red'] * 4), *(['lightblue'] * 6)]
graph.es['curved'] = False
# -
# +
weights_lux = [1.0,1,1,1,1,1,1,1,1,0.664, 1, 0.677, 1,1,1,1,1,0.381, 1, 1, 1, 1, 1, 1, 1, 0.99, 0.99]
graph.es['label'] = weights_lux
igraph.plot(graph, layout='kk')
# +
weights_cora_purged = [0.4, 0.62, 0.4, 0.4, 0.62, 0.52, 0.62, 0.74, 0.83, 0.74, 0.57, 0.65, 0.5, 0.5, 0.52, 0.64, 0.64, 0.52]
graph.es['label'] = weights_cora_purged
igraph.plot(graph, layout='kk')
# -
|
31.01.22/plot.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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 matplotlib.pyplot as plt
import random as rd
# +
def fx(theta):
#return sum(theta**2) #Q1a, Q1b
#return sum((theta-np.ones(theta.shape))**2) #Q1c, Q1d
return sum((y-np.matmul(x, theta))**2) #Q1e
def delop(theta0, dx):
theta = np.copy(theta0)
ans = np.zeros(theta0.shape)
for i in range(len(theta)):
theta[i] += dx
ans[i] = (fx(theta)-fx(theta0))/dx
theta[i] -= dx
return ans
# -
theta = np.vstack([50.2, 100.5])
alpha = 0.01
for i in range(1000):
theta -= alpha*delop(theta, 10**-9)
print(theta)
data = pd.read_excel('dat.xlsx')
x = np.array(data['x'])
x = (x-np.mean(x))/np.std(x)
y = np.array(data['y'])
plt.scatter(x, y)
plt.show()
# +
x = np.array([np.ones(len(x)), x]).transpose()
y = np.vstack(y)
theta = np.vstack([-50.0, 20.9])
print(x.shape, theta.shape)
alpha = 0.01
itr = 1000
for i in range(itr):
theta -= alpha*delop(theta, 10**-5)
print(theta)
# +
def hx(theta, x):
return np.matmul(x, theta)
def delop_stochastic(theta0, dx):
theta = np.copy(theta0)
ans = np.zeros(theta0.shape)
sample_indx = rd.randint(0, len(x)-1)
for i in range(len(theta)):
theta[i] += dx
ans[i] = ((hx(theta, x[sample_indx])-y[sample_indx])**2-(hx(theta0, x[sample_indx])-y[sample_indx])**2)/dx
theta[i] -= dx
return ans
# -
theta = np.vstack([-50.0, 20.9])
alpha = 0.01
itr = 10000
for i in range(itr):
theta -= alpha*delop_stochastic(theta, 10**-9)
print(theta, float(fx(theta)))
def next_alpha(alpha, theta0, da):
delj = delop(theta0, da**2)
fpxh = (fx(theta0 - (alpha+da)*delj)-fx(theta0 - (alpha)*delj))/da
fpx = (fx(theta0 - (alpha)*delj)-fx(theta0 - (alpha-da)*delj))/da
fppx = (fpxh-fpx)/da
return alpha - (fpx/fppx)
theta = np.vstack([50.0, 50.0])
itr = 10000
alpha = 50
for i in range(itr):
alpha = next_alpha(alpha, theta, 10**-4)
theta_nxt = theta - alpha*delop(theta, 10**-4)
if sum((theta_nxt-theta)**2) < 10**-10:
print('Convergence in {} iterations with alpha = {}!'.format(i, *alpha))
break
theta = theta_nxt.copy()
print(theta)
|
Smit/Sem V/ML/drive-download-20191116T123739Z-001/.ipynb_checkpoints/Lab2-checkpoint.ipynb
|
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # A Gentle Introduction to HARK In Perfect Foresight
#
# This notebook provides a simple, hands-on tutorial for first time HARK users -- and potentially first time Python users. It does not go "into the weeds" - we have hidden some code cells that do boring things that you don't need to digest on your first experience with HARK. Our aim is to convey a feel for how the toolkit works.
#
# For readers for whom this is your very first experience with Python, we have put important Python concepts in \textbf{boldface}.
#
# For those for whom this is the first time they have used a Jupyter notebook, we have put Jupyter instructions in \textit{italics}. Only cursory definitions (if any) are provided here. If you want to learn more, there are many online Python and Jupyter tutorials.
# %% code_folding=[]
# This cell has just a bit of initial setup. You can click the triangle to the left to expand it.
# Click the "Run" button immediately above the notebook in order to execute the contents of any cell
# WARNING: Each cell in the notebook relies upon results generated by previous cells
# The most common problem beginners have is to execute a cell before all its predecessors
# If you do this, you can restart the kernel (see the "Kernel" menu above) and start over
# %matplotlib inline
import matplotlib.pyplot as plt
# The first step is to be able to bring things in from different directories
import sys
import os
sys.path.insert(0, os.path.abspath('../lib'))
from util import log_progress
import numpy as np
import HARK
from time import clock
from copy import deepcopy
mystr = lambda number : "{:.4f}".format(number)
from HARK.utilities import plotFuncs
# %% [markdown]
# ## Your First HARK Model: Perfect Foresight
#
# We start with almost the simplest possible consumption model: A consumer with CRRA utility $U(C) = \frac{C^{1-\rho}}{1-\rho}$ has perfect foresight about everything except the (stochastic) date of death, which occurs with probability $\mathsf{D}$, implying a "survival probability" $(1-\mathsf{D}) < 1$. Permanent labor income $P_t$ grows from period to period by a factor $\Gamma_t$. At the beginning of each period $t$, the consumer has some amount of market resources $M_t$ (which includes both market wealth and currrent income) and must choose how much of those resources to consume $C_t$ and how much to retain in a riskless asset $A_t$ which will earn return factor $R$. The agent receives a flow of utility $U(C_t)$ from consumption (with CRRA preferences) and geometrically discounts future utility flows by factor $\beta$. Between periods, the agent dies with probability $\mathsf{D}_t$, ending his problem.
#
# The agent's problem can be written in Bellman form as:
#
# \begin{eqnarray*}
# V_t(M_t,P_t) &=& \max_{C_t} U(C_t) + \beta (1-\mathsf{D}_{t+1}) V_{t+1}(M_{t+1},P_{t+1}), \\
# & s.t. & \\
# %A_t &=& M_t - C_t, \\
# M_{t+1} &=& R (M_{t}-C_{t}) + Y_{t+1}, \\
# P_{t+1} &=& \Gamma_{t+1} P_t, \\
# \end{eqnarray*}
#
# A particular perfect foresight agent's problem can be characterized by values of risk aversion $\rho$, discount factor $\beta$, and return factor $R$, along with sequences of income growth factors $\{ \Gamma_t \}$ and death probabilities $\{\mathsf{D}_t\}$. To keep things simple, let's forget about "sequences" of income growth and mortality, and just think about an \textit{infinite horizon} consumer with constant income growth and survival probability.
#
# ## Representing Agents in HARK
#
# HARK represents agents solving this type of problem as \textbf{instances} of the \textbf{class} $\texttt{PerfForesightConsumerType}$, a \textbf{subclass} of $\texttt{AgentType}$. To make agents of this class, we must import the class itself into our workspace. (Run the cell below in order to do this).
# %%
from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType
# %% [markdown]
# The $\texttt{PerfForesightConsumerType}$ class contains within itself the python code that constructs the solution for the perfect foresight model we are studying here, as specifically articulated in [these lecture notes](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA/).
#
# To create an instance of $\texttt{PerfForesightConsumerType}$, we simply call the class as if it were a function, passing as arguments the specific parameter values we want it to have. In the hidden cell below, we define a \textbf{dictionary} named $\texttt{PF_dictionary}$ with these parameter values:
#
# | Param | Description | Code | Value |
# | :---: | --- | --- | --- |
# | $\rho$ | Relative risk aversion | $\texttt{CRRA}$ | 2.5 |
# | $\beta$ | Discount factor | $\texttt{DiscFac}$ | 0.96 |
# | $R$ | Risk free interest factor | $\texttt{Rfree}$ | 1.03 |
# | $1 - \mathsf{D}$ | Survival probability | $\texttt{LivPrb}$ | 0.98 |
# | $\Gamma$ | Income growth factor | $\texttt{PermGroFac}$ | 1.01 |
#
#
# For now, don't worry about the specifics of dictionaries. All you need to know is that a dictionary lets us pass many arguments wrapped up in one simple data structure.
# %% code_folding=[]
# This cell defines a parameter dictionary. You can expand it if you want to see what that looks like.
PF_dictionary = {
'CRRA' : 2.5,
'DiscFac' : 0.96,
'Rfree' : 1.03,
'LivPrb' : [0.98],
'PermGroFac' : [1.01],
'T_cycle' : 1,
'cycles' : 0,
'AgentCount' : 10000
}
# To those curious enough to open this hidden cell, you might notice that we defined
# a few extra parameters in that dictionary: T_cycle, cycles, and AgentCount. Don't
# worry about these for now.
# %% [markdown]
# Let's make an \textbf{object} named $\texttt{PFexample}$ which is an \textbf{instance} of the $\texttt{PerfForesightConsumerType}$ class. The object $\texttt{PFexample}$ will bundle together the abstract mathematical description of the solution embodied in $\texttt{PerfForesightConsumerType}$, and the specific set of parameter values defined in $\texttt{PF_dictionary}$. Such a bundle is created passing $\texttt{PF_dictionary}$ to the class $\texttt{PerfForesightConsumerType}$:
# %%
PFexample = PerfForesightConsumerType(**PF_dictionary)
# the asterisks ** basically say "here come some arguments" to PerfForesightConsumerType
# %% [markdown]
# In $\texttt{PFexample}$, we now have _defined_ the problem of a particular infinite horizon perfect foresight consumer who knows how to solve this problem.
#
# ## Solving an Agent's Problem
#
# To tell the agent actually to solve the problem, we call the agent's $\texttt{solve}$ \textbf{method}. (A \textbf{method} is essentially a function that an object runs that affects the object's own internal characteristics -- in this case, the method adds the consumption function to the contents of $\texttt{PFexample}$.)
#
# The cell below calls the $\texttt{solve}$ method for $\texttt{PFexample}$
# %%
PFexample.solve()
# %% [markdown]
# Running the $\texttt{solve}$ method creates the \textbf{attribute} of $\texttt{PFexample}$ named $\texttt{solution}.$ In fact, every subclass of $\texttt{AgentType}$ works the same way: The class definition contains the abstract algorithm that knows how to solve the model, but to obtain the particular solution for a specific instance (paramterization/configuration), that instance must be instructed to $\texttt{solve()}$ its problem.
#
# The $\texttt{solution}$ attribute is always a \textit{list} of solutions to a single period of the problem. In the case of an infinite horizon model like the one here, there is just one element in that list -- the solution to all periods of the infinite horizon problem. The consumption function stored as the first element (element 0) of the solution list can be retrieved by:
# %%
PFexample.solution[0].cFunc
# %% [markdown]
# One of the results proven in the associated [the lecture notes](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA/) is that, for the specific problem defined above, there is a solution in which the _ratio_ $c = C/P$ is a linear function of the _ratio_ of market resources to permanent income, $m = M/P$.
#
# This is why $\texttt{cFunc}$ can be represented by a linear interpolation. It can be plotted using the command below:
#
# %%
mPlotTop=10
plotFuncs(PFexample.solution[0].cFunc,0.,mPlotTop)
# %% [markdown]
# The figure illustrates one of the surprising features of the perfect foresight model: A person with zero money should be spending at a rate more than double their income ($\texttt{cFunc}(0.) \approx 2.08$). What gives?
#
# The answer is that we have not incorporated any constraint that would prevent the agent from borrowing against the entire PDV of future earnings -- human wealth.
#
# How much is that? An equivalent question is: What's the minimum value of $m_t$ where the consumption function is defined (that is, where the consumer has a positive expected _total wealth_ (the sum of human and nonuman wealth)? Let's check:
# %%
humanWealth = PFexample.solution[0].hNrm
mMinimum = PFexample.solution[0].mNrmMin
print("This agent's human wealth is " + str(humanWealth) + ' times his current income level.')
print("This agent's consumption function is defined down to m_t = " + str(mMinimum))
# %% [markdown]
# Yikes! Let's take a look at the bottom of the consumption function. In the cell below, set the bounds of the $\texttt{plotFuncs}$ function to display down to the lowest defined value of the consumption function.
# %%
# YOUR FIRST HANDS-ON EXERCISE!
# Fill in the value for "mPlotBottom" to plot the consumption function from the point where it is zero.
plotFuncs(PFexample.solution[0].cFunc,mPlotBottom,mPlotTop)
# %% [markdown]
# ## Changing Agent Parameters
#
# Suppose you wanted to change one (or more) of the parameters of the agent's problem and see what that does. We want to compare consumption functions before and after we change parameters, so let's make a new instance of $\texttt{PerfForesightConsumerType}$ by copying $\texttt{PFexample}$.
# %%
NewExample = deepcopy(PFexample)
# %% [markdown]
# In Python, you can set an \textbf{attribute} of an object just like any other variable. For example, we could make the new agent less patient:
# %%
NewExample.DiscFac = 0.90
NewExample.solve()
mPlotBottom = mMinimum
plotFuncs([PFexample.solution[0].cFunc,NewExample.solution[0].cFunc],mPlotBottom,mPlotTop)
# %% [markdown]
# (Note that you can pass a list of functions to $\texttt{plotFuncs}$ as the first argument rather than just a single function. Lists are written inside of [square brackets].)
#
# Let's try to deal with the "problem" of massive human wealth by making another consumer who has essentially no future income. We can almost eliminate human wealth by making the permanent income growth factor $\textit{very}$ small.
#
# In $\texttt{PFexample}$, the agent's income grew by 1 percent per period-- his $\texttt{PermGroFac}$ took the value 1.01. What if our new agent had a growth factor of 0.01 -- his income \textit{shrinks} by 99 percent each period? In the cell below, set $\texttt{NewExample}$'s discount factor back to its original value, then set its $\texttt{PermGroFac}$ attribute so that the growth factor is 0.01 each period.
#
# Important: Recall that the model at the top of this document said that an agent's problem is characterized by a sequence of income growth factors, but we tabled that concept. Because $\texttt{PerfForesightConsumerType}$ treats $\texttt{PermGroFac}$ as a \textit{time-varying} attribute, it must be specified as a \textbf{list} (with a single element in this case).
# %%
# Revert NewExample's discount factor and make his future income minuscule
your lines here!
# Compare the old and new consumption functions
plotFuncs([PFexample.solution[0].cFunc,NewExample.solution[0].cFunc],0.,10.)
# %% [markdown]
# Now $\texttt{NewExample}$'s consumption function has the same slope (MPC) as $\texttt{PFexample}$, but it emanates from (almost) zero-- he has basically no future income to borrow against!
#
# If you'd like, use the cell above to alter $\texttt{NewExample}$'s other attributes (relative risk aversion, etc) and see how the consumption function changes. However, keep in mind that _no solution exists_ for some combinations of parameters. HARK should let you know if this is the case if you try to solve such a model.
#
#
#
|
notebooks/Gentle-Intro-To-HARK-PerfForesightCRRA.ipynb
|
# ---
# jupyter:
# jupytext:
# text_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"}
# # Working with Messy Data
# ## Cleaning Data in OpenRefine
# <img src="assets/or-logo.png" alt="OpenRefine Logo" width="200" align="right"/>
# <br>
# <br>
# <b><NAME></b>, Data Services Librarian<br>
# <b><NAME></b>, Life Sciences Librarian<br>
# <br>
# February 04, 2020
#
#
#
# + [markdown] slideshow={"slide_type": "slide"}
# ## Agenda and Topics
#
# - Overview of the OpenRefine Application
# - Loading data
# - Performing data operations in OpenRefine
# - Creating workflow scripts
# - Format conversion
# - Saving data
# + [markdown] slideshow={"slide_type": "slide"}
# # Files and Links
#
# **Download Open Refine for your machine:** [https://openrefine.org/download.html]()
#
# **Useful GREL Cheat Sheet:** [Cheat Sheet](assets/GoogleRefineCheatSheet.pdf)
#
# **Data for lesson/exercises:** [Data](data/doaj-article-sample.csv)
# + [markdown] slideshow={"slide_type": "slide"}
# # What is OpenRefine?
#
# >OpenRefine is a browser-based graphical application for working with structured data.
#
# - 'A tool for working with messy data'
# - Works best with data in a simple tabular format
# - Can help split data up into more granular parts
# - Can help match local data up to other data sets
# - Can help enhance a data set with with data from other sources
# + [markdown] slideshow={"slide_type": "slide"}
# ## Scenario: Date Formats
#
# >When you have a list of dates which are formatted in different ways, and want to change all the dates in the list to a single common date format. For example:
#
# <img src="assets/ex1.png">
# + [markdown] slideshow={"slide_type": "slide"}
# ## Scenario: Multiple Elements in a Single Field
#
# >Sometimes multiple elements end up in a single cell.
#
# For example, an address field (in the first column). Each part of the address could be in a separate field:
#
# <img src="assets/ex2.png">
# + [markdown] slideshow={"slide_type": "slide"}
# # Let's Load Some data
#
# Save a copy of this [csv](data/doaj-article-sample.csv). We'll use this file for the rest of the lesson (*it's also the same file listed earlier!*).
#
# >You can upload or import files in a variety of formats including:
#
# - TSV
# - CSV
# - Excel
# - JSON
# - XML
# - Google Spreadsheet
# + [markdown] slideshow={"slide_type": "slide"}
# ## Create your First Project
#
# >**NOTE**: If OpenRefine does not open in a browser window, open your browser and type `http://1192.168.127.12:3333/` to take you to the OpenRefine interface.
#
# 1. Click `Create Project` from the left hand menu and select `Get data from This Computer`
# 2. Click `Choose Files` (or 'Browse') and locate the file which you have downloaded called `doaj-article-sample.csv`
# 3. Click `Next >>` - the next screen gives you options to ensure the data is imported correctly. The options vary depending on the type of data you are importing.
# 4. Click in the `Character encoding` box and set it to `UTF-8`
# 5. Ensure the first row is used to create the column headings by checking `Parse next 1 line(s) as column headers`
# 6. Make sure the `Parse cell text into numbers, dates, ...` box is not checked so OpenRefine doesn't try to automatically detect numbers
# 7. The Project Name box in the upper right corner will default to the title of your imported file. Click in the `Project Name` box to give it a different name.
# 8. Click `Create Project >>` at the top right of the screen. This will create the project and open it for you. Projects are saved as you work on them, so there is no need to save copies as you go along.
#
# + [markdown] slideshow={"slide_type": "slide"}
# ## The Layout of OpenRefine
#
# >OpenRefine displays data in a tabular format. As with a spreadsheet, the individual bits of data live in ‘cells’ at the intersection of a row and a column.
#
# >OpenRefine only displays a limited number of rows of data at one time. You can adjust the number choosing between 5, 10 (the default), 25 and 50 at the top left of the table of data.
#
# >Most options to work with data in OpenRefine are accessed from drop down menus at the top of the data columns. When you select an option in a particular column (e.g. to make a change to the data), it will affect all the cells in that column, but only that column.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Rows vs. Records
#
# >OpenRefine has two modes of viewing data: ‘Rows’ and ‘Records’. At the moment we are in Rows mode, where each row represents a single record in the data set - in this case, an article. In Records mode, OpenRefine can link together multiple rows as belonging to the same Record.
# + [markdown] slideshow={"slide_type": "slide"}
# # Basic Data Operations
# + [markdown] slideshow={"slide_type": "slide"}
# ## Splitting Cells
#
# >To see how this works in practice, we'll use the Author column. You should be able to see multiple names in each cell separated by the pipe symbol ( | ).
#
# If we want to work with each author name individually, we need to have each name in its own cell. To split the names into their own cells, we can use a `Split multi-valued cells` function:
#
# - Click the dropdown menu at the top of the Author column
# - Choose `Edit cells -> Split multi-valued cells`
# - In the prompt type the ( | ) symbol and click `OK`
# - Note that the rows are still numbered sequentially
# - Click the `Records` option to change to Records mode
# - Note how the numbering has changed - indicating that several rows are related to the same record
# + [markdown] slideshow={"slide_type": "slide"}
# ## Joining Cells
#
# A common workflow with multi-valued cells is:
#
# - Split multi-valued cells into individual cells
# - Modify/refine/clean individual cells
# - Join multi-valued cells back together
#
# Modifying cells will be covered later, but for now we will join the cells back together.
#
# - Click the dropdown menu at the top of the Author column
# - Choose `Edit cells -> Join multi-valued cells`
# - In the prompt type the ( | ) 'pipe' symbol
# - Here we are specifying the *delimiter* character for OpenRefine to use to join the values together
# - Click `OK` to join the Authors cells back together
#
# + [markdown] slideshow={"slide_type": "slide"}
# >You will now see that the split rows have gone away - the Authors have been joined into a single cell with the specified delimiter.
#
# Our Rows and Records values will now be the same since we do not have any more columns with split (multi-valued) cells.
#
# - Click both the `Rows` and `Records` options and observe how the numbers of Rows and Records are equal.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Choosing a Good Separator
#
# >The value that separates multi-valued cells is called a separator or delimiter. In the examples, we've seen the pipe character ( | ) has been used.
#
# Choosing the wrong separator can lead to problems. Consider the following multi-valued Author example with a pipe as a separator.
#
# >`<NAME> | <NAME>.`
#
# When we tell OpenRefine to split this cell on the pipe ( | ), we will get two separate authors.
#
# Now imagine that the document creator has chosen a **comma** as the separator instead of a pipe.
#
# >`Jones, Andrew, <NAME>.`
#
# > Can you spot the problems? Can you tell where one author stops and the next begins?
# + [markdown] slideshow={"slide_type": "slide"}
# > OpenRefine will split on **every** separator it encounters, so we'll end up with 4 authors, not two. We will get four "authors" because there are 3 commas separating the names.
#
# - **Author 1:** Jones
# - **Author 2:** Andrew
# - **Author 3:** Davis
# - **Author 4:** S.
#
# Splitting on a comma will not work with Authors because the names may include commas within them.
#
# >When creating a spreadsheet with multi-valued cells, choose a separator that will never appear in the cell values themselves. Commas, colons, and semi-colons should be avoided as separators.
# + [markdown] slideshow={"slide_type": "slide"}
# # Exercise: Splitting the 'Subjects' Column
#
# 1. What separator character is used in the **Subjects** cells?
# 2. How would you split these subject words into individual cells?
#
# <details>
# <summary>Solution</summary>
# <ol>
# <li>The subject words/headings are delimited with the pipe ( | ) character.</li>
# <li>To split the subject words into individual cells you need to:
# <ul>
# <li>Click the drop-down menu at the top of the Subjects column</li>
# <li>Choose `Edit cells -> Split multi-valued cells`</li>
# <li>In the prompt, type the ( | ) character and click OK</li></ul></ol>
# </details>
# + [markdown] slideshow={"slide_type": "slide"}
# # Exercise: Join the 'Subjects' Column Back Together
#
# 1. Using what we've learned join the Subjects back together.
#
# <details>
# <summary>Solution</summary>
# <ol>
# <li>The subject words/headings were previously delimited with the pipe ( | ) character.</li>
# <li>To join the split subject cells back into a single cell you need to:
# <ul>
# <li>Click the dropdown menu at the top of Subjects column</li>
# <li>Choose `Edit cells -> Join multi-valued cells`</li>
# <li>In the prompt type the ( | ) character and click OK</li></ul></ol></details>
# + [markdown] slideshow={"slide_type": "slide"}
# ## Faceting and Filtering
#
# > What is a facet?
#
# Facets provide methods for both getting an overview of the data and to improve the consistency of the data.
#
# >Facets work by grouping all like values that appear in a column.
#
# The simplest type of fact is called a **'Text facet'**. This groups all the text values in a column and lists each value with the number of records/rows it appears in.
#
# + [markdown] slideshow={"slide_type": "slide"}
# To create a **Text Facet** for a column, click on the drop-down menu at the top of the Publisher column and choose `Facet -> Text Facet`.
#
# >You can use a facet to filter the data displayed by clicking on one of these headings.
#
# Use the `Include` option to view the results of a facet. **Hint: hover over the facet value to see the `Include` option.**
#
# You can include multiple values from the facet in a filter at one time by using the `Include` option which appears when you put your mouse over a value in the facet.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Let's Create a Text Facet
#
# 1. From the Publisher column drop-down, choose `Facet -> Text Facet`. The facet will then appear in the left hand panel.
# 2. To select a single value, click the relevant line in the facet.
# 3. To select multiple values click the `Include` option on the appropriate line in the facet (which only appears when you mouse over the line).
# 4. You can 'invert' your selections to exclude data from view.
# 5. Include a value and then look at top to invert inclusion.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Exercise: Text Facets
#
# >Which licences are used for articles in this file?
#
# Use a `text facet` for the `license` column and answer these questions?
# 1. What is the most common license in the file?
# 2. How many articles in the file don't have a license assigned?
#
# <details><summary>Solution</summary><ol><li>Create a facet for the License column</li><li>Sort values by `count`</li><li>What is the most common License in the file? <b>Answer:</b> `CC BY`</li><li>How many articles in the file don't have a license assigned? <b>Answer:</b> `6`</li></ol></details>
# + [markdown] slideshow={"slide_type": "slide"}
# ## Text Filters
#
# > What is a filter?
#
# **Text Filters** query the text of column and return a result if there is a match. Text filters are applied by clicking the drop down menu at the top of the column you want to apply the filter to and choosing `Text filter`.
#
# >The text filter works a lot like a search box.
#
# **Tip: If you know regular expressions, you can also use them in a text filter.** <a href="https://xkcd.com/208/"target="_blank">Relevant xckd</a>
# + [markdown] slideshow={"slide_type": "slide"}
# ## Working with Filtered and Faceted Data
#
# >When you have filtered the data in OpenRefine, any operations you carry out will apply only to the rows that match the filter.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Exercise: Facets
#
# > Use the `Facet by blank` function to find all publications in this data set without a DOI
#
# <details><summary>Solution</summary><ol><li>On the `DOI` column drop-down, select `Customized facets -> Facet by blank`</li><li>`True` means that it is blank, so you can:<ul><li>Select `Include` on `True` in the facet to filter the list of publications to only those that don't have a DOI</li></ul></li></ol></details>
# + [markdown] slideshow={"slide_type": "slide"}
# ## Editing Data through Facets
#
# >You can use a facet to 'subset' your data and the value for several records simultaneously. To do this, mouse-over the facet value you want to edit and click the `edit` option that appears.
#
# This approach is useful in relatively small facet results.
#
# * Punctuation errors
# * Misspellings
# * Restricted or limited values, e.g., days of the week
#
# The list of values in the facet will update as you make edits.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Exercise: Correct Language Values via Facet
#
# > Create a `Text Facet` on the `Language` column and correct the variation in the `EN` and `English` values. *Replace `English` with `EN`.*
#
# <details><summary>Solution</summary><ol><li>Create a `Text facet` on the `Language` column</li><li>Notice that there is both `EN` and `English`</li><li>Put the mouse over the `English` value</li><li>Click `Edit`</li><li>Type `EN` and click `Apply`</li><li>See how the Language facet updates</li></ol></details>
# + [markdown] slideshow={"slide_type": "slide"}
# # Column Operations
# + [markdown] slideshow={"slide_type": "slide"}
# ## Reordering Columns
#
# >You can re-order the columns by clicking the drop-down menu at the top of the first column (labelled `All`), and choosing `Edit columns -> Re-order / remove columns...`.
#
# * Drag to re-order columns
# * Drop to remove columns
# + [markdown] slideshow={"slide_type": "slide"}
# ## Renaming Columns
#
# >You can rename a column by opening the drop-down menu at the top of the column that you would like to rename, and choosing `Edit column -> Rename this column`. You will then be prompted to enter the new column name.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Sorting Data
#
# >You can sort data in OpenRefine by clicking on the drop-down menu for the column you want to sort on, and choosing `Sort`.
#
# A `Sort` drop-down menu will be displayed.
#
# Unlike in Excel, **Sorts** in OpenRefine are temporary. You can amend the sort, or you can remove it or make it permanent.
#
# >Sort multiple columns by sequentially adding sorts!
# + [markdown] slideshow={"slide_type": "slide"}
# ## Transformations
#
# >Facets, filters, and other operations in OpenRefine offer methods for getting an overview of the data and for making small changes across large sections of data.
#
# Sometimes there will be changes you want to make that cannot be achieved with facets and filters. Such changes include:
#
# - Splitting data that is in a single column into multiple columns
# - Standardizing the format of data in a column without changing the values
# - Extracting a particular data type from a longer text string
#
# >OpenRefine provides **Transformations**, or methods of manipulating data in columns.
#
# Transformations are written in **GREL** (General Refine Expression Language). GREL expressions are similar to Excel formulae, but emphasize manipulating text.
#
# Full documentation for the GREL is available at [https://github.com/OpenRefine/OpenRefine/wiki/General-Refine-Expression-Language](). This tutorial covers only a small subset of the commands available.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Common Transformations
#
# > Some transformations have shortcuts available directly through the drop-down menu.
#
# Below is a table of common transformations and the equivalent GREL expression.
#
# <img src="assets/ex3.png">
#
# + [markdown] slideshow={"slide_type": "slide"}
# ## Exercise: Correct Publisher Data
#
# 1. Create a text facet on the `Publisher` column
# 2. Note that the values there are two that look identical - why does this value appear twice? What can you do to fix it?
#
# <details><summary>Solution</summary>There is extra whitespace in the cell!<ol><li>On the publisher column use the drop-down menu to select `Edit cells -> Common transformations -> Trim leading and trailing whitespace`</li><li>Look at the publisher facet now - has it changed? <b>If it hasn't, try clicking the `Refresh` option to force an update.</b></li></ol></details>
# + [markdown] slideshow={"slide_type": "slide"}
# ## Writing Transformations
#
# Select a column on which to perform a transformation and choose `Edit cells -> Transform...`. In the prompt you have a place to write a script and then the ability to preview the effect the transformation would have on 10 rows of your data.
#
# >The simplest GREL expression is `value` - which means the value of a given cell in the current column.
#
# GREL functions are written by passing a value of some kind (text string, data, number, etc.) to a GREL function. Functions have two basic types of syntax:
#
# - `value.function(options)`
# - `function(value, options)`
#
# >Either is valid, but we'll use the first syntax from here on.
# + [markdown] slideshow={"slide_type": "slide"}
# ## Try it Out: Put Titles into Title Case
#
# >Use Facets and the GREL expression `value.toTitlecase()` to put the titles in Title Case.
#
# 1. Facet by publisher.
# 2. Select "Akshantala Enterprises" and "Society of Pharmaceutical Technocrats"
# 3. To select multiple values in the facet use the `include` link that appears to the right of the facet
# 4. See that the Titles for these are all in uppercase
# 5. Click the dropdown menu on the Title column
# 6. Choose `Edit cells -> Transform...`
# 7. In the expression box type `value.toTitlecase()`
# 8. In the Preview pane under `value.toTitlecase()` you can see what the effect of running this will be
# 9. Click `OK`
#
# + [markdown] slideshow={"slide_type": "slide"}
# ## Transformations for Strings, Numbers, Dates, and Booleans
#
# > Each datum in OpenRefine has a 'type'. The most common type is 'string', or a piece of text.
#
# ### Dates and Numbers
#
# >So far we’ve been looking only at ‘String’ type data and, for the most part, it's okay to treat numbers as strings.
#
# However, some operations and transformations only work on ‘number’ or ‘date’ types. The simplest example is sorting values in numeric or date order. To carry out these functions we need to convert the values to a date or number first.
# + [markdown] slideshow={"slide_type": "slide"}
# ### Reformat a Date
#
# 1. Remove any existing Facets or Filters.
# 2. On the Date column, use the drop-down menu to select `Edit cells -> Transform`.
# 3. In the expression box, type `value.toDate("dd/MM/yyyy")` and press OK (**Note: the original creators of this dataset are from the UK - notice the regional date format**).
# 4. Notice how the values are displayed in green and follow the ISO 8691 data convention - this indicates that values are now stored as date data types.
# 5. On the Date column drop-down, select `Edit column -> Add column based on this column`. Using this function you can created a new column, while preserving the old column.
# 6. In the `New column name` type "Formatted Date".
# 7. Let's change the regional date format to US. In the expression box, type `value.toString("MM/dd/yyyy")`
# + [markdown] slideshow={"slide_type": "slide"}
# ### Booleans
#
# > Booleans are binary values that can either be `true` or `false`. Booleans can be used directly in OpenRefine cells, but they are more useful when used in transformations as part of a GREL expression.
#
# For example, `value.contains("test")` generates a boolean value of `true` or `false` depending on whether the current value in the cell contains the string 'test' anywhere.
#
# >Such tests can be combined with other expressions to create complex transformations.
#
# For example, `if(value.contains("test"),"Test data",value)` replaces a cell value with the words "Test data" only *if* if the value in the cell contains the string "test" anywhere.
# + [markdown] slideshow={"slide_type": "slide"}
# # Undo and Redo
#
# >OpenRefine lets you undo, and redo, any number of steps you have taken in cleaning the data. This means you can always explore new transformations and 'undo' if needed.
#
# OpenRefine records the steps you have taken and even allows you to export steps in order to apply them to another data set.
#
# The `Undo` and `Redo` options are accessed via the lefthand panel.
#
# To undo, click on the last step you want to preserve in the list and it will revert back to that step.
#
# **Note: reverting to an earlier step will 'grey out' all steps after that point. Once you record a new step, all 'greyed out' steps will be overwritten.**
# + [markdown] slideshow={"slide_type": "slide"}
# ## Create a Workflow Script
#
# >You can save a set of steps to be used later, for example in a different project, you can click the `Extract` button.
#
# This gives you the option to select steps that you want to save, and extract a code for those steps (stored in JSON). You can save the JSON in a plain text file for later.
#
# >To apply a set of steps you have copied or saved, use the `Apply` button and paste in the JSON.
#
# **Note: Transformations exported will only work on similarly structured data, e.g., if you have no "Date" column but have transformations that require this column, none of these transformations will occur.**
# + [markdown] slideshow={"slide_type": "slide"}
# # Export your Data
#
# >Once you have finished working with a dataset in OpenRefine, you may wish to export or 'save' your dataset. The export options are access through the `Export` button at the top right of the OpenRefine interface.
#
# Export formats include:
#
# - HTML
# - Excel
# - Comma and Tab separated (CSV/TSV)
# - Custom exports for specific fields, including headers/footers, and specifying exact formats
# + [markdown] slideshow={"slide_type": "slide"}
# # Thanks!
#
# **<NAME>**<br>
# ✉️ [<EMAIL>](mailto:<EMAIL>)<br>
# 🖥 [lib.umd.edu/data](https://lib.umd.edu/data)
#
#
# **<NAME>**<br>
# ✉️ [<EMAIL>](mailto:<EMAIL>)<br>
#
#
# Workshop materials were adapted from ['Library Carpentry: OpenRefine'](https://librarycarpentry.org/lc-open-refine/) under a [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/) License. Content was edited for time and audience.
# -
|
200206-openrefine.ipynb
|