code stringlengths 38 801k | repo_path stringlengths 6 263 |
|---|---|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
project_dir = Path("__file__").resolve().parents[2]
project_dir
wind = pd.read_csv('{}/data/processed/resources/wind_processed.csv'.format(project_dir))
wind.head()
wind = wind.drop("Unnamed: 0", axis=1)
wind.head()
wind.plot()
wind.time = pd.to_datetime(wind.time)
wind_subset = wind[wind.time > "2010"]
wind_subset.head()
wind_subset['date'] = wind_subset['time'].dt.date
wind_subset['hour'] = wind_subset['time'].dt.hour
wind_subset.head()
each_day = wind_subset.pivot(index='date', columns='hour', values='offshore')
each_day = each_day.dropna()
each_day.head()
# +
# Visualise as PCA
pca = PCA(n_components=2)
pca_results = pca.fit_transform(each_day)
principal_df = pd.DataFrame(data = pca_results, columns = ['principal component 1', 'principal component 2'])
principal_df.plot()
# -
plt.scatter(principal_df['principal component 1'],principal_df['principal component 2'])
# t-SNE
# +
tsne = TSNE(n_components=2, random_state=0, n_iter=2000, early_exaggeration=4)
each_day_2d = tsne.fit_transform(each_day)
plt.scatter(each_day_2d[:,0], each_day_2d[:,1])
plt.show()
| notebooks/exploratory_stage/2.0-ajmk-explore-wind-data-clusters.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] colab_type="text" id="iPpI7RaYoZuE"
# ##### Copyright 2018 The TensorFlow Authors.
# + cellView="form" colab={} colab_type="code" id="hro2InpHobKk"
#@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="U9i2Dsh-ziXr"
# # Tensors and Operations
# + [markdown] colab_type="text" id="Hndw-YcxoOJK"
# <table class="tfo-notebook-buttons" align="left">
# <td>
# <a target="_blank" href="https://www.tensorflow.org/alpha/tutorials/eager/basics"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
# </td>
# <td>
# <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/tutorials/eager/basics.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
# </td>
# <td>
# <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/eager/basics.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
# </td>
# </table>
# + [markdown] colab_type="text" id="6sILUVbHoSgH"
# This is an introductory TensorFlow tutorial shows how to:
#
# * Import the required package
# * Create and use tensors
# * Use GPU acceleration
# * Demonstrate `tf.data.Dataset`
# + colab={} colab_type="code" id="miTaGiqV9RjO"
from __future__ import absolute_import, division, print_function
# !pip install tensorflow-gpu==2.0.0-alpha0
# + [markdown] colab_type="text" id="z1JcS5iBXMRO"
# ## Import TensorFlow
#
# To get started, import the `tensorflow` module. As of TensorFlow 2.0, eager execution is turned on by default. This enables a more interactive frontend to TensorFlow, the details of which we will discuss much later.
# + colab={} colab_type="code" id="vjBPmYjLdFmk"
import tensorflow as tf
# + [markdown] colab_type="text" id="H9UySOPLXdaw"
# ## Tensors
#
# A Tensor is a multi-dimensional array. Similar to NumPy `ndarray` objects, `tf.Tensor` objects have a data type and a shape. Additionally, `tf.Tensor`s can reside in accelerator memory (like a GPU). TensorFlow offers a rich library of operations ([tf.add](https://www.tensorflow.org/api_docs/python/tf/add), [tf.matmul](https://www.tensorflow.org/api_docs/python/tf/matmul), [tf.linalg.inv](https://www.tensorflow.org/api_docs/python/tf/linalg/inv) etc.) that consume and produce `tf.Tensor`s. These operations automatically convert native Python types, for example:
#
# + cellView="code" colab={} colab_type="code" id="ngUe237Wt48W"
print(tf.add(1, 2))
print(tf.add([1, 2], [3, 4]))
print(tf.square(5))
print(tf.reduce_sum([1, 2, 3]))
# Operator overloading is also supported
print(tf.square(2) + tf.square(3))
# + [markdown] colab_type="text" id="IDY4WsYRhP81"
# Each `tf.Tensor` has a shape and a datatype:
# + colab={} colab_type="code" id="srYWH1MdJNG7"
x = tf.matmul([[1]], [[2, 3]])
print(x)
print(x.shape)
print(x.dtype)
# + [markdown] colab_type="text" id="eBPw8e8vrsom"
# The most obvious differences between NumPy arrays and `tf.Tensor`s are:
#
# 1. Tensors can be backed by accelerator memory (like GPU, TPU).
# 2. Tensors are immutable.
# + [markdown] colab_type="text" id="Dwi1tdW3JBw6"
# ### NumPy Compatibility
#
# Converting between a TensorFlow `tf.Tensor`s and a NumPy `ndarray` is easy:
#
# * TensorFlow operations automatically convert NumPy ndarrays to Tensors.
# * NumPy operations automatically convert Tensors to NumPy ndarrays.
#
# Tensors are explicitly converted to NumPy ndarrays using their `.numpy()` method. These conversions are typically cheap since the array and `tf.Tensor` share the underlying memory representation, if possible. However, sharing the underlying representation isn't always possible since the `tf.Tensor` may be hosted in GPU memory while NumPy arrays are always backed by host memory, and the conversion involves a copy from GPU to host memory.
# + colab={} colab_type="code" id="lCUWzso6mbqR"
import numpy as np
ndarray = np.ones([3, 3])
print("TensorFlow operations convert numpy arrays to Tensors automatically")
tensor = tf.multiply(ndarray, 42)
print(tensor)
print("And NumPy operations convert Tensors to numpy arrays automatically")
print(np.add(tensor, 1))
print("The .numpy() method explicitly converts a Tensor to a numpy array")
print(tensor.numpy())
# + [markdown] colab_type="text" id="PBNP8yTRfu_X"
# ## GPU acceleration
#
# Many TensorFlow operations are accelerated using the GPU for computation. Without any annotations, TensorFlow automatically decides whether to use the GPU or CPU for an operation—copying the tensor between CPU and GPU memory, if necessary. Tensors produced by an operation are typically backed by the memory of the device on which the operation executed, for example:
# + cellView="code" colab={} colab_type="code" id="3Twf_Rw-gQFM"
x = tf.random.uniform([3, 3])
print("Is there a GPU available: "),
print(tf.test.is_gpu_available())
print("Is the Tensor on GPU #0: "),
print(x.device.endswith('GPU:0'))
# + [markdown] colab_type="text" id="vpgYzgVXW2Ud"
# ### Device Names
#
# The `Tensor.device` property provides a fully qualified string name of the device hosting the contents of the tensor. This name encodes many details, such as an identifier of the network address of the host on which this program is executing and the device within that host. This is required for distributed execution of a TensorFlow program. The string ends with `GPU:<N>` if the tensor is placed on the `N`-th GPU on the host.
# + [markdown] colab_type="text" id="ZWZQCimzuqyP"
#
#
# ### Explicit Device Placement
#
# In TensorFlow, *placement* refers to how individual operations are assigned (placed on) a device for execution. As mentioned, when there is no explicit guidance provided, TensorFlow automatically decides which device to execute an operation and copies tensors to that device, if needed. However, TensorFlow operations can be explicitly placed on specific devices using the `tf.device` context manager, for example:
# + colab={} colab_type="code" id="RjkNZTuauy-Q"
import time
def time_matmul(x):
start = time.time()
for loop in range(10):
tf.matmul(x, x)
result = time.time()-start
print("10 loops: {:0.2f}ms".format(1000*result))
# Force execution on CPU
print("On CPU:")
with tf.device("CPU:0"):
x = tf.random.uniform([1000, 1000])
assert x.device.endswith("CPU:0")
time_matmul(x)
# Force execution on GPU #0 if available
if tf.test.is_gpu_available():
print("On GPU:")
with tf.device("GPU:0"): # Or GPU:1 for the 2nd GPU, GPU:2 for the 3rd etc.
x = tf.random.uniform([1000, 1000])
assert x.device.endswith("GPU:0")
time_matmul(x)
# + [markdown] colab_type="text" id="o1K4dlhhHtQj"
# ## Datasets
#
# This section uses the [`tf.data.Dataset` API](https://www.tensorflow.org/guide/datasets) to build a pipeline for feeding data to your model. The `tf.data.Dataset` API is used to build performant, complex input pipelines from simple, re-usable pieces that will feed your model's training or evaluation loops.
# + [markdown] colab_type="text" id="zI0fmOynH-Ne"
# ### Create a source `Dataset`
#
# Create a *source* dataset using one of the factory functions like [`Dataset.from_tensors`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensors), [`Dataset.from_tensor_slices`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensor_slices), or using objects that read from files like [`TextLineDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TextLineDataset) or [`TFRecordDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset). See the [TensorFlow Dataset guide](https://www.tensorflow.org/guide/datasets#reading_input_data) for more information.
# + colab={} colab_type="code" id="F04fVOHQIBiG"
ds_tensors = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])
# Create a CSV file
import tempfile
_, filename = tempfile.mkstemp()
with open(filename, 'w') as f:
f.write("""Line 1
Line 2
Line 3
""")
ds_file = tf.data.TextLineDataset(filename)
# + [markdown] colab_type="text" id="vbxIhC-5IPdf"
# ### Apply transformations
#
# Use the transformations functions like [`map`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#map), [`batch`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#batch), and [`shuffle`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle) to apply transformations to dataset records.
# + colab={} colab_type="code" id="uXSDZWE-ISsd"
ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)
ds_file = ds_file.batch(2)
# + [markdown] colab_type="text" id="A8X1GNfoIZKJ"
# ### Iterate
#
# `tf.data.Dataset` objects support iteration to loop over records:
# + colab={} colab_type="code" id="ws-WKRk5Ic6-"
print('Elements of ds_tensors:')
for x in ds_tensors:
print(x)
print('\nElements in ds_file:')
for x in ds_file:
print(x)
| site/en/r2/tutorials/eager/basics.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
# ---
# # ABS Retail Turnover 8501
# + [markdown] toc=true
# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#Python-set-up" data-toc-modified-id="Python-set-up-1"><span class="toc-item-num">1 </span>Python set-up</a></span></li><li><span><a href="#Get-data-from-ABS" data-toc-modified-id="Get-data-from-ABS-2"><span class="toc-item-num">2 </span>Get data from ABS</a></span></li><li><span><a href="#Plot" data-toc-modified-id="Plot-3"><span class="toc-item-num">3 </span>Plot</a></span></li><li><span><a href="#Finished" data-toc-modified-id="Finished-4"><span class="toc-item-num">4 </span>Finished</a></span></li></ul></div>
# -
# ## Python set-up
# +
# system imports
import sys
import pathlib
import calendar
# analytic imports
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
# local imports
from finalise_plot import finalise_plot
from abs_common import (
get_fs_constants,
get_plot_constants,
get_ABS_meta_and_data,
get_identifier
)
# pandas display settings
pd.options.display.max_rows = 999
pd.options.display.max_columns = 999
# plotting stuff
plt.style.use('ggplot')
# -
catalogue_id = '8501'
source, CHART_DIR, META_DATA = get_fs_constants(catalogue_id)
# ## Get data from ABS
# do the data capture and extraction
abs = get_ABS_meta_and_data(catalogue_id)
if abs is None:
sys.exit(-1)
# ## Plot
meta = abs[META_DATA]
RECENT, plot_times, plot_tags = get_plot_constants(meta)
# +
table = '1'
df = abs[table]
plots = meta[meta['Table'] == table]['Data Item Description'].unique()
series_type = "Seasonally Adjusted"
for plot in plots:
series, units = get_identifier(meta, plot,
series_type, table)
for start, tag in zip(plot_times, plot_tags):
frame = df[df.index >= start] if start else df
ax = frame[series].plot(lw=2)
title = f"Retail Trade: {plot}".replace(" ; Total (State) ; ", "")
title = title.replace(" ;", "")
finalise_plot(ax, title, units, tag, CHART_DIR,
rfooter=f'{source}s {table}',
lfooter=f'From {series_type.lower()} series')
# -
# ## Finished
print('Finished')
| notebooks/ABS Monthly Retail Turnover 8501.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
# ---
# ---
# ### Universidad de Costa Rica
# #### IE0405 - Modelos Probabilísticos de Señales y Sistemas
# ---
#
# # `Py8` - *Simulaciones aleatorias*
#
# > Conocidas como **simulaciones de Monte Carlo**, las simulaciones o experimentos aleatorios repiten una acción utilizando datos aleatorios para analizar sus resultados. El objetivo es conocer el comportamiento de un fenómeno o sistema para el cual se conoce el modelo de probabilidad de sus entradas y el modelo propio.
#
# ---
# ## Introducción
#
# Taca taca...
# ---
# ## 8.1 - Simulaciones aleatorias aplicadas a transformaciones de variables aleatorias
#
# Aun sin conocer una expresión para la función de densidad $f_Y(y)$ de una variable aleatoria $Y$ producto de una transformación $Y = T(X)$, es posible conocer el efecto que tiene esta transformación sobre una muestra de datos aleatorios con una distribución de probabilidad $X$ conocida.
#
# ### Ejemplo de una distribución normal con una transformación cuadrática
#
# A una distribución $X \sim \mathcal{N}(0, 0.7737)$ se aplica una transformación $Y = X^2$. Es útil visualizar los dos conjuntos de datos.
# +
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import csv
# Repeticiones
N = 500
# Distribución de X
Xva = stats.truncnorm(-2,2)
# Muestra de N valores aleatorios
X = Xva.rvs(N)
# Función aplicada sobre X
Y = X**2
# Crear histograma de X
a,b,c = plt.hist(X,20)
plt.show()
# Crear histograma de Y
a,b,c = plt.hist(Y,20)
plt.show()
# -
# ### Ejemplo de (alguna distribución) con (una transformación)
#
# (Hacer otros ejemplos similares al anterior, con otras distribuciones. Colocar además sobre el histograma de la transformación el pdf de la función encontrada vía analítica)
Xva.var()
# ---
# ## 8.2 - Ejemplo del canal de comunicaciones
#
# (La diferencia aquí es que hay que utilizar un `for` para hacer una operación varias veces)
#
# Mencionar el ruido **AWGN** (*additive white Gaussian noise*)
# +
# Número de bits
B = 1000
# Niveles de ruido (varianza de la gaussiana)
N = range(10)
# Generar bits aleatorios
# Con un for, agregar ruido AWGN a cada bit
# "Recibir" los bits y "decidir" si es 1 o 0
# Comparar con los bits originales y contar errores
# Crear gráfica
# -
# ## 8.3 - Ejemplo de la aproximación del número $\pi$
#
# Para incluir en reportes, es útil...
# ---
# ### Más información
#
# * [Página web](https://www.google.com/)
# * Libro o algo
# * Tutorial [w3schools](https://www.w3schools.com/python/)
# ---
# ---
#
# **Universidad de Costa Rica**
#
# Facultad de Ingeniería
#
# Escuela de Ingeniería Eléctrica
#
# ---
| Py8.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/GodfreyMamauag/CPEN-21A-CPE-1-2/blob/main/Laboratory%201.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="CP7Vt6OS3q5w"
# Laboratory 1
# + id="LgMcH5Ff3wFg" outputId="70b5daa8-d940-4179-9645-f0ba2f58c207" colab={"base_uri": "https://localhost:8080/"}
a=('Welcome to Python Programming')
print(a)
# + id="1AQa1nw135vw" outputId="23ecb40a-8e6f-422b-ac7d-a4ccd2f8095a" colab={"base_uri": "https://localhost:8080/"}
a=('<NAME>')
b=("Alfonso,Cavite")
c=("18")
print("Name: "+a)
print("address: "+b)
print("age: "+c)
| Laboratory 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
# ---
# # Sample tweets based on community module or hashtag groupings
#
# If you are using .ftree files, then follow the below imoprting and process.
#
# If you already have edge data, then proceed to importing your tweet corpus.
# ## Import .ftree files and process into respective network edge and node data per module
# +
import nttc
# 1. Retrieve directory of .ftree files and save each line of the file within a list of lists to per Period Dict
ftree_path = '../infomap/output/nets/ftree/ftree'
# regex is the file pattern in a dedicated directory, e.g.,
# # r"\d{1,2}" will match the '1' in p1_ftree.ftree
dict_map = nttc.batch_map(regex=r"\d{1,2}", path=ftree_path, file_type='ftree')
# Print sample ftree modules
print(
'1.\nIndices: ',
dict_map['1']['indices']['ftree_modules'],
'\n\nFirst 5 file lines of module section: ',
dict_map['1']['lines'][dict_map['1']['indices']['ftree_modules'][0]:5],
'\n\n'
)
# Print sample ftree links
five = dict_map['1']['indices']['ftree_links']['1']['indices'][0]+5
print(
'1.\nIndices for module 1 links: ',
dict_map['1']['indices']['ftree_links']['1']['indices'],
'\n\nFirst 5 lines of period 1, module 1 links section: ',
dict_map['1']['lines'][dict_map['1']['indices']['ftree_links']['1']['indices'][0]:five],
'\n\n'
)
# -
# Check output
dict_map['1']['indices']['ftree_links']['1']
copy_dict_map = dict_map
# Process each period's module edge data and stores as a DataFrame.
dict_with_edges = nttc.ftree_edge_maker(copy_dict_map)
dict_with_edges['1']['indices']['ftree_links']['1']['df_edges'][:5]
# Take full listified .ftree file and write per Period per Module hubs as a Dict
new_dict = dict_with_edges
dh = nttc.infomap_hub_maker(new_dict, file_type='ftree', mod_sample_size=10, hub_sample_size=-1)
print(
'2.\nSample hub: ',
dh['1']['info_hub']['1'][:5]
)
# Write edge and node lists per module:
## Parameters: (Tuple period range, Tuple module range, Dict of module data from infomap_hub_maker)
## Below params parse modules 1-10 in periods 1-10
dict_full = nttc.networks_controller((1,10),(1,10),dh)
# Test outputs
dict_full['network']['10']['1']['edges'][:5]
dict_full['network']['10']['1']['nodes'][:5]
# # CREATE SAMPLED OUTPUTS
# ## Import tweet corpus
# +
# Import cleaned and combined CSV data as pandas dataframe
from os import listdir
from os.path import join
import csv
import pandas as pd
data_path = '../collection/twint/full-combined'
encoded_data_path = '../data/encoded'
csv_header = 'id,conversation_id,created_at,date,time,timezone,user_id,username,name,place,tweet,mentions,urls,photos,replies_count,retweets_count,likes_count,location,hashtags,link,retweet,quote_url,video'
dtype_dict={
'id': str,
'conversation_id': str,
'username': str,
'user_id': str,
'mentions': str,
'tweet': str,
'hashtags': str,
'link': str,
'user_rt': str,
}
__encoded_all_file__ = 'cleaned-all-combined.csv'
df_all = pd.read_csv(join(encoded_data_path, __encoded_all_file__),
delimiter=',',
dtype=dtype_dict)
df_all.describe()
# -
# Remove "Unnamed" column
del df_all['Unnamed: 0']
df_all[:2]
df_selected = df_all[['id', 'date', 'user_id', 'username', 'tweet', 'mentions', 'retweets_count', 'hashtags', 'link']]
df_selected[:2]
# ## Create desired metadata as per your project: period dates and hashtag groups
# +
# PERIOD DATES
ranges = [
('1', ['2018-01-01', '2018-03-30']),
('2', ['2018-04-01', '2018-06-12']),
('3', ['2018-06-13', '2018-07-28']),
('4', ['2018-07-29', '2018-10-17']),
('5', ['2018-10-18', '2018-11-24']),
('6', ['2018-11-25', '2018-12-10']),
('7', ['2018-12-11', '2018-12-19']),
('8', ['2018-12-20', '2018-12-25']),
('9', ['2018-12-26', '2019-02-13']),
('10', ['2019-02-14', '2019-02-28'])
]
period_dates = nttc.period_dates_writer(ranges=ranges)
# HASHTAG GROUPINGS
conservative_hashtag_list = [
'#bordercrisis', '#bordersecurity', '#buildthewall',
'#caravaninvasion', '#illegals', '#migrantcaravan',
'#nationalemergency', '#ronilsingh'
]
liberal_keyword_list = [
{
'#felipegomez': ['<NAME>', '<NAME>']
},
{
'#maquin': ['<NAME>', 'maquín', 'maquin' ]
}
]
liberal_fbt_list = [
'#familyseparation', '#familiesbelongtogether',
'#felipegomez', '#keepfamiliestogether',
'#maquin', '#noborderwall', '#wherearethechildren',
'<NAME>', 'maquín', 'maquin', '<NAME>',
'<NAME>'
]
liberal_antishutdown_list = [
'#shutdownstories','#trumpshutdown'
]
period_dates['1'][:10]
# -
# ### Sample hashtag groups
## Sample 1) certain periods, 2) certain hashtags
dict_samples = nttc.content_sampler(
dict_full['network'],
sample_size=50,
period_dates=period_dates,
corpus=df_selected,
sample_type='hashtag_group',
ht_group=liberal_fbt_list,
user_threshold=5,
random=False)
dict_samples['2']['3']
# ### Sample modules
## Sample 1) certain periods, 2) certain hashtags
dict_samples = nttc.content_sampler(
dict_full['network'],
sample_size=50,
period_dates=period_dates,
corpus=df_selected,
sample_type='modules',
ht_group=None,
user_threshold=5,
random=False)
dict_samples['10']['1']
# ## Batch outputs per module
# +
import pandas as pd
from os import listdir
from os.path import join
import csv
lister = []
for p in dict_samples:
for m in dict_samples[p]:
sub_list = []
print(p,m)
try:
records = dict_samples[p][m]['sample'].to_dict('records')
for r in records:
r['period'] = p
r['module'] = m
lister.append(r)
except AttributeError as e:
print(e)
lister[:5]
# -
df_full_samples = pd.DataFrame.from_dict(lister)
df_full_samples[:5]
# Drop duplicates
cleaned_df_full_samples = df_full_samples.drop_duplicates(subset=['id'], keep='first')
print(len(cleaned_df_full_samples), len(df_full_samples))
cdf = cleaned_df_full_samples[['period','module','username','tweet','retweets_count','hashtags','link','mentions','date','id','user_id']]
cdf[:2]
cdf.to_csv(join('../infomap/output/nets/ftree/csv', 'ftree_fbt_hashtag_groups_tweet_sample.csv'),
sep=',',
encoding='utf-8',
index=False)
# ## OUTPUT CSV OF EDGE DATA WITH USERNAMES
# OUTPUT EDGES
lister_edges = []
for p in dict_samples:
for m in dict_samples[p]:
sub_list = []
try:
records = dict_full['network'][p][m]['edges'].to_dict('records')
for r in records:
r['period'] = p
r['module'] = m
lister_edges.append(r)
except AttributeError as e:
print(e)
lister_edges[:5]
len(lister_edges)
df_full_edges = pd.DataFrame.from_dict(lister_edges)
df_full_edges[:5]
df_full_edges.to_csv(join('../infomap/output/nets/ftree/csv', 'infomap_edges_with_names_all_periods.csv'),
sep=',',
encoding='utf-8',
index=False)
df_full_samples.to_csv(join('../infomap/output/nets/ftree/csv', 'infomap_tweet_sample_all_periods.csv'),
sep=',',
encoding='utf-8',
index=False)
| assets/examples/example-infomap_ftree_sampling_hubs_users_and_tweets_to_csv.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
# ---
# # QCoDeS Tutorial-Mercury
# +
import numpy as np
import time
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rc('figure', figsize=(15, 10))
import qcodes as qc
# %matplotlib notebook
# +
from qcodes.instrument_drivers.oxford.mercuryiPS_VISA import MercuryiPS
magnet = MercuryiPS(name = 'Magnet', address='ASRL5::INSTR')
# +
print(magnet.axes)
print('Current B_x: {:f} T'.format(magnet.x_fld.get()))
print('Current I_x: {:f} A'.format(magnet.x_fldC.get()))
print('Status x: ', magnet.x_ACTN.get())
# -
magnet.x_rate.get()
magnet.x_setpoint.get()
# +
print('Current B_x: {:.2f}'.format(magnet.x_fld.get()))
magnet.x_fld.set(0.1) # waits until it gets there
print('Setting the new field...')
print('Current B_x: {:.2f}'.format(magnet.x_fld.get()))
# +
print('Current B_x: {:.2f}'.format(magnet.x_fld.get()))
magnet.x_fld.set(0)# waits until it gets there
print('Setting the new field...')
print('Current B_x: {:.2f}'.format(magnet.x_fld.get()))
# -
| docs/tutorial/QCoDeS Tutorial-Mercury.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
# ---
# <b>Phase 1 Assignment</b>
# %matplotlib inline
import pandas as pd
import matplotlib.pylab as plt
import numpy as np
# <b>Load and print head of dataset</b>
df = pd.read_csv('../data/BreastCancerWisconsin.csv')
print(df.head())
# <b>Replace ? by NaN in column A7</b>
df['A7'] = df['A7'].replace('?', np.NaN)
print(df[20:30])
# <b>Check datatype of columns</b>
print(df.dtypes)
# <b>Converted back to numeric</b>
df['A7'] = pd.to_numeric(df['A7'])
print(df[20:30])
# <b>Check datatype of columns</b>
print(df.dtypes)
# <b>Check Null Values and Total Count</b>
print(pd.isnull(df['A7']).sum())
# <b>Replace NaN values with the mean of column A7</b>
df = df.fillna(df.mean(skipna=True))
print(df[20:30])
# <b>Provide the summary statistics</b>
descdf=df.describe()
print(descdf.round(2))
# <b>Find number of columns and number of rows</b>
rows, columns = df.shape
print('Rows:: '+ str(rows) + '\nColumns:: ' + str(columns))
# <b>Report how many unique id values (column Scn)</b>
print(len(df['Scn'].unique()))
# <b>Draw histograms for columns A2-A10</b>
#df.iloc[:, 1:10].plot(kind='hist',bins=9,figsize=(12,6))
df.iloc[:,1:10].hist(bins=10,grid=False,figsize=(10,15),edgecolor='black',linewidth=1.25)
plt.tight_layout(rect=(0, 0, 1.2, 1.2))
# <b>Create a count based on groupby</b>
benign, malignant = pd.value_counts(df['CLASS'])
print( 'Benign::'+ str(benign) +'\nMalignant::'+str(malignant))
# <b>Make a bar plot for CLASS</b>
#ax = pd.value_counts(df['CLASS']).plot(kind='bar', title="Benign and Malignant in CLASS")
#ax.set_xlabel("Class")
#ax.set_ylabel("Counts of benign and malignant values")
ax = pd.value_counts(df['CLASS'].map({2:'Benign', 4:'Malignant'})).plot(kind='bar', title="The Number of Benign and Malignant Cancer Instances",color=['g','r'])
ax.set_xlabel("Type of Cancer Instance")
ax.set_ylabel("Number of each Instance")
# <b>Scatter chart for Clump Thickness and Normal Nuclei</b>
#ax =df.plot(kind='scatter', x='A2', y='A9', title="Scatter chart for Clump Thickness and Normal Nuclei")
ax =df.plot(kind='scatter', x='A2', y='A9', c=['red','blue'],alpha=.25, title="Scatter plot of Clump Thickness and Normal Nuclei")
ax.set_xlabel("Clump Thickness")
ax.set_ylabel("Normal Nuclei")
# <b>Graph a box plot to visualize the shape of the distribution, its central value, and its variability</b>
df.iloc[:, 1:10].plot(kind='box',figsize=(10,5),subplots=True)
plt.tight_layout(rect=(0, 0, 1.2, 1.2))
plt.show()
# <b>Summarize - Find the correlation for all variables</b>
cordf=df.iloc[:, 1:11].apply(lambda x: x.factorize()[0]).corr()
print(cordf.round(2))
# <b>Summarize - Find the standard deviation for all variables</b>
std_df=np.std(df.iloc[:, 1:10])
print(std_df.round(2))
# <b>Summarize - Find the variance for all variables </b>
var_df=np.var(df.iloc[:, 1:10])
print(var_df.round(2))
# <b>Summarize - Find the mode for all variables</b>
modedf=df.iloc[:, 1:11].mode()
modedf.rename(index={0:'mode'}, inplace=True)
print(modedf)
# <b>Final Summarization of Data: </b> All variables from A2 to A10 have a descrete ordinal property. The variable Class has a discrete dichotomos property. This affects their descriptive statistics. With descrete variables, statistics that describe frequency are most meaningful. There appears to be a large variance between most of the variables. This is probably because of their descrete properties. Most variables would probably need standardization. Variable A6 might be the only variable that might not need standardization.
| code/FinalAssignment-Phase1.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
# ---
# # Proyecto
#
# ## Instrucciones
#
# 1.- Completa los datos personales (nombre y rol USM) de cada integrante en siguiente celda.
#
# + [markdown] Collapsed="false"
# * __Nombre-Rol__:
#
# * <NAME> - 201610531-5
# * <NAME> - 201710515-1
# * <NAME> - 201710507-0
# * <NAME> - 201710519-4
#
# -
# 2.- Debes _pushear_ este archivo con tus cambios a tu repositorio personal del curso, incluyendo datos, imágenes, scripts, etc.
#
# 3.- Se evaluará:
# - Soluciones
# - Código
# - Que Binder esté bien configurado.
# - Al presionar `Kernel -> Restart Kernel and Run All Cells` deben ejecutarse todas las celdas sin error.
# ## I.- Sistemas de recomendación
#
#
#
# 
#
# ### Introducción
#
# El rápido crecimiento de la recopilación de datos ha dado lugar a una nueva era de información. Los datos se están utilizando para crear sistemas más eficientes y aquí es donde entran en juego los sistemas de recomendación. Los sistemas de recomendación son un tipo de sistemas de filtrado de información, ya que mejoran la calidad de los resultados de búsqueda y proporcionan elementos que son más relevantes para el elemento de búsqueda o están relacionados con el historial de búsqueda del usuario.
#
# Se utilizan para predecir la calificación o preferencia que un usuario le daría a un artículo. Casi todas las grandes empresas de tecnología los han aplicado de una forma u otra: Amazon lo usa para sugerir productos a los clientes, YouTube lo usa para decidir qué video reproducir a continuación en reproducción automática y Facebook lo usa para recomendar páginas que me gusten y personas a seguir. Además, empresas como Netflix y Spotify dependen en gran medida de la efectividad de sus motores de recomendación para sus negocios y éxitos.
# ### Objetivos
#
# Poder realizar un proyecto de principio a fin ocupando todos los conocimientos aprendidos en clase. Para ello deben cumplir con los siguientes objetivos:
#
# * **Desarrollo del problema**: Se les pide a partir de los datos, proponer al menos un tipo de sistemas de recomendación. Como todo buen proyecto de Machine Learning deben seguir el siguiente procedimiento:
# * **Lectura de los datos**: Describir el o los conjunto de datos en estudio.
# * **Procesamiento de los datos**: Procesar adecuadamente los datos en estudio. Para este caso ocuparan técnicas de [NLP](https://en.wikipedia.org/wiki/Natural_language_processing).
# * **Metodología**: Describir adecuadamente el procedimiento ocupado en cada uno de los modelos ocupados.
# * **Resultados**: Evaluar adecuadamente cada una de las métricas propuesta en este tipo de problemas.
#
#
# * **Presentación**: La presentación será levemente distinta a las anteriores, puesto que deberán ocupar la herramienta de Jupyter llamada [RISE](https://en.wikipedia.org/wiki/Natural_language_processing). Esta presentación debe durar aproximadamente entre 15-30 minutos, y deberán mandar sus videos (por youtube, google drive, etc.)
#
# ### Evaluación
#
# * **Códigos**: Los códigos deben estar correctamente documentados (ocupando las *buenas prácticas* de python aprendidas en este curso).
# * **Explicación**: La explicación de la metodología empleada debe ser clara, precisa y concisa.
# * **Apoyo Visual**: Se espera que tengan la mayor cantidad de gráficos y/o tablas que puedan resumir adecuadamente todo el proceso realizado.
#
#
#
#
#
# ### Esquema del proyecto
#
# El proyecto tendrá la siguiente estructura de trabajo:
# ```
# - project
# |
# |- data
# |- tmdb_5000_credits.csv
# |- tmdb_5000_movies.csv
# |- graficos.py
# |- lectura.py
# |- modelos.py
# |- preprocesamiento.py
# |- presentacion.ipynb
# |- project.ipynb
#
# ```
# donde:
#
# * `data`: carpeta con los datos del proyecto
# * `graficos.py`: módulo de gráficos
# * `lectura.py`: módulo de lectura de datos
# * `modelos.py`: módulo de modelos de Machine Learning utilizados
# * `preprocesamiento.py`: módulo de preprocesamiento de datos
# * `presentacion.ipynb`: presentación del proyecto (formato *RISE*)
# * `project.ipynb`: descripción del proyecto
# ### Apoyo
#
# Para que la carga del proyecto sea lo más amena posible, se les deja las siguientes referencias:
#
# * **Sistema de recomendación**: Pueden tomar como referencia el proyecto de Kaggle [Getting Started with a Movie Recommendation System](https://www.kaggle.com/ibtesama/getting-started-with-a-movie-recommendation-system/data?select=tmdb_5000_credits.csv).
# * **RISE**: Les dejo un video del Profesor <NAME> denomindo *Presentaciones y encuestas interactivas en jupyter notebooks y RISE* ([link](https://www.youtube.com/watch?v=ekyN9DDswBE&ab_channel=PyConColombia)). Este material les puede ayudar para comprender mejor este nuevo concepto.
| project/project.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# +
df_1 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161101.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_2 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161108.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_3 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161116.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_4 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161122.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_5 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161129.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_6 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20161206.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_7 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170110.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_8 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170116.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_9 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170117.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_10 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170124.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_11 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170131.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_12 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170207.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_13 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170214.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_14 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170221.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
df_15 = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/Rx_BenefitPlan_20170301.csv', sep='|', index_col='ClaimID', dtype=str, na_values=['nan', ' ', ' '])
# -
df_1["OriginalDataset"] = 1
df_2["OriginalDataset"] = 2
df_3["OriginalDataset"] = 3
df_4["OriginalDataset"] = 4
df_5["OriginalDataset"] = 5
df_6["OriginalDataset"] = 6
df_7["OriginalDataset"] = 7
df_8["OriginalDataset"] = 8
df_9["OriginalDataset"] = 9
df_10["OriginalDataset"] = 10
df_11["OriginalDataset"] = 11
df_12["OriginalDataset"] = 12
df_13["OriginalDataset"] = 13
df_14["OriginalDataset"] = 14
df_15['OriginalDataset'] = 0
df = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10, df_11, df_12, df_13, df_14, df_15])
df.columns
df_P = df[df.ClaimStatus=='P']
print(df_P.isnull().sum())
df_P.shape
print(df_P[df_P['IngredientCost'].isnull()])
print(df_P[df_P['IngredientCost'].isnull()].isnull().sum())
print(df_P.DispensingFee.describe())
print(df_P[df_P['IngredientCost'].isnull()].DispensingFee.describe())
# +
def get_total(row):
if row['IngredientCost'] and row['DispensingFee']:
cost1 = float(row['IngredientCost']) + float(row['DispensingFee'])
elif row['IngredientCost']:
cost1 = float(row['IngredientCost'])
else:
cost1 = 0
cost2 = float(row['OutOfPocket']) + float(row['PaidAmount'])
return max(cost1, cost2)
df_P['TotalCost'] = df_P.apply(lambda row: get_total(row), axis=1)
# -
print(df_P.TotalCost.describe())
print(df_P[df_P.TotalCost < 0])
df_P[df_P.TotalCost <= 0].count()
df_neg = df_P[df_P.TotalCost < 0]
df_pos = df_P[df_P.TotalCost > 0]
print(df_pos.TotalCost.describe())
df_pos.to_csv(path_or_buf='/Users/joannejordan/Desktop/RxClaims/All_data.csv', sep='|')
print(df_pos.isnull().sum())
#ndc_product = pd.read_table('/Users/joannejordan/Desktop/ndctext/product.txt')
ndc_package = pd.read_table('/Users/joannejordan/Desktop/ndctext/package.txt')
ndc_product = pd.read_table('/Users/joannejordan/Desktop/ndctext/product.txt', encoding = "ISO-8859-1")
ndc_package.head()
ndc_product.head()
df_pos.MailOrderPharmacy[df_pos.PharmacyZip.isnull()].unique()
df_pos.PharmacyState.unique()
df_nonan = df_pos.drop(columns=['PharmacyStreetAddress2', 'PrescriberFirstName', 'PresriberLastName', 'ClaimStatus']).dropna()
df_nonan.to_csv(path_or_buf='/Users/joannejordan/Desktop/RxClaims/first_pass_noNaN.csv', sep='|')
df_nonan.PharmacyState.unique()
df_pos.AHFSTherapeuticClassCode
ndc_rx = df_pos.copy()
ndc_package['PRODUCTNDC'] = ndc_package['PRODUCTNDC'].apply(lambda ndc: ndc.replace("-",""))
df_nonan.UnitMeasure.unique()
# +
def get_name(row):
if row['DrugLabelName']:
return row['DrugLabelName']
else:
global ndc_product
global ndc_package
ndc_pack = row['NDCCode']
ndc = ndc_package.PRODUCTNDC[ndc_package.NDCPACKAGECODE==ndc_pack]
DrugLabelName = ndc_product.PROPRIETARYNAME[ndc_product.PRODUCTND==ndc]
return DrugLabelName
def get_unit(row):
if row['DrugLabelName']:
return row['UnitMeasure']
else:
global ndc_product
global ndc_package
ndc_pack = row['NDCCode']
ndc = ndc_package.PRODUCTNDC[ndc_package.NDCPACKAGECODE==ndc_pack]
UnitMeasure = ndc_product.DOSAGEFORMNAME[ndc_product.PRODUCTND==ndc]
return UnitMeasure
def get_quant(row):
if row['DrugLabelName']:
return row['Quantity']
else:
global ndc_package
ndc_pack = row['NDCCode']
quantity = ndc_package.PACKAGEDESCRIPTION[ndc_package.NDCPACKAGECODE==ndc_pack]
return Quantity[:2]
# -
ndc_rx['DrugLabelName'] = ndc_rx.apply(lambda row: get_name(row), axis=1)
ndc_rx['Quantity'] = ndc_rx.apply(lambda row: get_quant(row), axis=1)
ndc_rx['UnitMeasure'] = ndc_rx.apply(lambda row: get_unit(row), axis=1)
ndc_rx.isnull().sum()
ndc_rx.NDCCode[ndc_rx.DrugLabelName.isnull()]
df_nonan[:10000].to_csv(path_or_buf='/Users/joannejordan/Desktop/RxClaims/third_pass_noNaN.csv')
rx_info = ndc_rx.drop(columns=['PharmacyStreetAddress2', 'PrescriberFirstName', 'PresriberLastName', 'ClaimStatus']).dropna(subset=['DrugLabelName'])
rx_info.isnull().sum()
def get_unit_cost(row):
if float(row['Quantity']) > 0:
return float(row['TotalCost'])/float(row['Quantity'])
else:
return row['TotalCost']
rx_info['UnitCost'] = rx_info.apply(lambda row: get_unit_cost(row), axis=1)
rx_info.UnitCost.describe()
rx_info.isnull().sum()
def get_zip(row):
if len(str(row['PharmacyZip'])) > 5:
return str(row['PharmacyZip'])[:5]
else:
return row['PharmacyZip']
rx_info['PharmacyZipCode'] = rx_info.apply(lambda row: get_zip(row), axis=1)
rx_info.PharmacyZipCode.isnull().sum()
dropped_zips = rx_info.dropna(subset=['PharmacyZipCode'])
dropped_zips.drop(columns=['PharmacyZip'], inplace=True)
dropped_zips.to_csv(path_or_buf='/Users/joannejordan/Desktop/RxClaims/all_data_w_zips.csv')
dropped_zips.isnull().sum()
#get mail order pharmacies back.
def mail_order_pharm(row):
if row['MailOrderPharmacy']=='Y':
return 99999
else:
return row['PharmacyZipCode']
rx_info.drop(columns=['PharmacyZip'], inplace=True)
rx_info['PharmacyZip'] = rx_info.apply(lambda row: mail_order_pharm(row), axis=1)
rx_info.isnull().sum()
inc_mail_order = rx_info.drop(columns=['PharmacyZipCode'])
grouped_meds = inc_mail_order.groupby(['NDCCode']).count()
grouped_meds
drug_by_pharm = inc_mail_order.groupby(['NDCCode', 'PharmacyZip']).count()
drug_by_pharm
'CLONAZEPAM' in inc_mail_order.DrugLabelName.unique()
drug_by_ph = inc_mail_order.groupby(['DrugLabelName', 'PharmacyZip']).count()
drug_by_ph
drugs = inc_mail_order.DrugLabelName.unique()
# +
med_freqs = []
for drug in drugs:
med_freqs.append(inc_mail_order.DrugLabelName.tolist().count(drug))
# +
zips = inc_mail_order.PharmacyZip.unique()
zip_freqs = []
for zip_code in zips:
zip_freqs.append(inc_mail_order.PharmacyZip.tolist().count(zip_code))
# +
#https://simplemaps.com/data/us-zips
zip_code_info = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/uszips.csv', index_col='zip')
# -
print(med_freqs)
print(zip_freqs)
zip_freqs
plt.hist(zip_freqs, log=True, range=(0,1000))
# +
from scipy import stats
stats.describe(zip_freqs)
# -
plt.hist(med_freqs, log=True, range=(0,100))
'HYDROCHLOROTHIAZIDE ' in inc_mail_order.DrugLabelName.tolist()
drugs
inc_mail_order
drug_names = inc_mail_order.copy()
#get rid of erroneous white space in DrugLabelName
drug_names['DrugLabelName'] = drug_names['DrugLabelName'].apply(lambda drug: ' '.join(drug.split()))
all_drugs = drug_names.DrugLabelName.unique()
all_drugs
# +
drug_freqs = []
for drug in all_drugs:
med_freqs.append(drug_names.DrugLabelName.tolist().count(drug))
# -
plt.hist(med_freqs, log=True)
# +
#make better notebook put on GitHub
#county data?
#first 3 digits of zip column?
#drug categories?
drug_names.to_csv(path_or_buf='/Users/joannejordan/Desktop/RxClaims/current_wk2_end.csv')
# -
drug_names.columns
EOW2_nonan = drug_names.drop(columns=['AHFSTherapeuticClassCode', 'CoInsurance', 'DateFilled',
'Deductible', 'DispensingFee', 'FillNumber', 'FillNumber',
'MemberID', 'GroupNumber', 'MailOrderPharmacy', 'PaidOrAdjudicatedDate',
'RxNumber', 'SeqNum', 'punbr_grnbr', 'CompoundDrugIndicator',
'Copay', 'IngredientCost', 'NDCCode', 'OutOfPocket', 'PaidAmount',
'Quantity', 'RxNumber', 'SeqNum', 'UnitMeasure']).dropna()
EOW2_nonan.to_csv(path_or_buf='/Users/joannejordan/Desktop/RxClaims/EOW2_simplified_df.csv')
EOW2_nonan
drug_by_pharm = EOW2_nonan.groupby(['PharmacyZip','PharmacyNPI', 'DrugLabelName']).mean()
simple = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/EOW2_simplified_df.csv', index_col='ClaimID', dtype=str)
# +
zips = simple.PharmacyZip.unique()
zip_freqs = []
for zip_code in zips:
zip_freqs.append(simple.PharmacyZip.tolist().count(zip_code))
# +
args = np.argpartition(np.array(zip_freqs), -6)[-6:]
top6 = zips[args]
top6
# -
simple.UnitCost = simple.UnitCost.astype(float)
simple.PharmacyNPI = simple.PharmacyNPI.apply(lambda ndc: str(ndc).replace(" ",""))
top_zip0 = simple[simple.PharmacyZip == top6[0]]
top_zip1 = simple[simple.PharmacyZip == top6[1]]
top_zip2 = simple[simple.PharmacyZip == top6[2]]
top_zip3 = simple[simple.PharmacyZip == top6[3]]
top_zip4 = simple[simple.PharmacyZip == top6[4]]
top_zip5 = simple[simple.PharmacyZip == top6[5]]
top_zip0.PharmacyNPI.unique()
t0_drug_by_ph = top_zip0.groupby(['DrugLabelName', 'PharmacyNPI']).mean()
t0_drug_by_ph = pd.DataFrame(t0_drug_by_ph)
# +
meds = simple.DrugLabelName.unique()
med_freqs = []
for drug in meds:
med_freqs.append(simple.DrugLabelName.tolist().count(drug))
# +
args_med = np.argpartition(np.array(med_freqs), -5)[-5:]
top5 = meds[args_med]
top5
# -
drug_names = pd.read_csv('/Users/joannejordan/Desktop/RxClaims/current_wk2_end.csv', index_col='ClaimID', dtype=str)
drug_names.PharmacyNPI = drug_names.PharmacyNPI.apply(lambda ndc: str(ndc).replace(" ",""))
simple.PharmacyNumber.unique().size
table = simple[simple.PharmacyZip=='03431']
table = table[table.DrugLabelName=='SIMVASTATIN']
pharmacies = table.groupby(['PharmacyName']).mean()
pharmacies
table = table[table.PharmacyName==pharmacies.UnitCost.idxmin()]
print('Pharmacy:\n{}\nAddress:\n{}\n{}'.format(table.PharmacyName.iloc[0], table.PharmacyStreetAddress1.iloc[0], table.PharmacyCity.iloc[0]))
def get_cheapest_pharm(zipcode, drug, table):
table = table[table.PharmacyZip==str(zipcode)]
table = table[table.DrugLabelName==str(drug)]
pharmacies = table.groupby(['PharmacyName']).mean()
pharmacy = pharmacies.UnitCost.idxmin()
table = table[table.PharmacyName==pharmacy]
print('Pharmacy:\n{}\nAddress:\n{}\n{}\n{}\n{}'.format(table.PharmacyName.iloc[0],
table.PharmacyStreetAddress1.iloc[0],
table.PharmacyCity.iloc[0],
table.PharmacyNPI.iloc[0],
table.PharmacyNumber.iloc[0]))
get_cheapest_pharm('03431', 'OMEPRAZOLE CAP 20MG', simple)
get_cheapest_pharm('03431', 'FLUTICASONE SPR 50MCG', simple)
get_cheapest_pharm('03431', 'LISINOPRIL', simple)
get_cheapest_pharm('03431', 'PROAIR HFA AER', simple)
get_cheapest_pharm('02128', 'PROAIR HFA AER', simple)
get_cheapest_pharm('02128', 'LISINOPRIL', simple)
get_cheapest_pharm('02128', 'FLUTICASONE SPR 50MCG', simple)
get_cheapest_pharm('02128', 'SIMVASTATIN', simple)
get_cheapest_pharm('02128', 'OMEPRAZOLE CAP 20MG', simple)
| exploratory-code/Medical Data Dashboard.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 matplotlib.pyplot as plt
import seaborn as sns
# +
gender_submission = pd.read_csv('Titanic/gender_submission.csv')
train = pd.read_csv('Titanic/train.csv', dtype={'Survived':int,
'Pclass':str,
'Sex':str,
'Age':float,
'Sib Sp':int,
'Parch':int,
'Ticket':str,
'Fare':float,
'Cabin':str,
'Embarked':str})
test = pd.read_csv('Titanic/test.csv', dtype={'Pclass':str,
'Sex':str,
'Age':float,
'Sib Sp':int,
'Parch':int,
'Ticket':str,
'Fare':float,
'Cabin':str,
'Embarked':str})
train = train[train.columns[1:]] # removing column 'id'
test = test[test.columns[1:]] # removing column 'id'
# -
from DimensionalityReduction import DimensionalityReduction
dr = DimensionalityReduction()
dr.fit(train, 'Survived', label_encoding=True) # since there are str in data
dr.plot()
| 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
# name: python3
# ---
# + [markdown] id="x_og8NITgOXG" colab_type="text"
# # This is a notebook template
# + id="H1pCgovOf7Ub" colab_type="code" outputId="0b2e5534-96f7-457f-ade8-61dfc7810e64" colab={"base_uri": "https://localhost:8080/", "height": 52}
a = 345
print (4 + a)
def test():
print("test")
test()
test()
test()
| test.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3.6 - AzureML
# language: python
# name: python3-azureml
# ---
# # 데이터 사용
#
# 데이터는 기계 학습 모델 작성 과정의 토대가 되는 요소라 할 수 있습니다. 전문 데이터 과학 솔루션을 빌드하려면 클라우드에서 중앙 집중식으로 데이터를 관리하고, 여러 워크스테이션과 컴퓨팅 대상에서 실험 실행 및 모델 학습을 진행하는 데이터 과학자 팀에게 해당 데이터 액세스 권한을 제공해야 합니다.
#
# 이 Notebook에서는 데이터 사용을 위한 두 가지 Azure Machine Learning 개체인 *데이터 저장소* 및 *데이터 세트*를 살펴봅니다.
# ## 작업 영역에 연결
#
# 이 Notebook의 작업을 시작하려면 먼저 작업 영역에 연결합니다.
#
# > **참고**: Azure 구독에 인증된 세션을 아직 설정하지 않은 경우에는 링크를 클릭하고 인증 코드를 입력한 다음 Azure에 로그인하여 인증하라는 메시지가 표시됩니다.
# +
import azureml.core
from azureml.core import Workspace
# Load the workspace from the saved config file
ws = Workspace.from_config()
print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))
# -
# ## 데이터 저장소 사용
#
# Azure ML에서 *데이터 저장소*는 Azure Storage Blob 컨테이너 등의 스토리지 위치에 대한 참조입니다. 모든 작업 영역에는 기본 데이터 저장소(대개 작업 영역과 함께 만들어진 Azure Storage Blob 컨테이너)가 있습니다. 다른 위치에 저장된 데이터를 사용해야 하는 경우에는 작업 영역에 사용자 지정 데이터 저장소를 추가하고 그 중 하나를 기본 데이터 저장소로 설정하면 됩니다.
#
# ### 데이터 저장소 확인
#
# 다음 코드를 사용하여 작업 영역의 데이터 저장소를 확인합니다.
# +
# Get the default datastore
default_ds = ws.get_default_datastore()
# Enumerate all datastores, indicating which is the default
for ds_name in ws.datastores:
print(ds_name, "- Default =", ds_name == default_ds.name)
# -
# [Azure Machine Learning Studio](https://ml.azure.com)의 작업 영역 **데이터 저장소** 페이지에서도 작업 영역의 데이터 저장소를 확인하고 관리할 수 있습니다.
#
# ### 데이터 저장소에 데이터 업로드
#
# 사용 가능한 데이터 저장소를 확인한 후에는 로컬 파일 시스템에서 데이터 저장소에 파일을 업로드할 수 있습니다. 그러면 실험 스크립트가 실제로 실행되는 위치에 관계없이 작업 영역에서 실행 중인 실험에서 해당 파일에 액세스할 수 있습니다.
default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'], # Upload the diabetes csv files in /data
target_path='diabetes-data/', # Put it in a folder path in the datastore
overwrite=True, # Replace existing files of the same name
show_progress=True)
# ## 데이터 세트 사용
#
# Azure Machine Learning에서는 *데이터 세트 형식의 데이터용 추상화가 제공됩니다. 데이터 세트는 실험에서 사용할 수 있는 특정 데이터 세트에 대한 버전이 지정된 참조입니다. 데이터 세트는 *테이블 형식* 또는 *파일* 기반 형식일 수 있습니다.
#
# ### 테이블 형식 데이터 세트 만들기
#
# 데이터 저장소에 업로드한 당뇨병 데이터에서 데이터 세트를 만들고 첫 20개 레코드를 살펴보겠습니다. 여기서 데이터는 CSV 파일에 포함된 구조적 형식이므로 *테이블 형식* 데이터 세트를 사용합니다.
# +
from azureml.core import Dataset
# Get the default datastore
default_ds = ws.get_default_datastore()
#Create a tabular dataset from the path on the datastore (this may take a short while)
tab_data_set = Dataset.Tabular.from_delimited_files(path=(default_ds, 'diabetes-data/*.csv'))
# Display the first 20 rows as a Pandas dataframe
tab_data_set.take(20).to_pandas_dataframe()
# -
# 위의 코드에 나와 있는 것처럼 테이블 형식 데이터 세트는 Pandas 데이터 프레임으로 쉽게 변환할 수 있습니다. 따라서 일반 Python 기술을 통해 데이터를 사용할 수 있습니다.
#
# ### 파일 데이터 세트 만들기
#
# 앞에서 만든 데이터 세트는 *테이블 형식* 데이터 세트입니다. 이 데이터 세트는 데이터 세트 정의에 포함된 구조적 파일의 모든 데이터가 들어 있는 데이터 프레임으로 읽을 수 있습니다. 테이블 형식 데이터의 경우 이러한 방식이 적합합니다. 하지만 비구조적 데이터를 사용해야 하는 기계 학습 시나리오도 있고, 직접 작성한 코드에서 파일의 데이터 읽기를 처리하려는 경우도 있을 수 있습니다. 이러한 경우에는 *파일* 데이터 세트를 사용할 수 있습니다. 파일 데이터 세트에서는 가상 탑재 지점에 파일 경로 목록이 작성되는데, 이 목록을 사용하여 파일의 데이터를 읽을 수 있습니다.
# +
#Create a file dataset from the path on the datastore (this may take a short while)
file_data_set = Dataset.File.from_files(path=(default_ds, 'diabetes-data/*.csv'))
# Get the files in the dataset
for file_path in file_data_set.to_path():
print(file_path)
# -
# ### 데이터 세트 등록
#
# 당뇨병 데이터를 참조하는 데이터 세트를 만든 후에는 작업 영역에서 실행되는 모든 실험에서 쉽게 액세스할 수 있도록 데이터 세트를 등록할 수 있습니다.
#
# 테이블 형식 데이터 세트는 **당뇨병 데이터 세트**로 등록하고 파일 데이터 세트는 **당뇨병 파일**로 등록하겠습니다.
# +
# Register the tabular dataset
try:
tab_data_set = tab_data_set.register(workspace=ws,
name='diabetes dataset',
description='diabetes data',
tags = {'format':'CSV'},
create_new_version=True)
except Exception as ex:
print(ex)
# Register the file dataset
try:
file_data_set = file_data_set.register(workspace=ws,
name='diabetes file dataset',
description='diabetes files',
tags = {'format':'CSV'},
create_new_version=True)
except Exception as ex:
print(ex)
print('Datasets registered')
# -
# [Azure Machine Learning Studio](https://ml.azure.com)의 작업 영역 **데이터 세트 페이지에서 데이터 세트를 확인하고 관리할 수 있습니다. 작업 영역 개체에서 데이터 세트 목록을 가져올 수도 있습니다.
print("Datasets:")
for dataset_name in list(ws.datasets.keys()):
dataset = Dataset.get_by_name(ws, dataset_name)
print("\t", dataset.name, 'version', dataset.version)
# 데이터 세트의 버전을 지정하는 기능을 사용하면 이전 정의를 사용하는 파이프라인이나 기존 실험을 그대로 유지하면서 데이터 세트를 다시 정의할 수 있습니다. 기본적으로는 명명된 데이터 세트의 최신 버전이 반환되지만 다음과 같이 버전 번호를 지정하여 데이터 세트의 특정 버전을 검색할 수 있습니다.
#
# ```python
# dataset_v1 = Dataset.get_by_name(ws, 'diabetes dataset', version = 1)
# ```
#
#
# ### 테이블 형식 데이터 세트에서 모델 학습 진행
#
# 데이터 세트를 만들었으므로 이제 해당 데이터 세트에서 모델 학습을 시작할 수 있습니다. 스크립트를 실행하는 데 사용되는 추정기의 *입력*으로 데이터 세트를 스크립트에 전달할 수 있습니다.
#
# 아래의 두 코드 셀을 실행하여 다음 항목을 만듭니다.
#
# 1. **diabetes_training_from_tab_dataset** 폴더
# 2. 분류 모델을 학습시키는 스크립트. 이 스크립트는 전달된 테이블 형식 데이터 세트를 인수로 사용합니다.
# +
import os
# Create a folder for the experiment files
experiment_folder = 'diabetes_training_from_tab_dataset'
os.makedirs(experiment_folder, exist_ok=True)
print(experiment_folder, 'folder created')
# +
# %%writefile $experiment_folder/diabetes_training.py
# Import libraries
import os
import argparse
from azureml.core import Run, Dataset
import pandas as pd
import numpy as np
import joblib
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
# Get the script arguments (regularization rate and training dataset ID)
parser = argparse.ArgumentParser()
parser.add_argument('--regularization', type=float, dest='reg_rate', default=0.01, help='regularization rate')
parser.add_argument("--input-data", type=str, dest='training_dataset_id', help='training dataset')
args = parser.parse_args()
# Set regularization hyperparameter (passed as an argument to the script)
reg = args.reg_rate
# Get the experiment run context
run = Run.get_context()
# Get the training dataset
print("Loading Data...")
diabetes = run.input_datasets['training_data'].to_pandas_dataframe()
# Separate features and labels
X, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values
# Split data into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)
# Train a logistic regression model
print('Training a logistic regression model with regularization rate of', reg)
run.log('Regularization Rate', np.float(reg))
model = LogisticRegression(C=1/reg, solver="liblinear").fit(X_train, y_train)
# calculate accuracy
y_hat = model.predict(X_test)
acc = np.average(y_hat == y_test)
print('Accuracy:', acc)
run.log('Accuracy', np.float(acc))
# calculate AUC
y_scores = model.predict_proba(X_test)
auc = roc_auc_score(y_test,y_scores[:,1])
print('AUC: ' + str(auc))
run.log('AUC', np.float(auc))
os.makedirs('outputs', exist_ok=True)
# note file saved in the outputs folder is automatically uploaded into experiment record
joblib.dump(value=model, filename='outputs/diabetes_model.pkl')
run.complete()
# -
# > **참고**: 스크립트에서 데이터 세트는 매개 변수나 인수로 전달됩니다. 테이블 형식 데이터 세트의 경우 이 인수에는 등록된 데이터 세트의 ID가 포함됩니다. 그러므로 다음과 같이 실행 컨텍스트에서 실험의 작업 영역을 가져온 다음 해당 ID를 사용하여 데이터 세트를 가져오는 코드를 스크립트에 작성할 수 있습니다.
# >
# > ```
# > run = Run.get_context()
# > ws = run.experiment.workspace
# > dataset = Dataset.get_by_id(ws, id=args.training_dataset_id)
# > diabetes = dataset.to_pandas_dataframe()
# > ```
# >
# > 그러나 Azure Machine Learning 실행에서는 명명된 데이터 세트를 참조하는 인수를 자동으로 식별하여 실행의 **input_datasets** 컬렉션에 추가합니다. 따라서 데이터 세트 "식별 이름"을 지정해 이 컬렉션에서 데이터 세트를 검색할 수도 있습니다. 식별 이름(잠시 후에 살펴볼 예정)은 실험의 스크립트 실행 구성에 포함된 인수 정의에서 지정됩니다. 위 스크립트에는 이 방식이 사용되었습니다.
#
# 이제 학습 데이터 세트용 인수를 정의하여 스크립트를 실험으로 실행할 수 있습니다. 스크립트는 이 데이터 세트를 읽습니다.
#
# > **참고**: **Dataset** 클래스는 **azureml-dataprep** 패키지에 있는 일부 구성 요소에 종속되므로 학습 환경을 실행할 환경에 이 패키지를 포함해야 합니다. **azureml-dataprep** 패키지는 **azure-defaults** 패키지에 포함되어 있습니다.
# +
from azureml.core import Experiment, ScriptRunConfig, Environment
from azureml.widgets import RunDetails
# Create a Python environment for the experiment (from a .yml file)
env = Environment.from_conda_specification("experiment_env", "environment.yml")
# Get the training dataset
diabetes_ds = ws.datasets.get("diabetes dataset")
# Create a script config
script_config = ScriptRunConfig(source_directory=experiment_folder,
script='diabetes_training.py',
arguments = ['--regularization', 0.1, # Regularizaton rate parameter
'--input-data', diabetes_ds.as_named_input('training_data')], # Reference to dataset
environment=env)
# submit the experiment
experiment_name = 'mslearn-train-diabetes'
experiment = Experiment(workspace=ws, name=experiment_name)
run = experiment.submit(config=script_config)
RunDetails(run).show()
run.wait_for_completion()
# -
# > **참고:** **--input-data** 인수는 데이터 세트를 *명명된 입력*으로 전달합니다. 이 입력에는 데이터 세트의 *식별 이름*이 포함되어 있는데, 스크립트는 이 이름을 사용하여 실험 실행의 **input_datasets** 컬렉션에서 해당 데이터 세트를 읽습니다. **--input-data** 인수의 문자열 값은 실제로는 등록된 데이터 세트의 ID입니다. `diabetes_ds.id`만 전달할 수도 있습니다. 이 경우 스크립트는 스크립트 인수에서 데이터 세트 ID에 액세스한 다음 해당 ID를 사용하여 **input_datasets** 컬렉션이 아닌 작업 영역에서 데이터 세트를 가져올 수 있습니다.
#
# 실험을 처음 실행할 때는 Python 환경을 설정하는 데 시간이 다소 걸릴 수 있습니다. 후속 실행은 더 빠르게 진행됩니다.
#
# 실험이 완료되면 위젯에서 **azureml-logs/70_driver_log.txt** 출력 로그와 실행에서 생성된 메트릭을 확인합니다.
#
# ### 학습된 모델 등록
#
# 학습된 모델은 모든 학습 실험과 마찬가지로 검색하여 Azure Machine Learning 작업 영역에 등록할 수 있습니다.
# +
from azureml.core import Model
run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model',
tags={'Training context':'Tabular dataset'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']})
for model in Model.list(ws):
print(model.name, 'version:', model.version)
for tag_name in model.tags:
tag = model.tags[tag_name]
print ('\t',tag_name, ':', tag)
for prop_name in model.properties:
prop = model.properties[prop_name]
print ('\t',prop_name, ':', prop)
print('\n')
# -
# ### 파일 데이터 세트에서 모델 학습 진행
#
# 앞에서는 *테이블 형식* 데이터 세트의 학습 데이터를 사용해 모델을 학습시키는 방법을 살펴보았습니다. 이번에는 *파일* 데이터 세트를 사용하는 방법을 알아보겠습니다.
#
# 파일 데이터 세트를 사용할 때 스크립트에 전달되는 데이터 세트 인수는 파일 경로가 포함된 탑재 지점을 나타냅니다. 이러한 파일에서 데이터를 읽는 방법은 파일의 데이터 종류와 해당 데이터를 사용하여 수행하려는 작업에 따라 다릅니다. 당뇨병 CSV 파일의 경우에는 Python **glob** 모듈을 사용하여 데이터 세트에 의해 정의된 가상 탑재 지점에서 파일 목록을 만들 수 있으며, 모든 파일을 단일 데이터 프레임으로 연결된 Pandas 데이터 프레임으로 읽어들일 수 있습니다.
#
# 아래의 두 코드 셀을 실행하여 다음 항목을 만듭니다.
#
# 1. **diabetes_training_from_file_dataset** 폴더
# 2. 분류 모델을 학습시키는 스크립트. 이 스크립트는 전달된 파일 데이터 세트를 *입력*으로 사용합니다.
# +
import os
# Create a folder for the experiment files
experiment_folder = 'diabetes_training_from_file_dataset'
os.makedirs(experiment_folder, exist_ok=True)
print(experiment_folder, 'folder created')
# +
# %%writefile $experiment_folder/diabetes_training.py
# Import libraries
import os
import argparse
from azureml.core import Dataset, Run
import pandas as pd
import numpy as np
import joblib
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
import glob
# Get script arguments (rgularization rate and file dataset mount point)
parser = argparse.ArgumentParser()
parser.add_argument('--regularization', type=float, dest='reg_rate', default=0.01, help='regularization rate')
parser.add_argument('--input-data', type=str, dest='dataset_folder', help='data mount point')
args = parser.parse_args()
# Set regularization hyperparameter (passed as an argument to the script)
reg = args.reg_rate
# Get the experiment run context
run = Run.get_context()
# load the diabetes dataset
print("Loading Data...")
data_path = run.input_datasets['training_files'] # Get the training data path from the input
# (You could also just use args.dataset_folder if you don't want to rely on a hard-coded friendly name)
# Read the files
all_files = glob.glob(data_path + "/*.csv")
diabetes = pd.concat((pd.read_csv(f) for f in all_files), sort=False)
# Separate features and labels
X, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values
# Split data into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)
# Train a logistic regression model
print('Training a logistic regression model with regularization rate of', reg)
run.log('Regularization Rate', np.float(reg))
model = LogisticRegression(C=1/reg, solver="liblinear").fit(X_train, y_train)
# calculate accuracy
y_hat = model.predict(X_test)
acc = np.average(y_hat == y_test)
print('Accuracy:', acc)
run.log('Accuracy', np.float(acc))
# calculate AUC
y_scores = model.predict_proba(X_test)
auc = roc_auc_score(y_test,y_scores[:,1])
print('AUC: ' + str(auc))
run.log('AUC', np.float(auc))
os.makedirs('outputs', exist_ok=True)
# note file saved in the outputs folder is automatically uploaded into experiment record
joblib.dump(value=model, filename='outputs/diabetes_model.pkl')
run.complete()
# -
# 파일 데이터 세트도 테이블 형식 데이터 세트와 마찬가지로 식별 이름을 사용해 **input_datasets** 컬렉션에서 검색할 수 있습니다. 스크립트 인수에서 파일 데이터 세트를 검색할 수도 있습니다. 테이블 형식 데이터 세트의 경우 이 인수에 전달된 데이터 세트 ID가 포함되는 반면, 파일 데이터 세트의 경우에는 이 인수에 파일의 탑재 경로가 포함됩니다.
#
# 다음으로는 스크립트에 데이터 세트를 전달하는 방식을 변경해야 합니다. 즉, 스크립트가 파일을 읽을 수 있는 경로를 정의해야 합니다. **as_download** 또는 **as_mount** 메서드를 사용하여 이 변경을 수행할 수 있습니다. **as_download** 메서드를 사용하면 파일 데이터 세트의 파일이 스크립트를 실행하는 컴퓨팅 대상의 임시 위치에 다운로드됩니다. 반면 **as_mount** 사용 시에는 데이터 저장소에서 파일을 직접 스트리밍할 수 있는 탑재 지점이 생성됩니다.
#
# 액세스 방법과 **as_named_input** 메서드를 함께 사용하면 실험 실행의 **input_datasets** 컬렉션에 데이터 세트를 포함할 수 있습니다. 인수를 `diabetes_ds.as_mount()` 등으로 설정하여 이 메서드를 생략하면 스크립트가 스크립트 인수에서는 데이터 세트 탑재 지점에 액세스할 수 있지만 **input_datasets** 컬렉션에서는 탑재 지점에 액세스할 수 없습니다.
# +
from azureml.core import Experiment
from azureml.widgets import RunDetails
# Get the training dataset
diabetes_ds = ws.datasets.get("diabetes file dataset")
# Create a script config
script_config = ScriptRunConfig(source_directory=experiment_folder,
script='diabetes_training.py',
arguments = ['--regularization', 0.1, # Regularizaton rate parameter
'--input-data', diabetes_ds.as_named_input('training_files').as_download()], # Reference to dataset location
environment=env) # Use the environment created previously
# submit the experiment
experiment_name = 'mslearn-train-diabetes'
experiment = Experiment(workspace=ws, name=experiment_name)
run = experiment.submit(config=script_config)
RunDetails(run).show()
run.wait_for_completion()
# -
# 실험이 완료되면 위젯에서 **azureml-logs/70_driver_log.txt** 출력 로그를 표시하여 스크립트가 파일을 읽을 수 있도록 파일 데이터 세트의 파일이 임시 폴더에 다운로드되었는지 확인합니다.
#
# ### 학습된 모델 등록
#
# 이번에도 실험을 통해 학습된 모델을 등록할 수 있습니다.
# +
from azureml.core import Model
run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model',
tags={'Training context':'File dataset'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']})
for model in Model.list(ws):
print(model.name, 'version:', model.version)
for tag_name in model.tags:
tag = model.tags[tag_name]
print ('\t',tag_name, ':', tag)
for prop_name in model.properties:
prop = model.properties[prop_name]
print ('\t',prop_name, ':', prop)
print('\n')
# -
# > **추가 정보**: 데이터 세트를 사용하는 학습에 대한 자세한 내용은 Azure ML 설명서의 [데이터 세트로 학습](https://docs.microsoft.com/azure/machine-learning/how-to-train-with-datasets)을 참조하세요.
| 06 - Work with Data.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import sidecar
import ipyleaflet
import datacube
dc = datacube.Datacube()
data = dc.load(product='ga_ls8c_ard_3',
lat=(-35, -36), lon=(148, 149),
time='2018-01-01',
group_by='solar_day',
resolution=(30,30),
output_crs='epsg:3577',
dask_chunks={'time': 1, 'x': 2000, 'y': 2000})
from datacube.storage.masking import mask_invalid_data
blue = mask_invalid_data(data.nbar_blue)
blue[0, fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b, ::10].plot.imshow();
from datacube.utils.geometry import GeoBox, Geometry, CRS
# 1/27" = 1 m
# 1/27 / 60 / 60 deg
DEGREES_PER_METER = 1 / (27 * 60 * 60)
DEGREES_PER_METER
import numpy as np
from datacube.virtual.impl import reproject_array, reproject_band, compute_reproject_roi
from odc.algo import to_rgba
da = to_rgba(data, clamp=3000, bands=['nbart_red', 'nbart_green', 'nbart_blue'])
from collections.abc import Mapping
import xarray as xr
def reproject(ds, output_crs, output_res=None, resampling=None, dask_chunks=None):
if isinstance(ds, xr.DataArray):
return reproject_slice(ds, output_crs, output_res, resampling, dask_chunks)
output_crs = CRS(output_crs)
if output_res is None:
if output_crs.units[0] not in CRS(ds.crs).units:
raise ValueError
else:
output_res = ds.geobox.resolution
output_geobox = GeoBox.from_geopolygon(ds.geobox.geographic_extent, resolution=output_res, crs=output_crs)
output_bands = {}
for band_name, band in ds.items():
if hasattr(band.data, 'dask') and dask_chunks is None:
dask_chunks = dict(zip(band.dims, band.data.chunksize))
if isinstance(resampling, Mapping):
band_resampling = resampling[band_name] if band_name in resampling else 'nearest'
else:
band_resampling = resampling
output_bands[band_name] = reproject_band(band, output_geobox, resampling=band_resampling, dims=band.dims, dask_chunks=dask_chunks)
return xr.Dataset(output_bands)
def reproject_da(da, output_crs, output_res=None, resampling=None, dask_chunks=None):
output_crs = CRS(output_crs)
if output_res is None:
if output_crs.units[0] not in CRS(da.crs).units:
raise ValueError
else:
output_res = da.geobox.resolution
output_geobox = GeoBox.from_geopolygon(da.geobox.geographic_extent, resolution=output_res, crs=output_crs)
if hasattr(da.data, 'dask') and dask_chunks is None:
dask_chunks = dict(zip(da.dims, da.data.chunksize))
if 'nodata' not in da.attrs:
da.attrs['nodata'] = np.nan
return reproject_band(da, output_geobox, resampling=resampling, dims=da.dims, dask_chunks=dask_chunks)
def reproject_slice(da, output_crs, output_res, resampling, dask_chunks):
bad_dims = [dim for dim, dim_size in da.sizes.items() if dim not in ('x', 'y') and dim_size > 1]
if bad_dims:
dim_name = bad_dims[0]
return xr.concat([reproject_slice(
da.isel(**{dim_name:i}), output_crs, output_res, resampling, dask_chunks
) for i in range(da[dim_name].size)], dim=dim_name).transpose(*da.dims)
else:
return reproject_da(da, output_crs, output_res, resampling, dask_chunks)
reprojected_data = reproject(da, 'epsg:3857', resampling='nearest')
da.load()
da[0, ..., 0].plot();
| odc_accessibility/Reproject.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
# ---
# +
import os
import csv
import re
import networkx
import pandas
import do_tools
# -
# ! svn checkout svn://svn.code.sf.net/p/diseaseontology/code/trunk/ download
path = os.path.join('download', 'HumanDO.obo')
do = do_tools.load_do(path)
dox = do_tools.do_to_networkx(do)
# Create a table of descriptions
pattern = re.compile(r'^"(.*?)"')
rows = list()
for term in dox:
match = pattern.search(term.definition)
description = match.group(1) if match else ''
rows.append((term.id, term.name, description))
description_df = pandas.DataFrame(rows, columns = ['disease_id', 'name', 'description']).sort_values('disease_id')
description_df.to_csv('data/description.tsv', sep='\t', index=False)
description_df.head(2)
xref_rename = {
'ICD10CM': 'ICD10',
'ICD9CM': 'ICD9',
'NCI2009_04D': 'NCI',
'SNOMEDCT_2010_1_31': 'SNOMEDCT',
'SNOMEDCT_2013_01_31': 'SNOMEDCT',
'UMLS_CUI': 'UMLS',
}
# +
def write_xref_row(writer, doid_code, doid_name, xrefs, rename_dict):
rows = list()
for xref in xrefs:
resource, resource_id = xref.split(':', 1)
if resource in rename_dict:
resource = rename_dict[resource]
rows.append([doid_code, doid_name, resource, resource_id])
rows.sort()
writer.writerows(rows)
file_unprop = open(os.path.join('data', 'xrefs.tsv'), 'w')
file_prop = open(os.path.join('data', 'xrefs-prop.tsv'), 'w')
writer_unprop = csv.writer(file_unprop, delimiter='\t')
writer_prop = csv.writer(file_prop, delimiter='\t')
for writer in writer_unprop, writer_prop:
writer.writerow(['doid_code', 'doid_name', 'resource', 'resource_id'])
for term in networkx.topological_sort_recursive(dox, reverse=True):
xrefs = set(term.xrefs)
xrefs_prop = set(xrefs)
for ancestor in networkx.ancestors(dox, term):
xrefs_prop |= set(ancestor.xrefs)
write_xref_row(writer_unprop, term.id, term.name, xrefs, xref_rename)
write_xref_row(writer_prop, term.id, term.name, xrefs_prop, xref_rename)
for write_file in file_unprop, file_prop:
write_file.close()
# -
# list of xrefs
import pandas
path = os.path.join('data', 'xrefs.tsv')
xref_df = pandas.read_table(path)
set(xref_df.resource)
# create a name to term mapping
rows = list()
for term in dox:
rows.append({'doid': term.id, 'name': term.name, 'type': 'name'})
for synonym in term.synonyms:
rows.append({'doid': term.id, 'name': synonym[0], 'type': '{}-synonym'.format(synonym[1].lower())})
path = os.path.join('data', 'term-names.tsv')
with open(path, 'w') as write_file:
writer = csv.DictWriter(write_file, delimiter='\t', fieldnames=['doid', 'name', 'type'])
writer.writeheader()
writer.writerows(rows)
| DO-xrefs.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
# ---
# <center>
# <img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DL0110EN-SkillsNetwork/Template/module%201/images/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" />
# </center>
#
# <h1>Neural Networks with One Hidden Layer</h1>
#
# <h2>Objective</h2><ul><li> How to classify handwritten digits using Neural Network.</li></ul>
#
# <h2>Table of Contents</h2>
# <p>In this lab, you will use a single layer neural network to classify handwritten digits from the MNIST database.</p>
#
# <ul>
# <li><a href="https://#Model">Neural Network Module and Training Function</a></li>
# <li><a href="https://#Makeup_Data">Make Some Data</a></li>
# <li><a href="https://#Train">Define the Neural Network, Optimizer, and Train the Model</a></li>
# <li><a href="https://#Result">Analyze Results</a></li>
# </ul>
# <p>Estimated Time Needed: <strong>25 min</strong></p>
#
# <hr>
#
# <h2>Preparation</h2>
#
# We'll need the following libraries
#
# +
# Import the libraries we need for this lab
# Using the following line code to install the torchvision library
# # !mamba install -y torchvision
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as dsets
import torch.nn.functional as F
import matplotlib.pylab as plt
import numpy as np
# -
# Use the following helper functions for plotting the loss:
#
# +
# Define a function to plot accuracy and loss
def plot_accuracy_loss(training_results):
plt.subplot(2, 1, 1)
plt.plot(training_results['training_loss'], 'r')
plt.ylabel('loss')
plt.title('training loss iterations')
plt.subplot(2, 1, 2)
plt.plot(training_results['validation_accuracy'])
plt.ylabel('accuracy')
plt.xlabel('epochs')
plt.show()
# -
# Use the following function for printing the model parameters:
#
# +
# Define a function to plot model parameters
def print_model_parameters(model):
count = 0
for ele in model.state_dict():
count += 1
if count % 2 != 0:
print ("The following are the parameters for the layer ", count // 2 + 1)
if ele.find("bias") != -1:
print("The size of bias: ", model.state_dict()[ele].size())
else:
print("The size of weights: ", model.state_dict()[ele].size())
# -
# Define the neural network module or class:
#
# +
# Define a function to display data
def show_data(data_sample):
plt.imshow(data_sample.numpy().reshape(28, 28), cmap='gray')
plt.show()
# -
# <!--Empty Space for separating topics-->
#
# <h2 id="Model">Neural Network Module and Training Function</h2>
#
# Define the neural network module or class:
#
# +
# Define a Neural Network class
class Net(nn.Module):
# Constructor
def __init__(self, D_in, H, D_out):
super(Net, self).__init__()
self.linear1 = nn.Linear(D_in, H)
self.linear2 = nn.Linear(H, D_out)
# Prediction
def forward(self, x):
x = torch.sigmoid(self.linear1(x))
x = self.linear2(x)
return x
# -
# Define a function to train the model. In this case, the function returns a Python dictionary to store the training loss and accuracy on the validation data.
#
# +
# Define a training function to train the model
def train(model, criterion, train_loader, validation_loader, optimizer, epochs=100):
i = 0
useful_stuff = {'training_loss': [],'validation_accuracy': []}
for epoch in range(epochs):
for i, (x, y) in enumerate(train_loader):
optimizer.zero_grad()
z = model(x.view(-1, 28 * 28))
loss = criterion(z, y)
loss.backward()
optimizer.step()
#loss for every iteration
useful_stuff['training_loss'].append(loss.data.item())
correct = 0
for x, y in validation_loader:
#validation
z = model(x.view(-1, 28 * 28))
_, label = torch.max(z, 1)
correct += (label == y).sum().item()
accuracy = 100 * (correct / len(validation_dataset))
useful_stuff['validation_accuracy'].append(accuracy)
return useful_stuff
# -
# <!--Empty Space for separating topics-->
#
# <h2 id="Makeup_Data">Make Some Data</h2>
#
# Load the training dataset by setting the parameters <code>train</code> to <code>True</code> and convert it to a tensor by placing a transform object in the argument <code>transform</code>.
#
# +
# Create training dataset
train_dataset = dsets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor())
# -
# Load the testing dataset and convert it to a tensor by placing a transform object in the argument <code>transform</code>:
#
# +
# Create validating dataset
validation_dataset = dsets.MNIST(root='./data', download=True, transform=transforms.ToTensor())
# -
# Create the criterion function:
#
# +
# Create criterion function
criterion = nn.CrossEntropyLoss()
# -
# Create the training-data loader and the validation-data loader objects:
#
# +
# Create data loader for both train dataset and valdiate dataset
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=2000, shuffle=True)
validation_loader = torch.utils.data.DataLoader(dataset=validation_dataset, batch_size=5000, shuffle=False)
# -
# <!--Empty Space for separating topics-->
#
# <h2 id="Train">Define the Neural Network, Optimizer, and Train the Model</h2>
#
# Create the model with 100 neurons:
#
# +
# Create the model with 100 neurons
input_dim = 28 * 28
hidden_dim = 100
output_dim = 10
model = Net(input_dim, hidden_dim, output_dim)
# -
# Print the model parameters:
#
# +
# Print the parameters for model
print_model_parameters(model)
# -
# Define the optimizer object with a learning rate of 0.01:
#
# +
# Set the learning rate and the optimizer
learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# -
# Train the model by using 100 epochs **(this process takes time)**:
#
# +
# Train the model
training_results = train(model, criterion, train_loader, validation_loader, optimizer, epochs=30)
# -
# <!--Empty Space for separating topics-->
#
# <h2 id="Result">Analyze Results</h2>
#
# Plot the training total loss or cost for every iteration and plot the training accuracy for every epoch:
#
# +
# Plot the accuracy and loss
plot_accuracy_loss(training_results)
# -
# Plot the first five misclassified samples:
#
# +
# Plot the first five misclassified samples
count = 0
for x, y in validation_dataset:
z = model(x.reshape(-1, 28 * 28))
_,yhat = torch.max(z, 1)
if yhat != y:
show_data(x)
count += 1
if count >= 5:
break
# -
# <h3>Practice</h3>
#
# Use <code>nn.Sequential</code> to build exactly the same model as you just built. Use the function <train>train</train> to train the model and use the function <code>plot_accuracy_loss</code> to see the metrics. Also, try different epoch numbers.
#
# +
# Practice: Use nn.Sequential to build the same model. Use plot_accuracy_loss to print out the accuarcy and loss
# Type your code here
# -
# Double-click <b>here</b> for the solution.
#
# <!--
# input_dim = 28 * 28
# hidden_dim = 100
# output_dim = 10
#
# model = torch.nn.Sequential(
# torch.nn.Linear(input_dim, hidden_dim),
# torch.nn.Sigmoid(),
# torch.nn.Linear(hidden_dim, output_dim),
# )
# learning_rate = 0.01
# optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)
# training_results = train(model, criterion, train_loader, validation_loader, optimizer, epochs = 10)
# plot_accuracy_loss(training_results)
# -->
#
# <a href="https://dataplatform.cloud.ibm.com/registration/stepone?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDL0110ENSkillsNetwork20647811-2021-01-01&context=cpdaas&apps=data_science_experience%2Cwatson_machine_learning"><img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DL0110EN-SkillsNetwork/Template/module%201/images/Watson_Studio.png"/></a>
#
# <!--Empty Space for separating topics-->
#
# <h2>About the Authors:</h2>
#
# <a href="https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDL0110ENSkillsNetwork20647811-2021-01-01"><NAME></a> has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.
#
# Other contributors: <a href="https://www.linkedin.com/in/michelleccarey/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDL0110ENSkillsNetwork20647811-2021-01-01"><NAME></a>, <a href="https://www.linkedin.com/in/jiahui-mavis-zhou-a4537814a?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDL0110ENSkillsNetwork20647811-2021-01-01"><NAME></a>
#
# ## Change Log
#
# | Date (YYYY-MM-DD) | Version | Changed By | Change Description |
# | ----------------- | ------- | ---------- | ----------------------------------------------------------- |
# | 2020-09-23 | 2.0 | Shubham | Migrated Lab to Markdown and added to course repo in GitLab |
#
# <hr>
#
# ## <h3 align="center"> © IBM Corporation 2020. All rights reserved. <h3/>
#
| 4. Deep Neural Networks with PyTorch/4. Softmax Rergresstion/6. one_layer_neural_network_MNIST.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
# ---
# # Generating and Plotting Distributions, and the Perils of Small Sample-Sizes
# +
# all import modules
import matplotlib.pyplot as plt
import numpy as np
# set some global parameters
np.set_printoptions(suppress=True)
params = {'legend.fontsize': 18,
'axes.labelsize': 18,
'axes.titlesize':24,
'xtick.labelsize':18,
'ytick.labelsize':18,
'font.size': 24}
plt.rcParams.update(params)
# -
# ## Introduction
#
# What happens if I were to roll a 10-sided die again and again - what would the distribution of numbers that came up look like?
#
# What would happen if I were to roll **two** 10-sided dice again and again and took the average of their results?
#
# What if I added more of the same dice into the mix?
def dist_gen(samples=1e6, draws=4, lowBound=0, upBound=100):
count = []
samples = int(samples)
lowBound = int(lowBound)
upBound = int(upBound)
for i in range(samples):
for j in range(draws):
count.append(np.mean(np.random.randint(lowBound,
upBound + 1,
draws)))
plt.hist(count, bins=range(lowBound, upBound + 2))
plt.show()
lq = np.percentile(count, 25)
uq = np.percentile(count, 75)
mu = np.mean(count)
sig = np.std(count)
tot_N = samples * draws
snr = np.sqrt(tot_N)
std_err = mu/np.sqrt(tot_N)
print(
'For {0} iterations and {4} draws: '
'Mean = {1:.1f}, '
'Sigma = {5:.1f}, '
'LQ = {2:.1f}, '
'UQ = {3:.1f}, '
'SNR = {6:.1f}, '
'Std. Error = {7:.3f}'
.format(samples, mu, lq, uq, draws, sig, snr, std_err))
return samples, draws, mu, sig, lq, uq, snr, std_err
# +
# 10-sided
for i in range(1, 5):
dist_gen(samples=1e5, draws=i, lowBound=1, upBound=10)
# +
# increase resolution: 100-sided
for i in range(1, 5):
dist_gen(samples=1e5, draws=i, lowBound=1, upBound=100)
# -
# ## Shot-Noise
#
# If we roll a fair *n*-sided die *n*-times, in **theory** we should get each number once.
#
# However, does this happen in **practice**? If not, why, and how do we achieve the theoretical result?
# ### Example: 10-sided die
# +
# Shot-noise demonstration
values10 = np.zeros([5,8])
for row, i in enumerate(np.logspace(1, 5, num=5, base=10), start=0):
values10[row] = dist_gen(samples=i, draws=1, lowBound=1, upBound=10)
# -
# ### Example: 6-sided die
# +
values6 = np.zeros([5,8])
for row, i in enumerate(np.logspace(1, 5, num=5, base=6), start=0):
values6[row] = dist_gen(samples=i, draws=1, lowBound=1, upBound=6)
# -
# ### Example: 2-sided coin
# +
values2 = np.zeros([5,8])
for row, i in enumerate(np.logspace(1, 5, num=5, base=10), start=0):
values2[row] = dist_gen(samples=i, draws=1, lowBound=1, upBound=2)
# +
fig, ax = plt.subplots(1,3)
fig.set_size_inches(16, 8)
ax[0].scatter(values10[:, 0], values10[:,7], label='10-sided')
ax[1].semilogx(values10[:, 0], values10[:,7])
ax[2].loglog(values10[:, 0], values10[:,7])
ax[0].scatter(values6[:, 0], values6[:,7], label='6-sided')
ax[1].semilogx(values6[:, 0], values6[:,7])
ax[2].loglog(values6[:, 0], values6[:,7])
ax[0].scatter(values2[:, 0], values2[:,7], label='2-sided')
ax[1].semilogx(values2[:, 0], values2[:,7])
ax[2].loglog(values2[:, 0], values2[:,7])
ax[0].legend(loc=0)
ax[0].set_ylabel(r'Standard Error on $\mu$')
ax[1].set_xlabel(r'Number of Samples ($N$)')
ax[0].set_title(r'Linear Axes')
ax[1].set_title(r'Semi-Log X-axis')
ax[2].set_title(r'Log-log axes')
plt.show()
| Distributions_and_Shot_Noise.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
# ---
# + slideshow={"slide_type": "skip"}
# disable warnings
import warnings
warnings.filterwarnings('ignore')
TOPAZ = ("topaz","f071c66c")
WITTI = ("witti","f6775d07")
ALTONA = ("altona","fdca39b0")
MEDALLA = ("medalla","e7a75d5a")
# + tags=["parameters"]
NETWORK,FORK_DIGEST=MEDALLA
LOAD_SESSION=False
# +
import pandas as pd
from pathlib import Path
import glob
import os
import pickle
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import json
def load_crawl_data(network, fork_digest, from_pickel):
dfs = []
start = 12000
path = str(Path.home())+"/.{}/".format(network)
if from_pickel:
file = open('../data/{}-crawl-data.pkl'.format(network), 'rb')
(df_all_with_dups, df_all, df, tot_num_nodes, num_nodes) = pickle.load(file)
file.close()
else:
pattern = "{}{}".format(path,"crawler*")
numFiles = len(glob.glob(pattern)) #!ls -l ~/.$network/crawler* |wc -l
end = start + numFiles
for port in list(range(start,end)):
file = path+"/crawler"+str(port)+".csv"
df = pd.read_csv(file)
df.drop(columns=['index'])
dfs.append(df)
df_all_with_dups = pd.concat(dfs).reset_index(drop=True).sort_values(by=['seq_no'], ascending=False) #ensure we keep highest seq no
df_all = df_all_with_dups.drop_duplicates(subset="node_id", keep = 'first').reset_index(drop=True)
df_all.set_index('node_id')
df = df_all[df_all['fork_digest']==fork_digest]
tot_num_nodes = len(df_all)
num_nodes = len(df)
file = open('../data/{}-crawl-data.pkl'.format(NETWORK), 'wb')
foo = (df_all_with_dups, df_all, df, tot_num_nodes, num_nodes)
pickle.dump(foo,file)
file.close()
return (df_all_with_dups, df_all, df, tot_num_nodes, num_nodes)
def load_consensus_data(network,from_pickel):
active_validators = 0
path = str(Path.home())+"/.{}/".format(network)
if from_pickel:
file = open('../data/{}-consensus-data.pkl'.format(network), 'rb')
active_validators = pickle.load(file)
file.close()
else:
url = "https://{}.beaconcha.in".format(network);
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
response = urlopen(req)
bs = BeautifulSoup(response.read(), 'html.parser')
target = '"active_validators":'
for tag in bs.find_all('script'):
if target in tag.get_text():
text = tag.get_text()
start_index = text.index(target)+len(target)
end_index = start_index + text[start_index:].index(",")
active_validators = int(text[start_index:end_index])
break
file = open('../data/{}-consensus-data.pkl'.format(NETWORK), 'wb')
pickle.dump(active_validators,file)
file.close()
return active_validators
# -
# + slideshow={"slide_type": "skip"}
# %%capture
import ipinfo
import pickle
if LOAD_SESSION is True:
active_validators = load_consensus_data(NETWORK,True)
(df_all_with_dups, df_all, df, tot_num_nodes, num_nodes) = load_crawl_data(NETWORK,FORK_DIGEST,True)
# load any stored ip info
ips = df["ip4"].to_list()
file = open('../data/ips_info.pkl', 'rb')
saved_ips_info = pickle.load(file)
file.close()
else:
active_validators = load_consensus_data(NETWORK,False)
(df_all_with_dups, df_all, df, tot_num_nodes, num_nodes) = load_crawl_data(NETWORK,FORK_DIGEST,False)
# load any stored ip info
ips = df["ip4"].to_list()
file = open('../data/ips_info.pkl', 'rb')
saved_ips_info = pickle.load(file)
file.close()
# determine what ips we need to lookup
need_info = []
for ip in ips:
if ip not in saved_ips_info:
need_info.append(ip)
print("Fetching missing info for ", len(need_info), " ip addresses.");
# get missing ip info
handler = ipinfo.getHandler('7bbf8b616179fb')
ips_info = [handler.getDetails(ip) for ip in need_info]
# save the ip info for next time
file = open('../data/ips_info.pkl', 'wb')
for ip_info in ips_info:
saved_ips_info[ip_info.ip] = ip_info.all
pickle.dump(saved_ips_info,file)
file.close()
ips_info={}
for ip in ips:
ips_info[ip]=saved_ips_info[ip]
bad_ips = []
for ip,info in ips_info.items():
if info['country_name'] == None:
bad_ips.append(ip)
# collect node_ids of the records with bad ip addresses
bad_ip_node_ids = df[df['ip4'].isin(bad_ips)]['node_id'].to_list()
asn_orgs = [info['org'] if 'org' in info else 'None' for ip,info in ips_info.items()]
asn_orgs = [' '.join(org.split(' ')[1:]) for org in asn_orgs if org != 'None']
# + slideshow={"slide_type": "skip"}
# + slideshow={"slide_type": "slide"} variables={" NETWORK.title() ": "Topaz", " num_nodes ": "464", " tot_num_nodes ": "465", "-NETWORK.title()-": "<p><strong>SyntaxError</strong>: invalid syntax (<ipython-input-32-bef0a151a7ea>, line 1)</p>\n"}
from IPython.display import Markdown as md
# A (DHT) Crawl Through The {{ NETWORK.title() }} Testnet 🕷
display(md("# A (DHT) Crawl Through The {} Testnet 🕷".format(NETWORK.title())))
display(md("##### by [<NAME>](https://twitter.com/JonnyRhea) of [TXRX Research](https://twitter.com/TXRXResearch)"))
display(md("\n"))
display(md("Last Updated: {}".format(df.timestamp.max().split(']')[0])))
# + slideshow={"slide_type": "slide"} variables={" NETWORK.title() ": "Topaz", " num_nodes ": "464", " tot_num_nodes ": "465", "-NETWORK.title()-": "<p><strong>SyntaxError</strong>: invalid syntax (<ipython-input-32-bef0a151a7ea>, line 1)</p>\n"}
display(md("### 🕸 Crawl Summary 🕸"))
display(md("\n") )
display(md("- **Total number of nodes found:** {}".format(tot_num_nodes)))
display(md("- **Number of nodes on {}:** {}".format(NETWORK.title(), num_nodes)))
# + slideshow={"slide_type": "fragment"}
import matplotlib
# %matplotlib inline
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
fork_digests = df_all["fork_digest"].to_list()
counts = Counter(fork_digests)
counts = sorted(counts.items(), key=lambda i: i[1], reverse=True)
labels, values = zip(*counts)
indexes = np.arange(len(labels))
width = .5
plt.rc('font', family='serif')
plt.figure(figsize=(12,6))
plt.title('Node Count by Fork Digest')
plt.bar(indexes, values, width)
plt.xticks(indexes, labels)
plt.grid(linestyle='-', linewidth='0.5', color='grey')
plt.show()
# -
display(md("> #### Only nodes with fork-digest `{}` are members of the `{}` network.".format(FORK_DIGEST,NETWORK.title())))
# + slideshow={"slide_type": "fragment"}
import matplotlib.pyplot as plt
from collections import Counter
from matplotlib.ticker import MaxNLocator
#plot node count by country
countries=[]
for ip,info in ips_info.items():
if info['country_name'] != None:
countries.append(info['country'])
counts = Counter(countries)
counts = sorted(counts.items(), key=lambda i: i[1], reverse=True)
title_text = NETWORK.title()+' Node Count by Country'
if len(counts) >= 10:
title_text = NETWORK.title()+' Node Count by Country (Top 10)'
counts = counts[:10]
labels, values = zip(*counts)
indexes = np.arange(len(labels))
width = .5
fig,ax = plt.subplots(1,figsize=(24,12))
ax.set_title(title_text,fontsize=30)
ax.bar(indexes, values, width)
ax.set_xticks(indexes)
ax.set_xticklabels(labels)
ax.set_xlabel("Country",fontsize=30)
ax.tick_params(size=12,labelsize=20)
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
plt.grid(linestyle='-', linewidth='0.5', color='grey')
plt.rc('font', family='serif')
plt.tight_layout()
plt.show()
# + slideshow={"slide_type": "fragment"}
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from collections import Counter
import numpy as np
# plot nodes on map
lats=[]
lons=[]
for ip,info in ips_info.items():
if info['country_name'] != None:
lats.append(float(info['latitude']))
lons.append(float(info['longitude']))
fig,ax = plt.subplots(1,figsize=(24,24))
map = Basemap(projection='cyl', resolution='l',ax=ax)
map.drawlsmask()
x, y = map(lons, lats)
map.scatter(x, y, s=100, color='#ff0000', marker='o', alpha=0.9)
ax.set_title(NETWORK.title()+' Node Location',fontsize=30)
plt.rc('font', family='serif')
plt.tight_layout()
plt.show()
# + [markdown] slideshow={"slide_type": "fragment"}
# > Node location information is gathered by geolocating ip addresses 🌍
# + slideshow={"slide_type": "skip"}
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
counts = Counter(asn_orgs)
counts = sorted(counts.items(), key=lambda i: i[1], reverse=True)
title_text = NETWORK.title()+' IP Address ASNs'
if len(counts) >= 10:
title_text = NETWORK.title()+' IP Address ASNs (Top 10)'
counts = counts[:10]
labels, values = zip(*counts)
indexes = np.arange(len(labels))
width = .75
plt.rc('font', family='serif')
plt.figure(figsize=(30,20))
plt.title(title_text, fontsize=30)
plt.bar(indexes, values, width)
plt.xticks(rotation=90)
plt.xticks(indexes, labels, fontsize=16)
plt.yticks(fontsize=20)
ax = plt.axes()
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
plt.grid(linestyle='-', linewidth='0.5', color='grey')
plt.tight_layout()
plt.show()
# -
# > This plot gives us an idea of the network's reliance on ISPs and cloud providers.
# + slideshow={"slide_type": "fragment"}
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
from collections import Counter
NUM_NODES = len(df)
df_nodes_with_bad_ip = df_all_with_dups[df_all_with_dups['node_id'].isin(bad_ip_node_ids)].drop_duplicates(subset="node_id", keep = 'first')
PERCENT_WITH_BAD_IP = len(df_nodes_with_bad_ip[df_nodes_with_bad_ip['fork_digest']==FORK_DIGEST])/NUM_NODES
num_nodes_cloud_hosted = 0
for org in asn_orgs:
if "Amazon" in org or "Google" in org or "Microsoft" in org or "DigitalOcean" in org:
num_nodes_cloud_hosted += 1
PERCENT_CLOUD_HOSTED=num_nodes_cloud_hosted/NUM_NODES
# Data
r = [0,1]
raw_data = {'blueBars': [1-PERCENT_WITH_BAD_IP,PERCENT_CLOUD_HOSTED], 'orangeBars': [PERCENT_WITH_BAD_IP,1-PERCENT_CLOUD_HOSTED]}
df_nodes = pd.DataFrame(raw_data)
# From raw value to percentage
totals = [i+j for i,j in zip(df_nodes['blueBars'], df_nodes['orangeBars'])]
blueBars = [i / j * 100 for i,j in zip(df_nodes['blueBars'], totals)]
orangeBars = [i / j * 100 for i,j in zip(df_nodes['orangeBars'], totals)]
# plot
barWidth = 0.45
names = ('Nodes With Valid IPs','Nodes on AWS,GCP,Azure,DigitalOcean')
fig,ax = plt.subplots(figsize=(18,8))
ax.bar(r, blueBars, color='C0', edgecolor='white', width=barWidth)
ax.bar(r, orangeBars, bottom=blueBars, color='C1', edgecolor='white', width=barWidth)
ax.set_ylabel('Percent',fontsize=17)
ax.tick_params(size=12,labelsize=17)
for p in ax.patches:
width, height = p.get_width(), p.get_height()
x, y = p.get_xy()
if height > 5:
ax.text(x+width/2,
y+height/2,
'{:.0f} %'.format(height),
horizontalalignment='center',
verticalalignment='center',
fontsize = 17,
color='white')
plt.title(NETWORK.title()+' Node IP Info',fontsize=20)
# Custom x axis
plt.xticks(r, names)
plt.rc('font', family='serif')
# Show graphic
plt.show()
# + [markdown] slideshow={"slide_type": "fragment"}
# > - **Nodes with Valid IPs:** IP address within one of the private IPv4 network ranges were considered invalid.
# > - **Nodes on AWS, GCP, Azure, Digital Ocean:** IP addresses that corresponded to an ASN that belongs to Amazon, Google, Microsoft, or Digital Ocean.
# +
import matplotlib.pyplot as plt
from pywaffle import Waffle
# - 105 nodes * .56 = 58.8 ~ 59 validating nodes
# - 453 subnet subscriptions
# - 832 active validators
# 453/59 ~ 7.7 subnet subscriptions per node
# 453/64 ~ 7 subscriptions per subnet
# 832/59
vc_list = []
for ids_str in df["subnet_ids"].to_list():
ids = eval(ids_str)
vc_list.append(len(ids))
df_vc = pd.DataFrame(vc_list, columns =['subnet count group'])
bins = list(range(0, 64, 7))+[64]
df_vc['buckets']=pd.cut(df_vc['subnet count group'], bins)
df_vc['subnet_ids']=df["subnet_ids"].reset_index(drop=True)
subnet_count_per_node = list(df_vc['subnet count group'])
validating_node_count = sum([1 for i in subnet_count_per_node if i > 0])
#consider any node with gte 64 subnet subscriptions a supernode
supernode_count = sum([1 for i in subnet_count_per_node if i==64])
num_subnet_subscriptions = sum(subnet_count_per_node)
#calc num validators on reg nodes
validators_on_regnodes = sum([i for i in subnet_count_per_node if i<64])
#calc number of validators hosted on supernodes
validators_on_supernodes = active_validators - validators_on_regnodes
data = {'Validating nodes': 100*validating_node_count/num_nodes,
'Non-validating nodes': 100*(1-validating_node_count/num_nodes)}
legend_data = {'Validating nodes': validating_node_count,
'Non-validating nodes': num_nodes-validating_node_count}
fig = plt.figure(
FigureClass=Waffle,
rows=5,
values=data,
colors=("C0","C1"),
title={'label': 'Validating vs. Non-Validating Nodes', 'loc': 'center','fontsize':'20'},
labels=["{0} ({1} nodes)".format(k, v) for k, v in legend_data.items()],
legend={'loc': 'lower left', 'bbox_to_anchor': (0, -0.2), 'ncol': 2, 'framealpha': 0},
icons='server', icon_size=38,
icon_legend=True,
figsize=(12, 12)
)
plt.show()
# -
# > If a node's ENR indicated that it belonged to one or more persistent committees, then it was considered a validating node.
# + slideshow={"slide_type": "fragment"}
import numpy as np
import matplotlib.pyplot as plt
subnets = df["subnet_ids"].to_list()
subnets = [subnet.replace('[','').replace(']','').replace(' ','') for subnet in subnets]
subnets = [subnet if len(subnet) > 0 else ' None' for subnet in subnets]
subnets = ','.join(subnets)
subnets = subnets.split(',')
labels = [str(label) for label in list(range(0,64))]# + [' None']
values = [subnets.count(label) for label in labels]
indexes = np.arange(len(labels))
width = .5
plt.figure(figsize=(18,8))
plt.title(NETWORK.title()+' Subnet Distribution',fontsize=30)
plt.bar(indexes, values, width)
plt.yticks(fontsize=12)
plt.xticks(indexes, labels,fontsize=12)
plt.xlabel("Subnet",fontsize=20)
plt.rc('font', family='serif')
plt.grid(linestyle='-', linewidth='0.5', color='grey')
plt.tight_layout()
plt.show()
# + [markdown] slideshow={"slide_type": "fragment"}
# > Subnet subscriptions should be evenly distributed from `0 - 63`.
# +
import matplotlib.pyplot as plt
from pywaffle import Waffle
groups = pd.DataFrame(df_vc.groupby(pd.cut(df_vc['subnet count group'], bins)).size(), columns =['count']).reset_index()
#groups = groups[groups['count']>0]
data = {}
legend_data = {}
for k,v in zip(list(groups['subnet count group']),list(groups['count'])):
key="{} < subnet subscriptions <= {}".format(k.left,k.right)
data[key]=v/validating_node_count*100
legend_data[key]=v
fig = plt.figure(
FigureClass=Waffle,
rows=5,
values=data,
colors=('C0', 'C1', 'C2', 'C3', 'C4','C5','C6','C7','C8','C9'),
title={'label': 'Validating Node Distribution', 'loc': 'center','fontsize':'20'},
labels=["{0} ({1} nodes)".format(k, v) for k, v in legend_data.items()],
legend={'loc': 'lower left', 'bbox_to_anchor': (0, -0.5), 'ncol': 2, 'framealpha': 0},
icons='server', icon_size=38,
icon_legend=True,
figsize=(12, 12),
rounding_rule='ceil'
)
plt.show()
# + [markdown] slideshow={"slide_type": "fragment"}
# > This chart bucketizes nodes by the number of subnets they are subscribed to. This info can be used to estimate how many validators a particular node hosts. 😅
# +
data = {'Regularnodes': 100*validators_on_regnodes/active_validators,
'Supernodes': 100*validators_on_supernodes/active_validators}
legend_data = {'Hosted by nodes with < 64 subnet subscriptions': validators_on_regnodes,
'Hosted by nodes with >= 64 subnet subscriptions': validators_on_supernodes}
fig = plt.figure(
FigureClass=Waffle,
rows=5,
values=data,
colors=('C0', 'C1'),
title={'label': 'Validator Clustering Across Nodes', 'loc': 'center','fontsize':'20'},
labels=["{0} ({1} validators)".format(k, v) for k, v in legend_data.items()],
legend={'loc': 'lower left', 'bbox_to_anchor': (0, -0.3), 'ncol': 1, 'framealpha': 0},
icons='child', icon_size=38,
icon_legend=True,
figsize=(12, 12)
)
plt.show()
# + [markdown] slideshow={"slide_type": "fragment"}
# > Again, the subnet subscriptions are used to bucketize nodes. If a node has < 64 subnet subscriptions, then it is blue; otherwise, orange.
# +
import numpy as np
import matplotlib.pyplot as plt
sorted_subnet_count_per_node=sorted([i for i in subnet_count_per_node if i > 0])
sorted_subnet_count_per_node=[i if i < 64 else validators_on_supernodes/supernode_count for i in sorted_subnet_count_per_node]
arr = np.array(sorted_subnet_count_per_node)
def gini(arr):
count = arr.size
coefficient = 2 / count
indexes = np.arange(1, count + 1)
weighted_sum = (indexes * arr).sum()
total = arr.sum()
constant = (count + 1) / count
return coefficient * weighted_sum / total - constant
def lorenz(arr):
# this divides the prefix sum by the total sum
# this ensures all the values are between 0 and 1.0
scaled_prefix_sum = arr.cumsum() / arr.sum()
# this prepends the 0 value (because 0% of all people have 0% of all wealth)
return np.insert(scaled_prefix_sum, 0, 0)
lorenz_curve = lorenz(arr)
plt.rc('font', family='serif')
plt.figure(figsize=(12,12))
plt.title(NETWORK.title()+' Validator Distribution Lorenz Curve (Gini={})'.format(round(gini(arr),2)), fontsize=20)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
ax = plt.axes()
ax.set_ylabel('Cumulative %Participation',fontsize=17)
ax.set_xlabel('Cumulative %Population',fontsize=17)
plt.grid(linestyle='-', linewidth='0.5', color='grey')
x=np.linspace(0.0, 1.0, lorenz_curve.size)
plt.plot(x,lorenz_curve,label='Lorenz Curve')
ax.fill_between(x,0,lorenz_curve)
plt.plot([0,1], [0,1],label='Line of Equality')
plt.legend(loc='upper center')
plt.tight_layout()
plt.show()
# + [markdown] slideshow={"slide_type": "fragment"}
# > The Gini coefficient and Lorenz Curve is another way to look at the distribution of validators across nodes. The closer the Gini coefficient is to zero, the more evenly distributed the validators are. Similarly, if every validating node hosted the same number of validators, then the shaded region would be the area under the 'Line of Equality' y=x.
# + slideshow={"slide_type": "skip"}
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
node_ids = df["node_id"].to_list()
node_ids = [node_id.strip() for node_id in node_ids]
node_ids_freq = [Counter(node_id) for node_id in node_ids]
hex_chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
freqs = []
for node_id_freq in node_ids_freq:
freqs.append([node_id_freq[hex_char] for hex_char in hex_chars])
x, y = np.meshgrid(hex_chars, node_ids)
intensity = np.array(freqs)
#plt.title(NETWORK.title()+' NodeId Character Heatmap',fontsize=40)
#plt.pcolormesh(x, y, intensity)
#plt.colorbar()
#plt.rc('font', family='serif')
#plt.xticks(fontsize=40)
#plt.rcParams["figure.figsize"] = (50,50)
#plt.tight_layout()
#plt.show()
# -
# +
pd.set_option('display.max_columns', None)
pd.set_option('display.expand_frame_repr', False)
pd.set_option('display.max_colwidth', -1)
pd.set_option('display.width', None)
#print(df[(df['next_fork_version']!=113) | (df['next_fork_epoch']!=18446744073709551615)])
# -
#for ip in ips_info:
# info = ips_info[ip]
# if info['country_name'] != None:
# if info['city'] == 'Madrid':
# print(df[df['ip4']==info['ip']])
pd.reset_option('display.max_columns')
pd.reset_option('display.expand_frame_repr')
pd.reset_option('display.max_colwidth')
pd.reset_option('display.width')
# +
# %%capture
df_dht = df
coordinates=[]
for node_id,ip in zip(df_dht["node_id"].to_list(),df_dht["ip4"].to_list()):
if node_id not in bad_ip_node_ids:
coordinates.append((ips_info[ip]['loc']))
else:
coordinates.append((0,0))
df_dht["coordinates"]=coordinates
# %store df_dht
# -
| analysis/testnet-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
# ---
# <h1> <b>Homework 2</b></h1>
# <i><NAME><br>
# <EMAIL><br>
# W261: Machine Learning at Scale<br>
# Week: 02<br>
# Jan 26, 2016</i></li>
# <h2>HW2.0. </h2>
# What is a race condition in the context of parallel computation? Give an example.
# What is MapReduce?
# How does it differ from Hadoop?
# Which programming paradigm is Hadoop based on? Explain and give a simple example in code and show the code running.
# <h2>HW2.1. Sort in Hadoop MapReduce</h2>
# Given as input: Records of the form '<'integer, “NA”'>', where integer is any integer, and “NA” is just the empty string.
# Output: sorted key value pairs of the form '<'integer, “NA”'>' in decreasing order; what happens if you have multiple reducers? Do you need additional steps? Explain.
#
# Write code to generate N random records of the form '<'integer, “NA”'>'. Let N = 10,000.
# Write the python Hadoop streaming map-reduce job to perform this sort. Display the top 10 biggest numbers. Display the 10 smallest numbers
#
#
# # Data
# +
import random
N = 10000 ### for a sample size of N
random.seed(0) ### pick a random seed to replicate results
input_file = open("numcount.txt", "w") # writing file
for i in range(N):
a = random.randint(0, 100) ### Select a random integer from 0 to 100
b = ''
input_file.write(str(a))
input_file.write(b)
input_file.write('\n')
input_file.close()
# -
# # Mapper
# +
# %%writefile mapper.py
# #!/usr/bin/python
## mapper.py
## Author: <NAME>
## Description: mapper code for HW2.2
import sys
import re
########## Collect user input ###############
filename = 'enronemail_1h.txt'
findwords = ['assistance', 'commercial', 'intelligence','call', 'yes', 'no', 'maybe', 'welcome', 'thank', 'hi']
counts = {}
##filename = sys.argv[1]
##findwords = re.split(" ",sys.argv[2].lower())
for keyword in findwords: ### Initialize to zero all keywords to find
counts[keyword] = 0
## open the input file
with open (filename, "r") as myfile:
for line in myfile.readlines():
record = re.split(r'\t+', line)
if len(record) == 4: ### Take only complete records
for keyword in findwords: ### For each word to find
for i in range (2,len(record)): ### Compare it to the words from each email
bagofwords = re.split(" ",record[i]) ### Break each email records into words
for word in bagofwords:
neword = word.strip(',') ### eliminate comas
if keyword in neword:
counts[keyword] += 1
for keyword in findwords: ### output results in the form:
print ('%s\t%s'% (keyword, str(counts[keyword]))) ### word to find, count
# -
# !chmod +x mapper.py
# # Reducer
# +
# %%writefile reducer.py
# #!/usr/bin/python
from operator import itemgetter
import sys
current_number = None
current_count = 0
number = None
numlist = []
# input comes from STDIN
for line in sys.stdin:
line = line.strip() ### remove leading and trailing whitespace
line = line.split('\t') ### parse the input we got from mapper.py
number = line[0] ### integer generated randomly we got from mapper.py
try:
count = line[1]
count = int(count) ### convert count (currently a string) to int
except ValueError: ### if count was not a number then silently
continue ### ignore/discard this line
if current_number == number: ### this IF-switch only works because Hadoop sorts map output
current_count += count ### by key (here: number) before it is passed to the reducer
else:
if current_number:
numlist.append((current_number,current_count)) ### store tuple in a list once totalize count per number
current_count = count ### set current count
current_number = number ### set current number
if current_number == number: ### do not forget to output the last word if needed!
numlist.append((current_number,current_count))
toplist = sorted(numlist,key=lambda record: record[1], reverse=True) ### sort list from largest count to smallest
bottomlist = sorted(numlist,key=lambda record: record[1]) ### sort list from smalles to largest
print '%25s' %'TOP 10', '%25s' % '', '%28s' %'BOTTOM 10'
print '%20s' %'Number', '%10s' %'Count', '%20s' % '', '%20s' %'Number','%10s' %'Count'
for i in range (10):
print '%20s%10s' % (toplist[i][0], toplist[i][1]),'%20s' % '', '%20s%10s' % (bottomlist[i][0], bottomlist[i][1])
# -
# !chmod +x reducer.py
# !echo "10 \n 10\n 5\n 6\n 8\n 9 \n 10 \n 9 \n 12 \n 21 \n 22 \n 23 \n 24 \n 25" | python mapper.py | sort -k1,1 | python reducer.py
# # Run numcount in Hadoop
# <h2>start yarn and hdfs</h2>
# !/usr/local/Cellar/hadoop/2.7.1/sbin/start-yarn.sh ### start up yarn
# !/usr/local/Cellar/hadoop/2.7.1/sbin/start-dfs.sh ### start up dfs
# <h2> remove files from prior runs </h2>
# !hdfs dfs -rm -r /user/venamax ### remove prior files
# <h2> create folder</h2>
# !hdfs dfs -mkdir -p /user/venamax ### create hdfs folder
# <h2> upload numcount.txt to hdfs</h2>
# !hdfs dfs -put enronemail_1h.txt /user/venamax #### save source data file to hdfs
# <h2> Hadoop streaming command </h2>
# hadoop jar hadoopstreamingjarfile \
#
# -D stream.num.map.output.key.fields=n \
# -mapper mapperfile \
# -reducer reducerfile \
# -input inputfile \
# -output outputfile
# !hadoop jar hadoop-*streaming*.jar -mapper mapper.py -reducer reducer.py -input enronemail_1h.txt -output testcountOutput
# <h2>show the results</h2>
# !hdfs dfs -cat numcountOutput/part-00000
# <h2>stop yarn and hdfs </h2>
# !/usr/local/Cellar/hadoop/2.7.1/sbin/stop-yarn.sh
# !/usr/local/Cellar/hadoop/2.7.1/sbin/stop-dfs.sh
# <h2>=====================
# END OF HW 2.1</h2>
# <h2>HW2.2. WORDCOUNT</h2>
# Using the Enron data from HW1 and Hadoop MapReduce streaming, write the mapper/reducer job that will determine the word count (number of occurrences) of each white-space delimitted token (assume spaces, fullstops, comma as delimiters). Examine the word “assistance” and report its word count results.
#
#
# CROSSCHECK: >grep assistance enronemail_1h.txt|cut -d$'\t' -f4| grep assistance|wc -l
# 8
# #NOTE "assistance" occurs on 8 lines but how many times does the token occur? 10 times! This is the number we are looking for!
# # Mapper
# +
# %%writefile mapper.py
# #!/usr/bin/python
## mapper.py
## Author: <NAME>
## Description: mapper code for HW2.2
import sys
import re
########## Collect user input ###############
filename = 'enronemail_1h.txt'
findwords = 'assistance'
##filename = sys.argv[1]
##findwords = re.split(" ",sys.argv[2].lower())
## open the input file
with open (filename, "r") as myfile:
## loop over the lines
for line in myfile.readlines( ) :
## check to see if we are counting up a specified set of words
## and if so initialize the list
ALLWORDS=False
counts = {}
if len(findwords) == 1 and findwords[0] == "*":
ALLWORDS=True
else:
for word in findwords:
counts[word] = 0
counts[word] = 0
## strip off line breaks
line = re.sub('\n','',line)
## make sure the format of the line is correct
if re.match("(.*?)\t(.*?)\t(.*?)\t(.*?)",line):
## store the line's data
[ID,SPAM,SUBJECT,CONTENT] = re.split("\t",line)
DAT = CONTENT.lower()
counts["SPAM"] = SPAM
if DAT != "NA":
## gather words by a regex split
words = re.split('[^A-Za-z\-\']+',DAT)
## loop over words
for word in words:
## clean up each word
neword = re.sub('^\'+','',word)
neword = re.sub('^\-+','',neword)
neword = re.sub('\-+$','',neword)
neword = re.sub('\'+','\'',neword)
neword = re.sub('\-+','-',neword)
## if there is a word left after the regex, count it
if re.match("[a-zA-Z]",neword):
if ALLWORDS:
if neword in counts.keys():
counts[neword] += 1
else:
counts[neword] = 1
elif neword in counts.keys():
counts[neword] += 1
dicStr = str(counts)
## print out the counts
print ID + '\t' + dicStr
### output: word, 1, id, spam truth and flag
# -
# !chmod +x mapper.py
# # Reducer
# +
# %%writefile reducer.py
# #!/usr/bin/python
from operator import itemgetter
import sys
current_word = None
current_count = 0
current_flag = 0
word = None
words = []
# input comes from STDIN
for line in sys.stdin:
line = line.strip() ### remove leading and trailing whitespace
line = line.split('\t') ### parse the input we got from mapper.py
word = line[0] ### word we got from mapper.py
try:
count = line[1]
count = int(count) ### convert count (currently a string) to int
## flag = line[4]
## flag = int(flag)
except ValueError: ### if count was not a number then silently
continue ### ignore/discard this line
if current_word == word: ### this IF-switch only works because Hadoop sorts map output
current_count += count ### by key (here: number) before it is passed to the reducer
else:
if current_word:
words.append((current_word,current_count)) ### store tuple in a list once totalize count per word
if current_word == 'assistance ':
print 'We found %s' %current_word, ' in %d occasion' %current_count
current_count = count ### set current count
current_word = word ### set current number
current_flag = flag
if current_word == word: ### do not forget to output the last word if needed!
words.append((current_word,current_count))
if current_word == 'assistance ':
print 'We found %s' %current_word, ' in %d occasions.' %current_count
# -
# !chmod +x reducer.py
grep assistance enronemail_1h.txt|cut -d$'\t' -f4| grep assistance|wc -l
# # Run numcount in Hadoop
# <h2>start yarn and hdfs</h2>
# !/usr/local/Cellar/hadoop/2.7.1/sbin/start-yarn.sh ### start up yarn
# !/usr/local/Cellar/hadoop/2.7.1/sbin/start-dfs.sh ### start up dfs
# <h2> remove files from prior runs</h2>
# !hdfs dfs -rm -r /user/venamax ### remove prior files
# <h2> create folder</h2>
# !hdfs dfs -mkdir -p /user/venamax ### create hdfs folder
# <h2> upload enronemail_1h.txt to hdfs</h2>
# !hdfs dfs -put enronemail_1h.txt /user/venamax #### save source data file to hdfs
# <h2> Hadoop streaming command </h2>
# !hadoop jar hadoop-*streaming*.jar -mapper mapper.py -reducer reducer.py -input enronemail_1h.txt -output wordcountOutput
# <h2>show the results</h2>
# !hdfs dfs -cat wordcountOutput/part-00000
# <h2>stop yarn and hdfs </h2>
# !/usr/local/Cellar/hadoop/2.7.1/sbin/stop-yarn.sh
# !/usr/local/Cellar/hadoop/2.7.1/sbin/stop-dfs.sh
# <h2>=====================
# END OF HW 2.2</h2>
# # Mapper
# +
# %%writefile mapper.py
# #!/usr/bin/python
## mapper.py
## Author: <NAME>
## Description: mapper code for HW2.2
import sys
import re
########## Collect user input ###############
filename = sys.argv[1]
findwords = re.split(" ",sys.argv[2].lower())
with open (filename, "r") as myfile:
for line in myfile.readlines():
line = line.strip()
record = re.split(r'\t+', line) ### Each email is a record with 4 components
### 1) ID 2) Spam Truth 3) Subject 4) Content
if len(record)==4: ### Take only complete records
for i in range (2,len(record)): ### Starting from Subject to the Content
bagofwords = re.split(" " | "," ,record[i])### Collect all words present on each email
for word in bagofwords:
flag=0
if word in findwords:
flag=1
print '%s\t%s\t%s\t%s\t%s' % (word, 1,record[0], record[1],flag)
### output: word, 1, id, spam truth and flag
# -
# !chmod +x mapper.py
# # Reducer
# +
# %%writefile reducer.py
# #!/usr/bin/python
from operator import itemgetter
import sys
from itertools import groupby
current_word, word = None, None
current_wordcount, current_spam_wordcount, current_ham_wordcount = 0,0,0
current_id, record_id = None, None
current_y_true, y_true = None, None
current_flag, flag = None,None
sum_records, sum_spamrecords, sum_hamrecords = 0,0,0
sum_spamwords, sum_hamwords = 0,0
flagged_words = []
emails={} #Associative array to hold email data
words={} #Associative array for word data
# input comes from STDIN
for line in sys.stdin:
line = line.strip() ### remove leading and trailing whitespace
line = line.split('\t') ### parse the input we got from mapper.py
word = line[0] ### word we get from mapper.py
try:
count = line[1]
count = int(count) ### convert count (currently a string) to int
email = line[2] ### id that identifies each email
y_true = line[3]
y_true = int(y_true) ### spam truth as an integer
flag = line[4]
flag = int(flag) ### flags if word is in the user specified list
except ValueError: ### if count was not a number then silently
continue ### ignore/discard this line
if current_word == word: ### this IF-switch only works because Hadoop sorts map output
current_count += count ### by key (here: word) before it is passed to the reducer
if current_word not in words.keys():
words[current_word]={'ham_count':0,'spam_count':0,'flag':flag}
if email not in emails.keys():
emails[current_email]={'y_true':y_true,'word_count':0,'words':[]}
sum_records +=1
if y_true == 1:
sum_spamrecords +=1
else
sum_hamrecords +=1
if y_true == 1: ### if record where word is located is a spam
current_spamcount += count ### add to spam count of that word
sum_spamwords += 1
else:
current_hamcount += count ### if not add to ham count of thet word
sum_hamwords +=1
emails[current_email]['word_count'] += 1
emails[current_email]['words'].append(current_word)### store words in email
else:
if current_word:
if flag==1 and current_word not in flagged_words:
flagged_words.append(current_word)
words[current_word]['flag'] = flag ### denote if current word is a word specified by the user list
words[current_word]['spam_count'] += current_spamcount ### update spam count for current word
words[current_word]['ham_count'] += current_hamcount ### update ham count for current word
current_count = count ### set current count
current_spamcount, current_hamcount = 0,0 ### initialize spam and ham wordcount
current_word = word ### set current number
current_email = email ### set current id of email
current_y_true = y_true ### set current spam truth
current_flag = flag ### set current flag
if current_word == word: ### do not forget to output the last word if needed!
emails[current_email]['word_count'] += 1
emails[current_email]['words'].append(current_word)### store words in email
words[current_word]['flag'] = flag ### denote if current word is a word specified by the user list
words[current_word]['spam_count'] += current_spamcount ### update spam count for current word
words[current_word]['ham_count'] += current_hamcount ### update ham count for current word
#Calculate stats for entire corpus
prior_spam= sum_spamrecords/sum_records
prior_ham=sum_hamrecords/sum_records
vocab_count=len(words)#number of unique words in the total vocabulary
for k,word in words.iteritems():
#These versions calculate conditional probabilities WITH Laplace smoothing.
#word['p_spam']=(word['spam_count']+1)/(spam_word_count+vocab_count)
#word['p_ham']=(word['ham_count']+1)/(ham_word_count+vocab_count)
#Compute conditional probabilities WITHOUT Laplace smoothing
word['p_spam']=(word['spam_count'])/(sum_spamwords)
word['p_ham']=(word['ham_count'])/(sum_hamwords)
#At this point the model is now trained, and we can use it to make our predictions
print '%30s' %'ID', '%10s' %'TRUTH', '%10s' %'CLASS', '%20s' %'CUMULATIVE ACCURACY'
miss, sample_size = 0,0
for j,email in emails.iteritems():
#Log versions - no longer used
#p_spam=log(prior_spam)
#p_ham=log(prior_ham)
p_spam=prior_spam
p_ham=prior_ham
for word in email['words']:
if word in flagged_words:
try:
#p_spam+=log(words[word]['p_spam']) #Log version - no longer used
p_spam*=words[word]['p_spam']
except ValueError:
pass #This means that words that do not appear in a class will use the class prior
try:
#p_ham+=log(words[word]['p_ham']) #Log version - no longer used
p_ham*=words[word]['p_ham']
except ValueError:
pass
if p_spam>p_ham:
y_pred=1
else:
y_pred=0
y_true = email['y_true']
if y_pred != y_true:
miss+= 1.0
sample_size += 1.0
accuracy = ((sample_size-miss)/sample_size)*100
print '%30s' %email, '%10d' %y_true, '%10d' %y_pred, '%18.2f %%' % accuracy
# -
# !chmod +x reducer.py
# # Run Hadoop MapReduce Streaming
# <h2> start up yarn and dfs </h2>
# !/usr/local/Cellar/hadoop/2.7.1/sbin/start-yarn.sh ### start up yarn
# !/usr/local/Cellar/hadoop/2.7.1/sbin/start-dfs.sh ### start up dfs
# <h2> create folder </h2>
# !hdfs dfs -mkdir -p /user/venamax ### create hdfs folder
# <h2> upload enronmail_1h.txt file </h2>
# !hdfs dfs -put enronemail_1h.txt /user/venamax #### save source data file to hdfs
# <h2> Hadoop streaming </h2>
# !hadoop jar hadoop-*streaming*.jar -mapper mapper.py -reducer reducer.py -input numcount.txt -output numcountOutput
# <h2>HW2.2.1</h2> Using Hadoop MapReduce and your wordcount job (from HW2.2) determine the top-10 occurring tokens (most frequent tokens)
# <h2>HW2.3. Multinomial NAIVE BAYES with NO Smoothing</h2>
# Using the Enron data from HW1 and Hadoop MapReduce, write a mapper/reducer job(s) that
# will both learn Naive Bayes classifier and classify the Enron email messages using the learnt Naive Bayes classifier. Use all white-space delimitted tokens as independent input variables (assume spaces, fullstops, commas as delimiters). Note: for multinomial Naive Bayes, the Pr(X=“assistance”|Y=SPAM) is calculated as follows:
#
# the number of times “assistance” occurs in SPAM labeled documents / the number of words in documents labeled SPAM
#
# E.g., “assistance” occurs 5 times in all of the documents Labeled SPAM, and the length in terms of the number of words in all documents labeled as SPAM (when concatenated) is 1,000. Then Pr(X=“assistance”|Y=SPAM) = 5/1000. Note this is a multinomial estimation of the class conditional for a Naive Bayes Classifier. No smoothing is needed in this HW. Multiplying lots of probabilities, which are between 0 and 1, can result in floating-point underflow. Since log(xy) = log(x) + log(y), it is better to perform all computations by summing logs of probabilities rather than multiplying probabilities. Please pay attention to probabilites that are zero! They will need special attention. Count up how many times you need to process a zero probabilty for each class and report.
#
# Report the performance of your learnt classifier in terms of misclassifcation error rate of your multinomial Naive Bayes Classifier. Plot a histogram of the log posterior probabilities (i.e., Pr(Class|Doc))) for each class over the training set. Summarize what you see.
#
# Error Rate = misclassification rate with respect to a provided set (say training set in this case). It is more formally defined here:
#
# Let DF represent the evalution set in the following:
# Err(Model, DF) = |{(X, c(X)) ∈ DF : c(X) != Model(x)}| / |DF|
#
# Where || denotes set cardinality; c(X) denotes the class of the tuple X in DF; and Model(X) denotes the class inferred by the Model “Model”
# <h2>HW2.4 Repeat HW2.3 with the following modification: use Laplace plus-one smoothing. </h2>
# Compare the misclassifcation error rates for 2.3 versus 2.4 and explain the differences.
#
# For a quick reference on the construction of the Multinomial NAIVE BAYES classifier that you will code,
# please consult the "Document Classification" section of the following wikipedia page:
#
# https://en.wikipedia.org/wiki/Naive_Bayes_classifier#Document_classification
#
# OR the original paper by the curators of the Enron email data:
#
# http://www.aueb.gr/users/ion/docs/ceas2006_paper.pdf
# <h2>HW2.5. Repeat HW2.4. This time when modeling and classification ignore tokens with a frequency of less than three (3) in the training set. </h2>How does it affect the misclassifcation error of learnt naive multinomial Bayesian Classifier on the training dataset:
# <h2>HW2.6 Benchmark your code with the Python SciKit-Learn implementation of the multinomial Naive Bayes algorithm</h2>
#
# It always a good idea to benchmark your solutions against publicly available libraries such as SciKit-Learn, The Machine Learning toolkit available in Python. In this exercise, we benchmark ourselves against the SciKit-Learn implementation of multinomial Naive Bayes. For more information on this implementation see: http://scikit-learn.org/stable/modules/naive_bayes.html more
#
# In this exercise, please complete the following:
#
# — Run the Multinomial Naive Bayes algorithm (using default settings) from SciKit-Learn over the same training data used in HW2.5 and report the misclassification error (please note some data preparation might be needed to get the Multinomial Naive Bayes algorithm from SkiKit-Learn to run over this dataset)
# - Prepare a table to present your results, where rows correspond to approach used (SkiKit-Learn versus your Hadoop implementation) and the column presents the training misclassification error
# — Explain/justify any differences in terms of training error rates over the dataset in HW2.5 between your Multinomial Naive Bayes implementation (in Map Reduce) versus the Multinomial Naive Bayes implementation in SciKit-Learn
#
#
# <h2>HHW 2.6.1 OPTIONAL (note this exercise is a stretch HW and optional)</h2>
# — Run the Bernoulli Naive Bayes algorithm from SciKit-Learn (using default settings) over the same training data used in HW2.6 and report the misclassification error
# - Discuss the performance differences in terms of misclassification error rates over the dataset in HW2.5 between the Multinomial Naive Bayes implementation in SciKit-Learn with the Bernoulli Naive Bayes implementation in SciKit-Learn. Why such big differences. Explain.
#
# Which approach to Naive Bayes would you recommend for SPAM detection? Justify your selection.
# <h2>HW2.7 OPTIONAL (note this exercise is a stretch HW and optional)</h2>
#
# The Enron SPAM data in the following folder enron1-Training-Data-RAW is in raw text form (with subfolders for SPAM and HAM that contain raw email messages in the following form:
#
# --- Line 1 contains the subject
# --- The remaining lines contain the body of the email message.
#
# In Python write a script to produce a TSV file called train-Enron-1.txt that has a similar format as the enronemail_1h.txt that you have been using so far. Please pay attend to funky characters and tabs. Check your resulting formated email data in Excel and in Python (e.g., count up the number of fields in each row; the number of SPAM mails and the number of HAM emails). Does each row correspond to an email record with four values? Note: use "NA" to denote empty field values.
# <h2>HW2.8 OPTIONAL</h2>
# Using Hadoop Map-Reduce write job(s) to perform the following:
# -- Train a multinomial Naive Bayes Classifier with Laplace plus one smoothing using the data extracted in HW2.7 (i.e., train-Enron-1.txt). Use all white-space delimitted tokens as independent input variables (assume spaces, fullstops, commas as delimiters). Drop tokens with a frequency of less than three (3).
# -- Test the learnt classifier using enronemail_1h.txt and report the misclassification error rate. Remember to use all white-space delimitted tokens as independent input variables (assume spaces, fullstops, commas as delimiters). How do we treat tokens in the test set that do not appear in the training set?
# <h2>HW2.8.1 OPTIONAL</h2>
# — Run both the Multinomial Naive Bayes and the Bernoulli Naive Bayes algorithms from SciKit-Learn (using default settings) over the same training data used in HW2.8 and report the misclassification error on both the training set and the testing set
# - Prepare a table to present your results, where rows correspond to approach used (SciKit-Learn Multinomial NB; SciKit-Learn Bernouili NB; Your Hadoop implementation) and the columns presents the training misclassification error, and the misclassification error on the test data set
# - Discuss the performance differences in terms of misclassification error rates over the test and training datasets by the different implementations. Which approch (Bernouili versus Multinomial) would you recommend for SPAM detection? Justify your selection.
#
# <h2>=====================
# END OF HOMEWORK</h2>
| hw2/MIDS-W261-2015-HWK-Week02-AlejandroJRojas-Copy1.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 sklearn
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
print sklearn.__version__
print np.__version__
print pd.__version__
titanic_df = pd.read_csv('datasets/titanic_train.csv')
titanic_df.head(10)
titanic_df.shape
titanic_df.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], 'columns', inplace=True)
titanic_df.head()
titanic_df[titanic_df.isnull().any(axis=1)].count() #checking for missing fields
titanic_df = titanic_df.dropna()
titanic_df.shape
titanic_df[titanic_df.isnull().any(axis=1)].count()
titanic_df.describe()
titanic_df.head()
fig, ax = plt.subplots(figsize=(12,8))
plt.scatter(titanic_df['Age'], titanic_df['Survived'])
plt.xlabel('Age')
plt.ylabel('Survived')
fig, ax = plt.subplots(figsize=(12,8))
plt.scatter(titanic_df['Fare'], titanic_df['Survived'])
plt.xlabel('Fare')
plt.ylabel('Survived')
pd.crosstab(titanic_df['Sex'], titanic_df['Survived'])
pd.crosstab(titanic_df['Pclass'], titanic_df['Survived'])
# +
titanic_data_corr = titanic_df.corr()
titanic_data_corr
# -
fig, ax = plt.subplots(figsize = (12,10))
sns.heatmap(titanic_data_corr, annot=True)
# +
from sklearn import preprocessing
label_encoding = preprocessing.LabelEncoder()
titanic_df['Sex'] = label_encoding.fit_transform(titanic_df['Sex'].astype(str))
titanic_df.head()
# -
label_encoding.classes_
titanic_df = pd.get_dummies(titanic_df, columns = ['Embarked'])
titanic_df.head()
titanic_df = titanic_df.sample(frac=1).reset_index(drop=True)
titanic_df.head()
titanic_df.shape
titanic_df.to_csv('datasets/titanic_processed.csv', index=False)
# !ls datasets
| Classification Models/ExploringTheTitanicDataset.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.11 64-bit (''Py38'': conda)'
# metadata:
# interpreter:
# hash: c59555f908daf203107fb62fabdd23083d24d776055fcdd77b1f4aca8a172ece
# name: python3
# ---
import modern_robotics as mr
import numpy as np
import sympy as sp
from sympy import*
from sympy.physics.mechanics import dynamicsymbols, mechanics_printing
mechanics_printing()
# ### Utilities
# +
def exp3(omega, theta):
omega = skew(omega)
R = sp.eye(3) + sp.sin(theta) * omega + (1 - sp.cos(theta)) * omega * omega
return R
def skew(v):
return Matrix([[0, -v[2], v[1]],
[v[2], 0, -v[0]],
[-v[1], v[0], 0]])
def exp6(twist, theta):
omega = skew(twist[:3])
v = Matrix(twist[3:])
T = eye(4)
T[:3,:3] = exp3(twist[:3], theta)
T[:3,3] = (eye(3) * theta + (1 - cos(theta)) * omega +
(theta-sin(theta)) * omega * omega) * v
return T
def Ad(T):
AdT = sp.zeros(6)
R = sp.Matrix(T[:3, :3])
AdT[:3, :3] = R
AdT[3:, 3:] = R
AdT[3:, :3] = skew(T[:3, 3]) * R
return AdT
def rotX(theta):
Rx = sp.eye(4)
Rx[1,1] = sp.cos(theta)
Rx[1,2] = -sp.sin(theta)
Rx[2,1] = sp.sin(theta)
Rx[2,2] = sp.cos(theta)
return Rx
def rotZ(theta):
Rz = sp.eye(4)
Rz[0,0] = sp.cos(theta)
Rz[0,1] = -sp.sin(theta)
Rz[1,0] = sp.sin(theta)
Rz[1,1] = sp.cos(theta)
return Rz
def PsFromTsd(Tsd):
#Finner Ps fra T_sd
#T_sd gir konfigurasjonen vi vil ha end-effector framen, B, i.
#B, og derav også M, er lik som i DH
#s er plassert nederst på roboten med positiv z oppover, altså ikke som i DH. Bør kanskje endres til å være lik DH
Pd = np.array([0,0,80,1])
Ps = Tsd@Pd
return Ps
# -
# ### Task 3-3
# +
#Definerer S og M
"""
S1 = np.array([0,0,-1,0,0,0])
S2 = np.array([0,1,0,-400,0,25])
S3 = np.array([0,1,0,-855,0,25])
S4 = np.array([-1,0,0,0,-890,0])
S5 = np.array([0,1,0,-890,0,445])
S6 = np.array([-1,0,0,0,-890,0])
Slist = np.array([S1,S2,S3,S4,S5,S6]).T
print(Slist)
M = np.array([[0,0,-1,525],
[0,1,0,0],
[1,0,0,890],
[0,0,0,1]])
thetasUp = [0,0,0,0,0,0]
thetasDown = [0,0,0,0,0,0]
#Limits til roboten slik den er gitt i oppgaven. Antar at ledd 5 har limit på +-90
theta_limits = [[-180,180],[-190+90,45+90],[-120-90, 156-90],[-180,180],[-90,90],[-180,180]]
"""
S1 = np.array([0,0,1,0,0,0])
S2 = np.array([0,-1,0,0,0,-25])
S3 = np.array([0,-1,0,-455,0,-25])
S4 = np.array([-1,0,0,0,490,0])
S5 = np.array([0,-1,0,-490,0,-445])
S6 = np.array([-1,0,0,0,490,0])
Slist = np.array([S1,S2,S3,S4,S5,S6]).T
print(Slist)
M = np.array([[0,0,-1,525],
[0,-1,0,0],
[-1,0,0,-490],
[0,0,0,1]])
thetasUp = [0,0,0,0,0,0]
thetasDown = [0,0,0,0,0,0]
# -
#Her endres thetasGen for å teste forskjellige konfigurasjoner:
thetasGen = np.array([3,3,1,2,1,0])
Tsd = mr.FKinSpace(M,Slist,thetasGen)
print("T_sd\n", Tsd)
# +
Ps = PsFromTsd(Tsd)
print("Ps", Ps)
Psmerket = [Ps[0], Ps[1], Ps[2]]
#theta1
thetasUp[0] = -atan2(-Psmerket[1],Psmerket[0]) #minus foran fordi vinkelen er definert andre vei ##
thetasDown[0] = thetasUp[0]
#theta2 and theta3
a = np.sqrt(420**2+35**2)
c = 455
b = np.sqrt((np.sqrt(Psmerket[0]**2+Psmerket[1]**2)-25)**2 + Psmerket[2]**2)
print("a",a,"c",c,"b", b)
print("d", np.sqrt((np.sqrt(Psmerket[0]**2+Psmerket[1]**2)-25)**2))
psi = np.arccos(420/a) #Vinkelen mellom den faktiske armen og den vi tegna for å få en trekant(Pga 35mm offset i elbow). Se notatbok
phi = atan2(-Psmerket[2], sqrt(Psmerket[0]**2 + Psmerket[1]**2)-25) ##
print("args", -Psmerket[2], sqrt(Psmerket[0]**2 + Psmerket[1]**2)-25)
alpha = np.arccos((b**2+c**2-a**2)/(2*b*c))
beta = np.arccos((a**2+c**2-b**2)/(2*a*c))
print("alpha:", np.rad2deg(alpha), "beta:", np.rad2deg(beta), "phi:", phi, "psi:", np.rad2deg(psi))
thetasUp[1] = np.pi/2 - (alpha + phi)
thetasDown[1] = np.pi/2 - (phi-alpha)
print(thetasUp[1])
thetasUp[2] = np.pi/2 - (beta-psi)
thetasDown[2] = -(2*np.pi - (beta+psi) - np.pi/2)
print(thetasUp, thetasDown)
#Vi har XYX euler angles. De er egentlig (-X)Y(-X) fordi det er slik S'ene er definert,.
#Elbow down:
T1 = exp6(S1, -thetasDown[0])
T2 = exp6(S2, -thetasDown[1])
T3 = exp6(S3, -thetasDown[2])
R = (T3@T2@T1@Tsd@np.linalg.inv(M)) #R er den resterende rotasjonen vi ønsker å få fra de tre siste leddene, definert i s
thetasDown[3] = -atan2(R[1,0], -R[2,0]) #minus foran theta4 og 6 fordi de er i minus x retning
thetasDown[4] = -atan2(sqrt(1-R[0,0]**2), R[0,0])
thetasDown[5] = -atan2(R[0,1], R[0,2])
#Elbow up:
T1 = exp6(S1, -thetasUp[0])
T2 = exp6(S2, -thetasUp[1])
T3 = exp6(S3, -thetasUp[2])
R = (T3@T2@T1@Tsd@np.linalg.inv(M))
thetasUp[3] = -atan2(R[1,0], -R[2,0])
thetasUp[4] = -atan2(sqrt(1-R[0,0]**2), R[0,0])
thetasUp[5] = -atan2(R[0,1], R[0,2])
# +
#testing av analytisk løsning:
#UP
thetasUpN = np.zeros(6)
thetasUpDeg = np.zeros(6)
for i in range(0,6):
thetasUpN[i] = N(thetasUp[i])
thetasUpDeg[i] = np.rad2deg(thetasUpN[i])
#print(thetas_deg, np.rad2deg(thetas_gen))
TupThetas = mr.FKinSpace(M,Slist,thetasUpN)
PUpReached = PsFromTsd(TupThetas)
#print(P_reached, P_s)
#DOWN
thetasDownN = np.zeros(6)
thetasDownDeg = np.zeros(6)
for i in range(0,6):
thetasDownN[i] = N(thetasDown[i])
thetasDownDeg[i] = np.rad2deg(thetasDownN[i])
#print(thetas_deg, np.rad2deg(thetas_gen))
TDownThetas = mr.FKinSpace(M,Slist,thetasDownN)
PDownReached = PsFromTsd(TDownThetas)
#fk_test = exp6(S4,thetas_num[3])@exp6(S5,thetas_num[4])@exp6(S6,thetas_num[5])@M
#R_test = rotX(thetas_num[3])@rotY(thetas_num[4])@rotX(thetas_num[5])
thetasCalc, asd = mr.IKinSpace(Slist,M,Tsd,[0,0,0,0,0,0],0.01,0.01)
Tsd, thetasGen, TupThetas, thetasUpN, TDownThetas, thetasDownN, Ps, PUpReached, PDownReached
# -
Tsd, thetasUpN, thetasDownN
| Arkiv/task2_3_DH.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
# ---
# ### Notebook permettant l'extraction de répertoire tgz
# +
nomsFichier = ['ascii']
import tarfile
for file in nomsFichier:
fname = file +'/' + file + '.tgz'
tar = tarfile.open(fname, "r:gz")
tar.extractall(path = file+'/')
tar.close()
| NoteBooks/Extractor tgz .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="zEpYxiZFWEGn" colab_type="code" outputId="3ef03bab-65a3-4344-b793-4226c4ebf0b5" executionInfo={"status": "ok", "timestamp": 1575590433196, "user_tz": 120, "elapsed": 20468, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mBvHx9tXeFERk41Be52ENu-PraTMAZmqtFfYESvJw=s64", "userId": "14318877200655399567"}} colab={"base_uri": "https://localhost:8080/", "height": 150}
from google.colab import drive
drive.mount('/content/drive')
# %cd /content/drive/Shared\ drives/cd2019-trabalho
# + [markdown] id="1uEQcTogRI_j" colab_type="text"
# #FMA
# + [markdown] id="5GjSSSWeRqJV" colab_type="text"
# ##Small
# + id="Ns1I3iUwbl_c" colab_type="code" outputId="bed96b65-772c-444a-f524-dfc39863207e" executionInfo={"status": "ok", "timestamp": 1574966515110, "user_tz": 120, "elapsed": 6821, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mBvHx9tXeFERk41Be52ENu-PraTMAZmqtFfYESvJw=s64", "userId": "14318877200655399567"}} colab={"base_uri": "https://localhost:8080/", "height": 63}
# !curl -O https://os.unil.cloud.switch.ch/fma/fma_small.zip
# !echo "ade154f733639d52e35e32f5593efe5be76c6d70 fma_small.zip" | sha1sum -c -
# + id="6qHGm9i26Ob1" colab_type="code" outputId="a1c5dc30-e62d-45f1-cd99-2f56d5a9ba46" executionInfo={"status": "ok", "timestamp": 1574977380492, "user_tz": 180, "elapsed": 862308, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mBvHx9tXeFERk41Be52ENu-PraTMAZmqtFfYESvJw=s64", "userId": "14318877200655399567"}} colab={"base_uri": "https://localhost:8080/", "height": 68}
# !unzip -q fma_small.zip
# + [markdown] id="KISIchNURt1c" colab_type="text"
# ## Metadata
# + id="IWl8u6KtR2ys" colab_type="code" outputId="c3501492-cad0-4aaa-a7b0-de17ee0998cb" executionInfo={"status": "ok", "timestamp": 1575133819734, "user_tz": 120, "elapsed": 113822, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mBvHx9tXeFERk41Be52ENu-PraTMAZmqtFfYESvJw=s64", "userId": "14318877200655399567"}} colab={"base_uri": "https://localhost:8080/", "height": 306}
# !curl -O https://os.unil.cloud.switch.ch/fma/fma_metadata.zip
# !echo "f0df49ffe5f2a6008d7dc83c6915b31835dfe733 fma_metadata.zip" | sha1sum -c -
# !unzip fma_metadata.zip
# + [markdown] id="FnGozTirROhm" colab_type="text"
# # pyAudioAnalysis
# + id="F69dCX4WnoPD" colab_type="code" outputId="7d8443c7-1f7e-4546-a396-1b099932055d" executionInfo={"status": "ok", "timestamp": 1574979307766, "user_tz": 180, "elapsed": 17759, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mBvHx9tXeFERk41Be52ENu-PraTMAZmqtFfYESvJw=s64", "userId": "14318877200655399567"}} colab={"base_uri": "https://localhost:8080/", "height": 153}
# !git clone https://github.com/tyiannak/pyAudioAnalysis.git
# + [markdown] id="b53w-XR2ftjE" colab_type="text"
# # GTZAN
# + id="SQez10d8fypu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 86} outputId="f7e5f081-375a-4289-ce29-2f4ff9a70a96"
# !curl -O http://opihi.cs.uvic.ca/sound/genres.tar.gz
# !tar -xvzf genres.tar.gz ./gtzan
| cloud_fetch.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 required libraries from normal distribution
from scipy.stats import norm
# +
#define 20 random variables for normal distribution of data
norm.rvs(loc=0, scale=1, size=20)
# +
#perform Cumulative Distribution Funciton of CDF for 10 random variables, loc=1 and scale =3
norm.cdf(10, loc=1, scale=3)
# +
#perform Probability Density Funciton of PDF for 14 random variables, loc=1 and scale =1
norm.pdf(14, loc=1, scale=1)
# -
| SciPy_Project02.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 h5py
import numpy as np
import matplotlib.pyplot as plt
from skimage import io, measure, morphology, segmentation, transform, filters
chosen_cells = {}
raw_folder = '/Users/ricardo/Documents/Temporary/Segmentations/';
for file_name in os.listdir(raw_folder + 'Images/'):
stack_ID = file_name.rstrip('.tif');
print(stack_ID)
chosen_cells[stack_ID] = set()
file_path = raw_folder + 'Cells/' + stack_ID + '_GOOD-CELLS.txt'
if not os.path.exists(file_path):
print('hi')
continue
with open(file_path, 'r') as file:
for cell in file:
cell = (int(cell),)
chosen_cells[stack_ID].add(cell)
file_path = raw_folder + 'Cells/' + stack_ID + '_SPLIT-CELLS.txt'
if not os.path.exists(file_path):
print('hi')
continue
with open(file_path, 'r') as file:
for cells in file:
cells = tuple([int(cell) for cell in cells.split()])
chosen_cells[stack_ID].add(cells)
raw_img = io.imread(raw_folder + 'Images/' + file_name);
seg_file = h5py.File(raw_folder + 'Segmentations/' + stack_ID + '_predictions_gasp_average.h5', 'r')
seg_data = seg_file['/segmentation'][()]
try:
good_seg_data = np.zeros_like(seg_data);
except Exception as e:
seg_data = np.array(segmentedImgh5.get('segmentation'));
good_seg_data = np.zeros_like(seg_data);
for cell in chosen_cells:
for num_cell in chosen_cells[cell]:
print(num_cell)
good_seg_data[seg_data == num_cell] = num_cell[0]
propertyTable = ('area', 'bbox', 'bbox_area', 'centroid', 'convex_area', 'convex_image', 'coords', 'eccentricity')
intensityProps = ('label', 'mean_intensity', 'weighted_centroid')
shapeProps = ('label', 'area', 'convex_area', 'equivalent_diameter',
'extent', 'feret_diameter_max', 'filled_area', 'major_axis_length',
'minor_axis_length', 'solidity')
#'eccentricity', 'perimeter' and 'perimeter_crofton' is not implemented for 3D images
props = measure.regionprops_table(good_seg_data, intensity_image=raw_img, properties=propertyTable)
np.savetxt(raw_folder + stack_ID + '_cell-analysis.csv', props, delimiter=", ", fmt="% s")
# -
skimage.__version__
import skimage
pip install --upgrade scikit-image
| SegmentationMain.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="q73_fLRvTQYI"
# #Train Model
# + [markdown] colab_type="text" id="X3PASjCITQC0"
# This colab demonstrates how to extract the AudioSet embeddings, using a VGGish deep neural network (DNN).
# + [markdown] colab_type="text" id="IKSLc0bIB1QS"
# Based on the directions at: https://github.com/tensorflow/models/tree/master/research/audioset
# + colab={"base_uri": "https://localhost:8080/", "height": 749} colab_type="code" executionInfo={"elapsed": 3825, "status": "ok", "timestamp": 1584890892031, "user": {"displayName": "<NAME>", "photoUrl": "https://lh4.googleusercontent.com/-TpQl_yrDGdU/AAAAAAAAAAI/AAAAAAAAAlQ/HoAfg_rDDrA/s64/photo.jpg", "userId": "01397164172225109514"}, "user_tz": -60} id="228fji9C6c-q" outputId="59191846-86c2-4ec8-bcd3-1f6448532cf2"
# !lscpu
# !nvidia-smi
# + colab={"base_uri": "https://localhost:8080/", "height": 124} colab_type="code" executionInfo={"elapsed": 30617, "status": "ok", "timestamp": 1585777391062, "user": {"displayName": "<NAME>", "photoUrl": "https://lh4.googleusercontent.com/-TpQl_yrDGdU/AAAAAAAAAAI/AAAAAAAAAlQ/HoAfg_rDDrA/s64/photo.jpg", "userId": "01397164172225109514"}, "user_tz": -120} id="xNUdYfA11vGR" outputId="55837ee7-83d9-4394-f1e8-d5e976a5ec9c"
#Google drive access
import os
from google.colab import drive
drive.mount('/content/gdrive',force_remount = True)
#Directory
root_path = 'gdrive/My Drive/SoundEventDetection/modelTraining'
os.chdir(root_path)
# + colab={} colab_type="code" id="O1YVQb-MBiUx"
# %%capture
#Install necessary software
# !pip install six
# !pip install h5py
# !pip install pydub
# !pip install numpy
# !pip install scipy
# !pip install keras
# !pip install future
# !pip install resampy
# !pip install ipython
# !pip install soundfile
# !pip install pysoundfile
# !pip install scikit-learn
# !apt-get install libsndfile1
# !pip install python==3.6
# !pip install matplotlib
# !pip install cudnn==7.1.2
# !pip install cudatoolkit==9
# !pip install tensorflow-gpu==1.12.0
#Install: cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb
# !dpkg -i cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb
# !apt-key add /var/cuda-repo-9-0-local/<KEY>
# !apt-get update
# !apt-get install cuda=9.0.176-1
#OR
# #!wget https://developer.nvidia.com/compute/cuda/9.0/Prod/local_installers/cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64-deb
#VGGish model checkpoint, in TensorFlow checkpoint format.
import os
os.chdir("trained_models")
# !wget https://storage.googleapis.com/audioset/vggish_model.ckpt
os.chdir("..")
# + colab={} colab_type="code" id="jmhLEKk8bxW2"
# %%capture
#Important DO NOT DELETE
#import six
import sys
#import h5py
#import math
#import glob
#import h5py
#import time
import numpy as np
import pandas as pd
import soundfile as sf
import tensorflow as tf
import matplotlib.pyplot as plt
#from pydub.playback import play
#from pydub import AudioSegment
#from scipy.io import wavfile
#from scipy.io.wavfile import write
sys.path.insert(1, os.path.join(sys.path[0], '../'))
#ML imports
#from keras.layers import Input, Dense, BatchNormalization, Dropout, Activation, Concatenate
from keras.layers import Lambda
#from keras.optimizers import Adam
from keras.models import load_model
from keras.models import Model
import keras.backend as K
#External .py scripts
from lib import mel_features
from lib import vggish_input
from lib import vggish_params
from lib import vggish_postprocess
from lib import vggish_slim
from lib import utilities
from lib import data_generator
from lib.train_functions import evaluateCore, trainCore, average_pooling, max_pooling, attention_pooling, pooling_shape, train, writeToFile
# + colab={"base_uri": "https://localhost:8080/", "height": 610} colab_type="code" executionInfo={"elapsed": 133843, "status": "ok", "timestamp": 1585779220354, "user": {"displayName": "<NAME>", "photoUrl": "https://lh4.googleusercontent.com/-TpQl_yrDGdU/AAAAAAAAAAI/AAAAAAAAAlQ/HoAfg_rDDrA/s64/photo.jpg", "userId": "01397164172225109514"}, "user_tz": -120} id="58_Ros7ywCCs" outputId="64ff3c74-f484-417b-c338-21d33f6cf3e8"
#Download dataset
# !wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=0B49XSFgf-0yVQk01eG92RHg4WTA' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=0B49XSFgf-0yVQk01eG92RHg4WTA" -O packed_features.zip && rm -rf /tmp/cookies.txt
# !unzip packed_features.zip
# + colab={} colab_type="code" id="QqSGe856SdEv"
#Set args
args = {
"data_dir" : "packed_features/",
"workspace" : "workspace/",
"mini_data" : False,
"balance_type" : "balance_in_batch", #'no_balance', 'balance_in_batch'
"model_type" : 'decision_level_single_attention', #'decision_level_max_pooling', 'decision_level_average_pooling', 'decision_level_single_attention', 'decision_level_multi_attention', 'feature_level_attention'
"learning_rate" : 1e-3,
}
args["filename"] = utilities.get_filename("work/")
#Logs
logs_dir = os.path.join(args["workspace"], 'logs', args["filename"])
utilities.create_folder(logs_dir)
logging = utilities.create_logging(logs_dir, filemode='w')
# + colab={"base_uri": "https://localhost:8080/", "height": 729} colab_type="code" id="HWFcyLrZSd01" outputId="ae26ad2b-dafc-458c-f765-caace81bfb4b"
#Train Model
def trainModel():
if True:
train(args, 0)
else:
args["bgn_iteration"] = 10000
args["fin_iteration"] = 50001
args["interval_iteration"] = 5000
utilities.get_avg_stats(args)
trainModel()
# + colab={} colab_type="code" id="4z_VLzUEs5cO"
| modelTraining/0_Train_Model.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: newbaseline
# language: python
# name: newbaseline
# ---
# +
import pandas
import matplotlib.pyplot as plt
import numpy as np
log_file0 = './logs/HalfCheetah-v1/10epoch/gym_eval.monitor.csv'
log_file1 = './logs/HalfCheetah-v1/20epoch/gym_eval.monitor.csv'
log_file2 = './logs/HalfCheetah-v1/30epoch/gym_eval.monitor.csv'
#log_file3 = './logs/HalfCheetah-v1/newer_expert_data_with_only_expert_actor_loss/gym_eval.monitor.csv'
log_file3 = './logs/HalfCheetah-v1/40epoch/gym_eval.monitor.csv'
log_file4 = './logs/HalfCheetah-v1/50epoch/gym_eval.monitor.csv'
log_file5 = './logs/HalfCheetah-v1/60epoch/gym_eval.monitor.csv'
log_file6 = './logs/HalfCheetah-v1/70epoch/gym_eval.monitor.csv'
log_file7 = './logs/HalfCheetah-v1/80epoch/gym_eval.monitor.csv'
log_file8 = './logs/HalfCheetah-v1/90epoch/gym_eval.monitor.csv'
log_file9 = './logs/HalfCheetah-v1/100epoch/gym_eval.monitor.csv'
log_file10 = './logs/HalfCheetah-v1/110epoch/gym_eval.monitor.csv'
log_file11 = './logs/HalfCheetah-v1/120epoch/gym_eval.monitor.csv'
data0 = pandas.read_csv(log_file0, index_col=None, comment='#')
data0 = data0['r']
data1 = pandas.read_csv(log_file1, index_col=None, comment='#')
data1 = data1['r']
data2 = pandas.read_csv(log_file2, index_col=None, comment='#')
data2 = data2['r']
data3 = pandas.read_csv(log_file3, index_col=None, comment='#')
data3 = data3['r']
data4 = pandas.read_csv(log_file4, index_col=None, comment='#')
data4 = data4['r']
data5 = pandas.read_csv(log_file5, index_col=None, comment='#')
data5 = data5['r']
data6 = pandas.read_csv(log_file6, index_col=None, comment='#')
data6 = data6['r']
data7 = pandas.read_csv(log_file7, index_col=None, comment='#')
data7 = data7['r']
data8 = pandas.read_csv(log_file8, index_col=None, comment='#')
data8 = data8['r']
data9 = pandas.read_csv(log_file9, index_col=None, comment='#')
data9 = data9['r']
data10 = pandas.read_csv(log_file10, index_col=None, comment='#')
data10 = data10['r']
data11 = pandas.read_csv(log_file11, index_col=None, comment='#')
data11 = data11['r']
plt.plot(data0)
plt.plot(data1)
plt.plot(data2)
plt.plot(data3)
plt.plot(data4)
plt.plot(data5)
plt.plot(data6)
plt.plot(data7)
plt.plot(data8)
plt.plot(data9)
plt.plot(data10)
plt.plot(data11)
#plt.legend(['baseline', 'both expert and ddpg', 'only ddpg', 'new loss'])#, 'only expert'])
plt.legend(['10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110', '120'])
plt.show()
#log_file0 = './logs/HalfCheetah-v1/2018-03-16-17-27-35-095198/progress.csv'
#data0 = pandas.read_csv(log_file0, index_col=None, comment='#')
#print(data0)
#lc = data0['train/dist'].values
#la = data0['train/loss_actor'].values
#print(lc)
#plt.plot(lc)
#plt.plot(la)
#plt.legend(['critic', 'actor'])#, 'only expert'])
#plt.grid()
#plt.show()
# +
import os
import pandas
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
def smooth(n,x,y):
sm = np.zeros(10000)
k=0
f = lambda x,l,h: x <= h and x >= l
sm_x = np.arange(1, np.max(x)-n+1, 100)
for i in sm_x:
idx = [f(var,i,i+n) for var in x]
sm[k] = np.dot(idx,y)/np.sum(idx)
k=k+1
sm = sm[:k]
sm_x = sm_x[:k] + np.floor(n/2)
return sm, sm_x
env_ids = ['HalfCheetah-v1', 'Hopper-v1', 'Walker2d-v1']#, 'HumanoidStandup-v1']
ave_rewards = [4721.3959546, 1982.82768185, 3062.83132533]
expertfiles = [os.path.join('./logs', var, 'expert/gym_eval.monitor.csv') for var in env_ids]
baselinefiles = [os.path.join('./logs', var, 'baseline/gym_eval.monitor.csv') for var in env_ids]
expertdata = [pandas.read_csv(file, index_col=None, comment='#') for file in expertfiles]
baselinedata = [pandas.read_csv(file, index_col=None, comment='#') for file in baselinefiles]
x_expert = [np.cumsum(var['l'].values) for var in expertdata]
x_baseline = [np.cumsum(var['l'].values) for var in baselinedata]
r_expert = [var['r'] for var in expertdata]
r_baseline = [var['r'] for var in baselinedata]
r_baseline_smooth = [var['r'] for var in baselinedata]
'''
for i in range(len(x_expert)):
if i==0:
sm_n = 10000
else:
sm_n = 30000
r_expert_smooth, x_expert_smooth = smooth(sm_n, x_expert[i], r_expert[i])
r_baseline_smooth, x_baseline_smooth = smooth(sm_n, x_baseline[i], r_baseline[i])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x_baseline[i]/1e5*2, r_baseline[i], 'C0', alpha=0.3, label='')
ax.plot(x_expert[i]/1e5*2, r_expert[i], 'C3', alpha=0.3, label='')
ax.plot(x_baseline_smooth/1e5*2, r_baseline_smooth, 'C0', label='DDPG')
ax.plot(x_expert_smooth/1e5*2, r_expert_smooth, 'C3', label='DDPG+Pretrain')
ax.vlines(0.6, 0, 1, transform=ax.get_xaxis_transform(), colors='k', linestyles = "dashed", label='')
ax.hlines(ave_rewards[i], 0, 1, transform=ax.get_yaxis_transform(), colors='C5', linestyles = "dashed", label='')
plt.xlabel('Simulation Steps /$10^5$')
plt.ylabel('Reward')
#plt.xticks([30000],['End of Pretrain'])
plt.legend()
plt.show()
'''
pdf = PdfPages('./DDPG_results.pdf')
fig = plt.figure(figsize=(6.4*3,4.0))
sm_n = 10000
r_expert_smooth, x_expert_smooth = smooth(sm_n, x_expert[0], r_expert[0])
r_baseline_smooth, x_baseline_smooth = smooth(sm_n, x_baseline[0], r_baseline[0])
ax = fig.add_subplot(131)
ax.plot(x_baseline[0]/1e5, r_baseline[0], 'C0', alpha=0.3, label='')
ax.plot(x_expert[0]/1e5, r_expert[0], 'C3', alpha=0.3, label='')
ax.plot(x_baseline_smooth/1e5, r_baseline_smooth, 'C0', label='DDPG')
ax.plot(x_expert_smooth/1e5, r_expert_smooth, 'C3', label='DDPG+Pretrain')
ax.vlines(0.3, 0, 1, transform=ax.get_xaxis_transform(), colors='k', linestyles = "dashed", label='')
ax.hlines(ave_rewards[0], 0, 1, transform=ax.get_yaxis_transform(), colors='C5', linestyles = "dashed", label='')
plt.xlabel('Training Steps /$10^5$')
plt.ylabel('Reward')
plt.legend()
##################################################
sm_n = 30000
r_expert_smooth, x_expert_smooth = smooth(sm_n, x_expert[1], r_expert[1])
r_baseline_smooth, x_baseline_smooth = smooth(sm_n, x_baseline[1], r_baseline[1])
ax = fig.add_subplot(132)
ax.plot(x_baseline[1]/1e5, r_baseline[1], 'C0', alpha=0.3, label='')
ax.plot(x_expert[1]/1e5, r_expert[1], 'C3', alpha=0.3, label='')
ax.plot(x_baseline_smooth/1e5, r_baseline_smooth, 'C0', label='DDPG')
ax.plot(x_expert_smooth/1e5, r_expert_smooth, 'C3', label='DDPG+Pretrain')
ax.vlines(0.3, 0, 1, transform=ax.get_xaxis_transform(), colors='k', linestyles = "dashed", label='End of Pretrain')
ax.hlines(ave_rewards[1], 0, 1, transform=ax.get_yaxis_transform(), colors='C5', linestyles = "dashed", label='Average Reward of ED')
plt.xlabel('Training Steps /$10^5$')
#####################################################
r_expert_smooth, x_expert_smooth = smooth(sm_n, x_expert[2], r_expert[2])
r_baseline_smooth, x_baseline_smooth = smooth(sm_n, x_baseline[2], r_baseline[2])
ax = fig.add_subplot(133)
ax.plot(x_baseline[2]/1e5, r_baseline[2], 'C0', alpha=0.3, label='')
ax.plot(x_expert[2]/1e5, r_expert[2], 'C3', alpha=0.3, label='')
ax.plot(x_baseline_smooth/1e5, r_baseline_smooth, 'C0', label='DDPG')
ax.plot(x_expert_smooth/1e5, r_expert_smooth, 'C3', label='DDPG+Pretrain')
ax.vlines(0.3, 0, 1, transform=ax.get_xaxis_transform(), colors='k', linestyles = "dashed", label='End of Pretrain')
ax.hlines(ave_rewards[2], 0, 1, transform=ax.get_yaxis_transform(), colors='C5', linestyles = "dashed", label='Average Reward of ED')
plt.xlabel('Training Steps /$10^5$')
#plt.xticks([30000],['End of Pretrain'])
plt.show()
pdf.savefig(fig)
plt.close()
pdf.close()
# +
import os
import pandas
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
def smooth(n,x,y):
sm = np.zeros(10000)
k=0
f = lambda x,l,h: x <= h and x >= l
sm_x = np.arange(1, np.max(x)-n+1, 100)
for i in sm_x:
idx = [f(var,i,i+n) for var in x]
sm[k] = np.dot(idx,y)/np.sum(idx)
k=k+1
sm = sm[:k]
sm_x = sm_x[:k] + np.floor(n/2)
return sm, sm_x
env_ids = 'HalfCheetah-v1'#, 'Hopper-v1', 'Walker2d-v1']#, 'HumanoidStandup-v1']
ave_rewards = 4721.3959546#, 1982.82768185, 3062.83132533]
expertfiles = os.path.join('~/Projects/conda/baselines/baselines/ddpg/logs', env_ids, 'expert/gym_eval.monitor.csv')
baselinefiles = os.path.join('~/Projects/conda/baselines/baselines/ddpg/logs', env_ids, 'baseline/gym_eval.monitor.csv')
supervisedfiles = os.path.join('~/Projects/conda/baselines/baselines/ddpg/data/supplementary/logs',env_ids, 'supervise/gym_eval.monitor.csv')
superviseddata = pandas.read_csv(supervisedfiles, index_col=None, comment='#')
expertdata = pandas.read_csv(expertfiles, index_col=None, comment='#')
baselinedata = pandas.read_csv(baselinefiles, index_col=None, comment='#')
x_supervised = np.cumsum(superviseddata['l'].values)
x_expert = np.cumsum(expertdata['l'].values)
x_baseline = np.cumsum(baselinedata['l'].values)
r_supervised = superviseddata['r']
r_expert = expertdata['r']
r_baseline = baselinedata['r']
#r_baseline_smooth = baselinedata['r']
pdf = PdfPages('./test.pdf')
fig = plt.figure()#figsize=(6.4*3,4.0))
sm_n = 10000
r_expert_smooth, x_expert_smooth = smooth(sm_n, x_expert, r_expert)
r_baseline_smooth, x_baseline_smooth = smooth(sm_n, x_baseline, r_baseline)
r_supervised_smooth, x_supervised_smooth = smooth(sm_n, x_supervised, r_supervised)
ax = fig.add_subplot(111)
ax.plot(x_baseline/1e5, r_baseline, 'C0', alpha=0.3, label='')
ax.plot(x_expert/1e5, r_expert, 'C3', alpha=0.3, label='')
ax.plot(x_supervised/1e5, r_supervised, 'C4', alpha=0.3, label='')
ax.plot(x_baseline_smooth/1e5, r_baseline_smooth, 'C0', label='DDPG')
ax.plot(x_expert_smooth/1e5, r_expert_smooth, 'C3', label='DDPG+pre-train')
ax.plot(x_supervised_smooth/1e5, r_supervised_smooth, 'C4', label='DDPG+supervise')
ax.set_title(env_ids)
ax.vlines(0.3, 0, 1, transform=ax.get_xaxis_transform(), colors='k', linestyles = "dashed", label='')
ax.hlines(ave_rewards, 0, 1, transform=ax.get_yaxis_transform(), colors='C5', linestyles = "dashed", label='')
plt.xlabel('Training Steps /$10^5$')
plt.ylabel('Reward')
plt.legend()
plt.show()
pdf.savefig(fig)
plt.close()
pdf.close()
# -
env.close()
import pickle
import os
env_ids = ['HalfCheetah-v1', 'Hopper-v1', 'Walker2d-v1']
expert_dirs = [os.path.join('./expert', var) + '/expert.pkl' for var in env_ids]
for i in range(len(envs)):
expert_file = open(expert_dirs[i], 'rb')
expert_data = pickle.load(expert_file)
expert_file.close()
n = 0
r = 0
for episode_sample in expert_data:
for step_sample in episode_sample:
r += step_sample[2]
n +=1.
ave_r = r/n
print(ave_r)
| baselines/ddpg/plotlogs.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 tkinter import *
import sqlite3
import tkinter.messagebox
from PIL import Image,ImageTk
conn = sqlite3.connect('database.db')
c = conn.cursor()
ids =[]
class Application:
def __init__(self, master):
self.master = master
self.left = Frame(master, width = 800, height =720, bg = 'grey')
self.left.pack(side = LEFT)
self.right = Frame(master, width = 400, height = 720, bg ='grey')
self.right.pack(side = RIGHT)
self.heading = Label(self.left, text = "HOSPITAL APPOINTMENTS", font = ('arial 40 bold'))
self.heading.place(x=0, y=0)
self.name = Label(self.left, text = "Patient's Name", font =('arial 10 bold'), fg = 'black')
self.name.place(x =0, y = 100)
self.age =Label(self.left, text = "Age", font =('arial 10 bold'), fg = 'black')
self.age.place(x = 0, y =140)
self.gender = Label(self.left, text="Gender", font=('arial 10 bold'), fg='black')
self.gender.place(x=0, y=180)
self.location = Label(self.left, text="Location", font=('arial 10 bold'), fg='black')
self.location.place(x=0, y=220)
self.time = Label(self.left, text="Appointment time", font=('arial 10 bold'), fg='black')
self.time.place(x=0, y=260)
self.phone =Label(self.left, text ="Phone", font =('arial 10 bold'), fg ='black',)
self.phone.place(x =0, y= 300)
self.name_ent = Entry(self.left, width =30)
self.name_ent.place(x = 250, y =100)
self.age_ent = Entry(self.left, width=30)
self.age_ent.place(x=250, y=140)
self.gender_ent = Entry(self.left, width=30)
self.gender_ent.place(x=250, y=180)
self.location_ent = Entry(self.left, width=30)
self.location_ent.place(x=250, y=220)
self.time_ent = Entry(self.left, width=30)
self.time_ent.place(x=250, y=260)
self.phone_ent =Entry(self.left, width =30)
self.phone_ent.place(x =250, y = 300)
self.submit = Button(self.left, text = "Add Appointment", width = 20, height = 2, command = self.add_appointment)
self.submit.place(x = 280, y = 340)
sql2 = "SELECT ID FROM appointments"
self.result = c.execute(sql2)
for self.row in self.result:
self.id = self.row[0]
ids.append(self.id)
self.new = sorted(ids)
self.final_id = self.new[len(ids)-1]
self.logs = Label(self.right, text = "Logs", font = ('arial 20 bold'))
self.logs.place(x =0, y =0)
self.box = Text(self.right, width =60, height =40)
self.box.place(x =0, y =40)
self.box.insert(END, "Total appointments till now: " + str(self.final_id))
def add_appointment(self):
# print("This is working")
self.val1 = self.name_ent.get()
self.val2 = self.age_ent.get()
self.val3 = self.gender_ent.get()
self.val4 = self.location_ent.get()
self.val5 = self.time_ent.get()
self.val6 = self.phone_ent.get()
#print(self.val1)
if(self.val1== '' or self.val2 =='' or self.val3=='' or self.val4=='' or self.val5 =='' or self.val6 ==''):
tkinter.messagebox.showinfo("Warning", "Please fill up all boxes")
else:
sql = "INSERT INTO 'appointments' (name, age, gender , location , scheduled_time, phone) VALUES(?,?,?,?,?,?)"
c.execute(sql, (self.val1, self.val2, self.val3, self.val4, self.val5, self.val6))
conn.commit()
tkinter.messagebox.showinfo("Success","Appointment for " +str(self.val1) + " has been created!")
self.name_ent.delete(0, END)
self.age_ent.delete(0, END)
self.gender_ent.delete(0, END)
self.location_ent.delete(0, END)
self.time_ent.delete(0, END)
self.phone_ent.delete(0, END)
self.box.insert(END, '\nAppointment fixed for ' + str(self.val1) + ' at ' + str(self.val5))
root = Tk()
root.title('HOSPITAL MANAGEMENT SYSTEM')
b = Application(root)
root.geometry("1200x720+0+0")
root.resizable(False, False)
root.mainloop()
# -
| Hospital Management System/appointment.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
# ---
# # Cribbage Scoring
#
# This notebook will attempt to develop an algorithm to score a cribbage hand.
#
# https://github.com/CJOlsen/Cribbage-Helper/blob/master/cribbage.py
# https://www.pagat.com/adders/crib6.html
# http://boardgames.stackexchange.com/questions/24509/cribbage-scoring-rules-explanation
#
# > 15: Any combination of cards adding up to 15 pips scores 2 points. For example king, jack, five, five would score 10 points altogether: 8 points for four fifteens, since the king and the jack can each be paired with either of the fives, plus 2 more points for the pair of fives. You would say "Fifteen two, fifteen four, fifteen six, fifteen eight and a pair makes ten".
#
# > Pair: A pair of cards of the same rank score 2 points. Three cards of the same rank contain 3 different pairs and thus score a total of 6 points for pair royal. Four of a kind contain 6 pairs and so score 12 points.
#
# > Run: Three cards of consecutive rank (irrespective of suit), such as ace-2-3, score 3 points for a run. A hand such as 6-7-7-8 contains two runs of 3 (as well as two fifteens and a pair) and so would score 12 altogether. A run of four cards, such as 9-10-J-Q scores 4 points (this is slightly illogical - you might expect it to score 6 because it contains two runs of 3, but it doesn't. The runs of 3 within it don't count - you just get 4), and a run of five cards scores 5.
#
# > Flush: If all four cards of the hand are the same suit, 4 points are scored for flush. If the start card is the same suit as well, the flush is worth 5 points. There is no score for having 3 hand cards and the start all the same suit. Note also that there is no score for flush during the play - it only counts in the show.
#
# > One For His Nob: If the hand contains the jack of the same suit as the start card, you peg One for his nob (sometimes known, especially in North America, as "one for his nobs" or "one for his nibs")..
# ## Conventions
#
# The cards in a deck will be represented by two characters, the face value (A,2,3,4,5,6,7,8,9,10,J,Q,K) and the suit (S, H, D, C). So the king of spades would be: KS and the 2 of diamonds would be: 2D. Face cards have a point value of 10, the ace is 1 point and all other cards represent their value.
#
# The player has 4 cards in their hand and the cut card. The program should be able to accurately count the score.
#
# The following hand would be 1 pair for 2 points:
# 2D, 2S, KD, QD: 4C
#
# ----
# + language="javascript"
# //Disable autoscroll in the output cells
# IPython.OutputArea.prototype._should_scroll = function(lines) {
# return false;
# }
# -
# The following blocks of code are from GitHub: https://github.com/CJOlsen/Cribbage-Helper/blob/master/cribbage.py. It has the nicest card class and some good implmentations of the scoring routines.
#
# I am going to clean them up and modify them as I see fit...
# +
# http://www.fileformat.info/info/unicode/char/2666/index.htm
HEART = u'\u2665'
DIAMOND = u'\u2666'
SPADE = u'\u2660'
CLUB = u'\u2663'
# Suit name to symbol map
suits ={'heart':HEART,
'diamond':DIAMOND,
'spade':SPADE,
'club':CLUB,
'H':HEART,
'D':DIAMOND,
'S':SPADE,
'C':CLUB}
for k,v in suits.items():
print('{:7} = {}'.format(k,v))
# -
import random
# +
# Shared tuple that stores the card ranks
ranks = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
# shared tuple that stores the card suits
suits = ('D', 'H', 'C', 'S')
class Card(object):
"""
This is a card object, it has a rank, a value, a suit, and a display.
Value is an integer rank, suit and display are strings.
"""
# code for the class was inspired from:
# https://github.com/CJOlsen/Cribbage-Helper/blob/master/cribbage.py
# I have made some heavy modifications to the basic program
def __init__(self, rank=None, suit=None):
"""
Parameters
----------
rank - a string representing the rank of the card: A, 2, 3, 4, 5, 6, 7,
8, 9, 10, J, Q, K
suit - a string representing the suit of the card D, H, C or S
NOTE: If you send a combined string like '3H' or 'AS' in the rank slot.
This will be split into the rank and suit. The order matters 'H3'
or 'h3' or 'sa' won't be accepted.
"""
if rank and suit:
assert type(rank) == str and rank in ranks
assert type(suit) == str and suit in suits
elif rank:
assert type(rank) == str
assert len(rank) == 2
r, s = rank.upper()
# make sure the values are in the right order
if r in ranks and s in suits:
rank = r
suit = s
elif r in suits and s in ranks:
rank = s
suit = r
else:
raise ValueError('Rank and/or suit do not match!')
else:
raise ValueError('Rank and suit not properly set!')
# at this point the rank and suit should be sorted
self.rank = rank
self.suit = suit
if rank == 'A':
self.value = 1
elif rank in ('T', 'J', 'Q', 'K'):
self.value = 10
else:
self.value = int(rank)
self.display = rank + suit
suit_symbols = {'H': u'\u2665',
'D': u'\u2666',
'S': u'\u2660',
'C': u'\u2663'}
# TBW 2016-07-20
# display the card with the rank and a graphical symbol
# representing the suit
self.cool_display = rank + suit_symbols[suit]
# set the cards sorting order - useful for sorting a list of cards.
rank_sort_order_map = {'A': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'T': 10,
'J': 11,
'Q': 12,
'K': 13}
self.sort_order = rank_sort_order_map[rank]
def __eq__(self, other):
"""
This overrides the == operator to check for equality
"""
return self.__dict__ == other.__dict__
def __add__(self, other):
"""
"""
return self.value + other.value
def __radd__(self, other):
"""
"""
return self.value + other
# TBW 2016-07-21
def __lt__(self, other):
"""
Make the item sortable
"""
return self.sort_order < other.sort_order
def __hash__(self):
"""
Make the item hashable
"""
return hash(self.display)
def __str__(self):
return self.cool_display
def __repr__(self):
# return "Card('{}', '{}')".format(self.rank, self.suit)
return self.__str__() # I don't need to produce the above...
# -
print(Card('3S').cool_display)
print(Card('s3').cool_display)
print(Card('3', 'S').cool_display)
# print(Card('S', 'A').cool_display) # this will raise an assertion error
from itertools import chain, combinations, product
# +
def make_deck():
"""
Creates a deck of 52 cards. Returns the deck as a list
"""
cards = []
for p in product(ranks, suits):
cards.append(Card(*p))
return cards
# # Test code
# deck = make_deck()
# for c in deck:
# print(c.display, c.cool_display, c.sort_order)
# -
class Hand(list):
"""
A hand is a list of ***Card*** objects.
"""
def __init__(self, *args):
list.__init__(self, *args)
def display(self):
"""
Returns a list of ***Card*** objects in the hand in a format suitable
for display: [AD, 1D, 3S,4C]
"""
return [c.display for c in self]
def cool_display(self):
"""
Returns a list of ***Card*** objects in the hand in a format suitable
for display: [A♦, 1♦, 3♠, 4♣]
"""
return [c.cool_display for c in self]
def value(self):
"""
Returns the value of ***Card*** objects in the hand by summing
the individual card values.
A = 1
J,Q,K = 10
and the other cards are equal to the value of their rank.
"""
return sum([c.value for c in self])
def sorted(self):
"""
Return a new ***Hand*** in sorted order.
"""
return Hand(sorted(self, key=lambda c: c.sort_order, reverse=False))
def every_combination(self, **kwargs):
"""
A generator that will yield all possible combination of hands
from the current hand.
"""
if 'count' in kwargs:
for combo in combinations(self, kwargs['count']):
yield Hand(combo)
else:
for combo in chain.from_iterable(combinations(self, r)
for r in range(len(self) + 1)):
yield Hand(combo)
# +
deck = make_deck()
hand = Hand(random.sample(deck, 6))
print('Random Hand = {}'.format(hand.display()))
print('Random Hand = {}'.format(hand.cool_display()))
print('Sorted Hand = {}'.format(hand.sorted().cool_display()))
print('Hand Sum = {}'.format(hand.value()))
# +
# # iterate through every combination of the hand:
# for combo in hand.every_combination():
# print('Combination = {}'.format(combo.cool_display()))
# -
# # Scoring - Fifteens
# +
def find_fifteens_combos(hand):
"""
A generator that takes a hand of cards and finds all of the combinations of
cards that sum to 15. It returns a sub-hand containing the combination
"""
for combo in hand.every_combination():
if combo.value() == 15:
yield combo
def count_fifteens(hand):
"""
Counts the number of combinations within the hand of cards that sum to 15.
Each combination is worth 2 points.
Returns a tuple containing the total number of combinations and the total
points.
"""
combos = list(find_fifteens_combos(hand))
return len(combos), len(combos)*2
# +
hand = Hand(random.sample(deck, 5))
print('Hand = {}'.format(hand.sorted().cool_display()))
print('{} Fifteens for {}.'.format(*count_fifteens(hand)))
# display the combinations
for combo in find_fifteens_combos(hand):
print('{} = 15'.format(', '.join(combo.sorted().cool_display())))
# -
# # Scoring - Pairs
# +
def find_pairs(hand):
"""
A generator that will iterate through all of the combinations and yield
pairs of cards.
"""
for combo in hand.every_combination(count=2):
if combo[0].rank == combo[1].rank:
yield combo
def count_pairs(hand):
"""
Returns the score due to all the pairs found in the hand. Each pair is
worth 3 points.
"""
pairs = list(find_pairs(hand))
return len(pairs), len(pairs)*2
# +
# full_hand = Hand([Card('J','D'), Card('5', 'H'), Card('5', 'S'), Card('5', 'C'), Card('5','D')])
# for c in full_hand.every_combination(count=2):
# print(c.cool_display())
# # for this set there should be 10 combinations
# print()
# for combo in combinations(full_hand, 2):
# print(Hand(combo).cool_display())
# +
hand = Hand([Card('5','D'), Card('5', 'S'), Card('5', 'C'), Card('J', 'S'), Card('A','C')])
print('Hand = {}'.format(hand.sorted().cool_display()))
print()
print('{} Fifteens for {}.'.format(*count_fifteens(hand)))
print('{} Pairs for {}.'.format(*count_pairs(hand)))
print()
print('Fifteens====')
for combo in find_fifteens_combos(hand):
print('{} = 15'.format(', '.join(combo.cool_display())))
print()
print('Pairs====')
# display the pairs
for combo in find_pairs(hand):
print('{}'.format(', '.join(combo.cool_display())))
# +
m = [Card('J','D'), Card('5', 'H'), Card('5', 'S'), Card('5', 'C')]
hand = Hand([Card('J','D'), Card('5', 'H'), Card('5', 'S'), Card('5', 'C'), Card('5','D')])
print('Hand = {}'.format(hand.sorted().cool_display()))
print('{} Pairs for {}.'.format(*count_pairs(hand)))
print()
print('Pairs====')
# display the pairs
for combo in find_pairs(hand):
print('{}'.format(', '.join(combo.cool_display())))
# -
# # Scoring - Runs
from itertools import groupby
# +
def find_runs(hand):
"""
A generator that takes a hand of cards and finds all runs of 3 or more
cards. Returns each set of cards that makes a run.
"""
runs = []
for combo in chain.from_iterable(combinations(hand, r)
for r in range(3, len(hand)+1)):
for k, g in groupby(enumerate(Hand(combo).sorted()),
lambda ix: ix[0] - ix[1].sort_order):
# strip out the enumeration and get the cards in the group
new_hand = Hand([i[1] for i in g])
if len(new_hand) < 3:
continue
m = set(new_hand)
# check to see if the new run is a subset of an existing run
if any([m.issubset(s) for s in runs]):
continue
# if the new run is a super set of previous runs, we need to remove
# them
l = [m.issuperset(s) for s in runs]
if any(l):
runs = [r for r, t in zip(runs, l) if not t]
if m not in runs:
runs.append(m)
return [Hand(list(r)).sorted() for r in runs]
def count_runs(hand):
"""
Count the number of points in all the runs. 1 point per card in the run
(at least 3 cards).
"""
runs = list(find_runs(hand))
return len(runs), sum([len(r) for r in runs])
# +
hands = [Hand([Card('2','D'), Card('3', 'D'), Card('4', 'D'), Card('8', 'D'), Card('5','D')]),
Hand([Card('2','D'), Card('3', 'D'), Card('3', 'S'), Card('3', 'C'), Card('4','D')]),
Hand([Card('2','D'), Card('4', 'D'), Card('6', 'H'), Card('8', 'S'), Card('9','D')])]
for hand in hands:
print('Hand = {}'.format(hand.sorted().cool_display()))
print()
print('{} Runs for {}.'.format(*count_runs(hand)))
print()
print('Runs====')
for combo in find_runs(hand):
print(combo.cool_display())
print()
# -
# # Flushes
#
# A four-card flush scores four points, unless in the crib. A four-card flush occurs when all of the cards in a player's hand are the same suit and the start card is a different suit. In the crib, a four-card flush scores no points. A five-card flush scores five points.
#
# Basically this means that we have to take into account the cards in hand and the card in the cut. A flush is only counted if the 4 hand cards are the same suit for 4 points, If the cut card is the same, an additional point is awarded.
#
# In the crib, a four-card flush isn't counted. If the cut card is the same, then the flush is counted for 5 points
def count_flushes(hand, cut, is_crib=False):
"""
Scores the points for flushes.
"""
assert len(hand) == 4
m = set([c.suit for c in hand])
if len(m) == 1:
score = 4
if cut and m.pop() == cut.suit:
score += 1
if is_crib:
# The crib can only score a flush if all the cards
# in the crib are the same suit and the cut card
# is the same suit. Otherwise a flush isn't counted.
if score != 5:
return 0
return score
else:
return 0
# +
m = [Card('2','D'), Card('3', 'D'), Card('4', 'D'), Card('8', 'D')]
hand = Hand(m)
cut = Card('5','D')
full_hand = Hand(m + [cut])
print('Hand = {}'.format(hand.sorted().cool_display()))
print('Cut = {}'.format(cut.cool_display))
print('Full Hand = {}'.format(full_hand.sorted().cool_display()))
print()
print('{} Fifteens for {}.'.format(*count_fifteens(full_hand)))
print('{} Pairs for {}.'.format(*count_pairs(full_hand)))
print('{} Runs for {}.'.format(*count_runs(full_hand)))
print('Flush for {}.'.format(count_flushes(hand, cut)))
print()
print('Fifteens====')
for combo in find_fifteens_combos(hand):
print('{} = 15'.format(', '.join(combo.cool_display())))
print()
print('Pairs====')
for combo in find_pairs(hand):
print('{}'.format(', '.join(combo.cool_display())))
print()
print('Runs====')
for combo in find_runs(hand):
print(combo.cool_display())
# -
def count_nobs(hand, cut):
"""
Takes a 4 card hand and a cut card. If the hand contains a jack and it is
the same suit as the cut card than a point is scored. This is called nobs.
"""
assert len(hand) == 4
if not cut:
return 0
if any([c.suit == cut.suit and c.rank == 'J' for c in hand]):
return 1
else:
return 0
# +
m = [Card('2','D'), Card('3', 'D'), Card('J', 'D'), Card('8', 'D')]
hand = Hand(m)
cut = Card('5','D')
full_hand = Hand(m + [cut])
print('Hand = {}'.format(hand.sorted().cool_display()))
print('Cut = {}'.format(cut.cool_display))
print('Full Hand = {}'.format(full_hand.sorted().cool_display()))
print()
total_count = 0
number, value = count_fifteens(full_hand)
total_count += value
print('{} Fifteens for {}'.format(number, value))
number, value = count_pairs(full_hand)
total_count += value
print('{} Pairs for {}'.format(number, value))
number, value = count_runs(full_hand)
total_count += value
print('{} Runs for {}'.format(number, value))
value = count_flushes(hand, cut)
total_count += value
print('Flush for {}'.format(value))
value = count_nobs(hand, cut)
total_count += value
print('Nobs for {}'.format(value))
print('------------------')
print('Total {}'.format(total_count))
print()
print('Fifteens====')
for combo in find_fifteens_combos(hand):
print('{} = 15'.format(', '.join(combo.cool_display())))
print()
print('Pairs====')
for combo in find_pairs(hand):
print('{}'.format(', '.join(combo.cool_display())))
print()
print('Runs====')
for combo in find_runs(hand):
print(combo.cool_display())
# -
def score_hand(hand, cut, **kwargs):
"""
Takes a 4 card crib hand and the cut card and scores it.
Returns a dictionary containing the various items
"""
# defaults
is_crib = False if 'is_crib' not in kwargs else kwargs['is_crib']
full_hand = Hand(hand + [cut]) if cut else hand
scores = {} # contain the scores
count = {} # contain the counts for items that can hit multiple times
number, value = count_fifteens(full_hand)
count['fifteen'] = number
scores['fifteen'] = value
number, value = count_pairs(full_hand)
count['pair'] = number
scores['pair'] = value
number, value = count_runs(full_hand)
count['run'] = number
scores['run'] = value
scores['flush'] = count_flushes(hand, cut, is_crib)
scores['nobs'] = count_nobs(hand, cut)
return scores, count
def display_points(hand, cut, scores, counts):
print('Hand = {}'.format(','.join(hand.sorted().cool_display())))
print('Cut = {}'.format(cut.cool_display if cut else 'N/A'))
print()
print('{} Fifteens for {}'.format(counts['fifteen'], scores['fifteen']))
print('{} Pairs for {}'.format(counts['pair'], scores['pair']))
print('{} Runs for {}'.format(counts['run'], scores['run']))
print('Flush for {}'.format(scores['flush']))
print('Nobs for {}'.format(scores['nobs']))
print('-----------------')
print('Total {}'.format(sum([v for k, v in scores.items()])))
print()
full_hand = Hand(hand + [cut]) if cut else hand
print('Fifteens====')
for combo in find_fifteens_combos(full_hand):
print('{} = 15'.format(', '.join(combo.cool_display())))
print()
print('Pairs====')
for combo in find_pairs(full_hand):
print('{}'.format(', '.join(combo.cool_display())))
print()
print('Runs====')
for combo in find_runs(full_hand):
print(', '.join(combo.cool_display()))
# +
# Hand = 5♣,5♠,J♥,J♣
# Cut = J♠
# 6 Fifteens for 12
# 4 Pairs for 8
# 0 Runs for 0
# Flush for 0
# Nobs for 0
# ------------------
# Total 20
# Fifteens====
# J♥, 5♣ = 15
# J♥, 5♠ = 15
# 5♣, J♣ = 15
# J♣, 5♠ = 15
# Pairs====
# J♥, J♣
# 5♣, 5♠
# Runs====
hand = Hand([Card('5','C'), Card('5', 'S'), Card('J', 'H'), Card('J', 'C'), Card('J','S')])
print('Hand = {}'.format(hand.sorted().cool_display()))
print('{} Fifteens for {}.'.format(*count_fifteens(hand)))
# display the combinations
for combo in find_fifteens_combos(hand):
print('{} = 15'.format(', '.join(combo.sorted().cool_display())))
print('--------')
hand = Hand([Card('5','C'), Card('5', 'S'), Card('J', 'H'), Card('J', 'C')])
cut = Card('J','S')
scores, counts = score_hand(hand, cut)
display_points(hand, cut, scores, counts)
# this agrees now 2016-07-21
# +
deck = make_deck()
m = random.sample(deck, 5)
hand = Hand(m[:4])
cut = m[-1]
scores, counts = score_hand(hand, cut)
display_points(hand, cut, scores, counts)
# -
# It seems there is something wrong, the highest possible hand is 29,
#
# >The highest scoring cribbage hand you can get is worth 29 points. It consists of a Jack and three fives. The cut card is the five of the same suit as the Jack. So, there are actually four different hands that are worth 29 (each suit).
#
# We score the 29 hand in the same way as any other: taking 15s first, then pairs, runs, flushes and nobs.
#
# First count 15s. The Jack makes 15 with each of the 5s, that's 4 15s.
#
# Also, there are 4 ways of choosing three different 5s to make additional 15s. That's 8 in total, for 16 points.
#
# Then pairs: there are 6 different pairs of 5s, for another 12 points. That's 28 so far.
#
# There are no runs or flushes, so the Jack of nobs gives us a final point for 29.
# +
m = [Card('3','D'), Card('3', 'H'), Card('3', 'S'), Card('3', 'C')]
hand = Hand(m)
cut = Card('7','D')
scores, counts = score_hand(hand, cut)
display_points(hand, cut, scores, counts)
# -
# # Testing the cribbage.py module
from cribbage import Card, Hand,score_hand, display_points, make_deck
# +
deck = make_deck()
m = random.sample(deck, 5)
hand = Hand(m[:4])
cut = m[-1]
scores, counts = score_hand(hand, cut)
display_points(hand, cut, scores, counts)
| notebooks/archive/0 cribbage scoring 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 requests
import json5
import time
import pandas as pd
jobs = []
for pg in range(11596//50):
r = requests.get('https://www.indeed.com/jobs?q&l=Rancho%20Cordova%2C%20CA&radius=15&fromage=14&start={}&limit=50'.format(pg*50))
if r.status_code != 200:
print('Error',pg)
time.sleep(5)
continue
for i in range(50):
start = r.text.find('jobmap[{}]'.format(i))
if start==-1:
continue
end = r.text.find('jobmap[{}]'.format(i+1))
s = r.text.find('{',start)
e = r.text.find('}',s)+1
job = r.text[s:e]
p = job.find(': ')
while p != -1:
job = job.replace(': ',':')
p = job.find(': ')
job = json5.loads(job)
jobs.append(job)
time.sleep(5)
df = pd.DataFrame(jobs)
df.head()
df.drop_duplicates(inplace=True)
df.info()
df.to_csv('jobs.csv',index=False)
# +
# need to now use https://www.indeed.com/viewjob?jk=... to get job data
| Notebooks/Original_Indeed_Scraping.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.2 64-bit
# language: python
# name: python3
# ---
import torch
import matplotlib.pyplot as plt
from tqdm import tqdm
import random
def data_generation(true_w, true_b, n):
x = torch.normal(0, 1, (n, len(true_w)))
y = torch.matmul(x, true_w) + true_b
y += torch.normal(0, 0.01, y.shape)
return x, y.reshape(-1,1)
true_w = torch.tensor([4.2, -3.0])
true_b = torch.tensor([2.0])
n = 1000
train_data, labels = data_generation(true_w, true_b, 1000)
plt.scatter(train_data[:,0].detach().numpy(), labels.detach().numpy(), 1.5)
plt.show()
plt.scatter(train_data[:,1].detach().numpy(), labels.detach().numpy(), 1.5)
plt.show()
def data_iter(train_data, labels, batch_size):
nums = len(train_data)
indices = list(range(nums))
random.shuffle(indices)
for i in range(0, nums, batch_size):
batch_indices = torch.tensor([indices[i:min(i+batch_size, nums)]])
yield train_data[batch_indices], labels[batch_indices]
a, b = next(data_iter(train_data, labels, 10))
a,b
w = torch.normal(0, 0.01, (2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
def square_loss(y_hat, y):
return ((y_hat-y.reshape(y_hat.shape)) ** 2 / 2).sum()
def regression(w, b, x):
return torch.matmul(x, w) + b
def sgd(params, lr, batch_size):
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()
epochs = 20
batch_size = 10
lr = 0.03
net = regression
loss = square_loss
for epoch in range(epochs):
for x, y in tqdm(data_iter(train_data, labels, batch_size)):
y_hat = net(w, b, x)
l = loss(y_hat, y)
l.sum().backward()
sgd([w,b], lr, batch_size)
with torch.no_grad():
train_loss = loss(net(w, b, train_data), labels)
print(f'epoch: {epoch+1}, train loss: {train_loss.mean():f}')
| chapter 3 linear model/linear regression from zreo.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
# language: python
# name: python3
# ---
# # Abltion Analysis of The Prediction Model
#
# Using the data stored in `top_posts.csz.gz` this script will aim to make model that can predict the number of upvotes (likes) given all other data in the file excluding `number_of_upvotes`, `total_votes`, and `number_of_downvotes`.
#
# This script attempts to get a better understanding of how each feature influences the model through [Ablation Analysis](https://stats.stackexchange.com/questions/380040/what-is-an-ablation-study-and-is-there-a-systematic-way-to-perform-it). This means the model will be ran with specific features removed to compare their performance on the same dataset. To reduce clutter, this script uses methods stored in `ablation.py`.
import gzip
import nltk
import random
import numpy as np
from ablation import *
from csv import writer
from csv import DictReader
from datetime import date
from datetime import datetime
from collections import defaultdict
from sklearn.linear_model import Ridge
from nltk.tokenize import word_tokenize
# Download a few needed packages for the nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
# Debug variables
date = date.today().strftime("%b %d")
baseline = 0
pred_mse = 0
feature_list = []
shuffle = False
# +
# Most optimal size found for n-length list of popular words
n = 600
# Most optimal alpha found for Ridge Regression
alpha = 100
# -
data = []
word_popularity = defaultdict(int)
performance = []
# Open and store each post as a list of dict elements
with gzip.open('../data/top_posts.csv.gz', 'rt') as file:
csv_reader = DictReader(file)
for row in csv_reader:
data.append(row)
for word in word_tokenize(row['title']):
word_popularity[word] += 1
word_popularity = sorted(word_popularity.items(), key=lambda item: item[1], reverse=True)
word_popularity = [pair[0] for pair in word_popularity]
word_popularity = word_popularity[:n]
# Shuffle the data since it's sorted by subreddit to give a fairer distribution
random.shuffle(data)
shuffle = True
# Store an X vector for each feature vector
X_all = []
X_exc_score = []
X_exc_num_com = []
X_exc_len_char = []
X_exc_len_word = []
X_exc_oc = []
X_exc_pos = []
X_exc_ohe = []
X_exc_popular_word = []
# y is the list of labels (correct values)
y = []
for datum in data:
X_all.append(feature_all(datum, word_popularity, n))
X_exc_score.append(feature_exc_score(datum, word_popularity, n))
X_exc_num_com.append(feature_exc_num_com(datum, word_popularity, n))
X_exc_len_char.append(feature_exc_len_char(datum, word_popularity, n))
X_exc_len_word.append(feature_exc_len_word(datum, word_popularity, n))
X_exc_oc.append(feature_exc_oc(datum, word_popularity, n))
X_exc_pos.append(feature_exc_pos(datum, word_popularity, n))
X_exc_ohe.append(feature_exc_ohe(datum, word_popularity, n))
X_exc_popular_word.append(feature_exc_popular_word(datum, word_popularity, n))
y.append(int(datum['number_of_upvotes']))
# House Cleaning
del data
del popular_words
# Split the datum between training (80%), validation (10%), and test (10%)
train = round(len(X_all) * 0.8)
valid = train + round(len(X_all) * 0.1)
tests = train + round(len(X_all) * 0.1)
y_train = y[:train]
y_valid = y[train:valid]
y_tests = y[valid:]
# Get a baseline by testing the model against the average label
average_likes = np.mean(y)
y_avg = [average_likes] * len(y)
# Get the MSE from the baseline averages
baseline = MSE(y_avg[train:valid], y_valid)
# +
# Run the model
model = Ridge(fit_intercept=False, alpha=alpha)
model.fit(X_all[:train], y_train)
# Store the performance of this model
row = []
row.append(date)
row.append(baseline)
row.append(MSE(model.predict(X_all[train:valid]), y_valid))
row.append('score|number_of_comments|title_length|title_word_length|orginal_content|parts_of_speech|ohe_hour|ohe_week|{}_popular_words'.format(n))
row.append(shuffle)
performance.append(row)
del X_all
# +
# Run the model
model = Ridge(fit_intercept=False, alpha=alpha)
model.fit(X_exc_score[:train], y_train)
# Store the performance of this model
row = []
row.append(date)
row.append(baseline)
row.append(MSE(model.predict(X_exc_score[train:valid]), y_valid))
row.append('number_of_comments|title_length|title_word_length|orginal_content|parts_of_speech|ohe_hour|ohe_week|{}_popular_words'.format(n))
row.append(shuffle)
performance.append(row)
del X_exc_score
# +
# Run the model
model = Ridge(fit_intercept=False, alpha=alpha)
model.fit(X_exc_num_com[:train], y_train)
# Store the performance of this model
row = []
row.append(date)
row.append(baseline)
row.append(MSE(model.predict(X_exc_num_com[train:valid]), y_valid))
row.append('score|title_length|title_word_length|orginal_content|parts_of_speech|ohe_hour|ohe_week|{}_popular_words'.format(n))
row.append(shuffle)
performance.append(row)
del X_exc_num_com
# +
# Run the model
model = Ridge(fit_intercept=False, alpha=alpha)
model.fit(X_exc_len_char[:train], y_train)
# Store the performance of this model
row = []
row.append(date)
row.append(baseline)
row.append(MSE(model.predict(X_exc_len_char[train:valid]), y_valid))
row.append('score|number_of_comments|title_word_length|orginal_content|parts_of_speech|ohe_hour|ohe_week|{}_popular_words'.format(n))
row.append(shuffle)
performance.append(row)
del X_exc_len_char
# +
# Run the model
model = Ridge(fit_intercept=False, alpha=alpha)
model.fit(X_exc_len_word[:train], y_train)
# Store the performance of this model
row = []
row.append(date)
row.append(baseline)
row.append(MSE(model.predict(X_exc_len_word[train:valid]), y_valid))
row.append('score|number_of_comments|title_length|orginal_content|parts_of_speech|ohe_hour|ohe_week|{}_popular_words'.format(n))
row.append(shuffle)
performance.append(row)
del X_exc_len_word
# +
# Run the model
model = Ridge(fit_intercept=False, alpha=alpha)
model.fit(X_exc_oc[:train], y_train)
# Store the performance of this model
row = []
row.append(date)
row.append(baseline)
row.append(MSE(model.predict(X_exc_oc[train:valid]), y_valid))
row.append('score|number_of_comments|title_length|title_word_length|parts_of_speech|ohe_hour|ohe_week|{}_popular_words'.format(n))
row.append(shuffle)
performance.append(row)
del X_exc_oc
# +
# Run the model
model = Ridge(fit_intercept=False, alpha=alpha)
model.fit(X_exc_pos[:train], y_train)
# Store the performance of this model
row = []
row.append(date)
row.append(baseline)
row.append(MSE(model.predict(X_exc_pos[train:valid]), y_valid))
row.append('score|number_of_comments|title_length|title_word_length|orginal_content|ohe_hour|ohe_week|{}_popular_words'.format(n))
row.append(shuffle)
performance.append(row)
del X_exc_pos
# +
# Run the model
model = Ridge(fit_intercept=False, alpha=alpha)
model.fit(X_exc_ohe[:train], y_train)
# Store the performance of this model
row = []
row.append(date)
row.append(baseline)
row.append(MSE(model.predict(X_exc_ohe[train:valid]), y_valid))
row.append('score|number_of_comments|title_length|title_word_length|orginal_content|parts_of_speech|{}_popular_words'.format(n))
row.append(shuffle)
performance.append(row)
del X_exc_ohe
# +
# Run the model
model = Ridge(fit_intercept=False, alpha=alpha)
model.fit(X_exc_popular_word[:train], y_train)
# Store the performance of this model
row = []
row.append(date)
row.append(baseline)
row.append(MSE(model.predict(X_exc_popular_word[train:valid]), y_valid))
row.append('score|number_of_comments|title_length|title_word_length|orginal_content|parts_of_speech|ohe_hour|ohe_week')
row.append(shuffle)
performance.append(row)
del X_exc_popular_word
# -
# Append the debug data from this script to the CSV of MSE records
with open('../data/prediction_model_MSE.csv', 'a') as file:
csv_writer = writer(file)
for row in performance:
csv_writer.writerow(row)
| scripts/prediction_model_ablation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Introduction to Matplotlib
# %matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
plt.plot()
plt.plot();
plt.plot()
plt.show()
plt.plot([1,2,3,4]);
x=[1,2,3,4]
y=[11,22,33,44]
plt.plot(x,y);
# 1st method
fig=plt.figure() #creates a figures
ax=fig.add_subplot() # adds some axes
plt.show()
# 2nd method
fig=plt.figure() #creates a figure
ax=fig.add_axes([1,1,1,1])
ax.plot(x,y) #add come data
plt.show()
# 3rd method (recommended)
fig, ax=plt.subplots()
ax.plot(x,[50,100,200,250]); #add some data
type(fig),type(ax)
# # Matplotlib example workflow
# +
# 0. import matplotlib and get it ready for plotting in Jupyter
# %matplotlib inline
import matplotlib.pyplot as plt
# 1. prepare some data
x=[1,2,3,4]
y=[11,22,33,44]
# 2. setup plot
fig, ax=plt.subplots(figsize=(5,5)) #(width,heigh)
# 3. plot data
ax.plot(x,y)
# 4. customize plot
ax.set(title="Simple plot",
xlabel="x-axis",
ylabel="y-axis")
# 5. Save&show (you save the figure)
fig.savefig('img/sample-plot.png')
# -
# ## Making figures with NumPy arrays
# we want:
# * Line plot
# * Scatterplot
# * Bar plot
# * hist
# * histogram
# * subplot
import numpy as np
# create some data
x=np.linspace(0,10,100)
x[:10]
# Plot the data and create a line plot
fig, ax=plt.subplots()
ax.plot(x,x*x);
# Use same data to make scatter
fig,ax=plt.subplots()
ax.scatter(x,np.exp(x));
# Another scatter plot
fig,ax=plt.subplots()
ax.scatter(x,np.sin(x));
# Make a plot from dictionary
nut_butter_prices={"Almond butter":10,
"Peanut butter":8,
"Cashew butter":12}
fig, ax=plt.subplots()
ax.bar(nut_butter_prices.keys(),nut_butter_prices.values())
ax.set(title="Nut butter store",
ylabel="Price ($)",
xlabel="Type nuts");
fig,ax=plt.subplots()
ax.barh(list(nut_butter_prices.keys()),list(nut_butter_prices.values()));
#Make some data for histograms and plot it
x=np.random.randn(1000)
fig,ax=plt.subplots()
ax.hist(x);
# # Two options for subplots
# +
# subplots options 1
fig,((ax1,ax2),(ax3,ax4))=plt.subplots(nrows=2,
ncols=2,
figsize=(10,5))
#plot to each different axis
ax1.plot(x,x/2);
ax2.scatter(np.random.random(10),np.random.random(10));
ax3.bar(nut_butter_prices.keys(),nut_butter_prices.values());
ax4.hist(np.random.randn(100));
# -
# Subplots option 2
fig,ax=plt.subplots(nrows=2,
ncols=2,
figsize=(10,5))
# plot to each different index
ax[0,0].plot(x,x/2);
ax[0,1].scatter(np.random.random(10),np.random.random(10));
ax[1,0].bar(nut_butter_prices.keys(),nut_butter_prices.values());
ax[1,1].hist(np.random.randn(100));
# ## ploting from pandas dataframes
import pandas as pd
# Make a dataframe
car_sales=pd.read_csv("car-sales.csv")
car_sales
# +
ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
ts = ts.cumsum()
ts.plot();
# -
ts
car_sales
car_sales["Price"]=car_sales["Price"].str.replace("[\$\,\.]",'')
car_sales
# remove last two zeros
car_sales["Price"]=car_sales["Price"].str[:-2]
car_sales
car_sales["Sale Date"]=pd.date_range("1/2/2022",periods=len(car_sales))
car_sales
car_sales["Total sales"]=car_sales["Price"].astype(int).cumsum()
car_sales
type(car_sales["Price"][0])
# Let's plot the total sales
car_sales.plot(x="Sale Date",y="Total sales");
# +
# Reassing price column to int
car_sales["Price"]=car_sales["Price"].astype(int)
# plot scatter plot with price column as numeric
car_sales.plot(x="Odometer (KM)",y="Price",kind="scatter");
# +
# how about a bar graph?
x=np.random.rand(10,4)
x
# Turn it into a dataframe
df=pd.DataFrame(x,columns=['a','b','c','d '])
df
# -
df.plot.bar();
df.plot(kind="bar");
car_sales
car_sales.plot(x="Make",y="Odometer (KM)",kind="bar");
# how about histograms?
car_sales["Odometer (KM)"].plot.hist();
car_sales["Odometer (KM)"].plot(kind="hist");
car_sales["Odometer (KM)"].plot.hist(bins=10);
# Let's try on another dataset
heart_disease=pd.read_csv("heart-disease.csv")
heart_disease
heart_disease.head(10)
# create a histogram of age
heart_disease["age"].plot.hist(bins=10);
heart_disease.head()
heart_disease.plot.hist(figsize=(10,30),subplots=True);
# ### Which one should you use? (pyplot vs matplotlib 00 method?)
# * when plotting something quickly, okay to use the pyplot method
# * when plotting something more advanced, use the OO method
heart_disease.head()
over_50=heart_disease[heart_disease["age"]>50]
len(over_50)
over_50.head()
# pyplot method
over_50.plot(kind="scatter",
x="age",
y="chol",
c="target",
figsize=(10,6),
);
#OO method mixes with pyplot method
fix, ax=plt.subplots(figsize=(10,6))
over_50.plot(kind="scatter",
x="age",
y="chol",
c="target",
ax=ax);
# ax.set_xlim([45,100])
over_50.target.values
# +
# OO method from scratch
fig, ax=plt.subplots(figsize=(10,6))
#plot the data
scatter=ax.scatter(x=over_50["age"],
y=over_50["chol"],
c=over_50["target"])
#customize the plot
ax.set(title="Heart Disease and Cholesterol Levels",
xlabel="Age",
ylabel="Cholesterol")
# add a legend
ax.legend(*scatter.legend_elements(),title="Target")
# add a horizontal line
ax.axhline(over_50["chol"].mean(),
linestyle="--");
# -
over_50.head()
# +
# Subplot of chol, age, thalach
fig,(ax0,ax1)=plt.subplots(nrows=2,
ncols=1,
figsize=(10,10),
sharex=True)
#Add data to ax0
scatter=ax0.scatter(x=over_50["age"],
y=over_50["chol"],
c=over_50["target"])
# customize ax0
ax0.set(title="Heart disease and cholesterol levels",
ylabel="Cholesterol")
# add legend to ax0
ax0.legend(*scatter.legend_elements(),title="Target")
# add a meanline
ax0.axhline(y=over_50["chol"].mean(),
linestyle="--");
# add data to ax1
scatter=ax1.scatter(x=over_50["age"],
y=over_50["thalach"],
c=over_50["target"])
# customize ax1
ax1.set(title="Heart diesease and Max Heart Rate",
xlabel="Age",
ylabel="Max Heart Rate");
# add a legend
ax1.legend(*scatter.legend_elements(),title="Target")
# add a meanline
ax1.axhline(y=over_50["thalach"].mean(),
linestyle="--")
# add a title to figure
fig.suptitle("Heart Disease Analysis",fontsize=16, fontweight="bold");
# -
# ## Customizing matplotlib plots and getting stylish
# see the different styles available
plt.style.available
car_sales.head()
car_sales["Price"].plot();
plt.style.use("seaborn-whitegrid")
car_sales["Price"].plot();
plt.style.use("seaborn")
car_sales["Price"].plot();
car_sales.plot(x="Odometer (KM)",y="Price",kind="scatter");
plt.style.use("ggplot")
car_sales["Price"].plot();
# create some data
x=np.random.randn(10,4)
x
df=pd.DataFrame(x,columns=["a","b","c","d"])
df
ax=df.plot(kind="bar")
type(ax)
# +
# customize out plot with the set method
ax=df.plot(kind="bar")
# add some labels and a title
ax.set(title="Random Number Bar Graph from DataFrame",
xlabel="Row number",
ylabel="Random number")
# make the legend visible
ax.legend().set_visible(True);
# +
# set the style
plt.style.use("seaborn-whitegrid")
# OO method from scratch
fig, ax=plt.subplots(figsize=(10,6))
#plot the data
scatter=ax.scatter(x=over_50["age"],
y=over_50["chol"],
c=over_50["target"],
cmap="winter") #this changes the colours scheme
#customize the plot
ax.set(title="Heart Disease and Cholesterol Levels",
xlabel="Age",
ylabel="Cholesterol")
# add a legend
ax.legend(*scatter.legend_elements(),title="Target")
# add a horizontal line
ax.axhline(over_50["chol"].mean(),
linestyle="--");
# +
# customizing the y and x axis limitations
# Subplot of chol, age, thalach
fig,(ax0,ax1)=plt.subplots(nrows=2,
ncols=1,
figsize=(10,10),
sharex=True)
#Add data to ax0
scatter=ax0.scatter(x=over_50["age"],
y=over_50["chol"],
c=over_50["target"],
cmap="winter")
# customize ax0
ax0.set(title="Heart disease and cholesterol levels",
ylabel="Cholesterol")
# Change the x axis limits
ax0.set_xlim([50,80])
# add legend to ax0
ax0.legend(*scatter.legend_elements(),title="Target")
# add a meanline
ax0.axhline(y=over_50["chol"].mean(),
linestyle="--");
# add data to ax1
scatter=ax1.scatter(x=over_50["age"],
y=over_50["thalach"],
c=over_50["target"],
cmap="winter")
# customize ax1
ax1.set(title="Heart diesease and Max Heart Rate",
xlabel="Age",
ylabel="Max Heart Rate");
# change ax1 x axis limits
ax1.set_xlim([50,80])
ax1.set_ylim([60,200])
# add a legend
ax1.legend(*scatter.legend_elements(),title="Target")
# add a meanline
ax1.axhline(y=over_50["thalach"].mean(),
linestyle="--")
# add a title to figure
fig.suptitle("Heart Disease Analysis",fontsize=16, fontweight="bold");
# -
fig.savefig("heart-disease-analysis-plot.png")
| matplotlib plotting and data visualization/Introduction to matplotlib.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
# ---
# +
# Adds link to the scripts folder
import sys
import os
sys.path.append("../../scripts/")
import matplotlib.pyplot as plt
import numpy as np
from divergence import load_divergence_dict, WH_evo_rate
# -
time_average = np.arange(0, 3100, 100)
divergence_dict = load_divergence_dict("../../divergence_dict")
# # Plot for rev / non_rev
# +
colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
fontsize = 16
plt.figure(figsize=(14, 10))
for ii, region in enumerate(["env","pol","gag"]):
plt.plot(time_average, divergence_dict[region]["consensus"]["all"], '-', color=colors[ii], label=region)
plt.plot(time_average, divergence_dict[region]["non_consensus"]["all"], '--', color=colors[ii])
plt.plot([0], [0], 'k-', label="Consensus")
plt.plot([0], [0], 'k--', label="Non-consensus")
plt.grid()
plt.xlabel("Time since infection [days]", fontsize=fontsize)
plt.ylabel("Divergence", fontsize=fontsize)
plt.legend(fontsize=fontsize)
plt.show()
# -
# # By fitness value for each region
# +
colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
fontsize = 16
region = "env"
# Divergence
plt.figure(figsize=(14, 10))
for key in divergence_dict[region].keys():
for key2 in divergence_dict[region][key].keys():
plt.plot(time_average, divergence_dict[region][key][key2], label=f"{key} {key2}")
plt.grid()
plt.xlabel("Time since infection [days]", fontsize=fontsize)
plt.ylabel("Divergence", fontsize=fontsize)
plt.legend(fontsize=fontsize)
plt.show()
# Evolution rate (derivative of divergence)
evo_rate = WH_evo_rate(divergence_dict, time_average)
plt.figure(figsize=(14, 10))
for key in evo_rate[region].keys():
for key2 in ["high","low"]:
plt.plot(time_average, evo_rate[region][key][key2], label=f"{key} {key2}")
plt.grid()
plt.xlabel("Time since infection [days]", fontsize=fontsize)
plt.ylabel("Evolution rate (per site per day)", fontsize=fontsize)
plt.legend(fontsize=fontsize)
plt.show()
# +
colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
fontsize = 16
region = "pol"
# Divergence
plt.figure(figsize=(14, 10))
for key in divergence_dict[region].keys():
for key2 in divergence_dict[region][key].keys():
plt.plot(time_average, divergence_dict[region][key][key2], label=f"{key} {key2}")
plt.grid()
plt.xlabel("Time since infection [days]", fontsize=fontsize)
plt.ylabel("Divergence", fontsize=fontsize)
plt.legend(fontsize=fontsize)
plt.show()
# Evolution rate (derivative of divergence)
evo_rate = WH_evo_rate(divergence_dict, time_average)
plt.figure(figsize=(14, 10))
for key in evo_rate[region].keys():
for key2 in ["high","low"]:
plt.plot(time_average, evo_rate[region][key][key2], label=f"{key} {key2}")
plt.grid()
plt.xlabel("Time since infection [days]", fontsize=fontsize)
plt.ylabel("Evolution rate (per site per day)", fontsize=fontsize)
plt.legend(fontsize=fontsize)
plt.show()
# +
colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
fontsize = 16
region = "gag"
# Divergence
plt.figure(figsize=(14, 10))
for key in divergence_dict[region].keys():
for key2 in divergence_dict[region][key].keys():
plt.plot(time_average, divergence_dict[region][key][key2], label=f"{key} {key2}")
plt.grid()
plt.xlabel("Time since infection [days]", fontsize=fontsize)
plt.ylabel("Divergence", fontsize=fontsize)
plt.legend(fontsize=fontsize)
plt.show()
# Evolution rate (derivative of divergence)
evo_rate = WH_evo_rate(divergence_dict, time_average)
plt.figure(figsize=(14, 10))
for key in evo_rate[region].keys():
for key2 in ["high","low"]:
plt.plot(time_average, evo_rate[region][key][key2], label=f"{key} {key2}")
plt.grid()
plt.xlabel("Time since infection [days]", fontsize=fontsize)
plt.ylabel("Evolution rate (per site per day)", fontsize=fontsize)
plt.legend(fontsize=fontsize)
plt.show()
# +
evo_rate = WH_evo_rate(divergence_dict, time_average)
time_interval = [500, 2000]
for region in ["env","pol","gag"]:
for site in ["consensus", "non_consensus"]:
for fitness in ["low", "high"]:
rate = evo_rate[region][site][fitness]
rate = rate[np.logical_and(time_average>time_interval[0],time_average<time_interval[1])]
rate = np.mean(rate)
print(f"{region} {site} {fitness} : {rate}")
# -
evo_rates = {
"env": {"consensus": {"low": 1.0426e-5, "high": 3.1066e-6}, "non_consensus": {"low": 4.8899e-5, "high": 3.6908e-5}},
"pol": {"consensus": {"low": 5.7398e-6, "high": 1.5924e-7}, "non_consensus": {"low": 2.2535e-5, "high": 2.7416e-5}},
"gag": {"consensus": {"low": 6.4968e-6, "high": 9.5654e-7}, "non_consensus": {"low": 3.8259e-5, "high": 3.1537e-5}}
}
# # Evo rates by positions for pol
# +
colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
fontsize = 16
region = "pol"
plt.figure(figsize=(14, 10))
for ii, position in enumerate(["first","second","third"]):
plt.plot(time_average, divergence_dict[region]["consensus"][position], '-', color=colors[ii], label=position)
plt.plot(time_average, divergence_dict[region]["non_consensus"][position], '--', color=colors[ii])
plt.plot([0], [0], 'k-', label="Consensus")
plt.plot([0], [0], 'k--', label="Non-consensus")
plt.grid()
plt.xlabel("Time since infection [days]", fontsize=fontsize)
plt.ylabel("Divergence", fontsize=fontsize)
plt.legend(fontsize=fontsize)
plt.show()
# +
region = "pol"
fontsize = 16
evo_rate = WH_evo_rate(divergence_dict, time_average)
plt.figure(figsize=(14, 10))
for key in evo_rate[region].keys():
for key2 in ["first", "second", "third"]:
plt.plot(time_average, evo_rate[region][key][key2], label=f"{key} {key2}")
plt.grid()
plt.xlabel("Time since infection [days]", fontsize=fontsize)
plt.ylabel("Evolution rate (per site per day)", fontsize=fontsize)
plt.legend(fontsize=fontsize)
plt.show()
# +
time_interval = [500, 2000]
region = "pol"
for site in ["consensus", "non_consensus"]:
for key in ["first", "second", "third"]:
rate = evo_rate[region][site][key]
rate = rate[np.logical_and(time_average>time_interval[0],time_average<time_interval[1])]
rate = np.mean(rate)
print(f"{region} {site} {key} : {rate}")
# -
| notebooks/paper_draft_2020/new_divergence.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
from sklearn.metrics import confusion_matrix
import seaborn as sns
import numpy as np
from keras.utils.np_utils import to_categorical
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Flatten, Dense, Dropout
from keras.layers import MaxPooling2D, ZeroPadding2D
from keras.layers.convolutional import Convolution2D
from keras.layers.core import Activation
from keras import backend as K
from keras.utils import np_utils
# %matplotlib inline
keras.__version__
import tensorflow as tf
tf.__version__
# +
USE_GPU = True
if USE_GPU:
device = '/device:GPU:0'
else:
device = '/cpu:0'
# # Constant to control how often we print when training models
# print_every = 100
print('Using device: ', device)
# +
# Data loading + reshape to 4D
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# introduce 10% noise into training labels
# print(len(y_train))
noise_level = 0.0001
y_train_noise = y_train.copy()
for i in np.random.choice(len(y_train), int(noise_level * len(y_train)), replace = False):
flag = True
while flag:
a = np.random.randint(0,10)
if y_train_noise[i] != a:
y_train_noise[i] = a
flag = False
diff = y_train_noise-y_train
indx = np.where(diff!=0)
print(1-(len(diff[diff!=0]))/len(diff)) # 0.9
noisy_image_idx = indx[0][0]
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train/=255
X_test/=255
print(X_train.shape)
print(X_test.shape)
num_training=55000
num_validation=5000
num_test=10000
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val_noise = y_train_noise[mask]
mask = range(num_training)
X_train = X_train[mask]
y_train_noise = y_train_noise[mask]
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
# print(X_val.shape)
# print(X_train.shape)
# X_train_orignal = np.concatenate((X_val,X_train))
# print(X_train_orignal.shape)
mean_pixel = X_train.mean(axis=(0, 1, 2), keepdims=True)
std_pixel = X_train.std(axis=(0, 1, 2), keepdims=True)
X_train = (X_train - mean_pixel) / std_pixel
X_val = (X_val - mean_pixel) / std_pixel
X_test = (X_test - mean_pixel) / std_pixel
print(X_train.shape)
print(X_val.shape)
print(y_train_noise.shape)
print(y_val_noise.shape)
X_train_all = np.concatenate((X_train,X_val))
y_train_noise_all = np.concatenate((y_train_noise,y_val_noise))
print(X_train_all.shape)
print(y_train_noise_all.shape)
# -
plt.imshow(np.squeeze(X_train[66]), cmap='gray')
print(y_train_noise[66])
# +
number_of_classes = 10
Y_train = to_categorical(y_train_noise, number_of_classes)
Y_val = to_categorical(y_val_noise, number_of_classes)
Y_test = to_categorical(y_test, number_of_classes)
print(Y_train.shape)
# Y_train_noise = to_categorical(y_train_noise, number_of_classes)
y_train_noise[1], Y_train[1]
# +
# def load_mnist(num_training=49000, num_validation=1000, num_test=10000):
# mnist = mnist.load_data()
# (X_train, y_train), (X_test, y_test) = mnist
# X_train = np.asarray(X_train, dtype=np.float32)
# y_train = np.asarray(y_train, dtype=np.int32).flatten()
# X_test = np.asarray(X_test, dtype=np.float32)
# y_test = np.asarray(y_test, dtype=np.int32).flatten()
# # Subsample the data
# mask = range(num_training, num_training + num_validation)
# X_val = X_train[mask]
# y_val = y_train[mask]
# mask = range(num_training)
# X_train = X_train[mask]
# y_train = y_train[mask]
# mask = range(num_test)
# X_test = X_test[mask]
# y_test = y_test[mask]
# # Normalize the data: subtract the mean pixel and divide by std
# mean_pixel = X_train.mean(axis=(0, 1, 2), keepdims=True)
# std_pixel = X_train.std(axis=(0, 1, 2), keepdims=True)
# X_train = (X_train - mean_pixel) / std_pixel
# X_val = (X_val - mean_pixel) / std_pixel
# X_test = (X_test - mean_pixel) / std_pixel
# return X_train, y_train, X_val, y_val, X_test, y_test
# X_train, y_train, X_val, y_val, X_test, y_test = load_mnist()
class Dataset(object):
def __init__(self, X, y, batch_size, shuffle=False):
assert X.shape[0] == y.shape[0], 'Got different numbers of data and labels'
self.X, self.y = X, y
self.batch_size, self.shuffle = batch_size, shuffle
def __iter__(self):
N, B = self.X.shape[0], self.batch_size
idxs = np.arange(N)
if self.shuffle:
np.random.shuffle(idxs)
return iter((self.X[i:i+B], self.y[i:i+B]) for i in range(0, N, B))
train_dset = Dataset(X_train, y_train_noise, batch_size=64, shuffle=True)
val_dset = Dataset(X_val, y_val_noise, batch_size=64, shuffle=False)
test_dset = Dataset(X_test, y_test, batch_size=64)
def check_accuracy(sess, dset, x, scores, is_training=None):
num_correct, num_samples = 0, 0
for x_batch, y_batch in dset:
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
num_samples += x_batch.shape[0]
num_correct += (y_pred == y_batch).sum()
acc = float(num_correct) / num_samples
print('Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))
return acc
def train_noisyCNN(model_init_fn, optimizer_init_fn, num_epochs=1):
tf.reset_default_graph()
with tf.device(device):
x = tf.placeholder(tf.float32, [None, 28, 28, 1])
y = tf.placeholder(tf.int32, [None])
is_training = tf.placeholder(tf.bool, name='is_training')
scores, scores_2 = model_init_fn(x, is_training)
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores)
loss = tf.reduce_mean(loss)
loss_2 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores_2)
loss_2 = tf.reduce_mean(loss_2)
optimizer = optimizer_init_fn()
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss)
train_op_2 = optimizer.minimize(loss_2)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
t = 0
for epoch in range(num_epochs):
print('Starting epoch %d' % epoch)
for x_np, y_np in train_dset:
feed_dict = {x: x_np, y: y_np, is_training:1}
loss_np, _ = sess.run([loss, train_op], feed_dict=feed_dict)
loss_np_2, _ = sess.run([loss_2, train_op_2], feed_dict=feed_dict)
if t % print_every == 0:
print('Iteration %d, loss = %.4f' % (t, loss_np))
print('Iteration %d, loss_2 = %.4f' % (t, loss_np_2))
check_accuracy(sess, val_dset, x, scores, is_training=is_training)
check_accuracy(sess, val_dset, x, scores_2, is_training=is_training)
print()
t += 1
print('model 1 test accuracy:')
check_accuracy(sess, test_dset, x, scores, is_training=is_training)
print('model 2 test accuracy:')
check_accuracy(sess, test_dset, x, scores_2, is_training=is_training)
def model_init_fn(inputs, is_training):
# initializer = tf.variance_scaling_initializer(scale=2.0)
model = Sequential()
model.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1 = Activation('relu')
model.add(convout1)
convout2 = MaxPooling2D()
model.add(convout2)
model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()
model_2 = Sequential()
model_2.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1_2 = Activation('relu')
model_2.add(convout1)
convout2_2 = MaxPooling2D()
model_2.add(convout2)
model_2.add(Flatten())
model_2.add(Dense(128))
model_2.add(Activation('relu'))
model_2.add(Dropout(0.2))
model_2.add(Dense(10))
model_2.add(Activation('softmax'))
model_2.summary()
return model(inputs), model_2(inputs)
learning_rate = 4e-4
def optimizer_init_fn():
optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate)
return optimizer
print_every = 700
num_epochs = 2
train_noisyCNN(model_init_fn, optimizer_init_fn, num_epochs)
# -
#testing cell
import numpy as np
a=np.array([i for i in range(100)])
print(a.shape)
cnt=0
for aa in iter(a[i:i+10] for i in range(0, 100, 10)):
# print(aa.shape) # (10,)
if cnt==0:
c=aa
else:
c=np.vstack((c,aa))
cnt+=1
print(c)
# +
#testing cell
def Dataset(X, y, batch_size, shuffle=False):
N, B = X.shape[0], batch_size
idxs = np.arange(N)
if shuffle:
np.random.shuffle(idxs)
cnt=0
it=iter((X[i:i+B], y[i:i+B]) for i in range(0, N, B))
for (x_batch, y_batch) in it:
if cnt==0:
x_dset = x_batch
# print(x_dset.shape)
y_dset = y_batch
else:
x_dset = np.vstack((x_dset,x_batch))
y_dset = np.vstack((y_dset,y_batch))
# print(cnt)
cnt+=1
x_dset=x_dset.reshape((-1,batch_size,28,28,1))
print(x_dset.shape)
print(y_dset.shape)
return x_dset, y_dset
# Data loading + reshape to 4D
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# introduce 10% noise into training labels
# print(len(y_train))
noise_level = 0.7
y_train_noise = y_train.copy()
for i in np.random.choice(len(y_train), int(noise_level * len(y_train)), replace = False):
flag = True
while flag:
a = np.random.randint(0,10)
if y_train_noise[i] != a:
y_train_noise[i] = a
flag = False
diff = y_train_noise-y_train
indx = np.where(diff!=0)
print(1-(len(diff[diff!=0]))/len(diff)) # 0.9
noisy_image_idx = indx[0][0]
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train/=255
X_test/=255
print(X_train.shape)
print(X_test.shape)
num_training=55000
num_validation=5000
num_test=10000
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val_noise = y_train_noise[mask]
mask = range(num_training)
X_train = X_train[mask]
y_train_noise = y_train_noise[mask]
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
# print(X_val.shape)
# print(X_train.shape)
# X_train_orignal = np.concatenate((X_val,X_train))
# print(X_train_orignal.shape)
mean_pixel = X_train.mean(axis=(0, 1, 2), keepdims=True)
std_pixel = X_train.std(axis=(0, 1, 2), keepdims=True)
X_train = (X_train - mean_pixel) / std_pixel
X_val = (X_val - mean_pixel) / std_pixel
X_test = (X_test - mean_pixel) / std_pixel
number_of_classes = 10
Y_train = to_categorical(y_train_noise, number_of_classes)
Y_val = to_categorical(y_val_noise, number_of_classes)
Y_test = to_categorical(y_test, number_of_classes)
Y_train_noise = to_categorical(y_train_noise, number_of_classes)
y_train_noise[1], Y_train[1]
batch_size=100
x_train_dset, y_train_dset = Dataset(X_train, y_train_noise, batch_size, shuffle=True)
x_val_dset, y_val_dset = Dataset(X_val, y_val_noise, batch_size, shuffle=False)
x_test_dset, y_test_dset = Dataset(X_test, y_test, batch_size)
# +
#testing cell
x_train_all = np.vstack((x_train_dset, x_val_dset))
x_train_all = x_train_all.reshape((-1,28,28,1))
print(x_train_all.shape)
y_train_all = np.vstack((y_train_dset, y_val_dset))
y_train_all=y_train_all.flatten()
print(y_train_all.shape)
# for (x,y) in zip(x_train_dset, y_train_dset):
# print(x.shape)
# print(y.shape)
# +
#testing cell
cnt=0
for idx, (x,y) in enumerate(zip(x_train_dset, y_train_dset)):
if cnt==0:
print(idx)
print(x.shape)
print(y)
y_train_dset[idx]=np.zeros(100)
# print(y)
cnt+=1
cnt=0
for idx, (x,y) in enumerate(zip(x_train_dset, y_train_dset)):
if cnt==0:
print(y)
cnt+=1
# +
# ICL-R: Iterative Cross Learning - Random
def Dataset(X, y, batch_size, shuffle=False):
N, B = X.shape[0], batch_size
idxs = np.arange(N)
if shuffle:
np.random.shuffle(idxs)
cnt=0
it=iter((X[i:i+B], y[i:i+B]) for i in range(0, N, B))
for (x_batch, y_batch) in it:
if cnt==0:
x_dset = x_batch
# print(x_dset.shape)
y_dset = y_batch
else:
x_dset = np.vstack((x_dset,x_batch))
y_dset = np.vstack((y_dset,y_batch))
# print(cnt)
cnt+=1
x_dset=x_dset.reshape((-1,batch_size,28,28,1))
# print(x_dset.shape)
# print(y_dset.shape)
return x_dset, y_dset
def check_accuracy(sess, dset, x, scores, is_training=None):
num_correct, num_samples = 0, 0
for x_batch, y_batch in dset:
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
num_samples += x_batch.shape[0]
num_correct += (y_pred == y_batch).sum()
acc = float(num_correct) / num_samples
# print(y_pred)
print('Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))
return acc
def cross_check(sess, x_val_dset, y_val_dset, x, scores, scores_2, is_training, flag):
num_correct, num_correct2, num_samples = 0, 0, 0
for idx, (x_batch, y_batch) in enumerate(zip(x_val_dset, y_val_dset)):
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
scores_np_2 = sess.run(scores_2, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
y_pred_2 = scores_np_2.argmax(axis=1)
if flag: # RUN ICL-RANDOM
difference = [i - j for i, j in zip(y_pred, y_pred_2)]
diff_idx = [l for l, e in enumerate(difference) if e != 0]
for k in diff_idx:
y_batch[k] = np.random.randint(0,10)
y_val_dset[idx] = y_batch
num_samples += x_batch.shape[0]
num_correct += (y_pred == y_batch).sum()
num_correct2 += (y_pred_2 == y_batch).sum()
acc = float(num_correct) / num_samples
acc2 = float(num_correct2) / num_samples
# print(y_pred)
print('model 1: Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))
print('model 2: Got %d / %d correct (%.2f%%)' % (num_correct2, num_samples, 100 * acc2))
def train_noisyCNN(model_init_fn, optimizer_init_fn, num_epochs=1):
# Data loading + reshape to 4D
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# introduce 10% noise into training labels
# print(len(y_train))
noise_level = 0.7 # SET NOISE LEVEL
y_train_noise = y_train.copy()
for i in np.random.choice(len(y_train), int(noise_level * len(y_train)), replace = False):
flag = True
while flag:
a = np.random.randint(0,10)
if y_train_noise[i] != a:
y_train_noise[i] = a
flag = False
diff = y_train_noise-y_train
indx = np.where(diff!=0)
print(1-(len(diff[diff!=0]))/len(diff)) # 0.9
noisy_image_idx = indx[0][0]
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train/=255
X_test/=255
# print(X_train.shape)
# print(X_test.shape)
num_training=55000
num_validation=5000
num_test=10000
batch_size=100
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val_noise = y_train_noise[mask]
mask = range(num_training)
X_train = X_train[mask]
y_train_noise = y_train_noise[mask]
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
# print(X_val.shape)
# print(X_train.shape)
# X_train_orignal = np.concatenate((X_val,X_train))
# print(X_train_orignal.shape)
mean_pixel = X_train.mean(axis=(0, 1, 2), keepdims=True)
std_pixel = X_train.std(axis=(0, 1, 2), keepdims=True)
X_train = (X_train - mean_pixel) / std_pixel
X_val = (X_val - mean_pixel) / std_pixel
X_test = (X_test - mean_pixel) / std_pixel
# number_of_classes = 10
# Y_train = to_categorical(y_train_noise, number_of_classes)
# Y_val = to_categorical(y_val_noise, number_of_classes)
# Y_test = to_categorical(y_test, number_of_classes)
# Y_train_noise = to_categorical(y_train_noise, number_of_classes)
# y_train_noise[1], Y_train[1]
x_train_dset, y_train_dset = Dataset(X_train, y_train_noise, batch_size, shuffle=True)
x_val_dset, y_val_dset = Dataset(X_val, y_val_noise, batch_size, shuffle=False)
x_test_dset, y_test_dset = Dataset(X_test, y_test, batch_size)
tf.reset_default_graph()
with tf.device(device):
x = tf.placeholder(tf.float32, [None, 28, 28, 1])
y = tf.placeholder(tf.int32, [None])
is_training = tf.placeholder(tf.bool, name='is_training')
scores, scores_2 = model_init_fn(x, is_training)
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores)
loss = tf.reduce_mean(loss)
loss_2 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores_2)
loss_2 = tf.reduce_mean(loss_2)
optimizer = optimizer_init_fn()
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss)
train_op_2 = optimizer.minimize(loss_2)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
t = 0
for epoch in range(num_epochs):
if epoch <=1:
flag=True
else:
flag=True
print('Starting epoch %d' % epoch)
for x_np, y_np in zip(x_train_dset, y_train_dset):
feed_dict = {x: x_np, y: y_np, is_training:1}
loss_np, _ = sess.run([loss, train_op], feed_dict=feed_dict)
loss_np_2, _ = sess.run([loss_2, train_op_2], feed_dict=feed_dict)
if t % print_every == 0:
print('Iteration %d, loss = %.4f' % (t, loss_np))
print('Iteration %d, loss_2 = %.4f' % (t, loss_np_2))
cross_check(sess, x_val_dset, y_val_dset, x, scores, scores_2, is_training, flag)
print()
t += 1
# reshuffle data to train/val for each epoch
print('reshuffling data..')
x_train_all = np.vstack((x_train_dset, x_val_dset))
x_train_all = x_train_all.reshape((-1,28,28,1))
y_train_all = np.vstack((y_train_dset, y_val_dset))
y_train_all = y_train_all.flatten()
mask = range(num_training, num_training + num_validation)
X_val = x_train_all[mask]
y_val_noise = y_train_all[mask]
mask = range(num_training)
X_train = x_train_all[mask]
y_train_noise = y_train_all[mask]
x_train_dset, y_train_dset = Dataset(X_train, y_train_noise, batch_size, shuffle=True)
x_val_dset, y_val_dset = Dataset(X_val, y_val_noise, batch_size, shuffle=False)
# print('model 1 test accuracy:')
acc1 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores, is_training=is_training)
# print('model 2 test accuracy:')
acc2 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores_2, is_training=is_training)
score = scores if acc1>acc2 else scores_2
print('\nbest final model: ') # max 'ensemble'
check_accuracy(sess, zip(x_test_dset, y_test_dset), x, score, is_training)
def model_init_fn(inputs, is_training):
# initializer = tf.variance_scaling_initializer(scale=2.0)
model = Sequential()
model.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1 = Activation('relu')
model.add(convout1)
convout2 = MaxPooling2D()
model.add(convout2)
model.add(Convolution2D(64, kernel_size=(2, 2), input_shape=(13,13,32)))
model.add(Activation('relu'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()
model_2 = Sequential()
model_2.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1_2 = Activation('relu')
model_2.add(convout1)
convout2_2 = MaxPooling2D()
model_2.add(convout2)
model_2.add(Flatten())
model_2.add(Dense(128))
model_2.add(Activation('relu'))
model_2.add(Dropout(0.2))
model_2.add(Dense(10))
model_2.add(Activation('softmax'))
model_2.summary()
return model(inputs), model_2(inputs)
learning_rate = 4e-4
def optimizer_init_fn():
optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate)
return optimizer
print_every = 700
num_epochs = 10
train_noisyCNN(model_init_fn, optimizer_init_fn, num_epochs)
# +
# ICML: Iterative Cross Majority Learning
def Dataset(X, y, batch_size, shuffle=False):
N, B = X.shape[0], batch_size
idxs = np.arange(N)
if shuffle:
np.random.shuffle(idxs)
cnt=0
it=iter((X[i:i+B], y[i:i+B]) for i in range(0, N, B))
for (x_batch, y_batch) in it:
if cnt==0:
x_dset = x_batch
# print(x_dset.shape)
y_dset = y_batch
else:
x_dset = np.vstack((x_dset,x_batch))
y_dset = np.vstack((y_dset,y_batch))
# print(cnt)
cnt+=1
x_dset=x_dset.reshape((-1,batch_size,28,28,1))
# print(x_dset.shape)
# print(y_dset.shape)
return x_dset, y_dset
def check_accuracy(sess, dset, x, scores, is_training=None):
num_correct, num_samples = 0, 0
for x_batch, y_batch in dset:
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
num_samples += x_batch.shape[0]
num_correct += (y_pred == y_batch).sum()
acc = float(num_correct) / num_samples
# print(y_pred)
print('Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))
return acc
def cross_check_multi(sess, x_val_dset, y_val_dset, x, scores, scores_2, scores_3, is_training, flag):
num_correct, num_correct2, num_correct3, num_samples = 0, 0, 0, 0
for idx, (x_batch, y_batch) in enumerate(zip(x_val_dset, y_val_dset)):
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
scores_np_2 = sess.run(scores_2, feed_dict=feed_dict)
scores_np_3 = sess.run(scores_3, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
y_pred_2 = scores_np_2.argmax(axis=1)
y_pred_3 = scores_np_3.argmax(axis=1)
if flag: # RUN ICML
for k in range(y_pred.size):
lst = [y_pred[k],y_pred_2[k],y_pred_3[k]]
y_batch[k] = max(set(lst), key=lst.count) # majority vote
y_val_dset[idx] = y_batch
num_samples += x_batch.shape[0]
num_correct += (y_pred == y_batch).sum()
num_correct2 += (y_pred_2 == y_batch).sum()
num_correct3 += (y_pred_3 == y_batch).sum()
acc = float(num_correct) / num_samples
acc2 = float(num_correct2) / num_samples
acc3 = float(num_correct3) / num_samples
print('model 1: Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))
print('model 2: Got %d / %d correct (%.2f%%)' % (num_correct2, num_samples, 100 * acc2))
print('model 3: Got %d / %d correct (%.2f%%)' % (num_correct3, num_samples, 100 * acc3))
def train_noisyCNN(model_init_fn, optimizer_init_fn, num_epochs=1):
# Data loading + reshape to 4D
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# introduce 10% noise into training labels
# print(len(y_train))
noise_level = 0.7 # SET NOISE LEVEL
y_train_noise = y_train.copy()
for i in np.random.choice(len(y_train), int(noise_level * len(y_train)), replace = False):
flag = True
while flag:
a = np.random.randint(0,10)
if y_train_noise[i] != a:
y_train_noise[i] = a
flag = False
diff = y_train_noise-y_train
indx = np.where(diff!=0)
print(1-(len(diff[diff!=0]))/len(diff)) # 0.9
noisy_image_idx = indx[0][0]
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train/=255
X_test/=255
# print(X_train.shape)
# print(X_test.shape)
num_training=55000
num_validation=5000
num_test=10000
batch_size=100
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val_noise = y_train_noise[mask]
mask = range(num_training)
X_train = X_train[mask]
y_train_noise = y_train_noise[mask]
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
# print(X_val.shape)
# print(X_train.shape)
# X_train_orignal = np.concatenate((X_val,X_train))
# print(X_train_orignal.shape)
mean_pixel = X_train.mean(axis=(0, 1, 2), keepdims=True)
std_pixel = X_train.std(axis=(0, 1, 2), keepdims=True)
X_train = (X_train - mean_pixel) / std_pixel
X_val = (X_val - mean_pixel) / std_pixel
X_test = (X_test - mean_pixel) / std_pixel
# number_of_classes = 10
# Y_train = to_categorical(y_train_noise, number_of_classes)
# Y_val = to_categorical(y_val_noise, number_of_classes)
# Y_test = to_categorical(y_test, number_of_classes)
# Y_train_noise = to_categorical(y_train_noise, number_of_classes)
# y_train_noise[1], Y_train[1]
x_train_dset, y_train_dset = Dataset(X_train, y_train_noise, batch_size, shuffle=True)
x_val_dset, y_val_dset = Dataset(X_val, y_val_noise, batch_size, shuffle=False)
x_test_dset, y_test_dset = Dataset(X_test, y_test, batch_size)
tf.reset_default_graph()
with tf.device(device):
x = tf.placeholder(tf.float32, [None, 28, 28, 1])
y = tf.placeholder(tf.int32, [None])
is_training = tf.placeholder(tf.bool, name='is_training')
scores, scores_2, scores_3 = model_init_fn(x, is_training)
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores)
loss = tf.reduce_mean(loss)
loss_2 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores_2)
loss_2 = tf.reduce_mean(loss_2)
loss_3 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores_3)
loss_3 = tf.reduce_mean(loss_3)
optimizer = optimizer_init_fn()
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss)
train_op_2 = optimizer.minimize(loss_2)
train_op_3 = optimizer.minimize(loss_3)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
t = 0
for epoch in range(num_epochs):
if epoch <=1: # controller
flag=True
else:
flag=True
print('Starting epoch %d' % epoch)
for x_np, y_np in zip(x_train_dset, y_train_dset):
feed_dict = {x: x_np, y: y_np, is_training:1}
loss_np, _ = sess.run([loss, train_op], feed_dict=feed_dict)
loss_np_2, _ = sess.run([loss_2, train_op_2], feed_dict=feed_dict)
loss_np_3, _ = sess.run([loss_3, train_op_3], feed_dict=feed_dict)
if t % print_every == 0:
print('Iteration %d, loss = %.4f' % (t, loss_np))
print('Iteration %d, loss_2 = %.4f' % (t, loss_np_2))
print('Iteration %d, loss_3 = %.4f' % (t, loss_np_3))
cross_check_multi(sess, x_val_dset, y_val_dset, x, scores, scores_2, scores_3, is_training, flag)
print()
t += 1
# reshuffle data to train/val for each epoch
print('reshuffling data..')
x_train_all = np.vstack((x_train_dset, x_val_dset))
x_train_all = x_train_all.reshape((-1,28,28,1))
y_train_all = np.vstack((y_train_dset, y_val_dset))
y_train_all = y_train_all.flatten()
mask = range(num_training, num_training + num_validation)
X_val = x_train_all[mask]
y_val_noise = y_train_all[mask]
mask = range(num_training)
X_train = x_train_all[mask]
y_train_noise = y_train_all[mask]
x_train_dset, y_train_dset = Dataset(X_train, y_train_noise, batch_size, shuffle=True)
x_val_dset, y_val_dset = Dataset(X_val, y_val_noise, batch_size, shuffle=False)
acc1 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores, is_training=is_training)
acc2 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores_2, is_training=is_training)
acc3 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores_3, is_training=is_training)
print('\nbest final model accuracy: ', max(acc1,acc2,acc3)) # max 'ensemble'
def model_init_fn(inputs, is_training):
# initializer = tf.variance_scaling_initializer(scale=2.0)
model = Sequential()
model.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1 = Activation('relu')
model.add(convout1)
convout2 = MaxPooling2D()
model.add(convout2)
model.add(Convolution2D(64, kernel_size=(2, 2), input_shape=(13,13,32)))
model.add(Activation('relu'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()
model_2 = Sequential()
model_2.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1_2 = Activation('relu')
model_2.add(convout1_2)
convout2_2 = MaxPooling2D()
model_2.add(convout2_2)
model_2.add(Flatten())
model_2.add(Dense(128))
model_2.add(Activation('relu'))
model_2.add(Dropout(0.2))
model_2.add(Dense(10))
model_2.add(Activation('softmax'))
model_2.summary()
model_3 = Sequential()
model_3.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1_3 = Activation('relu')
model_3.add(convout1_3)
convout2_3 = MaxPooling2D()
model_3.add(convout2_3)
model_3.add(Convolution2D(64, kernel_size=(2, 2), input_shape=(13,13,32)))
model_3.add(Activation('relu'))
model_3.add(MaxPooling2D())
model_3.add(Convolution2D(32, kernel_size=(2, 2), padding = 'valid', input_shape=(6,6,64)))
model_3.add(Activation('relu'))
model_3.add(Flatten())
model_3.add(Dense(128))
model_3.add(Activation('relu'))
model_3.add(Dropout(0.2))
model_3.add(Dense(10))
model_3.add(Activation('softmax'))
model_3.summary()
return model(inputs), model_2(inputs), model_3(inputs)
learning_rate = 4e-4
def optimizer_init_fn():
optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate)
return optimizer
print_every = 700
num_epochs = 10
train_noisyCNN(model_init_fn, optimizer_init_fn, num_epochs)
# +
# ICL-R + ICML
# faster learning convergence
def Dataset(X, y, batch_size, shuffle=False):
N, B = X.shape[0], batch_size
idxs = np.arange(N)
if shuffle:
np.random.shuffle(idxs)
cnt=0
it=iter((X[i:i+B], y[i:i+B]) for i in range(0, N, B))
for (x_batch, y_batch) in it:
if cnt==0:
x_dset = x_batch
# print(x_dset.shape)
y_dset = y_batch
else:
x_dset = np.vstack((x_dset,x_batch))
y_dset = np.vstack((y_dset,y_batch))
# print(cnt)
cnt+=1
x_dset=x_dset.reshape((-1,batch_size,28,28,1))
# print(x_dset.shape)
# print(y_dset.shape)
return x_dset, y_dset
def check_accuracy(sess, dset, x, scores, is_training=None):
num_correct, num_samples = 0, 0
for x_batch, y_batch in dset:
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
num_samples += x_batch.shape[0]
num_correct += (y_pred == y_batch).sum()
acc = float(num_correct) / num_samples
# print(y_pred)
print('Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))
return acc
def cross_check_multi(sess, x_val_dset, y_val_dset, x, scores, scores_2, scores_3, is_training, flag):
num_correct, num_correct2, num_correct3, num_samples = 0, 0, 0, 0
for idx, (x_batch, y_batch) in enumerate(zip(x_val_dset, y_val_dset)):
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
scores_np_2 = sess.run(scores_2, feed_dict=feed_dict)
scores_np_3 = sess.run(scores_3, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
y_pred_2 = scores_np_2.argmax(axis=1)
y_pred_3 = scores_np_3.argmax(axis=1)
if flag: # RUN ICL-R + ICML hybrid label update strategy
for k in range(y_pred.size):
if y_pred[k]!=y_pred_2[k] and y_pred[k]!=y_pred_3[k] and y_pred_2[k]!=y_pred_3[k]: # if predicted labels are all different
y_batch[k] = np.random.randint(0,10) # set label random
continue
lst = [y_pred[k],y_pred_2[k],y_pred_3[k]]
y_batch[k] = max(set(lst), key=lst.count) # else set label as majority vote
y_val_dset[idx] = y_batch
num_samples += x_batch.shape[0]
num_correct += (y_pred == y_batch).sum()
num_correct2 += (y_pred_2 == y_batch).sum()
num_correct3 += (y_pred_3 == y_batch).sum()
acc = float(num_correct) / num_samples
acc2 = float(num_correct2) / num_samples
acc3 = float(num_correct3) / num_samples
print('model 1: Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))
print('model 2: Got %d / %d correct (%.2f%%)' % (num_correct2, num_samples, 100 * acc2))
print('model 3: Got %d / %d correct (%.2f%%)' % (num_correct3, num_samples, 100 * acc3))
def check_test_accuracy_ensemble(sess, x_test_dset, y_test_dset, x, scores, scores_2, scores_3, is_training):
num_correct, num_correct2, num_correct3, num_samples = 0, 0, 0, 0
for idx, (x_batch, y_batch) in enumerate(zip(x_test_dset, y_test_dset)):
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
scores_np_2 = sess.run(scores_2, feed_dict=feed_dict)
scores_np_3 = sess.run(scores_3, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
y_pred_2 = scores_np_2.argmax(axis=1)
y_pred_3 = scores_np_3.argmax(axis=1)
num_samples += x_batch.shape[0]
y_pred_ensemble=np.zeros(y_pred.size)
for k in range(y_pred.size):
lst = [y_pred[k],y_pred_2[k],y_pred_3[k]]
y_pred_ensemble[k] = max(set(lst), key=lst.count) # ensemble learning prediction
num_correct += (y_pred_ensemble == y_batch).sum()
accuracy = float(num_correct) / num_samples
return accuracy
def train_noisyCNN(model_init_fn, optimizer_init_fn, num_epochs=1):
# Data loading + reshape to 4D
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# introduce 10% noise into training labels
# print(len(y_train))
noise_level = 0.7 # SET NOISE LEVEL
y_train_noise = y_train.copy()
for i in np.random.choice(len(y_train), int(noise_level * len(y_train)), replace = False):
flag = True
while flag:
a = np.random.randint(0,10)
if y_train_noise[i] != a:
y_train_noise[i] = a
flag = False
diff = y_train_noise-y_train
indx = np.where(diff!=0)
print(1-(len(diff[diff!=0]))/len(diff)) # 0.9
noisy_image_idx = indx[0][0]
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train/=255
X_test/=255
# print(X_train.shape)
# print(X_test.shape)
num_training=55000
num_validation=5000
num_test=10000
batch_size=100
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val_noise = y_train_noise[mask]
mask = range(num_training)
X_train = X_train[mask]
y_train_noise = y_train_noise[mask]
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
# print(X_val.shape)
# print(X_train.shape)
# X_train_orignal = np.concatenate((X_val,X_train))
# print(X_train_orignal.shape)
mean_pixel = X_train.mean(axis=(0, 1, 2), keepdims=True)
std_pixel = X_train.std(axis=(0, 1, 2), keepdims=True)
X_train = (X_train - mean_pixel) / std_pixel
X_val = (X_val - mean_pixel) / std_pixel
X_test = (X_test - mean_pixel) / std_pixel
# number_of_classes = 10
# Y_train = to_categorical(y_train_noise, number_of_classes)
# Y_val = to_categorical(y_val_noise, number_of_classes)
# Y_test = to_categorical(y_test, number_of_classes)
# Y_train_noise = to_categorical(y_train_noise, number_of_classes)
# y_train_noise[1], Y_train[1]
x_train_dset, y_train_dset = Dataset(X_train, y_train_noise, batch_size, shuffle=True)
x_val_dset, y_val_dset = Dataset(X_val, y_val_noise, batch_size, shuffle=False)
x_test_dset, y_test_dset = Dataset(X_test, y_test, batch_size)
tf.reset_default_graph()
with tf.device(device):
x = tf.placeholder(tf.float32, [None, 28, 28, 1])
y = tf.placeholder(tf.int32, [None])
is_training = tf.placeholder(tf.bool, name='is_training')
scores, scores_2, scores_3 = model_init_fn(x, is_training)
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores)
loss = tf.reduce_mean(loss)
loss_2 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores_2)
loss_2 = tf.reduce_mean(loss_2)
loss_3 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores_3)
loss_3 = tf.reduce_mean(loss_3)
optimizer = optimizer_init_fn()
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss)
train_op_2 = optimizer.minimize(loss_2)
train_op_3 = optimizer.minimize(loss_3)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
t = 0
for epoch in range(num_epochs):
if epoch <=1: # controller
flag=True
else:
flag=True
print('Starting epoch %d' % epoch)
for x_np, y_np in zip(x_train_dset, y_train_dset):
feed_dict = {x: x_np, y: y_np, is_training:1}
loss_np, _ = sess.run([loss, train_op], feed_dict=feed_dict)
loss_np_2, _ = sess.run([loss_2, train_op_2], feed_dict=feed_dict)
loss_np_3, _ = sess.run([loss_3, train_op_3], feed_dict=feed_dict)
if t % print_every == 0:
print('Iteration %d, loss = %.4f' % (t, loss_np))
print('Iteration %d, loss_2 = %.4f' % (t, loss_np_2))
print('Iteration %d, loss_3 = %.4f' % (t, loss_np_3))
cross_check_multi(sess, x_val_dset, y_val_dset, x, scores, scores_2, scores_3, is_training, flag)
print()
t += 1
# reshuffle data to train/val for each epoch
print('reshuffling data..')
x_train_all = np.vstack((x_train_dset, x_val_dset))
x_train_all = x_train_all.reshape((-1,28,28,1))
y_train_all = np.vstack((y_train_dset, y_val_dset))
y_train_all = y_train_all.flatten()
mask = range(num_training, num_training + num_validation)
X_val = x_train_all[mask]
y_val_noise = y_train_all[mask]
mask = range(num_training)
X_train = x_train_all[mask]
y_train_noise = y_train_all[mask]
x_train_dset, y_train_dset = Dataset(X_train, y_train_noise, batch_size, shuffle=True)
x_val_dset, y_val_dset = Dataset(X_val, y_val_noise, batch_size, shuffle=False)
acc1 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores, is_training=is_training)
acc2 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores_2, is_training=is_training)
acc3 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores_3, is_training=is_training)
print('\nbest final model accuracy: ', max(acc1,acc2,acc3)) # max 'ensemble'
# ENSEMBLE LEARNING (max vote)
accuracy = check_test_accuracy_ensemble(sess, x_test_dset, y_test_dset, x, scores, scores_2, scores_3, is_training=is_training)
print('\nfinal ensemble learning prediction accuracy: ', accuracy) # ensemble learning
def model_init_fn(inputs, is_training):
# initializer = tf.variance_scaling_initializer(scale=2.0)
model = Sequential()
model.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1 = Activation('relu')
model.add(convout1)
convout2 = MaxPooling2D()
model.add(convout2)
model.add(Convolution2D(64, kernel_size=(2, 2), input_shape=(13,13,32)))
model.add(Activation('relu'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()
model_2 = Sequential()
model_2.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1_2 = Activation('relu')
model_2.add(convout1_2)
convout2_2 = MaxPooling2D()
model_2.add(convout2_2)
model_2.add(Flatten())
model_2.add(Dense(128))
model_2.add(Activation('relu'))
model_2.add(Dropout(0.2))
model_2.add(Dense(10))
model_2.add(Activation('softmax'))
model_2.summary()
model_3 = Sequential()
model_3.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1_3 = Activation('relu')
model_3.add(convout1_3)
convout2_3 = MaxPooling2D()
model_3.add(convout2_3)
model_3.add(Convolution2D(64, kernel_size=(2, 2), input_shape=(13,13,32)))
model_3.add(Activation('relu'))
model_3.add(MaxPooling2D())
model_3.add(Convolution2D(32, kernel_size=(2, 2), padding = 'valid', input_shape=(6,6,64)))
model_3.add(Activation('relu'))
model_3.add(Flatten())
model_3.add(Dense(128))
model_3.add(Activation('relu'))
model_3.add(Dropout(0.2))
model_3.add(Dense(10))
model_3.add(Activation('softmax'))
model_3.summary()
return model(inputs), model_2(inputs), model_3(inputs)
learning_rate = 4e-4
def optimizer_init_fn():
optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate)
return optimizer
print_every = 700
num_epochs = 10
train_noisyCNN(model_init_fn, optimizer_init_fn, num_epochs)
# +
# ICL-R + ICML MULTI-STAGE TRAINING
# HYBRID APPROACH: ICL-R BOOSTRAPING PHASE 1 + ICML IN PHASE 2
def Dataset(X, y, batch_size, shuffle=False):
N, B = X.shape[0], batch_size
idxs = np.arange(N)
if shuffle:
np.random.shuffle(idxs)
cnt=0
it=iter((X[i:i+B], y[i:i+B]) for i in range(0, N, B))
for (x_batch, y_batch) in it:
if cnt==0:
x_dset = x_batch
# print(x_dset.shape)
y_dset = y_batch
else:
x_dset = np.vstack((x_dset,x_batch))
y_dset = np.vstack((y_dset,y_batch))
# print(cnt)
cnt+=1
x_dset=x_dset.reshape((-1,batch_size,28,28,1))
# print(x_dset.shape)
# print(y_dset.shape)
return x_dset, y_dset
def check_accuracy(sess, dset, x, scores, is_training=None):
num_correct, num_samples = 0, 0
for x_batch, y_batch in dset:
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
num_samples += x_batch.shape[0]
num_correct += (y_pred == y_batch).sum()
acc = float(num_correct) / num_samples
# print(y_pred)
print('Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))
return acc
def cross_check_multi(sess, x_val_dset, y_val_dset, x, scores, scores_2, scores_3, is_training, flag):
num_correct, num_correct2, num_correct3, num_samples = 0, 0, 0, 0
for idx, (x_batch, y_batch) in enumerate(zip(x_val_dset, y_val_dset)):
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
scores_np_2 = sess.run(scores_2, feed_dict=feed_dict)
scores_np_3 = sess.run(scores_3, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
y_pred_2 = scores_np_2.argmax(axis=1)
y_pred_3 = scores_np_3.argmax(axis=1)
if flag: # RUN ICL-R + ICML hybrid label update strategy
for k in range(y_pred.size):
if y_pred[k]!=y_pred_2[k] and y_pred[k]!=y_pred_3[k] and y_pred_2[k]!=y_pred_3[k]: # if predicted labels are all different
y_batch[k] = np.random.randint(0,10) # set label random
continue
lst = [y_pred[k],y_pred_2[k],y_pred_3[k]]
y_batch[k] = max(set(lst), key=lst.count) # else set label as majority vote
y_val_dset[idx] = y_batch
else: # RANDOM
for k in range(y_pred.size):
if y_pred[k]==y_pred_2[k] and y_pred[k]==y_pred_3[k] and y_pred_2[k]==y_pred_3[k]:
continue
else:
y_batch[k] = np.random.randint(0,10)
y_val_dset[idx] = y_batch
num_samples += x_batch.shape[0]
num_correct += (y_pred == y_batch).sum()
num_correct2 += (y_pred_2 == y_batch).sum()
num_correct3 += (y_pred_3 == y_batch).sum()
acc = float(num_correct) / num_samples
acc2 = float(num_correct2) / num_samples
acc3 = float(num_correct3) / num_samples
print('model 1: Got %d / %d correct (%.2f%%)' % (num_correct, num_samples, 100 * acc))
print('model 2: Got %d / %d correct (%.2f%%)' % (num_correct2, num_samples, 100 * acc2))
print('model 3: Got %d / %d correct (%.2f%%)' % (num_correct3, num_samples, 100 * acc3))
def check_test_accuracy_ensemble(sess, x_test_dset, y_test_dset, x, scores, scores_2, scores_3, is_training):
num_correct, num_correct2, num_correct3, num_samples = 0, 0, 0, 0
for idx, (x_batch, y_batch) in enumerate(zip(x_test_dset, y_test_dset)):
feed_dict = {x: x_batch, is_training: 0}
scores_np = sess.run(scores, feed_dict=feed_dict)
scores_np_2 = sess.run(scores_2, feed_dict=feed_dict)
scores_np_3 = sess.run(scores_3, feed_dict=feed_dict)
y_pred = scores_np.argmax(axis=1)
y_pred_2 = scores_np_2.argmax(axis=1)
y_pred_3 = scores_np_3.argmax(axis=1)
num_samples += x_batch.shape[0]
y_pred_ensemble=np.zeros(y_pred.size)
for k in range(y_pred.size):
lst = [y_pred[k],y_pred_2[k],y_pred_3[k]]
y_pred_ensemble[k] = max(set(lst), key=lst.count) # ensemble learning prediction
num_correct += (y_pred_ensemble == y_batch).sum()
accuracy = float(num_correct) / num_samples
return accuracy
def train_noisyCNN(model_init_fn, optimizer_init_fn, num_epochs=1):
# Data loading + reshape to 4D
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# introduce 10% noise into training labels
# print(len(y_train))
noise_level = 0.7 # SET NOISE LEVEL
y_train_noise = y_train.copy()
for i in np.random.choice(len(y_train), int(noise_level * len(y_train)), replace = False):
flag = True
while flag:
a = np.random.randint(0,10)
if y_train_noise[i] != a:
y_train_noise[i] = a
flag = False
diff = y_train_noise-y_train
indx = np.where(diff!=0)
print(1-(len(diff[diff!=0]))/len(diff)) # 0.9
noisy_image_idx = indx[0][0]
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train/=255
X_test/=255
# print(X_train.shape)
# print(X_test.shape)
num_training=55000
num_validation=5000
num_test=10000
batch_size=100
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val_noise = y_train_noise[mask]
mask = range(num_training)
X_train = X_train[mask]
y_train_noise = y_train_noise[mask]
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
# print(X_val.shape)
# print(X_train.shape)
# X_train_orignal = np.concatenate((X_val,X_train))
# print(X_train_orignal.shape)
mean_pixel = X_train.mean(axis=(0, 1, 2), keepdims=True)
std_pixel = X_train.std(axis=(0, 1, 2), keepdims=True)
X_train = (X_train - mean_pixel) / std_pixel
X_val = (X_val - mean_pixel) / std_pixel
X_test = (X_test - mean_pixel) / std_pixel
# number_of_classes = 10
# Y_train = to_categorical(y_train_noise, number_of_classes)
# Y_val = to_categorical(y_val_noise, number_of_classes)
# Y_test = to_categorical(y_test, number_of_classes)
# Y_train_noise = to_categorical(y_train_noise, number_of_classes)
# y_train_noise[1], Y_train[1]
x_train_dset, y_train_dset = Dataset(X_train, y_train_noise, batch_size, shuffle=True)
x_val_dset, y_val_dset = Dataset(X_val, y_val_noise, batch_size, shuffle=False)
x_test_dset, y_test_dset = Dataset(X_test, y_test, batch_size)
tf.reset_default_graph()
with tf.device(device):
x = tf.placeholder(tf.float32, [None, 28, 28, 1])
y = tf.placeholder(tf.int32, [None])
is_training = tf.placeholder(tf.bool, name='is_training')
scores, scores_2, scores_3 = model_init_fn(x, is_training)
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores)
loss = tf.reduce_mean(loss)
loss_2 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores_2)
loss_2 = tf.reduce_mean(loss_2)
loss_3 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores_3)
loss_3 = tf.reduce_mean(loss_3)
optimizer = optimizer_init_fn()
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss)
train_op_2 = optimizer.minimize(loss_2)
train_op_3 = optimizer.minimize(loss_3)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
t = 0
for epoch in range(num_epochs):
if epoch <=1: # stage controller (when threshold set to 0 it is ICML, when set to num_epochs it is ICL-R)
flag=False
else:
flag=True
print('Starting epoch %d' % epoch)
for x_np, y_np in zip(x_train_dset, y_train_dset):
feed_dict = {x: x_np, y: y_np, is_training:1}
loss_np, _ = sess.run([loss, train_op], feed_dict=feed_dict)
loss_np_2, _ = sess.run([loss_2, train_op_2], feed_dict=feed_dict)
loss_np_3, _ = sess.run([loss_3, train_op_3], feed_dict=feed_dict)
if t % print_every == 0:
print('Iteration %d, loss = %.4f' % (t, loss_np))
print('Iteration %d, loss_2 = %.4f' % (t, loss_np_2))
print('Iteration %d, loss_3 = %.4f' % (t, loss_np_3))
cross_check_multi(sess, x_val_dset, y_val_dset, x, scores, scores_2, scores_3, is_training, flag)
print()
t += 1
# reshuffle data to train/val for each epoch
print('reshuffling data..')
x_train_all = np.vstack((x_train_dset, x_val_dset))
x_train_all = x_train_all.reshape((-1,28,28,1))
y_train_all = np.vstack((y_train_dset, y_val_dset))
y_train_all = y_train_all.flatten()
mask = range(num_training, num_training + num_validation)
X_val = x_train_all[mask]
y_val_noise = y_train_all[mask]
mask = range(num_training)
X_train = x_train_all[mask]
y_train_noise = y_train_all[mask]
x_train_dset, y_train_dset = Dataset(X_train, y_train_noise, batch_size, shuffle=True)
x_val_dset, y_val_dset = Dataset(X_val, y_val_noise, batch_size, shuffle=False)
acc1 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores, is_training=is_training)
acc2 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores_2, is_training=is_training)
acc3 = check_accuracy(sess, zip(x_test_dset, y_test_dset), x, scores_3, is_training=is_training)
# ENSEMBLE LEARNING (max vote)
accuracy = check_test_accuracy_ensemble(sess, x_test_dset, y_test_dset, x, scores, scores_2, scores_3, is_training=is_training)
print('\nfinal ensemble learning prediction accuracy: ', accuracy) # ensemble learning
def model_init_fn(inputs, is_training):
# initializer = tf.variance_scaling_initializer(scale=2.0)
model = Sequential()
model.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1 = Activation('relu')
model.add(convout1)
convout2 = MaxPooling2D()
model.add(convout2)
model.add(Convolution2D(64, kernel_size=(2, 2), input_shape=(13,13,32)))
model.add(Activation('relu'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()
model_2 = Sequential()
model_2.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1_2 = Activation('relu')
model_2.add(convout1_2)
convout2_2 = MaxPooling2D()
model_2.add(convout2_2)
model_2.add(Flatten())
model_2.add(Dense(128))
model_2.add(Activation('relu'))
model_2.add(Dropout(0.2))
model_2.add(Dense(10))
model_2.add(Activation('softmax'))
model_2.summary()
model_3 = Sequential()
model_3.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1_3 = Activation('relu')
model_3.add(convout1_3)
convout2_3 = MaxPooling2D()
model_3.add(convout2_3)
model_3.add(Convolution2D(64, kernel_size=(2, 2), input_shape=(13,13,32)))
model_3.add(Activation('relu'))
model_3.add(MaxPooling2D())
model_3.add(Convolution2D(32, kernel_size=(2, 2), padding = 'valid', input_shape=(6,6,64)))
model_3.add(Activation('relu'))
model_3.add(Flatten())
model_3.add(Dense(128))
model_3.add(Activation('relu'))
model_3.add(Dropout(0.2))
model_3.add(Dense(10))
model_3.add(Activation('softmax'))
model_3.summary()
return model(inputs), model_2(inputs), model_3(inputs)
learning_rate = 4e-4
def optimizer_init_fn():
optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate)
return optimizer
print_every = 700
num_epochs = 10
train_noisyCNN(model_init_fn, optimizer_init_fn, num_epochs)
# +
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# +
# Model
model = Sequential()
model.add(Convolution2D(32, kernel_size=(3, 3), input_shape=(28,28,1)))
convout1 = Activation('relu')
model.add(convout1)
convout2 = MaxPooling2D()
model.add(convout2)
model.add(Convolution2D(64, kernel_size=(2, 2), input_shape=(13,13,32)))
model.add(Activation('relu'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(10))
model.add(Activation('softmax'))
# -
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(X_train, Y_train, batch_size=128, nb_epoch=5, validation_data=(X_test, Y_test))
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(loss) + 1)
plt.plot(epochs, loss, color='red', label='Training loss')
plt.plot(epochs, val_loss, color='green', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
acc = history.history['acc']
val_acc = history.history['val_acc']
plt.plot(epochs, acc, color='red', label='Training acc')
plt.plot(epochs, val_acc, color='green', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
def layer_to_visualize(img_to_visualize, layer):
# Keras requires the image to be in 4D, so we add an extra dimension to it.
img_to_visualize = np.expand_dims(img_to_visualize, axis=0)
inputs = [K.learning_phase()] + model.inputs
_convout1_f = K.function(inputs, [layer.output])
def convout1_f(X):
# The [0] is to disable the training phase flag
return _convout1_f([0] + [X])
convolutions = convout1_f(img_to_visualize)
convolutions = np.squeeze(convolutions)
convolutions = convolutions.transpose(2, 0, 1)
print('Shape of conv:', convolutions.shape)
print(len(convolutions))
n = convolutions.shape[0]
n = int(np.ceil(np.sqrt(n)))
# Visualization of each filter of the layer
fig = plt.figure(figsize=(12,8))
for i in range(len(convolutions)):
ax = fig.add_subplot(n,n,i+1)
ax.imshow(convolutions[i], cmap='gray')
# +
# Specify the layer to want to visualize
layer_to_visualize(X_train[65], convout1)
# As convout2 is the result of a MaxPool2D layer
# We can see that the image has blurred since
# the resolution has reduced
layer_to_visualize(X_train[65], convout2)
# -
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
y_prob = model.predict(X_test)
y_classes = y_prob.argmax(axis=-1)
label = np.argmax(Y_test, axis=1)
confusion_mtx = confusion_matrix(label, y_classes)
plt.figure(figsize=(10,8))
sns.heatmap(confusion_mtx, annot=True, fmt="d")
diff = y_classes-label
ind = np.where(diff!=0)
print(ind)
print(1-(len(diff[diff!=0]))/len(diff))
layer_to_visualize(X_test[321], convout1)
layer_to_visualize(X_test[321], convout2)
print(label[321], y_classes[321]) # true label vs predicted label (misclassified ones)
# train different model based on noisy labeled training data
history = model.fit(X_train, Y_train_noise, batch_size=128, nb_epoch=5, validation_data=(X_test, Y_test))
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(loss) + 1)
plt.plot(epochs, loss, color='red', label='Training loss')
plt.plot(epochs, val_loss, color='green', label='Validation loss')
plt.title('Training and validation loss on noisy data')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
acc = history.history['acc']
val_acc = history.history['val_acc']
plt.plot(epochs, acc, color='red', label='Training acc')
plt.plot(epochs, val_acc, color='green', label='Validation acc')
plt.title('Training and validation accuracy on noisy data')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
y_prob = model.predict(X_test)
y_classes = y_prob.argmax(axis=-1)
label = np.argmax(Y_test, axis=1)
confusion_mtx = confusion_matrix(label, y_classes)
plt.figure(figsize=(10,8))
sns.heatmap(confusion_mtx, annot=True, fmt="d");
print(y_train[noisy_image_idx], y_train_noise[noisy_image_idx]) # true label vs noisy label
layer_to_visualize(X_train[noisy_image_idx], convout1)
layer_to_visualize(X_train[noisy_image_idx], convout2)
# +
# visualize weights & compare statistics; validate pattern on more datasets (e.g. CIFAR)
# +
# majority vote ensemble learning (change cross accuracy checking for test set in last epoch)
# -
| Noise_CNN.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
# ---
# # The numpy.random module
# The "import" statement brings in other *namespaces* where functions and variables may live.
# import *module* as *name* allows for not retyping the whole name of a module if it will be used a lot.
# The primary module for numerical computing we use is called __numpy__, and contains functions for mathematical work and random number generation.
import numpy as np
# To call a function that requires no arguments, we simply append () to its name. The module _np.random_ contains "random" number generation, with the function _random_ that generates a single continuous uniform `[0,1]`.
for i in range(3):
print(np.random.random())
# The numbers generated by random() are not truly random -- they are called __psuedorandom__ numbers. They are given by a deterministic stream of numbers starting at a _seed_ value:
np.random.seed(126)
for i in range(3):
print(np.random.random())
np.random.seed(126)
for i in range(3):
print(np.random.random())
# Using seeds is extremely important since we want our results to be replicable, both by ourselves and by others. "True" sources of randomness, e.g. what you might get from atmospheric noise from https://www.random.org/, are not useful for us and should not typically be used in economics.
# __Always__ set a seed at the beginning of an analysis.
# # Linear congruential generators
# A pseudo-random number drawn from $X$ is intuitively defined by two properties:
# 1. The empirical distribution of the pseduo-random numbers should match that of X as closely as possible as the number of draws gets large.
# 2. Knowledge of previous pseudo-random draws from X gives no information about the next draw of X.
#
# Amazingly, there are very simple deterministic procedures that can satisfy 1. and 2. fairly well, and refinements of these methods can be indistinguishable from a true string of random numbers with our current technology.
#
# The easiest method to explain to generate $Uniform[0,1]$ variates -- which we will then use to draw from arbitrary distributions -- is a class of functions called _Linear Congruential Generators_. These generate $X$ using the recurrence relation
#
# $X_{n} = (a X_{n-1} + c) \mod m$
#
# for some non-negative integer parameters $a$ (_multiplier_), $c$ (_increment_), $m$ (_modulus_), and $X_0$ (_seed_).
# For an obvious non-random example, consider the case $m$ prime, $c=0$:
import matplotlib.pyplot as plt
plt.figure()
x = 1
for i in range(100):
plt.plot(i, x, 'ro')
x = (7 * x + 0) % 17
plt.show()
# By choosing particular values of the seed, multiplier, and increment, you can find particularly good properties of the generated output, with millions of draws before a cycle. There are also bad values of these parameters, but any programming language implementation should be fine for our purposes.
plt.figure()
x = 2**23 + 3**15
for i in range(100):
plt.plot(i, x, 'go')
x = (1103515245 * x + 12345) % 2**32
plt.show()
# Generate 1000 values from this LCG and draw the histogram. Not bad.
x = np.zeros(1000, dtype=np.intp)
x[0] = 2**23 + 3**15
for i in range(1,1000):
x[i] = (1103515245 * x[i-1] + 12345) % 2**32
plt.figure()
plt.hist(x/2**32) #rescale between 0,1
plt.show()
# Does the approximation to the Uniform improve after a million draws?
x = np.zeros(1000000, dtype=np.intp)
x[0] = 2**23 + 3**15
for i in range(1,1000000):
x[i] = (1103515245 * x[i-1] + 12345) % 2**32
plt.figure()
plt.hist(x/2**32)
plt.show()
# And lastly, what is the correlation between each draw and the previous one?
print(np.corrcoef(x[:-1], x[1:])[1,0])
def uniformrv(length, seed=2**23 + 3**15):
x = np.zeros(length, dtype=np.float64)
for i in range(length):
x[i] = (1103515245 * x[i-1] + 12345) % 2**32
return x/2**32
# # Drawing from non-uniform random variables
# The easiest way to sample from a random variable with known CDF $F(x)$ is what is known as Inverse Transform Sampling. (Easiest conceptually and easiest to program, but this is often computationally inefficient.) Inverse transform sampling uses the fact that for a random variable $X$ with CDF $F(x)$ and a $Uniform[0,1]$ rv $U$,
#
# $F^{-1}(U)\sim X$,
#
# that is, $F^{-1}(U)$ has the same distribution as $X$.
#
# It's easy to see this fact from our CDF transform method.
#
# If $\Pr(U\leq u) = u$ and $\Pr(X\leq x) = F(x)$, $\Pr(F^{-1}(U)\leq x) = \Pr(U\leq F(x)) = F(x)$ as desired.
#
# ### Exponential Distribution
# For example, we know the CDF of the Exponential($\lambda$) distribution is
# $F(x) \equiv z = 1 - e^{-\lambda x}$, and we can invert this to find $F^{-1}(z) = -\frac{1}{\lambda} \log(1-z)$.
# +
z = uniformrv(10000)
lam = 2.0
inversetransformsampled = -1/lam * np.log(1-z)
plt.figure()
plt.hist(inversetransformsampled, bins=100)
plt.show()
# -
# ### Logistic Distribution
# $F(x) \equiv z = \frac {1}{(1 + \exp(-x))} \rightarrow x = \log(\frac{z}{1-z})$
# +
# same z (uniform draws) as above
inversetransformsampled = np.log(z/(1-z))
plt.figure()
plt.hist(inversetransformsampled, bins=100)
plt.show()
# -
# ### Cauchy Distribution
# $F(x) \equiv z = \frac{1}{2} + \arctan(x) \rightarrow x = \tan(\pi(z-\frac{1}{2}))$
# As you can see, generating from the Cauchy using the inverse transform sampling method has some issues. The Cauchy can be written as the ratio of two standard normals, but still is difficult to work with.
inversetransformsampled = np.tan(np.pi * (z-.5))
plt.figure()
plt.hist(inversetransformsampled, bins=100)
plt.show()
inversetransformsampled = np.random.normal(size=z.size)/np.random.normal(size=z.size)
plt.figure()
plt.hist(inversetransformsampled, bins=100)
plt.show()
inversetransformsampled = np.random.standard_cauchy(size=z.size)
plt.figure()
plt.hist(inversetransformsampled, bins=100)
plt.show()
# ### Standard Normal
# Unfortunately, since the standard normal has no closed-form CDF, the inverse transform sampling method requires numerical evaluation of $\Phi^{-1}(z)$, which is relatively computationally expensive. There are plenty of algorithms out there that use special transformations, e.g. https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform, and any programming language you use will have a good one.
# Just to show we can use the inverse tranform sampling method in a pinch, the module scipy.stats has the inverse normal CDF in a function called "norm.ppf".
import scipy.stats
inversetransformsampled = scipy.stats.norm.ppf(z)
plt.figure()
plt.hist(inversetransformsampled, bins=100)
plt.show()
# But as you can see, this method is signficantly slower (even with the uniforms already generated!) then simply using a built-in efficient random normal generator. If a library provides a dedicated random number generator for a distribution, it is almost always going to be signficantly faster than a manual implementation.
# %timeit scipy.stats.norm.ppf(z)
# %timeit (np.random.normal(size=z.size))
| Basic Random Variate Generation.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
# ---
# # 1A.1 - Variables, boucles, tests
#
# Répétitions de code, exécuter une partie plutôt qu'une autre.
from jyquickhelper import add_notebook_menu
add_notebook_menu()
# ### Partie 1 : variables, int, float, str, list
# Un algorithme manipule des données. Ces données ne sont pas connues au moment où on écrit l'algorithme. Les variables servent à nommer ces données afin de pouvoir écrire cet algorithme. On procède la plupart du temps dans l'ordre suivant :
#
# * On écrit l'algorithme.
# * On affecte des valeurs aux variables.
# * On exécute l'algorithme.
#
# Quelques exemples à essayer autour des variables :
i = 3 # entier = type numérique (type int)
r = 3.3 # réel = type numérique (type float)
s = "exemple" # chaîne de caractères = type str (exemple n'est pas une variable)
s = 'exemple' # " et ' peuvent être utilisées pour définir une chaîne de caractères
sl = """ exemple sur
plusieurs lignes""" # on peut définir une chaîne sur plusieurs lignes avec """ ou '''
n = None # None signifie que la variable existe mais qu'elle ne contient rien
# elle est souvent utilisée pour signifier qu'il n'y a pas de résultat
# car... une erreur s'est produite, il n'y a pas de résultat
# (racine carrée de -1 par exemple)
i,r,s,n, sl # avec les notebooks, le dernier print n'est pas nécessaire, il suffit d'écrire
# i,r,s,n
v = "anything" # affectation
print ( v ) # affichage
v1, v2 = 5, 6 # double affectation
v1,v2
# Par défaut, le notebook affiche le résultat présent sur la dernière ligne de la cellule. S'il on souhaite en afficher plusieurs, il faut utiliser la fonction [print](https://docs.python.org/3/library/functions.html?highlight=print#print).
x = 3
print(x)
y = 5 * x
y
x,y = 4,5
s = "addition"
"{3} de {0} et {1} donne : {0} + {1} = {2}".format (x,y,x+y,s)
# La dernière écriture permet d'assembler différentes valeurs en une seule chaînes de caractères. C'est très pratique lorsqu'on veut répéter le même assemblage un grand nombre de fois. Ce mécanisme ressemble à celui des lettres type : c'est un texte à trou qu'on remplit avec des valeurs différentes à chaque fois.
for prenom in [ "xavier", "sloane"] :
print ("Monsieur {0}, vous avez gagné...".format(prenom))
# **Type d'une variable :**
print ( type ( v ) ) # affiche le type d'une variable
print ( isinstance (v, str) ) # pour déterminer si v est de type str
# **Les tableaux ou listes (list) :**
c = (4,5) # couple de valeurs (ou tuple)
l = [ 4, 5, 6.5] # listes de valeurs ou tableaux
x = l [0] # obtention du premier élément de la liste l
y = c [1] # obtention du second élément
le = [ ] # un tableau vide
c,l,x,y,le
l = [ 4, 5 ]
l += [ 6 ] # ajouter un élément
l.append ( 7 ) # ajouter un élément
l.insert (1, 8) # insérer un élément en seconde position
print(l)
del l [0] # supprimer un élément
del l [0:2] # supprimer les deux premiers éléments
l
# **Longueur d'une liste et autres :**
l = [ 4, 5, 6 ]
print ( len(l) ) # affiche la longueur du tableau
print ( max(l) ) # affiche le plus grand élément
s = l * 3 # création de la liste [ 4, 5, 6, 4, 5, 6, 4, 5, 6 ]
t = s [ 4:7 ] # extraction de la sous-liste de la position 4 à 7 exclu
s [4:7] = [ 4 ] # remplacement de cette liste par [ 4 ]
s
# Type **mutable** et **immutable** (voir aussi [Qu'est-ce qu'un type immuable ou immutable ?](http://www.xavierdupre.fr/app/ensae_teaching_cs/helpsphinx/all_FAQ.html#qu-est-ce-qu-un-type-immuable-ou-immutable)) : une liste est un type **mutable**. Cela veut dire que par défaut, l'instruction ``list1=list2`` ne recopie pas la liste, elle lui donne un autre nom qui peut être utilisé en même temps que le premier.
l1 = [ 0, 1 ,2 ]
l2 = l1
l2[0] = -1
l1,l2
# Les deux listes sont en apparence modifiées. En fait, il n'y en a qu'une. Pour créer une copie, il faut explicitement demander une copie.
l1 = [ 0, 1 ,2 ]
l2 = list(l1)
l2[0] = -1
l1,l2
# C'est un point très important du langage qu'il ne faut pas oublier. On retrouve cette convention dans la plupart des [langages interprétés](http://en.wikipedia.org/wiki/Interpreted_language) car faire une copie alourdit le temps d'exécution.
# ### Partie 2 : Tests
#
# Les tests permettent de faire un choix : selon la valeur d'une condition, on fait soit une séquence d'instructions soit une autre.
v = 2
if v == 2 :
print ("v est égal à 2")
else :
print ("v n'est pas égal à 2")
# La clause ``else`` n'est obligatoire :
v = 2
if v == 2 :
print ("v est égal à 2")
# Plusieurs tests enchaînés :
v = 2
if v == 2 :
print ("v est égal à 2")
elif v > 2 :
print ("v est supérieur à 2")
else :
print ("v est inférieur à 2")
# ### Partie 3 : boucles
# Les boucles permettent de répéter un nombre fini ou infini de fois la même séquence d'instructions.
# Quelques exemples à essayer autour des boucles :
for i in range (0, 10) : # on répète 10 fois
print ("dedans",i) # l'affichage de i
# ici, on est dans la boucle
# ici, on n'est plus dans la boucle
"dehors",i # on ne passe par 10
# **Boucle while :**
i = 0
while i < 10 :
print (i)
i += 1
# **Interrompre une boucle :**
for i in range (0, 10) :
if i == 2 :
continue # on passe directement au suivant
print (i)
if i > 5 :
break # interruption définitive
# **Parcours d'une liste :** observer les différences entre les trois écritures
l = [ 5, 3, 5, 7 ]
for i in range (0, len(l)) :
print ("élément ",i, "=", l [ i ] )
l = [ 5, 3, 5, 7 ]
for v in l :
print ("élément ", v )
l = [ 5, 3, 5, 7 ]
for i,v in enumerate(l) :
print ("élément ",i, "=", v )
# **Que fait le programme suivant ?**
l = [ 4, 3, 0, 2, 1 ]
i = 0
while l[i] != 0 :
i = l[i]
print (i) # que vaut l[i] à la fin ?
# On peut jouer avec des cartes pour faire dénouer le côté sybillin de ce programme : [La programmation avec les cartes](http://www.xavierdupre.fr/app/code_beatrix/helpsphinx/blog/2015-09-05_jeu_pour_les_grands.html).
# ### Partie 4 : les listes compactes, les ensembles
#
# Plutôt que d'écrire :
l = [ ]
for i in range (10) :
l.append( i*2+1)
l
# On peut écrire :
l = [ i*2+1 for i in range(10) ]
l
# Quelques examples à essayer :
l = [ i*2 for i in range(0,10) ]
l # qu'affiche l ?
l = [ i*2 for i in range(0,10) if i%2==0 ]
l # qu'affiche l ?
# Les ensembles ou **set** sont des listes pour lesqueelles les éléments sont uniques. Si deux nombres nombres *int* et *float* sont égaux, seul le premier sera conservé.
l = [ "a","b","c", "a", 9,4,5,6,7,4,5,9.0]
s = set(l)
s
# ### Partie 5 : recherche non dichotomique (exercice)
#
# On veut écrire quelques instructions pour trouver la position du nombre ``x = 7`` dans la liste ``l``. Il faut compléter le programme suivant en utilisant une boucle et un test.
# +
l = [ 3, 6, 2 , 7, 9 ]
x = 7
# ......
print ( position )
# -
# ### Partie 6 : Recherche dichotomique
# La [recherche dichotomique](http://fr.wikipedia.org/wiki/Dichotomie) consiste à chercher un élément ``e`` dans un tableau trié ``l``. On cherche sa position :
#
# * On commence par comparer ``e`` à l'élément placé au milieu du tableau d'indice ``m``, s'ils sont égaux, on a trouvé,
# * s'il est inférieur, on sait qu'il se trouve entre les indices 0 et ``m-1``,
# * s'il est supérieur, on sait qu'il se trouve entre les indices ``m+1`` et la fin du tableau.
#
# Avec une comparaison, on a déjà éliminé une moitié de tableau dans laquelle on sait que ``p`` ne se trouve pas. On applique le même raisonnement à l'autre moitié pour réduire la partie du tableau dans laquelle on doit chercher.
# +
l = sorted( [ 4, 7, -1,3, 9, 5, -5 ] )
# recherche dichotomique
# la position retournée est correspond à celle de l'élément dans le tableau trié
# -
# ### Partie 7 : pour aller plus loin
#
# * Que fait la fonction écrite à la question précédente lorsque l'élément ne se trouve pas dans le tableau ?
# * Comparer le coût d'une recherche classique et celui d'une recherche dichotomique. On appelle coût d'un algorithme le nombre d'opérations qu'il faut pour atteindre le résultats. Dans ce cas, ce coût correspond au nombre d'itérations, c'est-à-dire le nombre de passage dans la boucle. Comme ce coût dépend des données en entrée, on experime généralement ce coût en fonction de la taille des données.
| _doc/notebooks/td1a/td1a_cenonce_session2.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.9 64-bit (''py36'': conda)'
# language: python
# name: python36964bitpy36conda0e8829d2adb54b9eb5e6d97f2a5f186a
# ---
# # [Color Embedding](https://philippmuens.com/word2vec-intuition/)
# +
import json
import pandas as pd
import seaborn as sns
import numpy as np
from IPython.display import HTML, display
# prettier Matplotlib plots
import matplotlib.pyplot as plt
import matplotlib.style as style
style.use('seaborn')
# -
# # 1. Dataset
# #### Download
# + language="bash"
# if [[ ! -f "data/colors-256.json" ]]; then
# mkdir -p data
# wget -nc \
# https://jonasjacek.github.io/colors/data.json \
# -O data/colors-256.json 2> /dev/null
# fi
# -
color_data = json.loads(open("data/colors-256.json", 'r').read())
color_data[:5]
# #### Preprocess
# +
colors = dict()
for color in color_data:
name = color['name'].lower()
r = color['rgb']['r']
g = color['rgb']['g']
b = color['rgb']['b']
rgb = tuple([r, g, b])
colors[name] = rgb
# -
print('Black: %s' % (colors['black'],))
print('White: %s' % (colors['white'],))
print('Red: %s' % (colors['red'],))
print('Lime: %s' % (colors['lime'],))
print('Blue: %s' % (colors['blue'],))
df = pd.DataFrame.from_dict(
data=colors,
orient='index',
columns=['r', 'g', 'b'])
df.head()
# # 2. Model
# #### Visualize color
def render_color(color: tuple) -> None:
'''Render color (r, g, b)'''
(r, g, b) = color
display(HTML('''
<div style="background-color: rgba(%d, %d, %d, 1); height: 20px;"></div>
''' % (r, g, b)),
metadata=dict(isolated=True))
render_color( (0, 0, 0) )
render_color( (128, 128, 1) )
# #### Cosine similarity
# $$\text{similarity}\ =\ cos(\theta)\ =\ \frac{A \cdot B}{\| A \| \| B \|}$$
def similar(df, coord, n=10):
# RGB values (3D coordinates) into a numpy array
v1 = np.array(coord, dtype=np.float64)
df_copy = df.copy()
for i in df_copy.index:
item = df_copy.loc[i]
v2 = np.array([item.r, item.g, item.b], dtype=np.float64)
#### cosine similarty ####
theta_sum = np.dot(v1, v2)
theta_den = np.linalg.norm(v1) * np.linalg.norm(v2)
# check if we're trying to divide by 0
if theta_den == 0:
theta = None
else:
theta = theta_sum / theta_den
# adding the `distance` column with the result of our computation
df_copy.at[i, 'distance'] = theta
# sorting the resulting DataFrame by distance
df_copy.sort_values(
by='distance',
axis=0,
ascending=False,
inplace=True)
return df_copy.head(n)
# # 3. Test similar color
# #### Similar color to red
render_color(colors['red'])
df_red = similar(df, colors['red'])
df_red
for c in df_red.index:
render_color(colors['{}'.format(c)])
# #### Similar color to (100, 20, 120)
render_color((100, 20, 120))
df_render = similar(df, [100, 20, 120])
df_render
for c in df_render.index:
render_color(colors['{}'.format(c)])
| Problems/Embedding_2_Colors.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.1 64-bit
# name: python_defaultSpec_1600424669088
# ---
# <h1> The Sparks Foundation</h1>
# <h2>Task 2 To Explore supervised Machine Learning</h2>
# <h3> In this regression task we will predict the percentage of
# marks that a student is expected to score based upon the
# number of hours they studied. This is a simple linear
# regression task as it involves just two variables.
# Data can be found at http://bit.ly/w-data
#
# What will be predicted score if a student study for 9.25 hrs in a
# day?
# Sample Solution :
# https://drive.google.com/file/d/1koGHPElsHuXo9HPL4BQkZWRMJkOEHiv4/view
# </h3>
# Importing Libraries
#
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
# Display The Dataset
# + tags=[]
# Reading data from remote link
link = "http://bit.ly/w-data"
data = pd.read_csv(link)
print("Data Imported")
data.head(20)
# -
# Create a Plot
#To find Relationship between Hours and Scores
data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Study Hours')
plt.ylabel('Percentage Score')
plt.show()
# Splitting The Dataset
X = data['Hours'].values
y = data['Scores'].values
X = X.reshape(-1,1)
y = y.reshape(-1,1)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3, random_state=42)
#Creating a Linear Regression Module
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(X_train,y_train)
lr_pred = lr.predict(X_test)
# Plotting the regression line
line = lr.coef_*X+lr.intercept_
# Plotting for the test data
plt.scatter(X, y)
plt.plot(X, line);
plt.show()
# + tags=[]
print(X_test) # Testing data - In Hours
y_pred = lr.predict(X_test) #Predicting the scores
# -
# Evaluating the Module
# + tags=[]
#Evaluating the Module
from sklearn import metrics
print('Mean Absolute Error:',
metrics.mean_absolute_error(y_test, lr_pred))
# -
# What will be predicted score if a student study for 9.25 hrs in a day?
# + tags=[]
hours = [9.25]
prediction = lr.predict([hours])
print("No. of Hours = {}".format(hours[0]))
print("Predicted Score = {}".format(prediction[0]))
# -
| Task 2.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
# ---
# ### Multicollinearity & VIFs
#
# Using the notebook here, answer the quiz questioons below regarding multicollinearity.
#
# To get started let's read in the necessary libraries and the data that will be used.
# +
import pandas as pd
import numpy as np
import seaborn as sns
from patsy import dmatrices
import statsmodels.api as sm;
from statsmodels.stats.outliers_influence import variance_inflation_factor
# %matplotlib inline
df = pd.read_csv('./house_prices.csv')
df.head()
# -
#
# `1.`Use [seaborn](https://seaborn.pydata.org/examples/scatterplot_matrix.html) to look at pairwise relationships for all of the quantitative, explanatory variables in the dataset by running the cell below. You might also try adding color (**hue**) for the house style or neighborhood. Use the plot to answer the first quiz questions below.
sns.pairplot(df[['bedrooms', 'bathrooms', 'area']]);
# `2.` Earlier, you fit linear models between each individual predictor variable and price, as well as using all of the variables and the price in a multiple linear regression model. Each of the individual models showed a positive relationship - that is, when bathrooms, bedrooms, or area increase, we predict the price of a home to increase.
#
# Fit a linear model to predict a home **price** using **bedrooms**, **bathrooms**, and **area**. Use the summary to answer the second quiz question below. **Don't forget an intercept.**
# +
df['intercept'] = 1
lm = sm.OLS(df['price'], df[['intercept', 'bathrooms', 'bedrooms', 'area']])
results = lm.fit()
results.summary()
# -
# `3.` Calculate the VIFs for each variable in your model. Use quiz 3 below to provide insights about the results of your VIFs. [Here](https://etav.github.io/python/vif_factor_python.html) is the helpful post again, in case you need it!
# +
# get y and X dataframes based on this regression:
y, X = dmatrices('price ~ bedrooms + bathrooms + area' , df, return_type='dataframe')
# For each X, calculate VIF and save in dataframe
vif = pd.DataFrame()
vif["VIF Factor"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]
vif["features"] = X.columns
# -
vif
# `4.` Remove bathrooms from your above model. Refit the multiple linear regression model and re-compute the VIFs. Use the final quiz below to provide insights about your results.
lm = sm.OLS(df['price'], df[['intercept', 'bedrooms', 'area']])
results = lm.fit()
results.summary()
# +
# get y and X dataframes based on this regression:
y, X = dmatrices('price ~ bedrooms + area' , df, return_type='dataframe')
# For each X, calculate VIF and save in dataframe
vif = pd.DataFrame()
vif["VIF Factor"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]
vif["features"] = X.columns
vif
# -
| Practical_Statistics/Practical_Statistics/13_MLR/Multicollinearity+%26+VIFs.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
# ---
# # Fakeddit Data Analysis
# This section displays the finding of a thorough data analysis of the `Fakeddit-Benchmark` dataset after *Nakamura et al. (2020)*. It is intended to provide an understanding for the decision making process in tuning and setting `hyperparameters`, defining model architecture as well as applied techniques and choosing input data for `DistilFND`and variants. In essence it gives an analytical insight into the `Fakeddit` dataset. Further, it provides an explanation and hands-on practices for preprocessing the input data of all modalities including post-title, images and comment data provided.
# # Importing needed modules
# +
#Importing needed modules
import os
import numpy as np
import keras
import pandas as pd
from tqdm import tqdm_notebook as tqdm
from PIL import Image
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
# Import widgets module
import ipywidgets as widgets
# Importing display function from IPython module
from IPython.display import display
# -
# # Analysis of data and token length distribution
# ### Fakeddit Data Distribution
# Fakeddit dataset splits are extremely imbalanced, as can be seen by plotted graph below. During model training, testing and validation the dataset splits will be left unchanged. Because of the long duration of scraping data from Reddit (about 10 years) it is assumed, that the current class distribution represents real world data distribution regarding specific types of Fake News on social media. Thus, keeping an uneven data dsitribution might possibly yield attributes favorable for correct classification and model training.
# Method to read input data from tsv file into dataframe
def initialize_dataframe(path, file):
dataframe = pd.read_csv(os.path.join(path, file), delimiter="\t")
# If comment data loaded, clean column 'Unnamed: 0'
if "Unnamed: 0" in dataframe.columns:
dataframe = dataframe.drop(["Unnamed: 0"], 1)
return dataframe
# Read input into dataframes
df_test = initialize_dataframe("dataset", "multimodal_test_public.tsv")
df_validate = initialize_dataframe("dataset", "multimodal_validate.tsv")
df_train = initialize_dataframe("dataset", "multimodal_train.tsv")
print("Training split contains: " + str(len(df_train)) + " samples")
print("Validate split contains: " + str(len(df_validate)) + " samples")
print("Test split contains: " + str(len(df_test)) + " samples")
def plot_data_distribution(dataframe):
ax = sns.countplot(dataframe["6_way_label"])
plt.xlabel("6 Way Classification");
# Define class names per integer value: see https://github.com/entitize/Fakeddit/issues/14
# for confirmation
class_names = ["True\n(0)", "Satire\n(1)", "False Conn.\n(2)", "Impost. Content\n(3)",
"Man. Content\n(4)", "Mis. Content\n(5)"]
# Set class names for x axis
ax.set_xticklabels(class_names);
# PLotting subtype class distribution for complete training set
plot_data_distribution(df_train)
# PLotting subtype class distribution for complete validation set
plot_data_distribution(df_validate)
# PLotting subtype class distribution for complete test set
plot_data_distribution(df_test)
# ### Splitting complete Fakeddit dataset in training, validate and test splits
# Apply `train_test_split()`function from Scikit-learn in order to minimize complete dataset
# with over *700.000* samples. Splitting complete dataset into custom training, validate and test sets,
# while reusing only *20%* of the original data (*80%* for training and *10%* for validation and testing each).
# Stratify function is applied in order to keep the
# per class sample distribution from original Fakeddit source dataset.
# Splitting complete Fakeddit-dataset into 20% training dataframe
# and 80% backup dataframe
df_train_split, df_backup = train_test_split(
df_train,
test_size=0.8,
shuffle=True,
# Apply stratification on basis of 6 way label classification
# maintaining percentage of samples per class as given by original dataset
stratify=df_train["6_way_label"]
)
# Keeping 80% of data samples for training and 20% for testing purposes
df_train_split, df_test_split = train_test_split(
df_train,
test_size=0.2,
shuffle=True,
# Apply stratification on basis of 6 way label classification
# maintaining percentage of samples per class as given by original dataset
stratify=df_train["6_way_label"]
)
# Dividing test split dataframe by factor 0,5 to have identically
# sized splits for validation and testing
df_test_split, df_validate_split = train_test_split(
df_test,
test_size=0.5,
shuffle=True,
# Apply stratification on basis of 6 way label classification
# maintaining percentage of samples per class as given by original dataset
stratify=df_test["6_way_label"]
)
# Number of samples contained in each of the splits
print("Training split contains: " + str(len(df_train_split)) + " samples")
print("Validate split contains: " + str(len(df_validate_split)) + " samples")
print("Test split contains: " + str(len(df_test_split)) + " samples")
# Stratifying keeps the percentage sample distribution per fake news subtype class. The complete splits are downsamples to only *20%* of the original data, yet the **class distribution is maintained in each of the splits**.
# PLotting subtype class distribution for downsized training set split
plot_data_distribution(df_train_split)
# PLotting subtype class distribution for downsized validate set split
plot_data_distribution(df_validate_split)
# PLotting subtype class distribution for downsized test set split
plot_data_distribution(df_test_split)
# ### Post-Title token length analysis
# Discovered is extreme density in short post title size **between 0 and 30 tokens**. Intuitively expected as text titles in posts on social media platform Reddit are usually kept very short, comparable to Twitter. To be on the safe side, **maximum length of 80 is chosen for sequence length**.
from transformers import DistilBertTokenizer
tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
def plot_token_distribution(dataframe):
token_length = []
# Iteration over given dataframe and count of tokens for every
# post sample
for post in tqdm(dataframe["clean_title"]):
tokens = tokenizer.encode(post)
token_length.append(len(tokens))
# Plotting post sample token counts with distribution plot
sns.distplot(token_length)
plt.xlim([0, 60])
plt.xlabel("Token Count")
# Plotting token length distribution for complete training set
plot_token_distribution(df_train)
# Plotting token length distribution for complete validation set
plot_token_distribution(df_validate)
# Plotting token length distribution for complete test set
plot_token_distribution(df_test)
# ### Analysis of information per sample
# To develop an understanding for Fakeddit dataset and the in **total 16 contained information/attributes per Reddit-Post sample**, for each complete data set (training, validation and test) the composition of attributes including the total count of available attributes is presented via the `dataframe.info()` function below. Further, the **first 5 rows of every dataframe** containing the complete training, validation and test sets is displayed below via the `dataframe.head()` function.
# Display info about contained attributes/information per Reddit-Post for training set
df_train.info()
# Display first 5 rows of complete training set
df_train.head()
# Display info about contained attributes/information per Reddit-Post for validation set
df_validate.info()
# Display first 5 rows of complete validation set
df_validate.head()
# Display info about contained attributes/information per Reddit-Post for test set
df_test.info()
# Display first 5 rows of complete test set
df_test.head()
# ### Analysis of sample count per class
# Counting the number of samples per subtype/class of contained fake news, authentic content and satire/parody samples. This information is needed, in order to adapt the weighted `CrossEntropyLoss` function for an adjusted loss calculation dependent of the prevalence of each individual class.
# +
# Counting the samples per class/subtype for complete training set
label_count = [df_train["6_way_label"].value_counts().sort_index(0)[0],
df_train["6_way_label"].value_counts().sort_index(0)[1],
df_train["6_way_label"].value_counts().sort_index(0)[2],
df_train["6_way_label"].value_counts().sort_index(0)[3],
df_train["6_way_label"].value_counts().sort_index(0)[4],
df_train["6_way_label"].value_counts().sort_index(0)[5]]
print(label_count)
# +
# Counting the samples per class/subtype for complete training set
label_count = [df_validate["6_way_label"].value_counts().sort_index(0)[0],
df_validate["6_way_label"].value_counts().sort_index(0)[1],
df_validate["6_way_label"].value_counts().sort_index(0)[2],
df_validate["6_way_label"].value_counts().sort_index(0)[3],
df_validate["6_way_label"].value_counts().sort_index(0)[4],
df_validate["6_way_label"].value_counts().sort_index(0)[5]]
print(label_count)
# +
# Counting the samples per class/subtype for complete training set
label_count = [df_test["6_way_label"].value_counts().sort_index(0)[0],
df_test["6_way_label"].value_counts().sort_index(0)[1],
df_test["6_way_label"].value_counts().sort_index(0)[2],
df_test["6_way_label"].value_counts().sort_index(0)[3],
df_test["6_way_label"].value_counts().sort_index(0)[4],
df_test["6_way_label"].value_counts().sort_index(0)[5]]
print(label_count)
# -
# # Example of DistilBert Post-Title tokenization process
# Following a tokenization process example is displayed by tokenizing a sample Reddit Post-Title via the DistilBert tokenizer pre-trained on the lower cased `English Wikipedia` and `Toronto Book Corpus`. The encoded `input_ids` and `attention_mask` of the post title are then fed to the pre-trained `DistilBert` model during training and prediction processes. However, down below the tokenized and encoded input sequence is decoded in the final step for the purpose of comparison and better understanding. Also, the special tokens `[CLS]` for an aggregated representation of the classification decision for the input sequence, the `[SEP]`token, which separating the input sequence and the `[PAD]`token for right-side passing and converting the input sequences to identical token lengths, become visible.
# +
# Load needed DistilBert tokenizer
from transformers import DistilBertTokenizer
# Assign tokenizer with pretrained language understanding of lower cased English text corpus
tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
# +
# Display original post title text input sequence
print("Post Titel:", end=" ")
post_title = df_test["clean_title"][3]
print(post_title)
print()
print()
# Tokenize post tile and display tokenized sequence
print("Tokens:", end=" ")
tokens = tokenizer.tokenize(post_title)
for i in range(len(tokens)):
print(tokens[i], end=" ")
print()
print()
print()
# Convert token sequence into sequence of numeric values / representations
print("Token ID:", end=" ")
token_ids = tokenizer.convert_tokens_to_ids(tokens)
for i in range(len(token_ids)):
print(token_ids[i], end=" ")
print()
print()
print()
# Encode tokenized numeric value sequence
encoding = tokenizer.encode_plus(
post_title,
max_length=80,
padding="max_length",
truncation=True,
add_special_tokens=True,
return_token_type_ids=False,
return_attention_mask=True,
return_tensors="pt",
)
# Display encoded post-title input_ids (input for DistilBert)
print("Encoded Input ID:", end=" ")
for i in range(0, 15):
print(encoding["input_ids"][0][i].item(), end=" ")
print()
print()
print()
# Display encoded post-title attention_mask (input for DistilBert)
print("Encoded Attention Mask:", end=" ")
for i in range(0, 15):
print(encoding["attention_mask"][0][i].item(), end=" ")
print()
print()
print()
# Display decoded input token sequence to convert sequence back to readable tokens
# Additionally, the special tokens [CLS], [SEP] and [PAD] become visible
encoding_tokens = tokenizer.convert_ids_to_tokens(encoding["input_ids"][0].flatten())
print("Decoded Zeichen / Token:", end=" ")
for i in range(len(encoding_tokens)):
if i == 15:
break
print(encoding_tokens[i], end=" ")
# -
# # Analysis Reddit Comment Data
# In this section, the data analysis and preprocessing steps for the Reddit comment data is displayed and explained. The complete comment data `tsv-file` contains a total of over **10 Million* data entries** and leads to a combined file size of approx. **1,87GB**. In order to reduce the file size for better data handling and loading. In order to reducing the inference / model training times, all comment data entries were preprocessed before model training. Essentially, an iteration over all post samples contained in training, validation and test set was conducted. A second iteration then processed the complete comments data file and identified associated comments via the `post id`, whereas `post id` in training, validation and test data sets equal the `submission_id`of entries in comment set. During this procedure for every Reddit post the **first 5 comments** were concatenated into one `String sequence` and implemented into a new `coomments` column within a copy of the original data split `pandas` dataframe. The resulting dataframe was then saved into separate `tsv-files` yielding to a `multimodal_train_comments.tsv`, `multimodal_validate_comments.tsv` and `multimodal_test_comments.tsv`, which contain the **original 16 attributes per row / post** and an **additional 17th column containing the first 5 comments per post**. If no comments could be found, an empty `String sequence`was implemented.
# Reading in all comment data
df_comments = initialize_dataframe("dataset", "all_comments.tsv")
# Display total number of comment data entries in complete comment tsv-file
print("Comment data contains: " + str(len(df_comments)) + " entries.")
# Display information / attributes (columns) for comments dataframe
df_comments.info()
-# Display first 5 rows of comments dataframe
df_comments.head()
# The associated comments of an original Reddit-Post are linked via
# the (post) id (in respective data set splits) eualling the submission_id in comments data set
df_train.loc[df_train["id"] == df_comments["submission_id"][0]]
# Iterate through initial train, test, validate splits and retrieve/process comment data from comment tsv file
def process_comment_data(df_input, df_comment_data, filename):
# Limit resulting comment text sequence to 2048 tokens
length = 2048
# Iterate over original post data set (df_train, df_validate, df_test)
# using the (post) id as a discriminator
for id in tqdm(df_input["id"]):
# List to append found comments to
post_comments = []
# Find corresponding comments via comparison of (post) id to submission_id in comment data
df_per_post = df_comment_data.loc[df_comment_data["submission_id"] == str(id)]
# If no comments assigned to specific post, assign empty string
if len(df_per_post) == 0:
df_input.loc[df_input.loc[df_input["id"] == str(id)].index[0], "comments"] = ""
else:
try:
#Iterate over all found comments --> Handling different indices and iteration counts
for i in range(df_per_post.index[0], df_per_post.index[0] + len(df_per_post)):
# If comment deleted, then skip
if df_per_post["body"][i] == "[deleted]":
continue
# If comment removed, then skip
elif df_per_post["body"][i] == "[removed]":
continue
else:
# If true comment found, append to corresponding comment list
comment = str(df_per_post["body"][i])
post_comments.append(comment)
# If indices do not match, assign empty string
# Usually indicated one single comment by moderator regarding
# general insignificant instruction for subbreddit conduct guidelines
except KeyError:
comment = ""
post_comments.append(comment)
# If no cases apply, empty string
if not post_comments:
post_comments.append("")
# Concatenate only first 5 found comments
comments = " ".join(post_comments[:5])
# If comments exceed given length limit, slice list
comments = (comments[:length]) if len(comments) > length else comments
# Implement found comments per post in 17th column of post dataframe
df_input.loc[df_input.loc[df_input["id"] == str(id)].index[0], "comments"] = comments
# Writing df_input split including comments column to tsv file
print("Writing comment data split to csv file.")
df_input.to_csv(f"data/{filename}", sep="\t", mode="a", index=True, header=False)
# %%time
# Process comment data for post training data set and write results to corresponding tsv-file
process_comment_data(df_train, df_comments, "multimodal_train_comments.tsv")
# %%time
# Process comment data for post validation data set and write results to corresponding tsv-file
process_comment_data(df_test, df_comments, "multimodal_validate_comments.tsv")
# %%time
# Process comment data for post test data set and write results to corresponding tsv-file
process_comment_data(df_test, df_comments, "multimodal_test_comments.tsv")
# After completion of the comment processing steps, the newly created data split dataframes can be loaded including the additional 17th comments column.
# Read input into dataframes
df_test = initialize_dataframe("dataset", "multimodal_test_comments.tsv")
df_validate = initialize_dataframe("dataset", "multimodal_validate_comments.tsv")
df_train = initialize_dataframe("dataset", "multimodal_train_comments.tsv")
# Display information/attributes of training set dataframe including comments column
df_train.info()
# Display first 5 rows of training set dataframe including comments column
df_train.head()
# Display information/attributes of validation set dataframe including comments column
df_validate.info()
# Display first 5 rows of validation set dataframe including comments column
df_validate.head()
# Display information/attributes of test set dataframe including comments column
df_test.info()
# Display first 5 rows of test set dataframe including comments column
df_test.head()
# # Processing Reddit-Image data
# Post-Images are fetched in similar fashion as associated comments. The `post_id`is used to fetch corresponding images from the image set folder. Before feeding the images to the pre-trained `ResNet34` model, which is trained on the `ImageNet 2021 Benchmark-Dataset` and can classify objects on images into a total of 1000 different classes, they are being processed by the `train_transform()` function for the training split and by the `val_transform()` function for the validation and test splits. Reason being, that random cropping and random horizontal flipping implements `Data augmentation`by artificially inflating the underlying data set. For humans it is easily recognizable that a mirrored image of an already seen image, displays the identical content. For a computer system this is not so obvious. The model architecture of `ResNet34`and the in-between results of the processing steps for converting the images to input feature tensors is displayed below.
# Importing needed modules
import torch
import torch.nn as nn
from torchvision import models
from PIL import Image
import matplotlib.pyplot as plt
# Initializing ResNet34 model after He et al. (2015) with pre-trained weights on ImageNet dataset
image_module = models.resnet34(pretrained="imagenet")
# Fully connected layer to map the 1000 out-features of last ResNet-layer on the 6 defined classes
num_classes = 6
image_module.fc = nn.Linear(in_features=1000, out_features=num_classes, bias=True)
# Display model architecture of ResNet34
print(image_module)
# +
# train_transform with data augmentation for training split,
# and val_transform without data augmentation for validation and test splits
from torchvision import transforms
# Data augmentation and normalization for training
train_transform = transforms.Compose([
transforms.RandomResizedCrop(224), # random resizing -> data augmentation
transforms.RandomHorizontalFlip(), # random flipping -> data augmentation
transforms.ToTensor(), # converting image data to tensor
transforms.Normalize( # normalizing image tensor
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.255]
)
])
# Just normalization for validation
val_transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.255]
)
])
# +
# Loading original image from image folder
image = Image.open("dataset/image_set/cozywbv.jpg")
# Transforming it for training and validation/test purposes
image_train = train_transform(image)
image_val = val_transform(image)
# -
# Display original image of post sample
# %matplotlib inline
plt.imshow(image)
plt.show()
# Display tensor representation of loaded image for training split
print(image_train)
# Display tensor representation of loaded image for validation/test splits
print(image_val)
# Display dimensions of image tensors for training and validation/test
# Dimensions are identical: [color_channels, height, width]
# In the actual training source code the unsqueeze() function extends
# tensor to a 4th dimension representing the count of images, e.g. [1, 3, 224, 224]
# for [image_count, color_channels, height in pixel, width in pixel]
print(image_train.shape)
print(image_val.shape)
| fakeddit_data_analysis.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## bayestestimation usage guide
#
# The `BayesTEstimation` class and its methods use a series of defaults which means that the user need not provide any information other than the data for samples A and B. This notebook covers usage where a user may want to use non-default parameters.
#
# #### Sections
#
# ##### Class BayesTEstimation
# - Initialise the class
#
# ##### Method fit_posterior
# - Set the number of draws from the posterior distribution to use in estimation.
# - Set the random seed used in the stan model.
# - Set alternative priors (alpha, beta, phi, mu, s)
#
# ##### Method quantile_summary
# - Include mean estimate or not
# - Set quantiles to report
# - Name the parameters
#
# ##### Method hdi_summary
# - Include mean estimate or not
# - Set a non-default HDI interval
# - Name the parameters
#
# ##### Method infer_delta_probability
# - Change the direction of the hypothesis
# - Add an additional constant to the hypothesis e.g. P(A > (B + constant))
# - Change the default print_inference
# - Name the parameters
#
# ##### Method infer_delta_bayes_factor
# - Change the direction of the hypothesis
# - Add an additional constant to the hypothesis e.g. P(A > (B + constant))
# - Change the default print_inference
# - Name the parameters
#
# ##### Method posterior_plot
# - Define the estimation method
# - Define the vertical line on the delta plot
# - Use a non-default colour on the plots
# - Use non-default intervals for the plot
# - Name the parameters
# - Explicitly define the fig size
#
from bayestestimation.bayestestimation import BayesTEstimation
# +
import numpy as np
np.random.seed(1)
a = np.random.normal(0, size = 20)
b = np.random.normal(0, size = 20)
# -
# ##### Class BayesProportionsEstimation
# - Initialise the class. The class has no optional parameters
ExampleBayes = BayesTEstimation()
# ##### Method fit_posterior
# - Set the number of draws from the posterior distribution to use in estimation.
ExampleBayes.fit_posteriors(a, b, n = 1000)
# - Set the random seed used in the stan model.
ExampleBayes.fit_posteriors(a, b, seed = 1234)
# - Set alternative priors (alpha, beta, phi, mu, s) (see [usage guide](https://github.com/oli-chipperfield/bayestestimation/blob/master/docs/bayestestimation_basis.ipynb) for details)
# +
alt_mu = 0
alt_s = 1000
alt_alpha = 0.01
alt_beta = 0.01
alt_phi = 1/3
ExampleBayes.fit_posteriors(a, b,
prior_mu = alt_mu,
prior_s = alt_s,
prior_alpha = alt_alpha,
prior_beta = alt_beta,
prior_phi = alt_phi)
# -
# ##### Method quantile_summary
# - Include mean estimate or not
ExampleBayes.fit_posteriors(a, b)
ExampleBayes.quantile_summary(mean=False)
# - Set quantiles to report
ExampleBayes.quantile_summary(quantiles=[0.01, 0.025, 0.05, 0.95, 0.975, 0.99])
# - Name the parameters
# +
parameter_names = ['Mean of A',
'Mean of B',
'Mean of B - mean of A',
'Standard deviation of A',
'Standard deviarion of B',
'Degrees of freedom']
ExampleBayes.quantile_summary(names = parameter_names)
# -
# ##### Method hdi_summary
# - Include mean estimate or note
#
ExampleBayes.hdi_summary(mean=False)
# - Set a non-default HDI interval
#
ExampleBayes.hdi_summary(interval=0.99)
# - Name the parameters
# +
parameter_names = ['Mean of A',
'Mean of B',
'Mean of B - mean of A',
'Standard deviation of A',
'Standard deviarion of B',
'Degrees of freedom']
ExampleBayes.hdi_summary(names = parameter_names)
# -
# ##### Method infer_delta_probability
# - Change the direction of the hypothesis
print(ExampleBayes.infer_delta_probability(direction = 'less than'))
# - Add an additional constant to the hypothesis e.g. P(A > (B + constant))
print(ExampleBayes.infer_delta_probability(value = 0.05))
print(ExampleBayes.infer_delta_probability(print_inference = False))
print(ExampleBayes.infer_delta_probability(names = ['Mean of A', 'Mean of B', 'Mean of B - mean of A']))
# ##### Method infer_delta_bayes_factor
# - Change the direction of the hypothesis
#
print(ExampleBayes.infer_delta_bayes_factor(direction = 'less than'))
# - Add an additional constant to the hypothesis e.g. P(A > (B + constant))
#
print(ExampleBayes.infer_delta_bayes_factor(value = -0.5))
# - Change the default print_inference
#
print(ExampleBayes.infer_delta_bayes_factor(print_inference = False))
# - Name the parameters
print(ExampleBayes.infer_delta_bayes_factor(names = ['Mean of A', 'Mean of B', 'Mean of B - mean of A']))
# ##### Method posterior_plot
#
# Note plots aren't displayed in order to minimise file size.
#
# - Define the estimation method
#
p = ExampleBayes.posterior_plot(method = 'quantile')
# - Define the vertical line on the delta plot
#
p = ExampleBayes.posterior_plot(delta_line = -0.5)
# - Use a non-default colour on the plots
p = ExampleBayes.posterior_plot(col = 'green')
# - Use non-default intervals for the plot. If using `method` = `'hdi'`:
#
p = ExampleBayes.posterior_plot(bounds = 0.99)
# - Use non-default intervals for the plot. If using `method` = `'quantile'`:
p = ExampleBayes.posterior_plot(method = 'quantile', bounds = [0.005, 0.995])
# - Name the parameters
# +
parameter_names = ['Mean of A',
'Mean of B',
'Mean of B - mean of A',
'Standard deviation of A',
'Standard deviarion of B',
'Degrees of freedom']
p = ExampleBayes.posterior_plot(names = parameter_names)
# -
# - Explicitly define the fig size
p = ExampleBayes.posterior_plot(fig_size = (750, 600))
| docs/bayestestimation_usage.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
# ---
# (EIGVALEIGVEC)=
# # 2.2 Eigenvalores y eigenvectores
# ```{admonition} Notas para contenedor de docker:
#
# Comando de docker para ejecución de la nota de forma local:
#
# nota: cambiar `<ruta a mi directorio>` por la ruta de directorio que se desea mapear a `/datos` dentro del contenedor de docker.
#
# `docker run --rm -v <ruta a mi directorio>:/datos --name jupyterlab_optimizacion -p 8888:8888 -d palmoreck/jupyterlab_optimizacion:2.1.4`
#
# password para jupyterlab: `<PASSWORD>`
#
# Detener el contenedor de docker:
#
# `docker stop jupyterlab_optimizacion`
#
# Documentación de la imagen de docker `palmoreck/jupyterlab_optimizacion:2.1.4` en [liga](https://github.com/palmoreck/dockerfiles/tree/master/jupyterlab/optimizacion).
#
# ```
# ---
# Nota generada a partir de [liga](https://www.dropbox.com/s/s4ch0ww1687pl76/3.2.2.Factorizaciones_matriciales_SVD_Cholesky_QR.pdf?dl=0).
# ```{admonition} Al final de esta nota el y la lectora:
# :class: tip
#
# * Aprenderá las definiciones más relevantes en el tema de eigenvalores y eigenvectores para su uso en el desarrollo de algoritmos en el análisis numérico en la resolución de problemas del álgebra lineal numérica. En específico las definiciones de: diagonalizable o *non defective* y similitud son muy importantes.
#
# * Comprenderá el significado geométrico de calcular los eigenvalores y eigenvectores de una matriz simétrica para una forma cuadrática que define a una elipse.
#
# * Aprenderá cuáles problemas en el cálculo de eigenvalores y eigenvectores de una matriz son bien y mal condicionados.
#
# ```
# - El problema es calcular eigenvalores... vamos a ver si este cálculo está bien o mal condicionado.
# En esta nota **asumimos** que $A \in \mathbb{R}^{n \times n}$.
# ## Eigenvalor (valor propio o característico)
# ```{admonition} Definición
#
# El número $\lambda$ (real o complejo) se denomina *eigenvalor* de A si existe $v \in \mathbb{C}^n - \{0\}$ tal que $Av = \lambda v$. El vector $v$ se nombra eigenvector (vector propio o característico) de $A$ correspondiente al eigenvalor $\lambda$.
# ```
# ```{admonition} Observación
# :class: tip
#
# Observa que si $Av=\lambda v$ y $v \in \mathbb{C}^n-\{0\}$ entonces la matriz $A-\lambda I_n$ es singular por lo que su determinante es cero.
#
# ```
# ```{admonition} Comentarios
#
# * Una matriz con componentes reales puede tener eigenvalores y eigenvectores con valores en $\mathbb{C}$ o $\mathbb{C}^n$ respectivamente.
# * El conjunto de eigenvalores se le nombra **espectro de una matriz** y se denota como:
#
# $$\lambda(A) = \{ \lambda | \det(A-\lambda I_n) = 0\}.$$
#
# * El polinomio
#
# $$p(z) = \det(A-zI_n) = (-1)^nz^n + a_{n-1}z^{n-1}+ \dots + a_1z + a_0$$
#
# se le nombra **polinomio característico asociado a $A$** y sus raíces o ceros son los eigenvalores de $A$.
#
# * La multiplicación de $A$ por un eigenvector es un reescalamiento y posible cambio de dirección del eigenvector.
# * Si consideramos que nuestros espacios vectoriales se definen sobre $\mathbb{C}$ entonces siempre podemos asegurar que $A$ tiene un eigenvalor con eigenvector asociado. En este caso $A$ tiene $n$ eigenvalores y pueden o no repetirse.
#
# * Se puede probar que el determinante de $A$: $\det(A) = \displaystyle \prod_{i=1}^n \lambda_i$ y la traza de $A$: $tr(A) = \displaystyle \sum_{i=1}^n \lambda_i$.
# ```
# - Cuidado con no confundir los coeficientes del polinomio con la matriz.
# - El determinante de la matriz A es el producto de sus eigenvalores.
# ### Ejemplo
import numpy as np
np.set_printoptions(precision=3, suppress=True)
A=np.array([[10,-18],[6,-11]])
print(A)
# **En *NumPy* con el módulo [numpy.linalg.eig](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html) podemos obtener eigenvalores y eigenvectores**
evalue, evector = np.linalg.eig(A)
print('eigenvalores:')
print(evalue)
print('eigenvectores:')
print(evector)
# ```{margin}
#
# $Av_1 = \lambda_1 v_1$.
# ```
print('matriz * eigenvector:')
print(A@evector[:,0])
print('eigenvalor * eigenvector:')
print(evalue[0]*evector[:,0])
# ```{margin}
#
# $Av_2 = \lambda_2 v_2$.
# ```
# - Aquí estamos demostrando la igualdad vista.
print('matriz * eigenvector:')
print(A@evector[:,1])
print('eigenvalor * eigenvector:')
print(evalue[1]*evector[:,1])
# ### Ejemplo
#
# Si $v$ es un eigenvector entonces $cv$ es eigenvector donde: $c$ es una constante distinta de cero.
#
const = -2
const_evector = const*evector[:,0]
print(const_evector)
# ```{margin}
#
# $cv$ es un eigenvector con eigenvalor asociado $c\lambda$ pues $A(cv) = \lambda(cv)$ se satisface si $Av = \lambda v$ y $c \neq 0$.
#
# ```
print('matriz * (constante * eigenvector):')
print(A@const_evector)
print('eigenvalor * (constante * eigenvector):')
print(evalue[0]*const_evector)
# - Un punto importante es que el múltiplo de un eigenvector es también un eigenvector.
# ### Ejemplo
# Una matriz con entradas reales puede tener eigenvalores y eigenvectores complejos:
A=np.array([[3,-5],[1,-1]])
print(A)
evalue, evector = np.linalg.eig(A)
# ```{margin}
#
# Para $A \in \mathbb{R}^{n \times n}$ se tiene: $\lambda \in \mathbb{C}$ si y sólo si $\bar{\lambda} \in \mathbb{C}$ con $\bar{\lambda}$ el conjugado de $\lambda$.
#
# ```
print('eigenvalores:')
print(evalue)
print('eigenvectores:')
print(evector)
# ```{admonition} Observación
# :class: tip
#
# En el ejemplo anterior cada eigenvalor tiene una multiplicidad simple y la multiplicidad geométrica de cada eigenvalor es $1$.
#
# ```
# ### Ejemplo
# Los eigenvalores de una matriz diagonal son iguales a su diagonal y sus eigenvectores son los vectores canónicos $e_1, e_2, \dots e_n$.
A = np.diag([2, 2, 2, 2])
print(A)
evalue, evector = np.linalg.eig(A)
print('eigenvalores:')
print(evalue)
print('eigenvectores:')
print(evector)
# - Aquí vemos que los eigenvalores son uno mismo repetido muchas veces.
# - La multiplicidad geométrica se da con las columnas linealmente independientes.
# - En este ejemplo vemos que la multiplicidad geométrica es de 4.
# - La multiplicidad algebráica es simplemente ver cuales eigenvalores se repiten.
# - La función `eig` que usamos nos acomoda los eigenvalores y eigenvectores en orden.
# ```{admonition} Definición
#
# La **multiplicidad algebraica** de un eigenvalor es su multiplicidad considerado como raíz/cero del polinomio característico $p(z)$. Si no se repite entonces tal eigenvalor se le nombra de multiplicidad **simple**.
#
# La **multiplicidad geométrica** de un eigenvalor es el número máximo de eigenvectores linealmente independientes asociados a éste.
#
# ```
# ### Ejemplo
# Los eigenvalores de una matriz triangular son iguales a su diagonal.
A=np.array([[10,0, -1],
[6,10, 10],
[3, 4, 11.0]])
A = np.triu(A)
print(A)
evalue, evector = np.linalg.eig(A)
# ```{margin}
#
# Observa que el eigenvalor igual a $10$ está repetido dos veces (multiplicidad algebraica igual a $2$) y se tienen dos eigenvectores linealmente independientes asociados a éste (multiplicidad geométrica igual a $2$).
# ```
print('eigenvalores:')
print(evalue)
print('eigenvectores:')
print(evector)
# - Aquí vemos que dos eigenvectores asociados solo a un eigenvalor.
# - Aquí decimos que la multiplicidad geométrica del 10 es 2 porque hay dos vectores linealmente independientes asociados al 10.
# **Otro ejemplo:**
A=np.array([[10,18, -1],
[6,10, 10],
[3, 4, 11.0]])
A = np.triu(A)
print(A)
evalue, evector = np.linalg.eig(A)
# ```{margin}
#
# Observa que en este ejemplo el eigenvalor $10$ está repetido dos veces (multiplicidad algebraica es igual a $2$) y sus eigenvectores asociados son linealmente dependientes (multiplicidad geométrica es igual a $1$).
# ```
print('eigenvalores:')
print(evalue)
print('eigenvectores:')
print(evector)
# - En este caso hay eigenvectores linealmente dependientes.
# ### Ejemplo
# Un eigenvalor puede estar repetido y tener un sólo eigenvector linealmente independiente:
A = np.array([[2, 1, 0],
[0, 2, 1],
[0, 0, 2]])
evalue, evector = np.linalg.eig(A)
# ```{margin}
#
# Observa que en este ejemplo el eigenvalor $2$ está repetido tres veces (multiplicidad algebraica es igual a $3$) y sus eigenvectores asociados son linealmente dependientes (multiplicidad geométrica es igual a $1$).
# ```
print('eigenvalores:')
print(evalue)
print('eigenvectores:')
print(evector)
# - Veremos como regla que la multiplicidad geométrica será menor o igual que la algebráica.
# ```{admonition} Definición
#
# Si $(\lambda, v)$ es una pareja de eigenvalor-eigenvector de $A$ tales que $Av = \lambda v$ entonces $v$ se le nombra eigenvector derecho. Si $(\lambda, v)$ es una pareja de eigenvalor-eigenvector de $A^T$ tales que $A^Tv = \lambda v$ (que es equivalente a $v^TA=\lambda v^T$) entonces $v$ se le nombra eigenvector izquierdo.
# ```
# ```{admonition} Observaciones
# :class: tip
#
# * En todos los ejemplos anteriores se calcularon eigenvectores derechos.
#
# * Los eigenvectores izquierdos y derechos para una matriz simétrica son iguales.
#
# ```
# (DIAGONALIZABLE)=
# - Las matrices que tengan eigenvalores con multiplicidad algebráica y geométrica igual les llamaremos "no defectuosas" o "diagonalizable"
# ## $A$ diagonalizable
# ```{admonition} Definición
#
# Si $A$ tiene $n$ eigenvectores linealmente independientes entonces $A$ se nombra diagonalizable o *non defective*. En este caso si $x_1, x_2, \dots, x_n$ son eigenvectores de $A$ con $Ax_i = \lambda_i x_i$ para $i=1,\dots,n$ entonces la igualdad anterior se escribe en ecuación matricial como:
#
# $$AX = X \Lambda$$
#
# o bien:
#
# $$A = X \Lambda X^{-1}$$
#
# donde: $X$ tiene por columnas los eigenvectores de $A$ y $\Lambda$ tiene en su diagonal los eigenvalores de $A$.
#
# A la descomposición anterior $A = X \Lambda X^{-1}$ para $A$ diagonalizable o *non defective* se le nombra ***eigen decomposition***.
# ```
# - Esta eigen descomposición la aplicamos solo para las matrices no defectuosas.
# - La $X$ y la "lambda mayúscula" son matrices.
# ```{admonition} Observación
# :class: tip
#
# * Si $A = X \Lambda X^{-1}$ entonces $X^{-1}A = \Lambda X^{-1}$ y los renglones de $X^{-1}$ (o equivalentemente las columnas de $X^{-T}$) son eigenvectores izquierdos.
#
# * Si $A = X \Lambda X^{-1}$ y $b = Ax = (X \Lambda X^{-1}) x$ entonces:
#
# $$\tilde{b} = X^{-1}b = X^{-1} (Ax) = X^{-1} (X \Lambda X^{-1}) x = \Lambda X^{-1}x = \Lambda \tilde{x}.$$
#
# Lo anterior indica que el producto matricial $Ax$ para $A$ diagonalizable es equivalente a multiplicar una matriz diagonal por un vector denotado como $\tilde{x}$ que contiene los coeficientes de la combinación lineal de las columnas de $X$ para el vector $x$ . El resultado de tal multiplicación es un vector denotado como $\tilde{b}$ que también contiene los coeficientes de la combinación lineal de las columnas de $X$ para el vector $b$. En resúmen, si $A$ es diagonalizable o *non defective* la multiplicación $Ax$ es equivalente a la multiplicación por una matriz diagonal $\Lambda \tilde{x}$ (salvo un cambio de bases, ver [Change of basis](https://en.wikipedia.org/wiki/Change_of_basis)).
#
# * Si una matriz $A$ tiene eigenvalores distintos entonces es diagonalizable y más general: si $A$ tiene una multiplicidad geométrica igual a su multiplicidad algebraica de cada eigenvalor entonces es diagonalizable.
#
# ```
# ### Ejemplo
# La matriz:
#
# $$A = \left[
# \begin{array}{ccc}
# 1 & -4 & -4\\
# 8 & -11 & -8\\
# -8 & 8 & 5
# \end{array}
# \right]
# $$
#
# es diagonalizable.
A = np.array([[1, -4, -4],
[8, -11, -8],
[-8, 8, 5.0]])
print(A)
evalue, evector = np.linalg.eig(A)
print('eigenvalores:')
print(evalue)
# ```{margin}
#
# Se verifica que los eigenvectores de este ejemplo es un conjunto linealmente independiente por lo que $A=X\Lambda X^{-1}$.
#
# ```
print('eigenvectores:')
print(evector)
# - Las columnas de esta matriz son linealmente independientes.
X = evector
Lambda = np.diag(evalue)
# ```{margin}
#
# Observa que si $Z$ es desconocida y $X^T Z^T = \Lambda$ entonces $Z^T = X^{-T} \Lambda$ y por tanto $XZ =X\Lambda X^{-1}$.
# ```
print(X@np.linalg.solve(X.T, Lambda).T)
# - Este producto es en realidad "X" por "Lambda mayúscula" por "X^-1"
# - Se usa el solve porque estamos usando Gauss-Jordan. Estás resolviendo un sistema de ecuaciones lineales para sacar la inversa.
print(A)
# $A$ es diagonalizable pues: $X^{-1} A X = \Lambda$
# - Recordemos que $Lambda$ es una matriz diagonal.
# - Los valores de la diagonal son los eigenvalores.
# - Obtener los eigenvalores de una matriz diagonal superior también es muy fácil.
# ```{margin}
#
# Observa que si $Z$ es desconocida y $XZ = A$ entonces $Z = X^{-1}A$ y por tanto $ZX = X^{-1} A X$.
# ```
print(np.linalg.solve(X, A)@X)
print(Lambda)
# ```{admonition} Observación
# :class: tip
#
# Observa que **no necesariamente** $X$ en la *eigen decomposition* es una matriz ortogonal.
#
# ```
# - Si haces producto punto entre primera y segunda columna no necesariamente es cero.
# ```{margin}
#
# Aquí se toma $X[1:3,1]$ como la primera columna de $X$ y se satisface $X[1:3,1]^TX[1:3,1] = 1$ en este ejemplo pero en general esto no se cumple.
#
# ```
X[:,0].dot(X[:,0])
# ```{margin}
#
# $X[1:3,1]^TX[1:3,2] \neq 0$ por lo que la primera y segunda columna de $X$ no son ortogonales.
#
# ```
X[:,0].dot(X[:,1])
# **Eigenvectores derechos:**
# ```{margin}
#
# `x_1` es la primer columna de $X$: $X[1:3, 1]$ y `lambda_1` el eigenvalor asociado.
# ```
x_1 = X[:,0]
lambda_1 = Lambda[0,0]
print(A@x_1)
# ```{margin}
#
# $Ax_1 = \lambda_1 x_1$.
# ```
print(lambda_1*x_1)
# ```{margin}
#
# `x_2` es la segunda columna de $X$: $X[1:3, 2]$ y `lambda_2` el eigenvalor asociado.
# ```
x_2 = X[:,1]
lambda_2 = Lambda[1,1]
print(A@x_2)
# ```{margin}
#
# $Ax_2 = \lambda_2 x_2$.
# ```
print(lambda_2*x_2)
# **Eigenvectores izquierdos:**
# ```{admonition} Observación
# :class: tip
#
# Para los eigenvectores izquierdos se deben tomar los renglones de $X^{-1}$ (o equivalentemente las columnas de $X^{-T}$) sin embargo no se utiliza el método [inv](https://numpy.org/doc/stable/reference/generated/numpy.linalg.inv.html) de *NumPy* pues es más costoso computacionalmente y amplifica los errores por redondeo. En su lugar se utiliza el método [solve](https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html) y se resuelve el sistema: $X^{-T} z = e_i$ para $e_i$ $i$-ésimo vector canónico.
#
# ```
e1 = np.zeros((X.shape[0],1))
e1[0] = 1
print(e1)
# ```{margin}
#
# `x_inv_1` es el primer renglón de $X^{-1}$: $X^{-1}[1, 1:3]$.
# ```
# - Vemos que es mucho más barato calcular por un lado derecho que por varios lados derechos.
x_inv_1 = np.linalg.solve(X.T, e1)
print(x_inv_1)
print(A.T@x_inv_1)
# ```{margin}
#
# $A^TX^{-T}[1:3,1] = \lambda_1 X^{-T}[1:3,1]$, `lambda_1` el eigenvalor asociado a `x_inv_1`.
# ```
print(lambda_1*x_inv_1)
e2 = np.zeros((X.shape[0],1))
e2[1] = 1
# ```{margin}
#
# `x_inv_2` es el segundo renglón de $X^{-1}$: $X^{-1}[2, 1:3]$.
# ```
x_inv_2 = np.linalg.solve(X.T, e2)
print(x_inv_2)
print(A.T@x_inv_2)
# ```{margin}
#
# $A^TX^{-T}[1:3,2] = \lambda_2 X^{-T}[1:3,2]$, `lambda_2` el eigenvalor asociado a `x_inv_2`.
# ```
print(lambda_2*x_inv_2)
# ```{admonition} Ejercicio
# :class: tip
#
# ¿Es la siguiente matriz diagonalizable?
#
# $$A = \left [
# \begin{array}{ccc}
# -1 & -1 & -2\\
# 8 & -11 & -8\\
# -10 & 11 & 7
# \end{array}
# \right]
# $$
#
# si es así encuentra su *eigen decomposition* y diagonaliza a $A$.
# ```
# (DESCESP)=
# - El cálculo de eigenvalores y eigenvectores nos dan pie a métodos de clusterización, reconocimiento de imágenes, etc.
# - La idea es que entendamos qué está pasando detrás de los paquetes que utilizamos.
# ### Resultado: $A$ simétrica
#
# Si A es simétrica entonces tiene eigenvalores reales. Aún más: $A$ tiene eigenvectores reales linealmente independientes, forman un conjunto ortonormal y se escribe como un producto de tres matrices nombrado **descomposición espectral o *symmetric eigen decomposition***:
#
# $$A = Q \Lambda Q^T$$
#
# donde: $Q$ es una matriz ortogonal cuyas columnas son eigenvectores de $A$ y $\Lambda$ es una matriz diagonal con eigenvalores de $A$.
#
# - Aquí cambiamos la notación de $X$ a $Q$.
# - $Q$ es ortogonal.
# - Nótese que la inversa de una ortogonal es lo mismo que la traspuesta.
# ```{admonition} Comentarios
#
# * Por lo anterior una matriz simétrica es **ortogonalmente diagonalizable**, ver {ref}`A diagonalizable <DIAGONALIZABLE>`.
#
# * Los eigenvalores de $A$ simétrica se pueden ordenar:
#
# $$\lambda_n(A) \leq \lambda_{n-1}(A) \leq \dots \leq \lambda_1(A)$$
#
# con:
#
# $\lambda_{max}(A) = \lambda_1(A)$, $\lambda_{min}(A) = \lambda_n(A)$.
#
# * Se prueba para $A$ simétrica:
#
# $$\lambda_{max}(A) = \displaystyle \max_{x \neq 0} \frac{x^TAx}{x^Tx}$$
#
# $$\lambda_{min}(A) = \displaystyle \min_{x \neq 0} \frac{x^TAx}{x^Tx}.$$
#
# por lo tanto:
#
# $$\lambda_{min}(A) \leq \frac{x^TAx}{x^Tx} \leq \lambda_{max}(A) \forall x \neq 0.$$
#
# * $||A||_2 = \displaystyle \max\{|\lambda_1(A)|, |\lambda_n(A)|\}$.
#
# * $||A||_F = \left( \displaystyle \sum_{i=1}^n \lambda_i ^2 \right)^{1/2}$.
#
# * Los valores singulares de $A$ son el conjunto $\{|\lambda_1(A)|, \dots, |\lambda_{n-1}(A)|, |\lambda_n(A)|\}$.
# ```
# - Lo importante aquí es podemos acotar los eigenvalores a un rango.
# - También podemos sacar la norma de una matriz a través de sus eigenvalores.
# ### Ejemplo
# Matriz simétrica y descomposición espectral de la misma:
A=np.array([[5,4,2],[4,5,2],[2,2,2]])
print(A)
evalue, evector = np.linalg.eigh(A)
# - Aquí podemos usar la función especial `eigh` porque es más eficiente.
# ```{margin}
#
# Como $A$ es simétrica sus eigenvalores son reales y sus eigenvectores forman un conjunto linealmente independiente. Por lo anterior $A$ tiene descomposción espectral.
# ```
print('eigenvalores:')
print(evalue)
print('eigenvectores:')
print(evector)
# - Vemos que, como esperábamos, los eigenvalores son reales.
# - Los eigenvectores forman conjunto linealmente independiente.
# ```{margin}
#
# $A = Q \Lambda Q^T$
# ```
print('descomposición espectral:')
Lambda = np.diag(evalue)
Q = evector
print('QLambdaQ^T:')
print(Q@Lambda@Q.T)
print('A:')
print(A)
# A es diagonalizable pues: $Q^T A Q = \Lambda$
print(Q.T@A@Q)
print(Lambda)
# Ver [numpy.linalg.eigh](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.eigh.html).
# ## Condición del problema del cálculo de eigenvalores y eigenvectores
# La condición del problema del cálculo de eigenvalores y eigenvectores de una matriz, es la sensibilidad de los mismos ante perturbaciones en la matriz, ver {ref}`Condición de un problema y estabilidad de un algoritmo <CPEA>`. Diferentes eigenvalores o eigenvectores de una matriz no necesariamente son igualmente sensibles a perturbaciones en la matriz.
# ```{admonition} Observación
# :class: tip
#
# La condición del problema del cálculo de eigenvalores y eigenvectores de una matriz **no** es igual a la condición del problema de resolver un sistema de ecuaciones lineales, ver {ref}`Número de condición de una matriz <NCM>`.
#
# ```
# Se prueba que la condición de un eigenvalor **simple** de una matriz $A$ está dado por $\frac{1}{|y^Tx|}$ con $x$ eigenvector derecho, $y$ eigenvector izquierdo de $A$ ambos asociados al eigenvalor simple y normalizados esto es: $x^Tx = y^Ty=1$.
# ```{admonition} Comentarios
#
# * Para los casos en que: $\lambda$ eigenvalor de $A$ sea simple, $A$ sea diagonalizable, existen eigenvectores izquierdos y derechos asociados a un eigenvalor de $A$ tales que $y^Tx \neq 0$. En tales casos, el análisis del condicionamiento del problema del cálculo de eigenvalores y eigenvectores es más sencillo de realizar que para matrices no diagonalizables o eigenvalores con multiplicidad algebraica mayor a $1$. En particular, los eigenvalores de una matriz simétrica están muy bien condicionados: las perturbaciones en $A$ únicamente perturban a los eigenvalores en una magnitud medida con la norma de las perturbaciones y no depende de otros factores, por ejemplo del número de condición de $A$.
#
# * La sensibilidad de un eigenvector depende de la sensibilidad de su eigenvalor asociado y de la distancia de tal eigenvalor de otros eigenvalores.
#
# * Los eigenvalores que son "cercanos" o aquellos de multiplicidad mayor a $1$ pueden ser mal condicionados y por lo tanto difíciles de calcularse de forma exacta y precisa en especial si la matriz es defectuosa (no diagonalizable). Puede mejorarse el número de condición si se escala el problema por una matriz diagonal y similar a $A$, ver {ref}`similitud <SIMILITUD>`.
# ```
# (SIMILITUD)=
# ## Similitud
# - Si estoy haciendo transformaciones (e.g. hacerla diagonal superior), ¿qué me garantiza que se respeta el espectro?
# - Similitud es lo que nos ayuda a evaluar eso.
# ```{admonition} Definición
#
# Si existe $X \in \mathbb{R}^{n \times n}$ tal que $B = XAX^{-1}$ con $A, B \in \mathbb{R}^{n \times n}$ entonces $A$ y $B$ se nombran similares.
#
# ```
# ```{admonition} Observación
# :class: tip
#
# Las matrices que son similares tienen el mismo espectro, de hecho: $Ax = \lambda x$ si y sólo si $By = \lambda y$ para $y=Xx$. Lo anterior quiere decir que los eigenvalores de una matriz son **invariantes** ante cambios de bases o representación en coordenadas distintas.
#
# ```
# ### Ejemplo
# Dada la matriz
#
# $$A=
# \left [
# \begin{array}{cccc}
# -1 & -1 & -1 & -1\\
# 0 & -5 & -16 & -22\\
# 0 & 3 & 10 & 14\\
# 4 & 8 & 12 & 14
# \end{array}
# \right ]
# $$
# Definir matrices $B_1, B_2$ similares a $A$ a partir de las matrices:
#
# $$
# \begin{array}{l}
# X_1 =
# \left [
# \begin{array}{cccc}
# 2 & -1 & 0 & 0\\
# -1 & 2 & -1 & 0\\
# 0 & -1 & 2 & -1\\
# 0 & 0 & -1 & 1
# \end{array}
# \right ],
# X_2 = \left [
# \begin{array}{cccc}
# 2 & -1 & 1 & 0\\
# -1 & 2 & 0 & 0\\
# 0 & -1 & 0 & 0\\
# 0 & 0 & 0 & 1
# \end{array}
# \right ]
# \end{array}
# $$
# y verificar que los eigenvalores de $A$ son los mismos que los de $B_1, B_2$, esto es, tienen el mismo espectro.
# - Las matrices $X$ nos ayudan a preservar el espectro.
A = np.array([[-1, -1 , -1, -1],
[0, -5, -16, -22],
[0, 3, 10, 14],
[4, 8, 12, 14.0]])
X1 = np.array([[2, -1, 0, 0],
[-1, 2, -1, 0],
[0, -1, 2, -1],
[0, 0, -1, 1.0]])
# $B_1 = X_1^{-1}AX_1$:
# ```{margin}
#
# Calculamos $B1$ explícitamente para revisar qué forma tiene pero no es necesario.
#
# ```
# - Aqui estamos usando otra vez el `solve` aunque con ganamos en costo computacional.
B1 = np.linalg.solve(X1, A)@X1
print(B1)
X2 = np.array([[2, -1, 1, 0],
[-1, 2, 0, 0],
[0, -1, 0, 0],
[0, 0, 0, 1.0]])
# $B_2 = X_2^{-1}AX_2$:
# ```{margin}
#
# Calculamos $B2$ explícitamente para revisar qué forma tiene pero no es necesario.
#
# ```
B2 = np.linalg.solve(X2, A)@X2
print(B2)
# **$B1$ y $B2$ son similares a $A$ por tanto tienen los mismos eigenvalores:**
evalue, evector = np.linalg.eig(A)
# ```{margin}
#
# `evalue` son los eigenvalores de $A$.
#
# ```
print(evalue)
evalue_B1, evector_B1 = np.linalg.eig(B1)
# ```{margin}
#
# `evalue_B1` son los eigenvalores de $B_1$, obsérvese que son iguales a los de $A$ salvo el orden.
#
# ```
print(evalue_B1)
evalue_B2, evector_B2 = np.linalg.eig(B2)
# ```{margin}
#
# `evalue_B2` son los eigenvalores de $B_2$, obsérvese que son iguales a los de $A$ salvo el orden.
#
# ```
print(evalue_B2)
# Los eigenvectores **no son los mismos** pero pueden obtenerse vía multiplicación de matrices:
# - Los vectores van a generar el mismo subespacio vectorial.
# ```{margin}
#
# Elegimos un eigenvalor de $A$.
#
# ```
print(evalue[1])
# ```{margin}
#
# Y elegimos el mismo eigenvalor en el *array* `evalue_B1` para $B_1$ que para este ejemplo corresponde al índice $1$ (el mismo que en `evalue` pero podría haber sido otro).
#
# ```
print(evalue_B1[1])
# ```{margin}
#
# Su correspondiente eigenvector en el índice $1$ del *array* `evector_B1`.
#
# ```
print(evector_B1[:,1])
# **$X^{-1}x$ es eigenvector de $B_1$ para $x$ eigenvector de $A$**:
# ```{margin}
#
# `evector[:,1]` es el eigenvector de $A$ correspondiente al eigenvalor `evalue[1]`. En esta celda se hace el producto $X_1^{-1}x$ y `evector[:,1]` representa a $x$.
#
# ```
X1_inv_evector = np.linalg.solve(X1, evector[:,1])
print(X1_inv_evector)
print(B1@(X1_inv_evector))
# ```{margin}
#
# Se verifica que $B1(X_1^{-1}x) = \lambda (X_1^{-1}x)$ con $\lambda$ igual al valor `evalue_B1[1]`.
#
# ```
print(evalue_B1[1]*(X1_inv_evector))
# ```{admonition} Observación
# :class: tip
#
# Obsérvese que son los mismos eigenvectores salvo una constante distinta de cero.
#
# ```
print(evector_B1)
# ```{margin}
#
# El valor `1.33532534` es la primera entrada de `X1_inv_evector` que es $X_1^{-1}x$ y $x$ eigenvector de $A$. El valor `2.91920903` es la segunda entrada de `X_1_inv_evector`. Las entradas restantes son cercanas a cero.
# ```
print(1.33532534e+00/evector_B1[0,1])
print(2.91920903e+00/evector_B1[1,1])
# La constante es aproximadamente $-3.21$:
# ```{margin}
#
# `evector_B1` fue calculado con la función `eig` pero en la siguiente celda se observa que no es necesario si se tiene un eigenvector de $A$.
# ```
print(evector_B1[:,1]*(-3.21))
# - Con esto ya verificamos que se trata del mismo eigenvector.
# ```{margin}
#
# Recuerda que `X_1_inv_evector` es $X_1^{-1}x$ con $x$ eigenvector de $A$ que en este caso se utilizó `evector[:,1]`.
#
# ```
print(B1@(X1_inv_evector))
# ```{margin}
#
# Se comprueba que $X_1^{-1}x$ es eigenvector de $B$ si $x$ es eigenvector de $A$.
# ```
print(evalue_B1[1]*(X1_inv_evector))
# Como $A$ tiene eigenvalores distintos entonces es diagonalizable, esto es existen $X_3, \Lambda$ tales que $X_3^{-1} A X_3 = \Lambda$.
# - Las matrices que tienen distintos eigenvalores son diagonalizables.
X_3 = evector
Lambda = np.diag(evalue)
print(A)
print(np.linalg.solve(X_3, A)@X_3)
print(Lambda)
# ```{admonition} Comentario
#
# **$X_1$ diagonaliza a $A$ por bloques, $X_2$ triangulariza a $A$ por bloques y $X_3$ diagonaliza a $A$.** Las tres matrices representan al mismo operador lineal (que es una transformación lineal del espacio vectorial sobre sí mismo) pero en **coordenadas diferentes**. Un aspecto muy **importante** en el álgebra lineal es representar a tal operador lineal en unas coordenadas lo más simple posible. En el ejemplo la matriz $X_3$, que en sus columnas están los eigenvectores de $A$, ayuda a representarlo de forma muy simple.
#
# ```
# - Hay algoritmos que transformarán las matrices en lo más sencillo posible. Por ejemplo, una matriz casi diagnoal.
# - Vemos que en este caso, el método con las $X_3$ es el mejor porque nos da el resultado más simple.
# ```{admonition} Observación
# :class: tip
#
# $X_3$ es una matriz que diagonaliza a $A$ y tiene en sus columnas a eigenvectores de $A$, si el objetivo es diagonalizar a una matriz **no es necesario** resolver un problema de cálculo de eigenvalores-eigenvectores pues cualquier matriz $X$ no singular puede hacer el trabajo. Una opción es considerar una factorización para $A$ simétrica del tipo $LDL^T$ (que tiene un costo computacional bajo para calcularse), la matriz $L$ no es ortogonal y la matriz $D$ tiene los pivotes que se calculan en la eliminación Gaussiana, ver {ref}` Operaciones y transformaciones básicas del Álgebra Lineal Numérica <OTBALN>`.
#
# ```
# ```{admonition} Ejercicio
# :class: tip
#
# Considera
#
# $$A=
# \left [
# \begin{array}{cccc}
# -2 & -1 & -5 & 2\\
# -9 & 0 & -8 & -2\\
# 2 & 3 & 11 & 5\\
# 3 & -5 & -13 & -7
# \end{array}
# \right ]
# $$
#
# Define $X_1$ tal que $X_1^{-1}AX_1$ sea diagonal.
# ```
# ### Ejemplo
import sympy
import matplotlib.pyplot as plt
# Considérese la siguiente ecuación cuadrática:
#
# $$\frac{\tilde{x}^2}{16} + \frac{\tilde{y}^2}{9} = 1.$$
#
# Con Geometría Analítica sabemos que tal ecuación representa una elipse. Además si
#
D = sympy.Matrix([[sympy.Rational(1,16), 0],
[0, sympy.Rational(1,9)]])
sympy.pprint(D)
# Entonces el producto
#
# $$\left [ \begin{array}{c}
# \tilde{x}\\
# \tilde{y}
# \end{array}
# \right ] ^TD
# \left [
# \begin{array}{c}
# \tilde{x}\\
# \tilde{y}
# \end{array}
# \right ]
# $$
#
# es:
x_tilde, y_tilde = sympy.symbols("x_tilde, y_tilde")
x_y_tilde = sympy.Matrix([x_tilde, y_tilde])
sympy.pprint((x_y_tilde.T*D*x_y_tilde)[0])
# ```{admonition} Definición
#
# Al producto $x^TAx$ con $A$ simétrica se le nombra forma cuadrática y es un número en $\mathbb{R}$.
#
# ```
# Rotemos al [eje mayor de la elipse](https://en.wikipedia.org/wiki/Semi-major_and_semi-minor_axes) un ángulo de $\theta = \frac{\pi}{3}$ con una {ref}`transformación de rotación <TROT>` que genera la ecuación matricial:
#
# $$\begin{array}{l}
# \left[
# \begin{array}{c}
# x\\
# y
# \end{array}
# \right ]
# =
# \left [
# \begin{array}{cc}
# \cos(\theta) & -\sin(\theta)\\
# \sin(\theta) & \cos(\theta)
# \end{array}
# \right ]
# \left[
# \begin{array}{c}
# \tilde{x}\\
# \tilde{y}
# \end{array}
# \right ]
# =
# \left [
# \begin{array}{cc}
# \frac{1}{2} & -\frac{\sqrt{3}}{2}\\
# \frac{\sqrt{3}}{2} & \frac{1}{2}
# \end{array}
# \right ]
# \left[
# \begin{array}{c}
# \tilde{x}\\
# \tilde{y}
# \end{array}
# \right ]
# =
# Q\left[
# \begin{array}{c}
# \tilde{x}\\
# \tilde{y}
# \end{array}
# \right ]
# \end{array}
# $$
#
# donde: $Q$ es la matriz de rotación en sentido contrario a las manecillas del reloj por el ángulo $\theta$.
# Esto es:
#
# $$
# \begin{eqnarray}
# x =\frac{\tilde{x}}{2} - \frac{\tilde{y}\sqrt{3}}{2} \nonumber \\
# y =\frac{\tilde{x}\sqrt{3}}{2} + \frac{\tilde{y}}{2} \nonumber
# \end{eqnarray}
# $$
# Despejando $\tilde{x},\tilde{y}$ y sustituyendo en $\frac{\tilde{x}^2}{16} + \frac{\tilde{y}^2}{9} = 1$ resulta en la ecuación:
#
#
# +
theta = sympy.pi/3
Q = sympy.Matrix([[sympy.cos(theta), -sympy.sin(theta)],
[sympy.sin(theta), sympy.cos(theta)]])
x,y = sympy.symbols("x, y")
x_tilde = (Q.T*sympy.Matrix([x,y]))[0]
y_tilde = (Q.T*sympy.Matrix([x,y]))[1]
sympy.pprint((x_tilde**2/16 + y_tilde**2/9).expand()*576)
# -
# - Vemos en este caso que estamos obteniendo la representación de una elipse pero en una forma un poco más compleja.
# O equivalentemente el producto
#
# $$\left [ \begin{array}{c}
# x\\
# y
# \end{array}
# \right ]^T A
# \left [
# \begin{array}{c}
# x\\
# y
# \end{array}
# \right ]
# $$
#
# ```{margin}
#
# Esta es una ecuación de una elipse inclinada.
#
# ```
x_y = sympy.Matrix([x,y])
A = Q*D*Q.T
sympy.pprint(((x_y.T*A*x_y)[0]).expand()*576)
# con $A$ matriz dada por $A=QDQ^T$:
# - Vemos en este caso que la $A$ y la $D$ serán similares (mismos eigenvalores)
# ```{margin}
#
# Observa que $A$ es **simétrica**.
#
# ```
sympy.pprint(A)
# En este ejemplo la matriz $Q$ de rotación es la matriz que diagonaliza ortogonalmente a $A$ pues: $Q^TAQ = D.$
#
# Para realizar la **gráfica** de la elipse con *NumPy* observar que:
# - Aquí podemos ver que se preserva la elipse pero con distintos eigenvectores.
# ```{margin}
#
# Estas ecuaciones nos indican que la misma elipse se puede representar en diferentes coordenadas. El cambio de coordenadas se realiza con la matriz $Q$.
#
# ```
# $$
# \begin{eqnarray}
# 1&=&57x^2 - 14 \sqrt{3}xy + 43 y^2 \nonumber \\
# &=& \left [ \begin{array}{c}
# x\\
# y
# \end{array}
# \right ]^T A
# \left [
# \begin{array}{c}
# x\\
# y
# \end{array}
# \right ] \nonumber \\
# &=& \left [ \begin{array}{c}
# x\\
# y
# \end{array}
# \right ]^T QDQ^T \left [
# \begin{array}{c}
# x\\
# y
# \end{array}
# \right ] \nonumber \\
# &=& \left(Q^T \left [ \begin{array}{c}
# x\\
# y
# \end{array}
# \right ]\right)^TD\left(Q^T \left [ \begin{array}{c}
# x\\
# y
# \end{array}
# \right ]\right) \nonumber \\
# &=& \left [ \begin{array}{c}
# \tilde{x}\\
# \tilde{y}
# \end{array}
# \right ] ^TD
# \left [
# \begin{array}{c}
# \tilde{x}\\
# \tilde{y}
# \end{array}
# \right ] \nonumber \\
# &=& \frac{\tilde{x}^2}{16} + \frac{\tilde{y}^2}{9} \nonumber
# \end{eqnarray}
# $$
# **Gráfica para eigenvalores ordenados de forma decreciente en la diagonal de la matriz $D$.**
# ```{margin}
#
# Usamos [eig](https://numpy.org/doc/stable/reference/generated/numpy.linalg.eig.html) para el cálculo numérico de eigenvalores, eigenvectores de $A$.
#
# ```
A_np = np.array(A.evalf(),dtype = float)
evalue, evector = np.linalg.eig(A_np)
Q_np = evector
D_np = np.diag([evalue[0], evalue[1]])
print(Q_np)
Q = sympy.Matrix([Q[1,:],-Q[0,:]])
sympy.pprint(Q)
print(D_np)
D = sympy.Matrix([[D[1,1], 0],
[0, D[0,0]]])
sympy.pprint(D)
small_value = 1e-4
d1_inv=1/4
d2_inv=1/3
density=1e-2 + small_value
x=np.arange(-1/d1_inv,1/d1_inv,density)
y1=1/d2_inv*np.sqrt(1-(d1_inv*x)**2)
y2=-1/d2_inv*np.sqrt(1-(d1_inv*x)**2)
#transform
x_y1_hat = np.column_stack((x,y1))
x_y2_hat = np.column_stack((x,y2))
apply_Q = lambda vec : np.transpose(Q@np.transpose(vec))
Q_to_vector_1 = apply_Q(x_y1_hat)
Q_to_vector_2 = apply_Q(x_y2_hat)
fig = plt.figure(figsize=(12, 7))
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)
#first plot
ax1.plot(Q_to_vector_1[:,0],Q_to_vector_1[:,1],'g',
Q_to_vector_2[:,0],Q_to_vector_2[:,1],'g')
ax1.set_title("$57x^2-14\\sqrt{3}xy+43y^2=1$", fontsize=18)
ax1.set_xlabel("Ejes coordenados típicos")
ax1.axhline(color='r')
ax1.axvline(color='r')
#second plot
evector_1 = 1/d1_inv*Q_np[:,0]
evector_2 = 1/d2_inv*Q_np[:,1]
Evector_1 = np.row_stack((np.zeros(2), evector_1))
Evector_2 = np.row_stack((np.zeros(2), evector_2))
ax2.plot(Q_to_vector_1[:,0],Q_to_vector_1[:,1],
color='g', label = "Elipse")
ax2.plot(Q_to_vector_2[:,0],Q_to_vector_2[:,1],
color='g', label = "_nolegend_")
ax2.plot(Evector_1[:,0], Evector_1[:,1],
color='b', label = "Eigenvector Q[:,0], define al semieje mayor principal de la elipse")
ax2.plot(-Evector_1[:,0], -Evector_1[:,1],
color='b', label = "_nolegend_")
ax2.plot(Evector_2[:,0], Evector_2[:,1],
color='m', label = "Eigenvector Q[:,1], define al semieje menor principal de la elipse")
ax2.plot(-Evector_2[:,0], -Evector_2[:,1],
color='m', label = "_nolegend_")
ax2.set_title("$\\frac{\\tilde{x}^2}{16} + \\frac{\\tilde{y}^2}{9}=1$", fontsize=18)
ax2.set_xlabel("Ejes coordenados rotados")
ax2.legend(bbox_to_anchor=(1, 1))
fig.suptitle("Puntos en el plano que cumplen $z^TAz=1$ y $\\tilde{z}^TD\\tilde{z}=1$")
ax2.grid()
plt.show()
# - Podemos ver una gran diferencia en la complejidad de las dos ecuaciones que dibujan a la elipse.
# ```{margin}
#
# Recuerda que $A = Q D Q^T$, $A$ es similar a $D$ matriz diagonal y $Q$ es ortogonal.
#
# ```
# En la gráfica anterior se representa la rotación de los ejes coordenados definidos por los vectores canónicos $e_1, e_2$ y los rotados definidos por los eigenvectores de $A$. Los eigenvectores de $A$ están en las columnas de $Q$. La primera columna de $Q$ define al eje mayor principal de la elipse y la segunda columna al eje menor principal. La longitud de los semiejes están dados respectivamente por la raíz cuadrada de los recíprocos de los eigenvalores de $A$ que en este caso son: $\frac{1}{9}, \frac{1}{16}$, esto es: $3$ y $4$. Ver por ejemplo: [Principal_axis_theorem](https://en.wikipedia.org/wiki/Principal_axis_theorem), [Diagonalizable_matrix](https://en.wikipedia.org/wiki/Diagonalizable_matrix).
# ```{admonition} Ejercicio
# :class: tip
#
# Rotar los ejes coordenados $45^o$ la ecuación de la elipse:
#
# $$13x^2+10xy+13y^2=72$$
#
# para representar tal ecuación alineando los ejes mayor y menor de la elipse a sus eigenvectores. Encontrar las matrices $Q, D$ tales que $A=QDQ^T$ con $Q$ ortogonal y $D$ diagonal.
#
# ```
# ## Algunos algoritmos para calcular eigenvalores y eigenvectores
# Dependiendo de las siguientes preguntas es el tipo de algoritmo que se utiliza:
#
# * ¿Se requiere el cómputo de todos los eigenvalores o de sólo algunos?
#
# * ¿Se requiere el cómputo de únicamente los eigenvalores o también de los eigenvectores?
#
# * ¿$A$ tiene entradas reales o complejas?
#
# * ¿$A$ es de dimensión pequeña y es densa o grande y rala?
#
# * ¿$A$ tiene una estructura especial o es una matriz general?
# Para la última pregunta a continuación se tiene una tabla que resume las estructuras en las matrices que son relevantes para problemas del cálculo de eigenvalores-eigenvectores:
# |Estructura|Definición|
# |:---:|:---:|
# |Simétrica|$A=A^T$|
# |Ortogonal|$A^TA=AA^T=I_n$|
# |Normal|$A^TA = AA^T$|
# Ver {ref}`Ejemplos de matrices normales <EJMN>`.
# (EJMN)=
# ### Una opción (inestable numéricamente respecto al redondeo): encontrar raíces del polinomio característico...
# ```{margin}
#
# Como ejemplo que no es posible expresar las raíces o ceros por una fórmula cerrada que involucren a los coeficientes, operaciones aritméticas y raíces $\sqrt[n]{\cdot}$ para polinomios de grado mayor a $4$, considérese las raíces de $x^5 - x^2 + 1 = 0$.
#
# ```
# Por definición, los eigenvalores de $A \in \mathbb{R}^{n \times n}$ son las raíces o ceros del polinomio característico $p(z)$ por lo que un método es calcularlas vía tal polinomio. Sin embargo, **no es un buen método** calcular tales raíces o ceros pues para una $n > 4$ [Abel](https://en.wikipedia.org/wiki/Abel%E2%80%93Ruffini_theorem) probó de forma teórica que las raíces en general no son posibles expresarlas por una fórmula cerrada que involucren los coeficientes, operaciones aritméticas y raíces $\sqrt[n]{\cdot}$ . Por lo anterior para calcular eigenvalores de matrices con dimensión $n>4$ requiere de un **método iterativo**.
# ```{margin}
#
# Como ejemplo de este enunciado considérese:
#
# $$A=\left[
# \begin{array}{cc}
# 1 & \epsilon\\
# \epsilon & 1\\
# \end{array}
# \right]
# $$
#
# cuyos eigenvalores son $1 + \epsilon$, $1 - \epsilon$ con $\epsilon$ menor que $\epsilon_{maq}$. Usando aritmética en el SPF se prueba que las raíces del polinomio característico es $1$ de multiplicidad $2$.
# ```
# Además de lo anterior, en ciertas bases de polinomios, por ejemplo $\{1, x, x^2, \dots, x^n\}$, los coeficientes de los polinomios numéricamente no están bien determinados por los errores por redondeo y las raíces de los polinomios son muy sensibles a perturbaciones de los coeficientes, esto es, es un problema mal condicionado, ver {ref}`condición de un problema y estabilidad de un algoritmo <CPEA>`. Ver [Wilkinson's polynomial](https://en.wikipedia.org/wiki/Wilkinson%27s_polynomial) para un ejemplo.
# ### Alternativas
# Revisaremos en la nota {ref}`Algoritmos y aplicaciones de eigenvalores, eigenvectores de una matriz <AAEVALEVEC>` algunos algoritmos como:
#
# * Método de la potencia y método de la potencia inversa o iteración inversa.
#
# * Iteración por el cociente de Rayleigh.
#
# * Algoritmo QR.
#
# * Método de rotaciones de Jacobi.
# ---
# ## Ejemplos de matrices normales
# ```{sidebar} Descomposición espectral para matrices normales
#
# Las matrices normales generalizan al caso de entradas en $\mathbb{C}$ la diagonalización ortogonal al ser **unitariamente diagonalizables**. $A \in \mathbb{C}^{n \times n}$ es normal si y sólo si $A = U \Lambda U^H$ con $U$ matriz unitaria (generalización de una matriz ortogonal a entradas $\mathbb{C}$), $U^H$ la conjugada transpuesta de $U$ y $\Lambda$ matriz diagonal. Para $A \in \mathbb{R}^{n \times n}$ lo anterior se escribe como: $A$ es simétrica si y sólo si es ortogonalmente diagonalizable: $A = Q \Lambda Q^T$ (ver {ref}`descomposición espectral <DESCESP>`).
#
# ```
# $$\begin{array}{l}
# \left[
# \begin{array}{cc}
# 1 &-2 \\
# 2 &1
# \end{array}
# \right],
# \left[
# \begin{array}{ccc}
# 1 &2 & 0\\
# 0 & 1 & 2\\
# 2 & 0 & 1
# \end{array}
# \right]
# \end{array}
# $$
# Otro ejemplo:
#
# $$A =
# \left[
# \begin{array}{ccc}
# 1 &1 & 0\\
# 0 & 1 & 1\\
# 1 & 0 & 1
# \end{array}
# \right]
# $$
A = np.array([[1, 1, 0],
[0, 1, 1],
[1, 0, 1.0]])
print(A.T@A)
# ```{margin}
#
# Como $A$ es normal entonces se cumple que $AA^T=A^TA$.
#
# ```
print(A@A.T)
evalue, evector = np.linalg.eig(A)
print('eigenvalores:')
print(evalue)
# ```{margin}
#
# Se verifica que los eigenvectores de este ejemplo forman un conjunto linealmente independiente pues $A$ es normal.
#
# ```
print('eigenvectores:')
print(evector)
# ```{margin}
#
# Para una matriz normal $A$ se cumple que es unitariamente diagonalizable y $A = Q \Lambda Q^H$ donde: $Q^H$ es la conjugada transpuesta de $Q$.
#
# ```
print('descomposición espectral:')
Lambda = np.diag(evalue)
Q = evector
print('QLambdaQ^H:')
print(Q@Lambda@Q.conjugate().T)
print(A)
# ```{margin}
#
# Observa que $Q^HQ=QQ^H = I_3$ donde: $Q^H$ es la conjugada transpuesta de $Q$.
# ```
print(Q.conjugate().T@Q)
# ```{admonition} Observación
# :class: tip
#
# El problema del cálculo de eigenvalores para matrices normales es bien condicionado.
#
# ```
# **Preguntas de comprehensión:**
#
# 1)¿Qué son los eigenvalores de una matriz y qué nombre recibe el conjunto de eigenvalores de una matriz?
#
# 2)¿Cuántos eigenvalores como máximo puede tener una matriz?
#
# 3)¿Qué característica geométrica tiene multiplicar una matriz por su eigenvector?
#
# 4)¿A qué se le nombra matriz diagonalizable o *non defective*?
#
# 5)¿Cuál es el número de condición del problema de cálculo de eigenvalores con multiplicidad simple para una matriz simétrica?
#
# 6)¿Verdadero o Falso?
#
# a.Una matriz es diagonalizable entonces tiene eigenvalores distintos.
#
# b.Una matriz con eigenvalores distintos es diagonalizable.
#
# c.Si $A=XDX^{-1}$ con $X$ matriz invertible entonces en la diagonal de $D$ y en las columnas de $X$ encontramos eigenvalores y eigenvectores derechos de $A$ respectivamente.
#
# 7)Describe la descomposición espectral de una matriz simétrica.
#
# 8)¿Qué característica tienen las matrices similares?
# **Referencias:**
#
# 1. <NAME>, Scientific Computing. An Introductory Survey, McGraw-Hill, 2002.
#
# 2. <NAME>, <NAME>, Matrix Computations, John Hopkins University Press, 2013.
#
# 3. <NAME>, <NAME>, Numerical linear algebra, SIAM, 1997.
#
# 4. <NAME>, Matrix Analysis and Applied Linear Algebra, SIAM, 2000.
| libro_optimizacion/temas/II.computo_matricial/2.2/Eigenvalores_y_eigenvectores.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="fKsOW48t4oos"
# # **Deteksi Masker Menggunakan CNN - MobileNetV2**
#
# Program *Machine Learning* (*Deep Learning*) untuk mendeteksi pemakaian masker wajah. Program dibuat menggunakan metode CNN dengan arsitektur MobileNetV2.
# + [markdown] id="95IMc2Pb4sZ2"
# ## Mengimpor *Library*
# + id="VcKb_59jtr6m"
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from shutil import copyfile
from os import listdir
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
# + [markdown] id="zk6MTPs94kcm"
# ## *Preprocessing* Dataset
# + id="XVw0GMMPuZqB"
# Inisialisasi nilai Initial Learning Rate, berapa banyak Epoch Pelatihan, dan Batch Size
INIT_LR = 1e-4
EPOCHS = 10
BS = 32
# + id="C04TF99RulAF"
# Mengetahui jumlah citra pada data train menggunakan masker dengan tidak menggunakan masker
print("Jumlah gambar dengan masker wajah:",len(os.listdir('deteksi masker/train/with_mask')))
print("Jumlah gambar tanpa masker wajah:",len(os.listdir('deteksi masker/train/without_mask')))
# + id="ABqLCN9J4_n5"
# Mengetahui jumlah citra pada data train dan persentasenya
def data_summary(main_path):
yes_path = main_path+'with_mask'
no_path = main_path+'without_mask'
# Jumlah representasi data positif
m_pos = len(listdir(yes_path))
# Jumlah representasi data negatif
m_neg = len(listdir(no_path))
# Jumlah semua data
m = (m_pos+m_neg)
pos_prec = (m_pos*100.0)/m
neg_prec = (m_neg*100.0)/m
print(f"Jumlah semua data: {m}")
print(f"Persentasi data positif: {pos_prec}%, dengan jumlah data positif: {m_pos}")
print(f"Persentasi data negatif: {neg_prec}%, dengan jumlah data negatif: {m_neg}")
augmented_data_path = 'deteksi masker/train/'
data_summary(augmented_data_path)
# + id="4uSqPmAN5BOX"
# Me-split data
def split_data(SOURCE, TRAINING, TESTING, SPLIT_SIZE):
dataset = []
for unitData in os.listdir(SOURCE):
data = SOURCE + unitData
if(os.path.getsize(data) > 0):
dataset.append(unitData)
else:
print('Skipped ' + unitData)
print('Invalid file i.e zero size')
train_set_length = int(len(dataset) * SPLIT_SIZE)
test_set_length = int(len(dataset) - train_set_length)
train_set = dataset[0:train_set_length]
test_set = dataset[-test_set_length:]
for unitData in train_set:
temp_train_set = SOURCE + unitData
final_train_set = TRAINING + unitData
copyfile(temp_train_set, final_train_set)
for unitData in test_set:
temp_test_set = SOURCE + unitData
final_test_set = TESTING + unitData
copyfile(temp_test_set, final_test_set)
YES_SOURCE_DIR = "deteksi masker/source/with_mask/"
TRAINING_YES_DIR = "deteksi masker/train/with_mask/"
TESTING_YES_DIR = "deteksi masker/test/with_mask/"
NO_SOURCE_DIR = "deteksi masker/source/without_mask/"
TRAINING_NO_DIR = "deteksi masker/train/without_mask/"
TESTING_NO_DIR = "deteksi masker/test/without_mask/"
split_size = .8
split_data(YES_SOURCE_DIR, TRAINING_YES_DIR, TESTING_YES_DIR, split_size)
split_data(NO_SOURCE_DIR, TRAINING_NO_DIR, TESTING_NO_DIR, split_size)
# + id="jAZw9LQF5C9q"
# Menampilkan jumlah citra pada data train dan test
print("Jumlah gambar dengan masker wajah di set training berlabel 'yes':", len(os.listdir('deteksi masker/train/with_mask')))
print("Jumlah gambar dengan masker wajah di set test berlabel 'yes':", len(os.listdir('deteksi masker/test/with_mask')))
print("Jumlah gambar tanpa masker wajah di set training berlabel 'no':", len(os.listdir('deteksi masker/train/without_mask')))
print("Jumlah gambar tanpa masker wajah di set test berlabel 'no':", len(os.listdir('deteksi masker/test/without_mask')))
# + [markdown] id="BqAL2Gqi5Epm"
# ### Membuat objek ImageDataGenerator dan Data Augmentasi
# + id="RFrkeYTB5GFk"
# Membentuk training image generator untuk data augmentation
TRAINING_DIR = "deteksi masker/train"
train_datagen = ImageDataGenerator(rescale=1.0/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')
train_generator = train_datagen.flow_from_directory(TRAINING_DIR,
batch_size=BS,
target_size=(150, 150))
# Membentuk validation image generator
VALIDATION_DIR = "deteksi masker/test"
validation_datagen = ImageDataGenerator(rescale=1.0/255)
validation_generator = validation_datagen.flow_from_directory(VALIDATION_DIR,
batch_size=BS,
target_size=(150, 150))
checkpoint = ModelCheckpoint('model-{epoch:03d}.model',monitor='val_loss',verbose=0,save_best_only=True,mode='auto')
# + [markdown] id="FUGoHrX46M7E"
# ## Membuat Model Jaringan CNN
# + id="itxVKtq85J-E"
# Arsitektur jaringan MobileNetV2
baseModel = MobileNetV2(weights="imagenet", include_top=False, input_tensor=Input(shape=(150, 150, 3)))
# + [markdown] id="MbpfhD325NXu"
# ### *Feature Extraction*
#
# Menggunakan model *pre-trained* untuk ekstraksi fitur (*feature extraction*) : Ketika bekerja dengan dataset kecil, adalah umum untuk mengambil keuntungan dari fitur yang dipelajari oleh model yang dilatih pada dataset yang lebih besar dalam domain yang sama.
# + id="PhLkC31y5LsL"
baseModel.trainable = False
baseModel.summary()
# + [markdown] id="3P8ouvCl5TIN"
# ## Tahap Pembuatan Model
# + id="hQ5Y4K3a5Q7I"
# Membentuk bagian head dari model yang akan ditempatkan pada base model
headModel = baseModel.output
headModel = Conv2D(100, (3,3), activation='relu', input_shape=(150, 150, 3))(headModel)
headModel = MaxPooling2D(pool_size=(2, 2))(headModel)
headModel = Flatten(name="flatten")(headModel)
headModel = Dropout(0.5)(headModel)
headModel = Dense(50, activation="relu")(headModel)
headModel = Dense(2, activation="softmax")(headModel)
# Menempatkan head model pada base model
model = Model(inputs=baseModel.input, outputs=headModel)
# Perulangan pada seluruh base model
for layer in baseModel.layers:
layer.trainable = False
# Persiapan kompilasi model
print("Mengkompilasi model...")
opt = Adam(learning_rate=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["accuracy"])
print(model.summary())
# + [markdown] id="KTmXT8od5ZzL"
# ### Melakukan Pelatihan Model
# + id="6SYV2aYw5VqN"
# Pelatihan model
print("Training head model...")
H = model.fit(train_generator,
epochs=EPOCHS,
validation_data=validation_generator,
callbacks=[checkpoint])
# + [markdown] id="jjq_whJO5e0A"
# ### Menampilkan Kurva Model Hasil Pelatihan
# + id="CYdwLx465YRr"
# Kurva train loss/accuracy
n = EPOCHS
plt.style.use('ggplot')
plt.figure()
plt.plot(np.arange(0, n), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, n), H.history["accuracy"], label="train_acc")
plt.title("Train Loss and Accuracy Graph")
plt.xlabel("Epochs")
plt.ylabel("Train Loss/Accuracy")
plt.legend(loc="upper right", bbox_to_anchor=(1.25, 1))
plt.savefig("plot_train.png")
# + id="lM3jBJBt5iOt"
# Kurva validation loss/accuracy
n = EPOCHS
plt.style.use('ggplot')
plt.figure()
plt.plot(np.arange(0, n), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, n), H.history["val_accuracy"], label="val_acc")
plt.title("Validation Loss and Accuracy Graph")
plt.xlabel("Train Epochs")
plt.ylabel("Value Loss/Accuracy")
plt.legend(loc="upper right", bbox_to_anchor=(1.25, 1))
plt.savefig("plot_value.png")
# + id="vGLqXxnJ5jh0"
# Kurva train dan validation loss/accuracy
n = EPOCHS
plt.style.use('ggplot')
plt.figure()
plt.plot(np.arange(0, n), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, n), H.history["accuracy"], label="train_acc")
plt.plot(np.arange(0, n), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, n), H.history["val_accuracy"], label="val_acc")
plt.title("Train and Validation (Loss and Accuracy) Graph")
plt.xlabel("Train Epochs")
plt.ylabel("Loss/Accuracy")
plt.legend(loc="upper right", bbox_to_anchor=(1.25, 1))
plt.savefig("plot_train_value.png")
# + [markdown] id="AaoAZgTz5mvL"
# ### Evaluasi Jaringan
# + id="-pSLc6qh5k4-"
# Evaluasi train loss dan accuracy
modelTLoss, modelTAccuracy = model.evaluate(train_generator)
print('Train Loss: {}'.format(modelTLoss))
print('Train Accuracy: {}'.format(modelTAccuracy ))
# + id="HhvudC4E5rtB"
# Evaluasi test loss dan accuracy
modelLoss, modelAccuracy = model.evaluate(validation_generator)
print('Test Loss: {}'.format(modelLoss))
print('Test Accuracy: {}'.format(modelAccuracy ))
# + [markdown] id="zbFuVwl15zy7"
# ## Melakukan Pengujian dengan WebCam menggunakan OpenCV
# + id="FWFkt1Zi50p0"
labels_dict={0:'Dengan Masker',1:'Tanpa Masker'}
color_dict={0:(0,255,0),1:(0,0,255)}
size = 4
webcam = cv2.VideoCapture(2) # Ubah value untuk menyesuaikan source kamera
# Meload file xml
classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
while True:
(rval, im) = webcam.read()
im=cv2.flip(im,1,1) # Flip ke act sebagai mirror
# Resize citra untuk mempercepat pendeteksian
mini = cv2.resize(im, (im.shape[1] // size, im.shape[0] // size))
# Mendeteksi multiScale / banyak wajah
faces = classifier.detectMultiScale(mini)
# Menandai kotak disekitar area wajah
for f in faces:
(x, y, w, h) = [v * size for v in f] # Scale shapesize
# Menyimpan hanya kotak wajah ke SubRecFaces
face_img = im[y:y+h, x:x+w]
resized = cv2.resize(face_img,(150,150))
normalized = resized/255.0
reshaped = np.reshape(normalized,(1,150,150,3))
reshaped = np.vstack([reshaped])
result = model.predict(reshaped)
# print(result)
label=np.argmax(result,axis=1)[0]
cv2.rectangle(im,(x,y),(x+w,y+h),color_dict[label],2)
cv2.rectangle(im,(x,y-40),(x+w,y),color_dict[label],-1)
cv2.putText(im, labels_dict[label], (x, y-10),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,255,255),2)
# Menampilkan citra
cv2.imshow('Face Mask Detection', im)
key = cv2.waitKey(10)
# Tekan Esc key di keyboard untuk menghentikan loop dan keluar
if key == 27: # Tombol Esc
break
# Stop video
webcam.release()
# Menutup semua windows yang berjalan
cv2.destroyAllWindows()
| cnn.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.3 64-bit (''base'': conda)'
# name: python_defaultSpec_1611924171085
# ---
# # Results Notebooks
# To run the training of DFC and DEC please use main.ipynb or main.py
#
# In this Notebook we focus on simply loading the models and demonstrating the results for the final DFC with its encoder or the DEC with encoder.
# * For this Notebook to work you need to change the ArgsDFC providing all the paths for the encoders and DFC
# * Two examples are given at the end of the notebook; Office31 data and mnist with ups
# + tags=[]
import argparse
import numpy as np
from sklearn.metrics import normalized_mutual_info_score
import torch
from torch import nn
import plotly
from dataloader import get_dataset
from kmeans import get_cluster_centers
from module import Encoder
from adverserial import adv_loss
from eval import predict, cluster_accuracy, balance
from utils import set_seed, AverageMeter, target_distribution, aff, inv_lr_scheduler
import os
import wandb # Used to log progress and plot graphs.
from vae import DFC_VAE
from vae import train as train_vae
from dfc import train as train_dfc
from dec import train as train_dec
from dfc import DFC
from resnet50_finetune import *
import torchvision.models as models
import pytorch_lightning as pl
from pl_bolts.models.autoencoders import VAE
import pandas as pd
from ArgsDFC import args as arg_class
# + tags=[]
#Set wandb loging offline, avoid the need for an account.
wandbrun = wandb.init(project="offline-run")
os.environ["WANDB_MODE"] = "dryrun"
# -
# ## Arguments
# Change the Arguments in the at the end of the notebook with the main run code. Arguments are given in file Args_notebook.py.
# ## Define Functions
def get_encoder(args, log_name, legacy_path, path, dataloader_list, device='cpu', encoder_type='vae'):
if encoder_type == 'vae':
print('Loading the variational autoencoder')
if legacy_path:
encoder = Encoder().to(device)
encoder.load_state_dict(torch.load(
legacy_path, map_location=device))
else:
if path:
model = DFC_VAE.load_from_checkpoint(path).to(device)
else:
model = train_vae(args, log_name, dataloader_list, args.input_height,
is_digit_dataset=args.digital_dataset, device=device).to(device)
encoder = model.encoder
elif encoder_type == 'resnet50': # Maybe fine tune resnet50 here
print('Loading the RESNET50 encoder')
if path:
print('from pretrained file')
encoder = models.resnet50(pretrained=False)
encoder.load_state_dict(torch.load(path))
else:
encoder = models.resnet50(pretrained=True, progress=True)
set_parameter_requires_grad(encoder, req_grad=False)
encoder = encoder.to(device)
else:
raise NameError('The encoder_type variable has an unvalid value')
wandb.watch(encoder)
return encoder
# + tags=[]
def subgroups_encoders(args,device):
print("Loading the golden standard group 0 encoder")
encoder_group_0 = get_encoder(args, "encoder_0", args.encoder_0_legacy_path, args.encoder_0_path, [
dataloader_0], device=device, encoder_type=args.encoder_type)
print("Loading the golden standard group 1 encoder")
encoder_group_1 = get_encoder(args, "encoder_1", args.encoder_1_legacy_path, args.encoder_1_path, [
dataloader_1], device=device, encoder_type=args.encoder_type)
return encoder_group_0, encoder_group_1
# -
def get_dec_groups(args, device):
print("Load group 0 initial cluster definitions")
cluster_centers_0 = get_cluster_centers(file_path=args.cluster_0_path, device=device)
print("Load group 1 initial cluster definitions")
cluster_centers_1 = get_cluster_centers(file_path=args.cluster_number, device=device)
#Load DEC pretrained with the weight of the fairness losses are set to 0.
# making this a DEC instead of a DFC
print("Load golden standard group 0 DEC")
dfc_group_0 = DFC(cluster_number=args.cluster_number, hidden_dimension=args.dfc_hidden_dim).to(device)
dec.load_state_dict(torch.load(args.dfc_0_path, map_location=device))
print("Load golden standard group 1 DEC")
dfc_group_0 = DFC(cluster_number=args.cluster_number,hidden_dimension=args.dfc_hidden_dim).to(device)
dec.load_state_dict(torch.load(args.dfc_1_path, map_location=device))
return cluster_centers_0, cluster_centers_1, dfc_group_0, dfc_group_1
def get_dfc_module(args,device):
print("Load DFC")
dfc = DFC(cluster_number=args.cluster_number,
hidden_dimension=args.dfc_hidden_dim).to(device)
dfc.load_state_dict(torch.load(args.dfc_path, map_location=device))
return dfc
def eval_results(args, dataloader_list, encoder, dfc, device):
encoder.eval()
dfc.eval()
print("Evaluate model")
predicted, labels = predict(dataloader_list, encoder, dfc, device=device,encoder_type = args.encoder_type)
predicted, labels = predicted.cpu().numpy(), labels.numpy()
print("Calculating cluster accuracy")
_, accuracy = cluster_accuracy(predicted, labels, args.cluster_number)
nmi = normalized_mutual_info_score(labels, predicted, average_method="arithmetic")
len_image_0 = len(dataloader_list[0])
print("Calculating balance")
bal, en_0, en_1 = balance(predicted, len_image_0, k =args.cluster_number)
save_name = args.dataset
print(f"{save_name} Train Accuracy:", accuracy, f"{save_name} Train NMI:", nmi, f"{save_name} Train Bal:", bal,'\n',
f"{save_name} Train Entropy 0:", en_0, '\n',
f"{save_name} Train Entropy 1:", en_1)
# ## Main Code
def main_pipeline(args):
set_seed(args.seed)
os.makedirs(args.log_dir, exist_ok=True)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if torch.cuda.is_available():
torch.cuda.set_device(args.gpu)
print(f"Using {device}")
dataloader_0, dataloader_1 = get_dataset[args.dataset](args)
dataloader_list = [dataloader_0, dataloader_1]
print("Loading Encoder type:",args.encoder_type)
encoder = get_encoder(args, "encoder", args.encoder_legacy_path, args.encoder_path, dataloader_list, device=device, encoder_type=args.encoder_type)
print("Running method", args.method)
if args.method == 'dfc':
# encoder_group_0, encoder_group_1, = subgroups_encoders(args,device)
# cluster_centers_0, cluster_centers_1, dfc_group_0, dfc_group_1 = get_dec_groups(args,device)
dfc = get_dfc_module(args,device)
eval_results(args,dataloader_list, encoder, dfc, device=device)
if args.method == 'dec':
print("Load cluster centers for final DEC")
cluster_centers = get_cluster_centers(args, encoder, args.cluster_number, [dataloader_0, dataloader_1],
args.cluster_path, device=device, save_name="clusters_dec")
print("Train final DEC")
dec = get_dec(args,
encoder, "DEC", device=device, centers=cluster_centers)
del encoder
del dfc
# ## DFC Run
# In this section we have the cells with all the steps to train a DFC.
# We first load the encoders used for for the two dec, if no path is selected then we train new ones.
# Next we load or train with K-means the cluster centers
# + tags=[]
# # Example run.
# mnist_ups_args = arg_class()
# mnist_ups_args.set_mnist_ups()
# main_pipeline(mnist_ups_args)
# + tags=[]
office_args = arg_class()
office_args.set_office31_load_models()
main_pipeline(office_args)
# + tags=[]
mtfl_args = arg_class()
mtfl_args.set_mtfl_load_models()
main_pipeline(mtfl_args)
# + tags=[]
#Finish loggin in wandb
wandbrun.finish()
| results.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: env
# language: python
# name: env
# ---
# # Analysing results for general experiment (series of n)
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# +
experiment_id = "full_run"
filename_results = f"results_experiment_{experiment_id}.json"
df_results = pd.read_json(f"../data/{filename_results}")
# df_results.loc[df_results["status"].isnull(), "status"] = "Optimal"
# -
df_results.head()
# ## Data Validation
# +
num_solvers = len(df_results["solver"].unique())
if num_solvers == 1:
assert (df_results["tindar_id"].value_counts() == 1).all()
elif num_solvers == 2:
assert (df_results["tindar_id"].value_counts() == 2).all()
else:
raise Exception(f"Data says {num_solvers} solvers. Only 1 or 2 allowed")
# -
# ## Objective value: difference pulp & heuristic
# +
def solver_difference(df_sub):
opt = df_sub.loc[df_sub["solver"] == "pulp"]
heur = df_sub.loc[df_sub["solver"] == "heuristic"]
opt_obj = opt["objective_value"].values[0]
heur_obj = heur["objective_value"].values[0]
opt_solvetime = opt["time"].values[0]
heur_solvetime = heur["time"].values[0]
if opt_obj == 0:
perc_difference = 0
else:
perc_difference = (opt_obj - heur_obj)/opt_obj
return pd.Series({
"objective_difference_abs": opt_obj - heur_obj,
"objective_difference_perc": perc_difference,
"solvetime_difference_abs": opt_solvetime - heur_solvetime,
"solvetime_difference_perc": (opt_solvetime - heur_solvetime)/heur_solvetime,
"n": df_sub["n"].values[0],
"connectedness": df_sub["connectedness"].values[0],
})
df_solver_difference = df_results.groupby(["tindar_id"]).apply(solver_difference)
df_solver_difference.head()
# -
# ## statistics
var = "time"
df_results.groupby(["solver", "n"]).apply(lambda x: x[var].mean())
var = "solvetime_difference_abs"
df_solver_difference.groupby("n").apply(lambda x: x[var].mean())
# ## visualizations
# +
var_x = "n"
var_y = "objective_difference_perc"
plt.figure()
plt.title(f"Scatterplot of relative objective difference\n((pulp-heuristic)/pulp) vs {var_x} for experiment {experiment_id}")
sns.scatterplot(
x = var_x,
y = var_y,
data = df_solver_difference
)
plt.savefig(f"../documentation/figures/scatterplot_{var_x}_vs_{var_y}_experiment_{experiment_id}")
# +
var_y = "solvetime_difference_perc"
plt.figure()
plt.title(f"Scatterplot of relative solvetime difference\n((heuristic-pulp)/heuristic) for experiment {experiment_id}")
sns.scatterplot(
x = var_x,
y = var_y,
data = df_solver_difference
)
plt.savefig(f"../documentation/figures/scatterplot_{var_x}_vs_{var_y}_experiment_{experiment_id}")
# -
# ### Heatmaps for targets vs(n, connectedness)
# +
var_y = "objective_difference_perc"
print(var_y)
df_n_conn = df_solver_difference.groupby(["n", "connectedness"]).apply(lambda x: x[var_y].mean()).reset_index()
df_n_conn["n"] = df_n_conn["n"].astype(int)
df_n_conn.columns = list(df_n_conn.columns[:2]) + [var_y]
df_pivot = df_n_conn.pivot("n", "connectedness", var_y)
plt.figure()
plt.title(f"Mean relative objective difference ((pulp-heuristic)/pulp)\ngrouped by n and connectedness")
sns.heatmap(df_pivot)
plt.savefig(f"../documentation/figures/heatmap_{var_y}_experiment_{experiment_id}")
# +
var_y = "solvetime_difference_perc"
print(var_y)
df_n_conn = df_solver_difference.groupby(["n", "connectedness"]).apply(lambda x: x[var_y].mean()).reset_index()
df_n_conn["n"] = df_n_conn["n"].astype(int)
df_n_conn.columns = list(df_n_conn.columns[:2]) + [var_y]
df_pivot = df_n_conn.pivot("n", "connectedness", var_y)
plt.figure()
plt.title(f"Mean relative solvetime difference ((heuristic-pulp)/heuristic)\ngrouped by n and connectedness")
sns.heatmap(df_pivot)
plt.savefig(f"../documentation/figures/heatmap_{var_y}_experiment_{experiment_id}")
| notebooks/2. Analyze_results_general.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + colab={} colab_type="code" id="WZfZS53P6R8W"
import tensorflow
from keras.optimizers import SGD
# + colab={} colab_type="code" id="1pAz9wHn6mbR"
from __future__ import print_function
import keras
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from PIL import Image
import cv2
batch_size = 128
num_classes = 10
epochs = 12
# input image dimensions
img_rows, img_cols = 32, 32
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
X_train = []
X_test = []
for i in range(len(x_train)):
X_train.append(cv2.resize(x_train[i], (32,32)))
for i in range(len(x_test)):
X_test.append(cv2.resize(x_test[i], (32,32)))
X_train = numpy.asarray(X_train)
X_test = numpy.asarray(X_test)
# + colab={"base_uri": "https://localhost:8080/", "height": 33} colab_type="code" id="bDTL_RaQyxt1" outputId="22214cbc-44ef-497e-94e0-e1d48f80449b"
X_train.shape
# + colab={"base_uri": "https://localhost:8080/", "height": 67} colab_type="code" id="cV4SehixoEyq" outputId="6a9997d1-e6e4-49d9-860c-1d95221cf286"
if K.image_data_format() == 'channels_first':
x_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
x_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)
x_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
#Convert to float and then normalize the images by dividing by 255(max value of a pixel)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# + colab={} colab_type="code" id="yD9HtyQj0TYc"
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# + colab={"base_uri": "https://localhost:8080/", "height": 753} colab_type="code" id="K52GB5Sq1GTP" outputId="9c6d0eff-34ef-427c-f81f-37e7dda58ae5"
model = Sequential()
model.add(Conv2D(64, (3, 3), activation='relu', input_shape=input_shape, padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), strides = (2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), strides = (2, 2)))
model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), strides = (2, 2)))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), strides = (2, 2)))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(512, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2), strides = (2, 2)))
model.add(Flatten())
model.add(Dense(4096, activation='relu'))
model.add(Dense(4096, activation='relu'))
model.add(Dense(512, activation='relu'))
model.add(Dense(10, activation='softmax'))
print(model.summary())
# + colab={} colab_type="code" id="91B-XN-o1XO8"
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
# + colab={"base_uri": "https://localhost:8080/", "height": 368} colab_type="code" id="N5u_TXO-1coI" outputId="20e82abc-d67c-4cc4-d17d-c1f8d998753e"
history = model.fit(x_train, y_train, batch_size=32, validation_data=(x_test,y_test), epochs=10, verbose=1)
# + colab={"base_uri": "https://localhost:8080/", "height": 50} colab_type="code" id="D3JqjYYF1oAa" outputId="779035d3-48e4-4e28-d107-732b4a2c3aab"
score = model.evaluate(x_test, y_test, batch_size=32)
print(score)
# + colab={"base_uri": "https://localhost:8080/", "height": 70} colab_type="code" id="e3w3dYBH6vmT" outputId="6187acdf-0549-4ca7-92a9-aaff01cd1663"
print("History", history.history)
print("history.history.keys():", history.history.keys())
# + colab={"base_uri": "https://localhost:8080/", "height": 376} colab_type="code" id="ndPrnMTN7CMk" outputId="b7a07b64-f291-4083-c444-0651b5e8dd87"
import matplotlib.pyplot as plt
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.title('Train_Accuracy vs Epochs')
plt.ylabel('Accuracy')
plt.xlabel('Epochs')
plt.grid()
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 376} colab_type="code" id="LCTfI64H7IBU" outputId="25924b51-de5a-4da7-d879-d8db5b071466"
plt.plot(history.history['val_acc'])
plt.title('Test(Validation)_Accuracy vs Epochs')
plt.ylabel('Accuracy')
plt.xlabel('Epochs')
plt.grid()
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 376} colab_type="code" id="yvvB4s-27g5m" outputId="376e66a0-50ce-4e9e-812a-c654a39d64c0"
plt.plot(history.history['loss'])
plt.title('Train_loss vs Epochs')
plt.ylabel('Loss')
plt.xlabel('Epochs')
plt.grid()
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 376} colab_type="code" id="5DdFnoLE7wwL" outputId="22763cc0-2ce5-440c-9041-82a5496c4a7d"
plt.plot(history.history['val_loss'])
plt.title('Test(Validation)_Loss vs Epochs')
plt.ylabel('Loss')
plt.xlabel('Epochs')
plt.grid()
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 652} colab_type="code" id="1bxARCdI74PV" outputId="fdf14bc4-3c53-48f0-b62c-95b2e9d37d53"
s_loss = []
s_acc = []
for j in range(-45,50,5):
rotate_test_x = []
for i in range(len(X_test)):
X_test_rotate = Image.fromarray(X_test[i])
new_image = X_test_rotate.rotate(j)
img_array = numpy.array(new_image)
rotate_test_x.append(img_array)
X_test_rotate = numpy.asarray(rotate_test_x)
X_test_rotate = X_test_rotate.reshape(X_test_rotate.shape[0], img_rows, img_cols, 1)
score = model.evaluate(X_test_rotate, y_test, batch_size=32)
print("Rotation degree: " +str(j) + " Score:" + str(score))
s_loss.append(score[0])
s_acc.append(score[1])
# + colab={"base_uri": "https://localhost:8080/", "height": 334} colab_type="code" id="TWUZoUrWGA7V" outputId="6dcbe2bb-dab6-4af3-db92-49ef8e883419"
s_loss
# + colab={"base_uri": "https://localhost:8080/", "height": 334} colab_type="code" id="HnzZ0PZ_Ja4T" outputId="21a138a0-6c19-4cf7-a9ce-ccbc28a8b5cc"
s_acc
# + colab={"base_uri": "https://localhost:8080/", "height": 376} colab_type="code" id="qG1RN_fgJcPV" outputId="b813712b-67b4-4c84-ac95-350cb88dd1ee"
plt.plot( range(-45,50,5), s_loss)
plt.title('Test_Loss vs degree')
plt.ylabel('Loss')
plt.xlabel('degree')
plt.grid()
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 376} colab_type="code" id="4mtGMJqYJrlo" outputId="efeb0f3b-6953-4945-c019-5db77250305d"
plt.plot( range(-45,50,5), s_acc)
plt.title('Test_Accuracy vs degree')
plt.ylabel('Accuracy')
plt.xlabel('degree')
plt.grid()
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 251} colab_type="code" id="EOeawANwJ_uV" outputId="c7580947-0af7-46b0-8cb5-c2c39471356c"
from PIL import ImageFilter
s_loss = []
s_acc = []
for j in range(0,7):
filter_test_x = []
for i in range(len(X_test)):
X_test_filter = Image.fromarray(X_test[i])
new_image = X_test_filter.filter(ImageFilter.GaussianBlur(radius=j))
img_array = numpy.array(new_image)
filter_test_x.append(img_array)
X_test_filter = numpy.asarray(filter_test_x)
X_test_filter = X_test_filter.reshape(X_test_filter.shape[0], img_rows, img_cols, 1)
score = model.evaluate(X_test_filter, y_test, batch_size=32)
print("Filter radius: " +str(j) + " Score:" + str(score))
s_loss.append(score[0])
s_acc.append(score[1])
# + colab={"base_uri": "https://localhost:8080/", "height": 376} colab_type="code" id="-ZIdBwFrN-b8" outputId="d1a05cc5-cb5e-41c3-b927-fc922d13def6"
plt.plot( range(0,7), s_loss)
plt.title('Test_Loss vs Filter_radius')
plt.ylabel('Loss')
plt.xlabel('Filter_radius')
plt.grid()
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 376} colab_type="code" id="DL3g_S6yOeRS" outputId="7fa2c4fe-5a94-4535-8c76-ae8159c5390c"
plt.plot( range(0,7), s_acc)
plt.title('Test_Accuracy vs Filter_radius')
plt.ylabel('Accuracy')
plt.xlabel('Filter_radius')
plt.grid()
plt.show()
# + colab={} colab_type="code" id="ZtJIxIvgOtcv"
| VGG11.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/praveentn/hgwxx7/blob/master/deeplearning/pytorch/pytorch_udemy_01.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + id="vw0f0yTg6hj1" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="a3667b28-67bd-4029-b866-8f57e08be5a7"
# !pip3 install torch
# + id="Uh6m1K7f6oGc" colab_type="code" colab={}
import torch
# + id="1S4DaedS9YLz" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="77d2f6af-74a3-42fd-9821-fdbacf379f9d"
torch
# + id="zyuKcisW6ql2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="ef6d8eee-2430-4ebb-8f30-a5f3234013cf"
# 1d tensor
onedt = torch.tensor([1,2,1])
onedt
# + id="-V2nXLr063EX" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="5427e4d7-409c-4865-fcad-2038c1fe1c01"
onedt.dtype
# + id="8FUMV8Gz7hCq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="afb45435-7346-4e53-c72b-634d3107f365"
onedt[0]
# + id="AIFVcEmI7krs" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="e02590ef-a254-4cf7-b1ef-d5b12fc1d638"
onedt[1:]
# + id="rysNlqmS7s0m" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="df272dec-1e09-454f-a555-493e3cface7c"
onedtf = torch.FloatTensor([1.1,2.2,3])
onedtf
# + id="QJE5HfDU74OS" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="f3527bc5-600e-47d5-e543-0c60069b22da"
onedtf.dtype
# + id="XS7zF-e876lD" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="32725e79-6570-4bba-807f-88b73b0b3caa"
onedt.size()
# + id="gHAdl3lg8HU2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="7f0fe843-d8fd-45ca-eaa0-aeb780ade0ed"
onedtf.size()
# + id="9_nc_XjE8PjU" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="02565c33-d875-4e21-ecae-ab8a6dbcc5ac"
onedt * 3
# + id="lAGnQ3Y48JY2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="4247166f-f694-40f9-b0bd-7ebe2526ce17"
onedt.view(3)
# + id="Hnlj3miw8XBC" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="058b8611-f34c-46a1-ebff-57e2826f1acf"
onedt = torch.Tensor([2,4,6,8,10,12,14,16])
onedt.view(4,2)
# + id="YBIMXEPk8qg0" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="e738425e-a8bd-4971-b263-8854beab4488"
onedt.view(2,4)
# + id="mRKECp_j9Lb_" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="5857e0bd-b855-4288-d64d-17bde54d8ec5"
onedt.view(4,-1)
# + id="DbDQ3vOk9P0z" colab_type="code" colab={}
import numpy as np
# + id="9doP9a169WlJ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="ed3f7b39-2b2c-42ec-b79d-b589afde7f2f"
a = np.array([1,2,3,4,5])
a
# + id="yak0eykM9e9K" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="c2d5a989-85e1-4507-9430-ed592a64e063"
# convert numpy array to tensor
torch.from_numpy(a)
# + id="W77tRR-v9tGN" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="f6bd3469-9b11-4d36-8e59-0ddebed05eb4"
torch.from_numpy(a).type()
# + id="Y_Me9J6596B8" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="4b1960a5-40c4-4cf1-f09b-23cc58c0640d"
onedt.numpy()
# + id="ZL6KFOO4-GJR" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="1514a006-c0cd-454f-ee36-3b4377fa2d98"
# Vector ops
t1 = torch.Tensor([1,1,1])
t2 = torch.Tensor([1,2,3])
t1, t2
# + id="kqRe2fOu-esU" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="974a47b7-2bfb-4839-f640-061789c978a1"
dotprod = torch.dot(t1, t2)
dotprod
# + id="xjenrSqk-rWZ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="60a5ee2f-eeee-4b85-e5bf-89638e6b1518"
t1 + 3
# + id="TiYpir5m-thX" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="19ad5ce5-f32c-4abe-ce8f-760beace6d37"
t2 - 3
# + id="s0pIqO-7-vUA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="9ed2c931-19c4-4120-b750-a97814580f03"
t1 + t2
# + id="CAvi8x2O-w2v" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="bb9231de-4da4-49aa-f616-2cc902cfbfe4"
(t1 * t2) / 3
# + id="P5j-eiDd-2BB" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 221} outputId="43319475-2628-4fa8-b303-4c9ab37afdbe"
# linspace
torch.linspace(0,5)
# + id="bWlNpq9n_IwW" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="518e9891-80cd-4259-ed8e-0f3f3fb7614a"
torch.linspace(0,1,10)
# + id="jtWorCjH_Uyu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 527} outputId="218459b5-4b38-48dd-e4c6-8fa98348e3c6"
x = torch.linspace(0,10,100)
y = torch.exp(x)
x, y
# + id="MB_CYuwh_oNR" colab_type="code" colab={}
import matplotlib.pyplot as plt
# + id="kVEmQ2eR_vcq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 282} outputId="7d5b933d-5d42-44b7-c874-ea11ee6cbf4c"
plt.plot(x.numpy(), y.numpy())
# + id="TUIDPfzr_8Bt" colab_type="code" colab={}
y = torch.sin(x)
# + id="wHo3L7EiAJBi" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 282} outputId="f4909005-428a-4270-de38-53561c7155a3"
plt.plot(x.numpy(), y.numpy())
# + id="dzMrkl_9AKrQ" colab_type="code" colab={}
# dimensional tensors
# + id="vKv40T5VAuj9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="b3b91f51-02c0-46b5-9ec8-5829757fcf6b"
onedt = torch.arange(0,9)
onedt
# + id="iarPdMt_Azht" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="5e4a9dc9-6bf9-4d90-e905-f723c501862e"
twodt = onedt.view(3,-1)
twodt
# + id="vmTnxJehA5UT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="a6b06c44-8ac3-4a86-ee6d-31af8c792637"
onedt.dim()
# + id="AjZtqluAA7Q2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="890dfb33-ca24-4446-cb0e-3643b33c4103"
twodt.dim()
# + id="hfMm-eqqA_VG" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="63c6996f-2d50-4070-e94a-a45bae553c47"
twodt[1,2]
# + id="pessk7LOBcOA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 136} outputId="1a3eff96-504c-46e5-a2eb-9fa9ae661e69"
threedt = torch.arange(0,18).view(2,3,3)
threedt
# + colab_type="code" outputId="237d2a44-5313-4454-82a3-a4b2cdeee7d6" id="LhUxCCDTB5bs" colab={"base_uri": "https://localhost:8080/", "height": 204}
threedt2 = torch.arange(0,18).view(3,3,2)
threedt2
# + id="ncgb2CfXB8lm" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="717f052f-a4a4-426b-abe1-7cd8de0f3f7a"
threedt.dim(), threedt2.dim()
# + id="7RqEXTmQCDI2" colab_type="code" colab={}
# slicing tensors
# + id="FJbPJ4NiCGV-" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 153} outputId="90281979-5863-4a77-cda7-9dfba91a6830"
x = torch.arange(0,18).view(3,2,3)
x
# + id="_qbBr4FqCdyI" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="576564cc-45c0-4b12-e522-3b4f57420376"
x[0, 1, 2]
# + id="1EePIVXbDaTs" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="2436497c-fbf0-4ef7-81af-99da6ce3e88f"
x[1, :, :]
# + id="KYGj-fdUDhZE" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="58ee0a5c-64af-440c-feeb-ccd8e9f2a3eb"
x[1, 1, :]
# + id="zH2mkM-QDlGi" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="cad4b352-7aa4-4c8f-ba73-1cc88d25ccee"
x[1,1,1]
# + id="-5dRd5BZDonh" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 408} outputId="11caa001-8f8e-43b3-c891-01abb0d5cb4d"
x = torch.arange(0,18).view(6,3,-1)
x
# + id="0SyPNGGCF5cU" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="635c90a5-f8af-4d15-d43b-f06d8785fa28"
x[5,0,0]
# + id="eujzS5Z-GCaV" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="c907db60-e0d2-41be-c1d7-a249d981fa04"
x[5,2,0]
# + id="U_oZ-mnQGFdo" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 204} outputId="5087bb4d-9941-4f0c-eed8-7b7605e88b63"
x[2:5,:,:]
# + id="D9Gq4pl5GIyt" colab_type="code" colab={}
# matrix multiplication
# + id="v0_3xnvFGRKo" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="3a07a86f-22f1-4842-888a-2cf4a58bc1df"
x.dim()
# + id="Y1jlWbYXHDaO" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="e33a12a4-d680-4f10-c78c-e198b44ec9ba"
pq = torch.Tensor([2,3,4,5,6,7]).view(2,3)
pq
# + id="ij_a5zXEHSIk" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 68} outputId="7cab5026-f5da-44f8-dcd1-7f89a66e8273"
rs = torch.Tensor([2,3,4,5,6,7]).view(3,2)
rs
# + id="9DlaUHL0HaHB" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="c1ac6da9-2a96-4814-e767-404d1838a341"
pq @ rs
# + id="im59XDZxHcS4" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="ee37dd39-5de7-436a-9b3d-088d7277e350"
torch.matmul(pq, rs)
# + id="EMN4l6S4Hz2q" colab_type="code" colab={}
# derivatives
# + id="gGDS0SwxH8Os" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="7839dd29-2f9b-4c35-ca1b-00500a56cd9e"
x = torch.tensor(2.0, requires_grad=True)
y = 9*x**4 + 2*x**3 + 3*x**2 + 6*x + 1
y.backward()
x.grad
# + id="51z7sz9NIqIr" colab_type="code" colab={}
| deeplearning/pytorch/pytorch_udemy_01.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
# ---
# # Overview demonstration of OSMnx
#
# OSMnx is a Python library that lets you download spatial geometries and construct, project, and visualize street networks from OpenStreetMap's API.
#
# - [Overview of OSMnx](http://geoffboeing.com/2016/11/osmnx-python-street-networks/)
# - [GitHub repo](https://github.com/gboeing/osmnx)
# - [Examples, demos, tutorials](https://github.com/gboeing/osmnx-examples)
# - [Documentation](https://osmnx.readthedocs.io/en/stable/)
#
# #### These examples have been moved!
#
# See the new [OSMnx Examples](https://github.com/gboeing/osmnx-examples) GitHub repo.
| examples/01-overview-osmnx.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 2
# language: python
# name: python2
# ---
# +
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# 随机生成1000个点,围绕在y = 0.1 x + 0.3 的直线周围
num_points = 1000
vectors_set = []
for i in range(num_points):
x1 = np.random.normal(0.0, 0.55)
y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)
vectors_set.append([x1, y1])
# 生成一些样本
x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]
plt.scatter(x_data, y_data, c = 'r')
plt.show()
# +
# 生成1维度的W矩阵,取值是[-1, 1]之间的随机数
W = tf.Variable(tf.random.uniform([1], -1.0, 1.0), name = 'W')
# 生成1维的b矩阵, 初始值是0
b = tf.Variable(tf.zeros([1]), name = 'b')
# 经过计算得出预估值y
y = W * x_data + b
# 以预估值y和实际值y_data之间的均方差误差作为损失
loss = tf.reduce_mean(tf.square(y - y_data), name='loss')
# 采用低度下降法来优化参数
optimizer = tf.train.GradientDescentOptimizer(0.5)
# 训练的过程就是最小化这个误差值
train = optimizer.minimize(loss, name = 'train')
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
# 初始化的W和b是多少
print('W =', sess.run(W), 'b =', sess.run(b), 'loss =', sess.run(loss))
for step in range(20):
sess.run(train)
# 输出训练好的W和b
print('W =', sess.run(W), 'b =', sess.run(b), 'loss =', sess.run(loss))
# -
| basic_ml/Linear_Regression.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# +
import time
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
#keras.mixed_precision.set_global_policy("float32")
#keras.mixed_precision.set_global_policy("mixed_float16")
# -
(train_img, train_lbl), (test_img, test_lbl) = keras.datasets.mnist.load_data()
mdl = keras.Sequential([
layers.Dense(512, activation="relu"),
layers.Dense(16, activation="softmax", dtype="float32"),
])
mdl.compile(
optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
train_img = train_img.reshape((60000, 28*28)).astype("float32") / 255
test_img = test_img.reshape((10000, 28*28)).astype("float32") / 255
start = time.time()
mdl.fit(train_img, train_lbl, epochs=5, batch_size=1024, verbose=0)
pred = mdl.predict(test_img[0:10])
print(pred[0].argmax())
loss, acc = mdl.evaluate(test_img, test_lbl)
print("Accuracy: {:.4f}; done in {:.1f}s".format(acc, (time.time() - start)))
| notebooks/chap2.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="L9kcnFj64EWf" colab_type="code" colab={}
import numpy as np
# + id="LFf596DC3TY1" colab_type="code" colab={}
def lcs_brute_force(first, second):
"""
Use brute force to calculate the longest common substring of two strings
Args:
first: first string
second: second string
Returns:
the length of the longest common substring
"""
len_first = len(first)
len_second = len(second)
max_lcs = -1
lcs_start, lcs_end = -1, -1
# for every possible start in the first string
for i1 in range(len_first):
# for every possible end in the first string
for j1 in range(i1, len_first):
# for every possible start in the second string
for i2 in range(len_second):
# for every possible end in the second string
for j2 in range(i2, len_second):
# start and end position of the current
# candidates
slice_first = slice(i1, j1)
slice_second = slice(i2, j2)
# if the strings match and the length is the
# highest so far
if first[slice_first] == second[slice_second] \
and j1 - i1 > max_lcs:
# save the lengths
max_lcs = j1 - i1
lcs_start = i1
lcs_end = j1
print("LCS: ", first[lcs_start: lcs_end])
return max_lcs
# + id="fv5TTvyZ5S-E" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="b91e9021-8c59-4715-f56c-9f8ffb6a2921"
if __name__ == '__main__':
a = "BBBABDABAA"
b = "AAAABDABBAABB"
lcs_brute_force(a, b)
# + id="cEMg3gPd4Ip9" colab_type="code" colab={}
def lcs_tabular(first, second):
"""
Calculates the longest common substring using memoization.
Args:
first: the first string
second: the second string
Returns:
the length of the longest common substring.
"""
# initialize the table using numpy because it's convenient
table = np.zeros((len(first), len(second)), dtype=int)
for i in range(len(first)):
for j in range(len(second)):
if first[i] == second[j]:
table[i][j] += 1 + table[i - 1][j - 1]
print(table)
return np.max(table)
# + id="thGYZBtm4Kvn" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 194} outputId="887ba567-a83d-4527-8ec8-9f17fd76bb01"
if __name__ == '__main__':
a = "BBBABDABAA"
b = "AAAABDABBAABB"
lcs_tabular(a, b)
| Exercise02/Exercise02.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="-jgljXn7zzTg"
# #**1. Importing Required Packages**
# + id="cNzKzWc2_TCH" colab={"base_uri": "https://localhost:8080/"} outputId="6ebd5261-d3d2-4747-a534-b7458835da05"
#importing tensorflow.compat.v1 and disabling v2 behaviour
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
# + id="RElZ9HVE_Yrw"
import numpy as np #for storing dataset
import matplotlib.pyplot as plt #for plotting purpose
# + [markdown] id="21w2oWz_0tjC"
# #**2.Loading fashion_mnsit Dataset using Keras**
# + id="bHYrFplO_c0j"
#load fashion mnist dataset using keras
def load_data():
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_image_data, train_classes), (test_image_data, test_labels) = fashion_mnist.load_data()
train_image_data=train_image_data/255.0
test_image_data=test_image_data/255.0
return (train_image_data,train_classes,test_image_data,test_labels);
# + id="yiVeyqzJJ36x" colab={"base_uri": "https://localhost:8080/"} outputId="f86af13a-6dc5-419e-a572-11999fa7a3ff"
#downloading data and will store in four numpy arrays
train_image_data,train_classes,test_image_data,test_labels=load_data()
# + id="0a8J_06C_1fm"
#labels for claasified data
classification_labels = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# + [markdown] id="jWRvK4zV1AOB"
# #**3. Exploring Dataset**
# + colab={"base_uri": "https://localhost:8080/", "height": 269} id="maC5IkIzDF7I" outputId="514de233-928a-417b-c39d-bd70cf478c4a"
#plotting a sample image from train data
plt.imshow(train_image_data[1])
plt.colorbar()
plt.grid(False)
plt.show()
# + colab={"base_uri": "https://localhost:8080/"} id="zUNAznuwAHNx" outputId="c9339330-a1cf-4105-8e3d-00b52f0b5bf1"
train_image_data.shape
# + colab={"base_uri": "https://localhost:8080/"} id="62ahZFJkARic" outputId="2ef88423-debb-4a6f-ddbd-385aafdf1ac2"
train_classes.shape
# + colab={"base_uri": "https://localhost:8080/"} id="JY6UYa-VAXVy" outputId="a2599acc-c460-430a-cc1b-b50377d21361"
test_labels.shape
# + colab={"base_uri": "https://localhost:8080/"} id="pIxV3bqaAbpv" outputId="eb6d44bd-270b-43ab-b4e9-122293ce6238"
test_image_data.shape
# + colab={"base_uri": "https://localhost:8080/"} id="990UvW0MAg7N" outputId="fe3993ce-df84-4d5a-d9ee-488455749036"
train_classes
# + colab={"base_uri": "https://localhost:8080/"} id="jUr-WlpjOogY" outputId="49739ebc-3a78-4044-9f6e-d39b0b5595d6"
train_image_data[:3]
# + colab={"base_uri": "https://localhost:8080/"} id="HlrYKawVOtbP" outputId="24c45ea2-0974-4503-e518-b67bdfd634b5"
test_image_data[:3]
# + [markdown] id="E_-vlO511uP8"
# #**4. Randomally Splitting Training Data into Train Set and Validation Set**
# + id="ju1IoOtuOy_5"
#split train data into train set and validation set using given fraction size of validation set
def split_train_data(train_image_data,validation_set_size,seed_val):
from sklearn.model_selection import train_test_split
train_set, validation_set, train_labels,validation_labels = train_test_split(train_image_data, train_classes, test_size=validation_set_size, random_state=seed_val)
return (train_set, validation_set, train_labels,validation_labels);
# + id="kZhj65BKhrpq"
train_set, validation_set, train_labels,validation_labels=split_train_data(train_image_data,validation_set_size=0.15,seed_val=40)
# + [markdown] id="Vx2tzOJp5aEX"
# #**5. Exploring Splitted Dataset**
# + colab={"base_uri": "https://localhost:8080/", "height": 269} id="18-8SfhWPMxj" outputId="ae0ce9bc-5f8d-409d-a92e-4c0bfb5c5879"
#plotting a sample image from train set
plt.imshow(train_set[5])
plt.colorbar()
plt.grid(False)
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 476} id="WeSVjTOzP7S8" outputId="59f3dc58-618d-4c49-a69d-d2c999c336e5"
#plotting some train set images with their provided labels
plt.figure(figsize=(10,10))
for i in range(20):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_set[i], cmap=plt.cm.binary)
plt.xlabel(classification_labels[train_labels[i]])
plt.show()
# + colab={"base_uri": "https://localhost:8080/"} id="3_bwbRFE6axr" outputId="ead38ade-484d-48c3-dec1-9be437513d7c"
train_set.shape
# + colab={"base_uri": "https://localhost:8080/"} id="dFN7gasI6bJG" outputId="a68b38dd-fcbc-42a2-8fe3-3c5df539b9ad"
validation_set.shape
# + colab={"base_uri": "https://localhost:8080/"} id="D6BbLwmA6bd2" outputId="1b10788d-f053-4477-fc69-7170b46dfbb2"
train_labels.shape
# + colab={"base_uri": "https://localhost:8080/"} id="clbrJOi76cxF" outputId="cbe3df8d-3612-407c-e27c-f18a790ea68c"
validation_labels.shape
# + [markdown] id="SuyXlow767mR"
# #**6. Setting Parameters and Hyperparameters**
# + id="unwzJhQFP86U"
#Parameters
n_input = 28 # Fashion MNIST img shape: 28*28, so each row has 28 entries ,and one row will be input
n_timesteps = 28 # Timesteps in RNN, as 28 rows are there and one time one row will be input so 28 timesteps
n_labels = 10 # fashion MNIST total classes (0-9 digits)
# + id="lo2tbC0M72Kn"
#Hyperparameters
learning_rate = 0.001
n_hidden_states = 100 # hidden layer: num of features
layers=3
# + [markdown] id="v9iPAwTH_GET"
# #**Building RNN**
# + id="HUevMPygCfJV"
#Clears the default graph stack and resets the global default graph.
tf.reset_default_graph()
# + id="ZmKDE7VgBQxf"
def Build_RNN(n_hidden_states,X):
# Unstack to get a list of tensors ,it will be passed to tf.nn.static_rnn() function
x1 = tf.unstack(X, n_timesteps, 1)
#defining rnn cell using tensorflow with activation function tanh
rnn_cells = [tf.nn.rnn_cell.BasicRNNCell(num_units=n_hidden_states, activation = 'tanh',reuse=tf.AUTO_REUSE) for layer in range(layers)]
r_cells_drop = [tf.nn.rnn_cell.DropoutWrapper(cell, input_keep_prob=keep_prob) for cell in rnn_cells]
multi_layer_cell = tf.nn.rnn_cell.MultiRNNCell(r_cells_drop)
#creating RNN using tensorflow.compat.v1.nn.static_rnn
output, state = tf.nn.static_rnn(multi_layer_cell, x1, dtype=tf.float32)
return (output,state);
# + id="TXCakrJr-ILZ"
#placeholders for the 'inputs' and 'outputs'
inputs = tf.placeholder(tf.float32, [None, n_timesteps, n_input])
outputs = tf.placeholder(tf.int32, [None])
keep_prob = tf.placeholder(tf.float32)
# + colab={"base_uri": "https://localhost:8080/"} id="RSa8-ko3I9ah" outputId="d48114fb-a5f3-4ebf-b545-8ad5e3d57e4e"
output,states=Build_RNN(n_hidden_states,inputs)
# + [markdown] id="kqTtP-DfHjre"
# **Defining loss function,optimizer,prediction and accuracy**
# + colab={"base_uri": "https://localhost:8080/"} id="KQ5N8WF8-Il4" outputId="f9146c5a-7646-4b1b-d443-931f73b56f50"
states_concat = tf.concat(axis=1, values=states, name='states_reshape')
dense1 = tf.layers.dense(states_concat, 64, name='dense_1')
dense2 = tf.layers.dense(dense1, 32, name='dense_2')
logits = tf.layers.dense(dense2, n_labels)
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=outputs, logits=logits)
loss = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
prediction = tf.nn.in_top_k(logits, outputs, 1)
accuracy = tf.reduce_mean(tf.cast(prediction, tf.float32))
# + id="dxS6EETO-J2h"
#initializing all the global variables
init = tf.global_variables_initializer()
# + id="pgOgaqbpYzbe"
#reshaping the validation set
X_validation = validation_set
Y_validation = validation_labels
X_vlidation = X_validation.reshape([-1, n_timesteps, n_input])
# + [markdown] id="qOGbcA5jTa75"
# #**Training and Validation**
# + id="mXLehqv3NdRi"
#to save the best model and restore later
saver = tf.train.Saver()
# + id="Z3-6UE6ZJKu8"
#defining variables to implement "Early Stopping"
patience=10 # patience for Early Stopping
epochs_without_improvement=0
best_loss=np.infty #best_loss upto the last epoch
# + id="nxZAZtlKUjgh"
#defining list to create graphs later to analyze trained model
train_acc=[] #contain training accuracy of every epoch
validation_acc=[] #contain validation accuracy of every epoch
train_loss=[] #contain training loss of every epoch
validation_loss=[] #contain validation loss of every epoch
# + [markdown] id="X2DAD8ZFVcZQ"
# **Training and Validation**
# + id="0nDB-pjeZgh_"
#function to return next batch of train set to be sent to train model
def next_batch(current_batch,batch_size,train_set,train_labels):
i=current_batch*batch_size
j=(current_batch+1)*batch_size
X_train=train_set[i:j]
Y_train=train_labels[i:j]
return X_train,Y_train;
# + colab={"base_uri": "https://localhost:8080/"} id="9tShU5Km-KNX" outputId="e8a0c654-f5a1-4792-f291-b164dd2c8b68"
batch_size = 50 #barch size to train model
n_epochs = 150
with tf.Session() as sess:
sess.run(init)
#number of barches(iterations) to complete one epoch
n_batches = train_set.shape[0] // batch_size
for epoch in range(n_epochs):
for current_batch in range(n_batches):
X_train,Y_train=next_batch(current_batch,batch_size,train_set,train_labels)
X_train = X_train.reshape([-1, n_timesteps, n_input])
#running optimization(Back Propogation) with dropout(retention probability) 0.8
sess.run(optimizer, feed_dict={inputs: X_train, outputs: Y_train ,keep_prob: 0.8})
#calculating loss and accuracy after completion of epoch for train set
loss_train, acc_train = sess.run([loss, accuracy], feed_dict={inputs: X_train, outputs: Y_train,keep_prob: 0.8})
#calculating loss and accuracy after completion of epoch for validation set
loss_val, acc_val = sess.run([loss, accuracy], feed_dict={inputs: X_validation, outputs: Y_validation,keep_prob: 1.0})
#appending data to lists to plot graphs later
train_loss.append(loss_train)
train_acc.append(acc_train)
validation_loss.append(loss_val)
validation_acc.append(acc_val)
if epoch%5==0:
print('Epoch {}:\nTrain Loss: {:.3f}, Train Acc: {:.3f}'.format( epoch + 1, loss_train, acc_train))
print('Validation Loss: {:.3f}, Validation Acc: {:.3f}\n'.format(loss_val, acc_val))
if best_loss>loss_val:
#if train loss improved
best_loss=loss_val
#saving current best model
saver.save(sess, "/logs_rnn/my_best_model.ckpt")
else:
epochs_without_improvement+=1
#early stopping if perfomance is not improving over k(patience) iterations
if epochs_without_improvement>=patience:
print("\nEarly stopping at epoch {} ".format(epoch+1))
break
# + [markdown] id="sgQLhchrwj5x"
# #**Testing**
# + id="DyGm6isoz1MO"
test_image_data=test_image_data.reshape([-1, n_timesteps, n_input])
# + id="cmp7UMvh-Kft" colab={"base_uri": "https://localhost:8080/"} outputId="217bef20-b535-4128-d6b4-632135e5e4d0"
#Restoring saved model from "/logs_rnn/my_best_model" and testing on testdata
with tf.Session() as sess:
saver.restore(sess, "/logs_rnn/my_best_model.ckpt") #restored model
#testing model on testdata
loss_test, acc_test = sess.run([loss, accuracy], feed_dict={inputs: test_image_data, outputs: test_labels,keep_prob: 1.0})
print('Test Loss: {:.3f}, Test Acc: {:.3f}'.format(loss_test, acc_test))
# + [markdown] id="D71XRkYI3dNP"
# #**Graph Plots**
# + colab={"base_uri": "https://localhost:8080/", "height": 434} id="uPA2y9_HYiCx" outputId="0d44fd5a-0541-4ccd-a6d3-600ace9ebcbe"
#plotting graph between training acuracy vs validation accuracy
fig, (ax1) = plt.subplots(1, figsize=(15,6))
fig.suptitle('Evaluation results')
ax1.set_title("Training Accuracy vs Validation Accuracy")
ax1.plot(range(len(train_acc)), train_acc, color="b", label="Train Accuracy")
ax1.plot(range(len(validation_acc)), validation_acc, color="g", label="Validation Accuracy")
ax1.legend(loc='lower right')
# + colab={"base_uri": "https://localhost:8080/", "height": 434} id="CkOn9XVpyNTO" outputId="284470b1-e8a1-4a9b-8204-004c6d7cf870"
#plotting graph between training loss vs validation loss
fig, (ax2) = plt.subplots(1, figsize=(15,6))
fig.suptitle('Evaluation results')
ax2.set_title("Training Loss vs Validation Loss")
ax2.plot(range(len(train_loss)), train_loss, color="b", label="Train Loss")
ax2.plot(range(len(validation_loss)), validation_loss, color="g", label="Validation Loss")
ax2.legend(loc='lower right')
# + colab={"base_uri": "https://localhost:8080/"} id="foIqX45hfzrl" outputId="7655461a-99f6-4276-dff9-cd4ec0ee7a51"
with tf.Session() as sess:
saver.restore(sess, "/logs_rnn/my_best_model.ckpt")
prob = logits.eval(feed_dict={inputs: test_image_data, outputs: test_labels,keep_prob: 1.0})
# + id="dxVX1f6oG2hs"
def plot_predicted_entities():
fig, (ax_s) = plt.subplots(1, 5, figsize=(15,10))
perm = np.random.permutation(len(test_image_data))
perm = perm[:5]
for i in range(5):
title = "Predicted value:" + classification_labels[np.argmax(prob[perm[i]])] + ",\nTrue value: " + classification_labels[test_labels[perm[i]]]
ax_s[i].set_title(title)
ax_s[i].imshow(test_image_data[perm[i]],cmap =plt.cm.gray_r, interpolation = "nearest")
# + colab={"base_uri": "https://localhost:8080/", "height": 635} id="s-aOES0_G1Gm" outputId="f2b9322a-c651-4ccc-9bce-ca4851aa8215"
plot_predicted_entities()
plot_predicted_entities()
plot_predicted_entities()
# + id="uu7fakSXFx9R"
| Code/RNN.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
# ---
# # Pandas
# ** I will be showing an example of how to obtain Data about a stock for our analysis. In this example we will be using an API called Alpha Vantage and a python library called pandas in order to do this. **
#
# ** pandas is a library that provides fast and intuitive data structures for the use of data analysis. **
#
# [Documentation for pandas](https://pandas.pydata.org/pandas-docs/stable/)
#
# ** Alpha Vantage queries can return either a JSON response or a CVS (Comma Seperate Values) response. For the purpose of reading the data using the PANDAS library from python, we will be using the CVS format. **
#
# ** The instructions on how to format the queries can be found [here](https://www.alphavantage.co/documentation/). **
#
# ** An example of a query: https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv **
#
# ** Following this link will download the example CSV file, though we have provided the file for you. **
# +
# Import pandas library. It is common to refer to it as pd
import pandas as pd
# Display is used to display the dataframe, though it is not necessary
from IPython.display import display
# Parses the CSV file into a dataframe
stock_data = pd.read_csv("example.csv")
# A csv file can also be read from a URL that provides a CSV file
# The index_col parameter sets which column of the data set is to be used as the index
stock_data = pd.read_csv('https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv',
index_col='timestamp')
# -
# ** The dataframe and series objects are the two main data structures in pandas. **
#
# [Documentation for Dataframe](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame)
#
# **The dataframe is tabular data structure that contains rows(entries) and columns(attributes). **
#
# **stock_data = pandas.read_csv("example.csv") creates a dataframe from the example.csv file and assigns it to the stock_data variable. **
#
# ** The head() method prints the first k rows of a dataframe. The default amount is 5. **
#
# ** The tail() method prints the last k rows of a dataframe. **
# +
# Displays the first 5 rows in our dataframe
print(display(stock_data.head(3)))
# Reverses the data frame so the dates are in acsending order
stock_data = stock_data.iloc[::-1]
print(display(stock_data.head(3)))
# Displays the last 3 rows of our dataframe
print(display(stock_data.tail(3)))
# -
# ** We will now explore some basic features of a dataframe. **
# ** The .shape attribute of dataframes list the number of rows and the number of columns. **
# +
print(stock_data.shape)
# Prints only the number of rows
print("The number of rows in the dataframe is: ", stock_data.shape[0])
# Prints on the number of columns
print("The number of columns in the dataframe is: ", stock_data.shape[1])
# -
# ** The .dtypes attribute of dataframes lists the name and data type of each column. **
print(stock_data.dtypes)
# ** Here we have created a new dataframe that is identical to stock_data except now the volume column has been removed. Please note that stock_data has not been modified, we merely created a copy. To remove a column from the same dataframe would look like this.
# stock_data = stock_data.drop('volume', axis = 1) **
# +
# Drops the specified column from a dataframe
new_stock_data = stock_data.drop('volume', axis = 1)
# You'll be able to see that the volume column is no longer there
print(display(new_stock_data.head()))
# -
# ** A series is a one dimensional array that is used to store a single column from a dataframe. stock_data['close'] allows us to access a single column in the dataframe. If you wish to use a different column then simply change the string to the name of the column. **
# [Documentation for Series](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series)
# +
# Assigns the close column from the dataframe to the series variable, close_series
close_series = stock_data['close']
# prints the first five rows in the series
display(close_series.head(5))
# -
# ** Here we have created a subset of the dataframe. A subset can contain any number of columns from the original dataframe. Take note of how the column names are enclosed with double brackets. **
# +
# Creates a subset dataframe from another dataframe
stock_subset = stock_data[ [ 'open', 'close' ] ]
print(display(stock_subset.head(5)))
# -
# ** Here we have used the loc method to return all the entries that meet the condition that we want, in this case the entries where the value of close is greater then 80. **
# Display the entries where close is greater then 80
stock_data.loc[stock_data['close'] > 80]
# ** Here we have used the iloc method to find the entry at the 200th index and also to find the value of the close column of the first entry. **
# +
# Returns the entry at index of 200
display(stock_data.iloc[200])
# Returns the close value of the first entry
# The 0 is the index of the row
# The 3 is the index of the column, in this case it is the close column
print("The close value of the first entry is: ", stock_data.iloc[0, 3])
# -
# ** Here we have used the describe method to provide statistical information for each column such as the mean and standard deviation. Note that the 50th percentile is the same as the median. **
# Provides useful statistcal data on the data set
stock_data.describe()
| Section_05/Pandas.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
# ---
# # Foundations for statistical inference - Sampling distributions
# In this lab, we investigate the ways in which the statistics from a random sample of data can serve as point estimates for population parameters. We’re interested in formulating a sampling distribution of our estimate in order to learn about the properties of the estimate, such as its distribution.
#
# # The data
# We consider real estate data from the city of Ames, Iowa. The details of every real estate transaction in Ames is recorded by the City Assessor’s office. Our particular focus for this lab will be all residential home sales in Ames between 2006 and 2010. This collection represents our population of interest. In this lab we would like to learn about these home sales by taking smaller samples from the full population. Let’s load the data.
import pandas as pd
ames = pd.read_csv('ames.csv')
# We see that there are quite a few variables in the data set, enough to do a very in-depth analysis. For this lab, we’ll restrict our attention to just two of the variables: the above ground living area of the house in square feet (`Gr.Liv.Area`) and the sale price (`SalePrice`). To save some effort throughout the lab, create two variables with short names that represent these two variables.
area = ames['Gr.Liv.Area']
price = ames['SalePrice']
# Let’s look at the distribution of area in our population of home sales by calculating a few summary statistics and making a histogram.
area.describe()
import matplotlib.pyplot as plt
area.plot.hist()
plt.show()
# **Exercise 1** Describe this population distribution.
# # The unknown sampling distribution
# In this lab we have access to the entire population, but this is rarely the case in real life. Gathering information on an entire population is often extremely costly or impossible. Because of this, we often take a sample of the population and use that to understand the properties of the population.
#
# If we were interested in estimating the mean living area in Ames based on a sample, we can use the following command to survey the population.
samp1 = area.sample(50)
# This command collects a simple random sample of size 50 from the Series `area`, which is assigned to `samp1`. This is like going into the City Assessor’s database and pulling up the files on 50 random home sales. Working with these 50 files would be considerably simpler than working with all 2930 home sales.
# **Exercise 2** Describe the distribution of this sample. How does it compare to the distribution of the population?
# If we’re interested in estimating the average living area in homes in Ames using the sample, our best single guess is the sample mean.
samp1.mean()
# Depending on which 50 homes you selected, your estimate could be a bit above or a bit below the true population mean of 1499.69 square feet. In general, though, the sample mean turns out to be a pretty good estimate of the average living area, and we were able to get it by sampling less than 3% of the population.
# **Exercise 3** Take a second sample, also of size 50, and call it `samp2`. How does the mean of `samp2` compare with the mean of `samp1`? Suppose we took two more samples, one of size 100 and one of size 1000. Which would you think would provide a more accurate estimate of the population mean?
# Not surprisingly, every time we take another random sample, we get a different sample mean. It’s useful to get a sense of just how much variability we should expect when estimating the population mean this way. The distribution of sample means, called the *sampling distribution*, can help us understand this variability. In this lab, because we have access to the population, we can build up the sampling distribution for the sample mean by repeating the above steps many times. Here we will generate 5000 samples and compute the sample mean of each.
# +
sample_means50 = [None] * 5000
for i in range(0,5000):
samp = area.sample(50)
sample_means50[i] = samp.mean()
plt.hist(sample_means50)
plt.show()
# -
# If you would like to adjust the bin width of your histogram to show a little more detail, you can do so by changing the `bins` argument.
plt.hist(sample_means50, bins=25)
plt.show()
# Here we use Python to take 5000 samples of size 50 from the population, calculate the mean of each sample, and store each result in an array called `sample_means50`. On the next page, we’ll review how this set of code works.
# **Exercise 4** How many elements are there in `sample_means50`? Describe the sampling distribution, and be sure to specifically note its center. Would you expect the distribution to change if we instead collected 50,000 sample means?
# # Interlude: The `for` loop
# Let’s take a break from the statistics for a moment to let that last block of code sink in. You have just run your first `for` loop, a cornerstone of computer programming. The idea behind the for loop is iteration: it allows you to execute code as many times as you want without having to type out every iteration. In the case above, we wanted to iterate the two indented lines of code that take a random sample of size 50 from `area` then save the mean of that sample into the `sample_means50` array. Without the `for` loop, this would be painful:
# +
sample_means50 = [None] * 5000
samp = area.sample(50)
sample_means50[0] = samp.mean()
samp = area.sample(50)
sample_means50[1] = samp.mean()
samp = area.sample(50)
sample_means50[2] = samp.mean()
samp = area.sample(50)
sample_means50[3] = samp.mean()
# -
# and so on…
#
# With the `for` loop, these thousands of lines of code are compressed into a handful of lines. We’ve added one extra line to the code below, which prints the variable `i` during each iteration of the for loop. Run this code.
sample_means50 = [None] * 5000
for i in range(0,5000):
samp = area.sample(50)
sample_means50[i] = samp.mean()
print(i)
# Let’s consider this code line by line to figure out what it does. In the first line we initialized an array. In this case, we created an array of 5000 `None` values called `sample_means50`. This array will store values generated within the `for` loop.
#
# The second line calls the for loop itself. The syntax can be loosely read as, “for every element i from 0 to 4999, run the following lines of code”. You can think of `i` as the counter that keeps track of which loop you’re on. Therefore, more precisely, the loop will run once when `i = 0`, then once when `i = 1`, and so on up to `i = 4999`.
#
# The body of the `for` loop is the part that is indented, and this set of code is run for each value of `i`. Here, on every loop, we take a random sample of size 50 from `area`, take its mean, and store it as the ith element of `sample_means50`.
#
# In order to display that this is really happening, we asked Python to print `i` at each iteration. This line of code is optional and is only used for displaying what’s going on while the `for` loop is running.
#
# The for loop allows us to not just run the code 5000 times, but to neatly package the results, element by element, into the empty array that we initialized at the outset.
# **Exercise 5** To make sure you understand what you’ve done in this loop, try running a smaller version. Initialize an array of 100 `None`s called `sample_means_small`. Run a loop that takes a sample of size 50 from `area` and stores the sample mean in `sample_means_small`, but only iterate from 1 to 100. Print the output to your screen (type `sample_means_small` into the console and press enter). How many elements are there in this object called `sample_means_small`? What does each element represent?
# # Sample size and the sampling distribution
# Mechanics aside, let’s return to the reason we used a `for` loop: to compute a sampling distribution, specifically, this one.
plt.hist(sample_means50)
plt.show()
# The sampling distribution that we computed tells us much about estimating the average living area in homes in Ames. Because the sample mean is an unbiased estimator, the sampling distribution is centered at the true average living area of the the population, and the spread of the distribution indicates how much variability is induced by sampling only 50 home sales.
#
# To get a sense of the effect that sample size has on our distribution, let’s build up two more sampling distributions: one based on a sample size of 10 and another based on a sample size of 100.
sample_means10 = [None] * 5000
sample_means100 = [None] * 5000
for i in range(0,5000):
samp = area.sample(10)
sample_means10[i] = samp.mean()
samp = area.sample(100)
sample_means100[i] = samp.mean()
# Here we’re able to use a single `for` loop to build two distributions by adding additional indented lines. Don’t worry about the fact that `samp` is used for the name of two different objects. In the second command of the `for` loop, the mean of `samp` is saved to the relevant place in the array `sample_means10`. With the mean saved, we’re now free to overwrite the object `samp` with a new sample, this time of size 100. In general, anytime you create an object using a name that is already in use, the old object will get replaced with the new one.
#
# To see the effect that different sample sizes have on the sampling distribution, plot the three distributions on top of one another.
import numpy as np
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(4, 8))
left = np.min(sample_means10)
right = np.max(sample_means10)
axes[0].hist(sample_means10, bins=20)
axes[0].set_xlim(left, right)
axes[1].hist(sample_means50, bins=20)
axes[1].set_xlim(left, right)
axes[2].hist(sample_means100, bins=20)
axes[2].set_xlim(left, right)
plt.show()
# The first command specifies that you’d like to divide the plotting area into 3 rows and 1 column of plots (axes). The `bins` argument specifies the number of bins used in constructing the histogram. The `set_xlim` function specifies the range of the x-axis of the histogram, and by setting it equal for each histogram, we ensure that all three histograms will be plotted with the same limits on the x-axis.
# **Exercise 6** When the sample size is larger, what happens to the center? What about the spread?
# # On your own
# So far, we have only focused on estimating the mean living area in homes in Ames. Now you’ll try to estimate the mean home price.
#
# 1. Take a random sample of size 50 from `price`. Using this sample, what is your best point estimate of the population mean?
#
# 2. Since you have access to the population, simulate the sampling distribution for $\bar{x}_{price}$ by taking 5000 samples from the population of size 50 and computing 5000 sample means. Store these means in an array called `sample_means50`. Plot the data, then describe the shape of this sampling distribution. Based on this sampling distribution, what would you guess the mean home price of the population to be? Finally, calculate and report the population mean.
#
# 3. Change your sample size from 50 to 150, then compute the sampling distribution using the same method as above, and store these means in a new array called `sample_means150`. Describe the shape of this sampling distribution, and compare it to the sampling distribution for a sample size of 50. Based on this sampling distribution, what would you guess to be the mean sale price of homes in Ames?
#
# 4. Of the sampling distributions from 2 and 3, which has a smaller spread? If we’re concerned with making estimates that are more often close to the true value, would we prefer a distribution with a large or small spread?
# *This notebook is based on the OpenIntro R lab [Intro to Inference](http://htmlpreview.github.io/?https://github.com/andrewpbray/oiLabs-base-R/blob/master/sampling_distributions/sampling_distributions.html).*
| open-intro-statistics/python-labs/Intro to Inference.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/Icetalon21/Python_Projects/blob/master/Copy_of_MidTerm_Practice_Activity.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="yXb3VXKaIMx7" colab_type="text"
# #Mid-term Practice Activity: Exploratory Data Analysis with Python
# This is a practice activity for those in need of further practtice for mid-term exam of AIMS 4798- Machine Learning with Python. It involves ingesting, cleaning, preparing, exploring, and visualizing data using Python data analysis libraries.
#
# ## Case Background
# Here we have the U.S. Census 2017 dataset. The dataset includes 37 columns and more than 3K rows. Each row represent demographic data for one county in the United States. You are expected to write the code import the data and do some exploratory data analysis as requested in the instructions.
#
# ## Data Description
# The dataset is from [Kaggle website](https://www.kaggle.com/muonneutrino/us-census-demographic-data). You may download [the dataset here](https://drive.google.com/file/d/17x2GbLlwBMnHSBHE165tbsUNbjHtoJ4B/view?usp=sharing). It contains the following fields:
#
# * **Countyid:** unique identification number for each county or county equivalent
# * **State:** State, DC, or Puerto Rico
# * **County:** County or county equivalent
# * **TotalPop:** Total population
# * **Men:** Number of men
# * **Women:** Number of women
# * **Hispanic:** % of population that is Hispanic/Latino
# * **White:** % of population that is white
# * **Black:** % of population that is black
# * **Native:** % of population that is Native American or Native Alaskan
# * **Asian:** % of population that is Asian
# * **Pacific:** % of population that is Native Hawaiian or Pacific Islander
# * **Citizen:** Number of citizens
# * **Income:** Median household income in USD
# * **Income:** ErrMedian household income error in USD
# * **IncomePerCap:** Income per capita in USD
# * **IncomePerCapErr:** Income per capita error in USD
# * **Poverty:** % under poverty level
# * **ChildPoverty:** % of children under poverty level
# * **Professional:** % employed in management, business, science, and arts
# * **Service:** % employed in service jobs
# * **Office:** % employed in sales and office jobs
# * **Construction:** % employed in natural resources, construction, and maintenance
# * **Production:** % employed in production, transportation, and material movement
# * **Drive:** % commuting alone in a car, van, or truck
# * **Carpool:** % carpooling in a car, van, or truck
# * **Transit:** % commuting on public transportation
# * **Walk:** % walking to work
# * **OtherTransp:** % commuting via other means
# * **WorkAtHome:** % working at home
# * **MeanCommute:** Mean commute time (minutes)
# * **Employed:** Number of employed (16+)
# * **PrivateWork:** % employed in private industry
# * **PublicWork:** % employed in public jobs
# * **SelfEmployed:** % self-employed
# * **FamilyWork:** % in unpaid family work
# * **Unemployment:** Unemployment rate (%)
# + [markdown] id="MgyJSlVrn17M" colab_type="text"
# ## Problem Steps
# Please go through the following problems and produce the code that answers the problem. **Make sure you use exectly ONE CELL to answer each question. Properly comment your code so it is easy to understand what it does.**
# + [markdown] id="fwNho30LR79A" colab_type="text"
# ##Data Ingestion & Cleaning
#
# + [markdown] id="y_qOVKVI1Zlz" colab_type="text"
# 1. Read the dataset into a dataframe. Then check out the first few rows and summary statistics of the dataset.
# + [markdown] id="NVpvAF_dUyxf" colab_type="text"
# 2. Remove the duplicate records if there is any. Make sure you print out the number of records in the dataset before and after duplicate removal.
# + [markdown] id="E7vWlnck-POA" colab_type="text"
# 3. Drop the two columns of IncomeErr and IncomePerCapErr. Toy should drop both at once rather than one by one.
# + [markdown] id="345zoB9EBEOO" colab_type="text"
# 4. Drop the records for Puerto Rico which is a U.S. territory rather than a state.
# + [markdown] id="XMOWZgdfSQiV" colab_type="text"
# ## Data Preparation
# + [markdown] id="po6Sywl7-Jgo" colab_type="text"
# 5. Add a new column called 'unemployed' that is VotingAgeCitizen * (Unemployment/100).
# + [markdown] id="hAjBu0vUVVAg" colab_type="text"
# 6. Add another column that replaces the state names with their abriviations (Alabama: AL). You should replace the state names all at once, rather than repeating your code for each state. you can copy the list of state abbreviations [from here](https://www.50states.com/abbreviations.htm).
#
# + [markdown] id="atGw4NsQSgEV" colab_type="text"
# ##Data Exploration
# + [markdown] id="BJ6cTDc_M3Um" colab_type="text"
# 7. Calculate the number of unique states included in the dataset.
#
# + [markdown] id="j0ZOW8gHVOqD" colab_type="text"
# 8. Calculate the number of counties for each state.
#
# + [markdown] id="QHHWEBJmn9XS" colab_type="text"
# 9. Slice the data to display the states with more than 100 counties.
# + [markdown] id="LVLR6FMgVRkj" colab_type="text"
# 10. Caculate the total population, men, and women for each state. Sort the states based on their total population from high to low (descending).
# + [markdown] id="vKZhuGpfVe2H" colab_type="text"
# 11. Slice the data to display the U.S. mainland counties with unemployment ratio (Unemployment column) of over 20%. It means it should exclude counties from Hawaii, and Alaska. The output should display only three columns of State, County, and Poverty.
# + [markdown] id="I0SWk0tHVh0T" colab_type="text"
# 12. Display the top 5 richest and 5 poorest counties in the nation based on income per capita? Print out the name of these counties, their state, total population, hispanic, white, and black ratios.
#
# + [markdown] id="OjN6ZD7NcoUI" colab_type="text"
# 13. Create a function that receives a state and returns the summary statistics of the total population, income per capita, and poverty for each county of that state. The summary statistics would be calculated using the .describe() function.
# Use your function to print the statistics for California.
# + [markdown] id="CHBTZrJZVn-n" colab_type="text"
# 14. Create a function that receives the name of a state and returns top three counties in that state with highest number of unemployed people (unemployed column). Use the function to print the results for California.
# + [markdown] id="KDKp5-osVuR_" colab_type="text"
# 15. Create a function to receives a list of State values (a list that includes the name of states) and produce a dataframe that includes the average poverty (Poverty column) of counties in each of those states. It means the output should display the name of each state and the average poverty for each.
# + [markdown] id="VPW3SE_WVkAj" colab_type="text"
# 16. Calculate and display the correlation matrix that displays two-by-two correlatin between Poverty, Hispanic, White, Black, Native, and Asian.
# + [markdown] id="MgCIBGV-Smk-" colab_type="text"
# ##Data Visualization
# + [markdown] id="sP6skw5PcMxH" colab_type="text"
# 17. Use the function you created in step 15 to create a line chart that displays the average poverty for the states of Alabama, California, Georgia, and North Carolina. Properly title the plot and label the axes. Set the marker to a circle and the line style to dashed. The line should have a green color.
# + [markdown] id="rKp7UzT0ebEX" colab_type="text"
# 18. Create an scatter plot that displays the White ratio (White column) of all U.S. counties against their Poverty ratio (Poverty column). Set the marker to a dot.
# 19. Add anotehr scatter plot on the previous plot to display the Black ratio (Black column) of all U.S. counties against their Poverty ratio (Poverty column). Set the marker to a dot. Add proper title and axis labels. Make sure you add label for Black and White datapoint and display the plot legend.
| Copy_of_MidTerm_Practice_Activity.ipynb |
% ---
% jupyter:
% jupytext:
% text_representation:
% extension: .m
% format_name: light
% format_version: '1.5'
% jupytext_version: 1.14.4
% kernelspec:
% display_name: Octave
% language: octave
% name: octave
% ---
% # Working with Data
% ## Defining matrices and vectors
% In Octave or Mathlab, matrices are important first class concepts.
% Matrices can be defined and assigned to variables easily, e.g. by specifying them as a set of rows.
A=[16 2 3 13 ; 5 11 10 8 ; 9 7 6 12 ; 4 14 15 1]
% Accessing cells of a matrix is straight forward:
A(1,1)
A(3,4)
% Using the ':' syntax, we can easily work with parts of matrices. In the following example, we copy all rows from matrix A, but from these rows, we only copy columns 1 to 2.
B1 = A(:, 1:2)
% Here, we only copy rows 3 to 4 and columns 1 to 2.
B2 = A(3:4, 1:2)
% In Mathlab and Octave, indices start with 1, so the following code does not work correctly:
B4 = A(0:4, 0:2)
% A vector is a special case of a matrix.
k = [1, 2, -1, -2]'
% ## Computing with matrices and vectors
% Let's start with a very simple matrix multiplication. This is a naive implementation:
v = zeros(4, 1);
for i = 1:4
for j = 1:4
v(i) = v(i) + A(i, j) * k(j);
end
end
v
% Ocatve and Mathlab have powerful functions (and operators) that directly work with matrices.
v = A * k
v = k'* A
v = Ax
v = sum(A*k)
% Examples for working with vectors:
v = [1, 2, 3, 4, 5, 6, 7]'
w = [1, 2, 3, 4, 5, 6, 7]'
z = 0;
for i = 1:7
z = z + v(i) * w(i);
end
z
z = sum(v .* w)
z = w' * v
z = v * w'
z = w * v'
% Compare the following cell-based computations with their matrix-based counterparts:
X = rand (7,7)
for i = 1:7
for j = 1:7
A(i, j) = log(X(i, j));
B(i, j) = X(i, j) ^ 2;
C(i, j) = X(i, j) + 1;
D(i, j) = X(i, j) / 4;
end
end
A
A2 = log(X)
B
B2 = X^2
C
C2 = X + 1
D
D2 = X / 4
| 1st_steps/working_with_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
# ---
def read_questions(filename):
answers = {}
with open(filename, 'r') as f:
for line in f:
line = line.strip()
if line != '':
question, answer = line.split('=')
answers[question.strip()] = answer.strip()
return answers
read_questions('questions.txt')
# +
def ask_questions(answers):
correct = []
wrong = []
for question, answer in answers.items():
if input(question + ' = ').strip() == answer:
print("Correct!")
correct.append(question)
else:
print("Wrong! The correct answer is %s." % answer)
wrong.append(question)
return (correct, wrong)
def stats(correct, wrong, answers):
print("\n**** STATS ****\n")
print("You answered", len(correct), "questions correctly and",
len(wrong), "questions wrong.")
if wrong:
print("These would have been the correct answers:")
for question in wrong:
print(' ', question, '=', answers[question])
# -
answers = read_questions('questions.txt')
correct, wrong = ask_questions(answers)
stats(correct, wrong, answers)
def main():
filename = input("Name of the question file: ")
answers = read_questions(filename)
correct, wrong = ask_questions(answers)
stats(correct, wrong, answers)
| .ipynb_checkpoints/Writing a Program-checkpoint.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout, Bidirectional
from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from yahoo_fin import stock_info as si
from collections import deque
import os
import numpy as np
import pandas as pd
import random
# -
# set seed, so we can get the same results after rerunning several times
np.random.seed(314)
tf.random.set_seed(314)
random.seed(314)
# +
import os
import time
from tensorflow.keras.layers import LSTM
# Window size or the sequence length
N_STEPS = 50
# Lookup step, 1 is the next day
LOOKUP_STEP = 15
# whether to scale feature columns & output price as well
SCALE = True
scale_str = f"sc-{int(SCALE)}"
# whether to shuffle the dataset
SHUFFLE = True
shuffle_str = f"sh-{int(SHUFFLE)}"
# whether to split the training/testing set by date
SPLIT_BY_DATE = False
split_by_date_str = f"sbd-{int(SPLIT_BY_DATE)}"
# test ratio size, 0.2 is 20%
TEST_SIZE = 0.2
# features to use
FEATURE_COLUMNS = ["adjclose", "volume", "open", "high", "low"]
# date now
date_now = time.strftime("%Y-%m-%d")
### model parameters
N_LAYERS = 2
# LSTM cell
CELL = LSTM
# 256 LSTM neurons
UNITS = 256
# 40% dropout
DROPOUT = 0.4
# whether to use bidirectional RNNs
BIDIRECTIONAL = False
### training parameters
# mean absolute error loss
# LOSS = "mae"
# huber loss
LOSS = "huber_loss"
OPTIMIZER = "adam"
BATCH_SIZE = 64
EPOCHS = 500
# Amazon stock market
ticker = "AMZN"
ticker_data_filename = os.path.join("data", f"{ticker}_{date_now}.csv")
# model name to save, making it as unique as possible based on parameters
model_name = f"{date_now}_{ticker}-{shuffle_str}-{scale_str}-{split_by_date_str}-\
{LOSS}-{OPTIMIZER}-{CELL.__name__}-seq-{N_STEPS}-step-{LOOKUP_STEP}-layers-{N_LAYERS}-units-{UNITS}"
if BIDIRECTIONAL:
model_name += "-b"
# +
def shuffle_in_unison(a, b):
# shuffle two arrays in the same way
state = np.random.get_state()
np.random.shuffle(a)
np.random.set_state(state)
np.random.shuffle(b)
def load_data(ticker, n_steps=50, scale=True, shuffle=True, lookup_step=1, split_by_date=True,
test_size=0.2, feature_columns=['adjclose', 'volume', 'open', 'high', 'low']):
"""
Loads data from Yahoo Finance source, as well as scaling, shuffling, normalizing and splitting.
Params:
ticker (str/pd.DataFrame): the ticker you want to load, examples include AAPL, TESL, etc.
n_steps (int): the historical sequence length (i.e window size) used to predict, default is 50
scale (bool): whether to scale prices from 0 to 1, default is True
shuffle (bool): whether to shuffle the dataset (both training & testing), default is True
lookup_step (int): the future lookup step to predict, default is 1 (e.g next day)
split_by_date (bool): whether we split the dataset into training/testing by date, setting it
to False will split datasets in a random way
test_size (float): ratio for test data, default is 0.2 (20% testing data)
feature_columns (list): the list of features to use to feed into the model, default is everything grabbed from yahoo_fin
"""
# see if ticker is already a loaded stock from yahoo finance
if isinstance(ticker, str):
# load it from yahoo_fin library
df = si.get_data(ticker)
elif isinstance(ticker, pd.DataFrame):
# already loaded, use it directly
df = ticker
else:
raise TypeError("ticker can be either a str or a `pd.DataFrame` instances")
# this will contain all the elements we want to return from this function
result = {}
# we will also return the original dataframe itself
result['df'] = df.copy()
# make sure that the passed feature_columns exist in the dataframe
for col in feature_columns:
assert col in df.columns, f"'{col}' does not exist in the dataframe."
# add date as a column
if "date" not in df.columns:
df["date"] = df.index
if scale:
column_scaler = {}
# scale the data (prices) from 0 to 1
for column in feature_columns:
scaler = preprocessing.MinMaxScaler()
df[column] = scaler.fit_transform(np.expand_dims(df[column].values, axis=1))
column_scaler[column] = scaler
# add the MinMaxScaler instances to the result returned
result["column_scaler"] = column_scaler
# add the target column (label) by shifting by `lookup_step`
df['future'] = df['adjclose'].shift(-lookup_step)
# last `lookup_step` columns contains NaN in future column
# get them before droping NaNs
last_sequence = np.array(df[feature_columns].tail(lookup_step))
# drop NaNs
df.dropna(inplace=True)
sequence_data = []
sequences = deque(maxlen=n_steps)
for entry, target in zip(df[feature_columns + ["date"]].values, df['future'].values):
sequences.append(entry)
if len(sequences) == n_steps:
sequence_data.append([np.array(sequences), target])
# get the last sequence by appending the last `n_step` sequence with `lookup_step` sequence
# for instance, if n_steps=50 and lookup_step=10, last_sequence should be of 60 (that is 50+10) length
# this last_sequence will be used to predict future stock prices that are not available in the dataset
last_sequence = list([s[:len(feature_columns)] for s in sequences]) + list(last_sequence)
last_sequence = np.array(last_sequence).astype(np.float32)
# add to result
result['last_sequence'] = last_sequence
# construct the X's and y's
X, y = [], []
for seq, target in sequence_data:
X.append(seq)
y.append(target)
# convert to numpy arrays
X = np.array(X)
y = np.array(y)
if split_by_date:
# split the dataset into training & testing sets by date (not randomly splitting)
train_samples = int((1 - test_size) * len(X))
result["X_train"] = X[:train_samples]
result["y_train"] = y[:train_samples]
result["X_test"] = X[train_samples:]
result["y_test"] = y[train_samples:]
if shuffle:
# shuffle the datasets for training (if shuffle parameter is set)
shuffle_in_unison(result["X_train"], result["y_train"])
shuffle_in_unison(result["X_test"], result["y_test"])
else:
# split the dataset randomly
result["X_train"], result["X_test"], result["y_train"], result["y_test"] = train_test_split(X, y,
test_size=test_size, shuffle=shuffle)
# get the list of test set dates
dates = result["X_test"][:, -1, -1]
# retrieve test features from the original dataframe
result["test_df"] = result["df"].loc[dates]
# remove duplicated dates in the testing dataframe
result["test_df"] = result["test_df"][~result["test_df"].index.duplicated(keep='first')]
# remove dates from the training/testing sets & convert to float32
result["X_train"] = result["X_train"][:, :, :len(feature_columns)].astype(np.float32)
result["X_test"] = result["X_test"][:, :, :len(feature_columns)].astype(np.float32)
return result
# -
def create_model(sequence_length, n_features, units=256, cell=LSTM, n_layers=2, dropout=0.3,
loss="mean_absolute_error", optimizer="rmsprop", bidirectional=False):
model = Sequential()
for i in range(n_layers):
if i == 0:
# first layer
if bidirectional:
model.add(Bidirectional(cell(units, return_sequences=True), batch_input_shape=(None, sequence_length, n_features)))
else:
model.add(cell(units, return_sequences=True, batch_input_shape=(None, sequence_length, n_features)))
elif i == n_layers - 1:
# last layer
if bidirectional:
model.add(Bidirectional(cell(units, return_sequences=False)))
else:
model.add(cell(units, return_sequences=False))
else:
# hidden layers
if bidirectional:
model.add(Bidirectional(cell(units, return_sequences=True)))
else:
model.add(cell(units, return_sequences=True))
# add dropout after each layer
model.add(Dropout(dropout))
model.add(Dense(1, activation="linear"))
model.compile(loss=loss, metrics=["mean_absolute_error"], optimizer=optimizer)
return model
# + tags=["outputPrepend"]
# create these folders if they does not exist
if not os.path.isdir("results"):
os.mkdir("results")
if not os.path.isdir("logs"):
os.mkdir("logs")
if not os.path.isdir("data"):
os.mkdir("data")
# load the data
data = load_data(ticker, N_STEPS, scale=SCALE, split_by_date=SPLIT_BY_DATE,
shuffle=SHUFFLE, lookup_step=LOOKUP_STEP, test_size=TEST_SIZE,
feature_columns=FEATURE_COLUMNS)
# save the dataframe
data["df"].to_csv(ticker_data_filename)
# construct the model
model = create_model(N_STEPS, len(FEATURE_COLUMNS), loss=LOSS, units=UNITS, cell=CELL, n_layers=N_LAYERS,
dropout=DROPOUT, optimizer=OPTIMIZER, bidirectional=BIDIRECTIONAL)
# -
# some tensorflow callbacks
checkpointer = ModelCheckpoint(os.path.join("results", model_name + ".h5"), save_weights_only=True, save_best_only=True, verbose=1)
tensorboard = TensorBoard(log_dir=os.path.join("logs", model_name))
# train the model and save the weights whenever we see
# a new optimal model using ModelCheckpoint
history = model.fit(data["X_train"], data["y_train"],
batch_size=BATCH_SIZE,
epochs=EPOCHS,
validation_data=(data["X_test"], data["y_test"]),
callbacks=[checkpointer, tensorboard],
verbose=1)
# +
import matplotlib.pyplot as plt
def plot_graph(test_df):
"""
This function plots true close price along with predicted close price
with blue and red colors respectively
"""
plt.plot(test_df[f'true_adjclose_{LOOKUP_STEP}'], c='b')
plt.plot(test_df[f'adjclose_{LOOKUP_STEP}'], c='r')
plt.xlabel("Days")
plt.ylabel("Price")
plt.legend(["Actual Price", "Predicted Price"])
plt.show()
# -
def get_final_df(model, data):
"""
This function takes the `model` and `data` dict to
construct a final dataframe that includes the features along
with true and predicted prices of the testing dataset
"""
# if predicted future price is higher than the current,
# then calculate the true future price minus the current price, to get the buy profit
buy_profit = lambda current, pred_future, true_future: true_future - current if pred_future > current else 0
# if the predicted future price is lower than the current price,
# then subtract the true future price from the current price
sell_profit = lambda current, pred_future, true_future: current - true_future if pred_future < current else 0
X_test = data["X_test"]
y_test = data["y_test"]
# perform prediction and get prices
y_pred = model.predict(X_test)
if SCALE:
y_test = np.squeeze(data["column_scaler"]["adjclose"].inverse_transform(np.expand_dims(y_test, axis=0)))
y_pred = np.squeeze(data["column_scaler"]["adjclose"].inverse_transform(y_pred))
test_df = data["test_df"]
# add predicted future prices to the dataframe
test_df[f"adjclose_{LOOKUP_STEP}"] = y_pred
# add true future prices to the dataframe
test_df[f"true_adjclose_{LOOKUP_STEP}"] = y_test
# sort the dataframe by date
test_df.sort_index(inplace=True)
final_df = test_df
# add the buy profit column
final_df["buy_profit"] = list(map(buy_profit,
final_df["adjclose"],
final_df[f"adjclose_{LOOKUP_STEP}"],
final_df[f"true_adjclose_{LOOKUP_STEP}"])
# since we don't have profit for last sequence, add 0's
)
# add the sell profit column
final_df["sell_profit"] = list(map(sell_profit,
final_df["adjclose"],
final_df[f"adjclose_{LOOKUP_STEP}"],
final_df[f"true_adjclose_{LOOKUP_STEP}"])
# since we don't have profit for last sequence, add 0's
)
return final_df
def predict(model, data):
# retrieve the last sequence from data
last_sequence = data["last_sequence"][-N_STEPS:]
# expand dimension
last_sequence = np.expand_dims(last_sequence, axis=0)
# get the prediction (scaled from 0 to 1)
prediction = model.predict(last_sequence)
# get the price (by inverting the scaling)
if SCALE:
predicted_price = data["column_scaler"]["adjclose"].inverse_transform(prediction)[0][0]
else:
predicted_price = prediction[0][0]
return predicted_price
# load optimal model weights from results folder
model_path = os.path.join("results", model_name) + ".h5"
model.load_weights(model_path)
# evaluate the model
loss, mae = model.evaluate(data["X_test"], data["y_test"], verbose=0)
# calculate the mean absolute error (inverse scaling)
if SCALE:
mean_absolute_error = data["column_scaler"]["adjclose"].inverse_transform([[mae]])[0][0]
else:
mean_absolute_error = mae
# get the final dataframe for the testing set
final_df = get_final_df(model, data)
# predict the future price
future_price = predict(model, data)
# we calculate the accuracy by counting the number of positive profits
accuracy_score = (len(final_df[final_df['sell_profit'] > 0]) + len(final_df[final_df['buy_profit'] > 0])) / len(final_df)
# calculating total buy & sell profit
total_buy_profit = final_df["buy_profit"].sum()
total_sell_profit = final_df["sell_profit"].sum()
# total profit by adding sell & buy together
total_profit = total_buy_profit + total_sell_profit
# dividing total profit by number of testing samples (number of trades)
profit_per_trade = total_profit / len(final_df)
# printing metrics
print(f"Future price after {LOOKUP_STEP} days is {future_price:.2f}$")
print(f"{LOSS} loss:", loss)
print("Mean Absolute Error:", mean_absolute_error)
print("Accuracy score:", accuracy_score)
print("Total buy profit:", total_buy_profit)
print("Total sell profit:", total_sell_profit)
print("Total profit:", total_profit)
print("Profit per trade:", profit_per_trade)
# plot true/pred prices graph
plot_graph(final_df)
final_df.head(20)
final_df.tail(20)
# save the final dataframe to csv-results folder
csv_results_folder = "csv-results"
if not os.path.isdir(csv_results_folder):
os.mkdir(csv_results_folder)
csv_filename = os.path.join(csv_results_folder, model_name + ".csv")
final_df.to_csv(csv_filename)
| machine-learning/stock-prediction/stock_prediction.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
y_train = np.genfromtxt("y_train.csv", delimiter=",")
features_train = np.genfromtxt("x_train.csv", delimiter=",")
features_test = np.genfromtxt("x_test.csv", delimiter=",")
sample = np.genfromtxt("sample.csv", delimiter=",")
y_train.shape
plt.plot(y_train)
np.nanmin(y_train, axis = 0)
np.nanmean(y_train, axis= 0)
np.nanmax(y_train, axis = 0)
features_train.shape
np.histogram(y_train[~np.isnan(y_train)], density=True)
# ### We try replacing the missing values by the mean of each feature: ###
#For the training set
featureColsMeans = np.nanmean(features_train, axis= 0)
inds = np.where(np.isnan(features_train))
features_train[inds] = np.take(featureColsMeans, inds[1])
#features_train
#For the test set
featureColsMeansTest = np.nanmean(features_test, axis= 0)
indsTest = np.where(np.isnan(features_test))
features_test[indsTest] = np.take(featureColsMeansTest, indsTest[1])
#features_test
features_train2 = np.genfromtxt("x_train.csv", delimiter=",")
df2 = pd.DataFrame(data=features_train2)
df1 = pd.DataFrame(data=features_train)
numberNaN = np.count_nonzero(np.isnan(features_train2))
print("there are this much NaN:" + str(numberNaN))
print("from the size "+ str(1213*833)+ " array.")
print("this is a " + str(numberNaN/(1213*833))+ "%")
features_train.shape
# +
import datacompy
compare = datacompy.Compare(
df1,
df2,
on_index=True, #You can also specify a list of columns eg ['policyID','statecode']
abs_tol=0, #Optional, defaults to 0
rel_tol=0, #Optional, defaults to 0
df1_name='Original', #Optional, defaults to 'df1'
df2_name='New' #Optional, defaults to 'df2'
)
print(compare.report())
# -
# ### Now let's try catching the outliers. We will use the ... method ###
features_train[:,0].shape
from sklearn.ensemble import IsolationForest
import seaborn as sns
sns.boxplot(x=features_train[:,1])
from sklearn.ensemble import IsolationForest
clf = IsolationForest(max_samples=10)
clf.fit(features_train)
sns.boxplot(x=features_train[:,1])
features_trainNO = clf.predict(features_train)
features_trainNO
unique, counts = np.unique(features_trainNO, return_counts=True)
dict(zip(unique, counts))
counts[1]
# +
newSize = counts[1]
features_train_clean = np.zeros(shape=(newSize, 833) )
y_train_clean = np.zeros(shape=(newSize,2) )
for i in range(0,features_trainNO.shape[0]):
if (features_trainNO[i] == 1):
features_train_clean[counts[1] - newSize] = features_train[i]
y_train_clean[counts[1] - newSize] = y_train[i]
newSize -= 1
# -
y_train
y_train_clean
np.savetxt("x_trainIF.csv", features_train_clean, delimiter=",")
features_train_clean2 = np.genfromtxt("x_trainIF.csv", delimiter=",")
features_train_clean2.shape
np.savetxt("y_trainIF.csv", y_train_clean, delimiter=",")
| IsolationForest.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # 100 Days of Machine Learning
# This code and lesson plan comes from: https://github.com/Avik-Jain/100-Days-Of-ML-Code
# Import needed libraries
import pandas as pd
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Import the data into pandas dataframe
# Set variable for dependent and independent data
dataset = pd.read_csv('datasets/Data.csv')
X = dataset.iloc[ : , :-1].values
Y = dataset.iloc[ : , 3].values
X
Y
# Handle the missing values using simpleimputer from scikit learn
imputer = SimpleImputer(missing_values = np.nan, strategy = "mean")
imputer = imputer.fit(X[ : , 1:3])
X[ : , 1:3] = imputer.transform(X[ : , 1:3])
X
# Encode the X categorical data using labelencoder from scikit learn.
labelencoder_X = LabelEncoder()
X[ : , 0] = labelencoder_X.fit_transform(X[ : , 0])
X
Y
# Encode the Y data using labelencoder from scikit learn
labelencoder_Y = LabelEncoder()
Y = labelencoder_Y.fit_transform(Y)
Y
# Split the datasets into training sets and test sets
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)
X_train
X_test
Y_train
Y_test
# Scale the features using standardscaler from scikit learn
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.fit_transform(X_test)
X_train
X_test
| 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
# ---
# + [markdown] colab_type="text" id="I6RHEpi4wdtx"
# # Generators
#
# Generators are custom iterators.
#
# - Generator Function
# - Generator Expression
# - [Reinventing the Parser Generator | YouTube.com](https://www.youtube.com/watch?v=zJ9z6Ge-vXs) <NAME>
#
# + [markdown] colab_type="text" id="5hdwsPueMMcx"
# Generators are one way to make a function or expression that can be iterated in a loop or with the `next()` function.
#
# - [Python Generators | python.org](https://wiki.python.org/moin/Generators)
# + [markdown] colab_type="text" id="nfiq-xmJ4aEo"
# ## Generator Functions
# + colab={} colab_type="code" id="nJLF3OAxwaeX"
def counter_gen():
count = 0
while True:
count += 1
yield count
# + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="O7BT1YuI1CS2" outputId="6995ff80-3b1e-43b1-8e28-6bae5e1b5c1f"
for count in counter_gen():
print(count)
if count >= 10:
break
# + [markdown] colab_type="text" id="2ZMaMchB2-CV"
# Generator functions will not remember where they left off from one call to the next.
# + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="cQZdj2Tl3EZ_" outputId="de0eed20-d555-4fb2-cbc0-679e1b27baea"
for count in counter_gen():
print(count)
if count >= 10:
break
# + [markdown] colab_type="text" id="SLp9O9QzI1La"
# But there is a way to make them remember! Memoization. This ability is not unique to generator functions, you can memoize any function.
# + colab={} colab_type="code" id="nP0iU22_3lRP"
def smart_counter_gen():
if not hasattr(smart_counter_gen, "count"):
smart_counter_gen.count = 0
while True:
smart_counter_gen.count += 1
yield smart_counter_gen.count
# + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="Nfj_ItBm3wCJ" outputId="48bf90b0-1aea-4722-b5b1-35d903291acc"
for count in smart_counter_gen():
print(count)
if count >= 10:
break
# + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="GYivdvEs356q" outputId="55c926bb-bb3a-406a-bded-d61a9fc95cba"
for count in smart_counter_gen():
print(count)
if count >= 20:
break
# + [markdown] colab_type="text" id="qvWqLejYKE6C"
# What if we wanted a way to reset the counter?
# + colab={} colab_type="code" id="cH3hIgtTKIru"
def smart_counter(reset=False):
if reset or not hasattr(smart_counter, "count"):
smart_counter.count = 0
while True:
smart_counter.count += 1
yield smart_counter.count
# + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="ZGlQVNjsKPbL" outputId="5686d414-89e0-463b-ff2b-20e4d062d1fa"
for count in smart_counter():
print(count)
if count >= 10:
break
# + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="QeVNz7lvKSn0" outputId="21999dbd-a505-459f-df47-9dc5d1c1622b"
for count in smart_counter(reset=True):
print(count)
if count >= 10:
break
# + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="XrYlzN2UKdDk" outputId="660bbbec-0a40-4b9f-f754-2da55778e7dc"
for count in smart_counter():
print(count)
if count >= 20:
break
# + [markdown] colab_type="text" id="ULlLzgy04WHp"
# ## Generator Expressions
#
# Generator expressions look a lot like tuple comprehensions, but there is no such thing as a tuple comprehension in Python. Generator expressions can be a little tricky at first because they can only be evaluated once and this can be a subtle problem as there will be no error - it just wont do what you want after the first evaluation.
# + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="YnhBdl901KuP" outputId="9fedf651-3b4b-44e9-8f42-1870c4a932cf"
square_gen = (i*i for i in range(1, 11))
for square in square_gen:
print(square)
# + colab={} colab_type="code" id="Ft16kPt22NMB"
for square in square_gen:
print(square) # Prints Nothing! The generator is empty.
# + colab={} colab_type="code" id="OaUwylyh73Rt"
# + [markdown] colab_type="text" id="iMg6jLMy8Q66"
# ### Generator Expression that works like a Generator Function
#
# To make a generator expression or any iterator that can be used more than once, we must wrap it in a callable, like a lambda. Every time we call this lambda a new generator is created for us. This gives the added ability to parameterize the generator expression.
# + colab={} colab_type="code" id="cxL8tOVm8ZxQ"
square_gen = lambda n: (i*i for i in range(n+1))
# + colab={"base_uri": "https://localhost:8080/", "height": 187} colab_type="code" id="NLnfij6U6YDK" outputId="a6c7ff18-c835-4a8f-8f84-9212079afcaa"
for square in square_gen(9):
print(square)
# + colab={"base_uri": "https://localhost:8080/", "height": 119} colab_type="code" id="HZPayF1w6q66" outputId="3f1dd511-7926-4359-c16f-b3eb9b6f21f0"
for square in square_gen(5):
print(square)
| WEEKS/CD_Sata-Structures/_RESOURCES/python-prac/Intro_to_Python/14_generators.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: py3modeling
# language: python
# name: py3modeling
# ---
# + id="cpgfYiuw_wHM"
import numpy as np
from scipy.linalg import sqrtm
from scipy.special import softmax
import networkx as nx
from networkx.algorithms.community.modularity_max import greedy_modularity_communities
import matplotlib.pyplot as plt
from matplotlib import animation
# %matplotlib inline
from IPython.display import HTML
# + [markdown] id="X-A-TQwF_wHV"
# # Message Passing as Matrix Multiplication
# + id="9L6GZDEs_wHY" outputId="6eda630d-5d28-4c8c-a951-6a7298027f43"
A = np.array(
[[0, 1, 0, 0, 0], [1, 0, 1, 0, 0], [0, 1, 0, 1, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]]
)
A
# + id="xV_iHm9y_wHc" outputId="51bde64d-ada8-410e-d5ed-024d9e5791de"
feats = np.arange(A.shape[0]).reshape((-1,1))+1
feats
# + id="S3FkjqXs_wHe" outputId="4a3ee0bc-2c61-495e-fd55-6621bf8fd1ff"
H = A @ feats
H
# + [markdown] id="1CSpquIi_wHg"
# ## Scale neighborhood sum by neighborhood size (i.e. average values)
# + id="NGXMZBNR_wHh" outputId="f97c8466-f968-47f1-c06d-f0fc92f24ac9"
D = np.zeros(A.shape)
np.fill_diagonal(D, A.sum(axis=0))
D
# + id="9DH5B7Ps_wHj" outputId="4df1ce9b-904f-451a-daef-296e4efaae6a"
D_inv = np.linalg.inv(D)
D_inv
# + id="oGNtuMhl_wHk" outputId="f627a792-8beb-4345-a957-e76639012f55"
D_inv @ A
# + id="9XNzREKp_wHl" outputId="afa9774c-2c87-4ff3-b1dc-8fad8f7513e3"
H_avg = D_inv @ A @ feats
H_avg
# + [markdown] id="uAX9AksV_wHm"
# ## Normalized Adjacency Matrix
# Ultimately want to define and build:
#
# $$ \hat{A} = \tilde{D}^{-\frac{1}{2}} \tilde{A} \tilde{D}^{-\frac{1}{2}} $$
#
# + [markdown] id="kj4DGyUu_wHn"
# First, create $\tilde{A}$:
# $$ \tilde{A} = A + I $$
# + id="6JSu_-0N_wHn"
g = nx.from_numpy_array(A)
A_mod = A + np.eye(g.number_of_nodes())
# + [markdown] id="DcknOZ1s_wHo"
# Then create $ \tilde{D}^{-\frac{1}{2}} $, where $D$ is the diagonal degree matrix:
#
# $$ (D)_{ij} = \delta_{i,j} \sum_k A_{i,k} $$
# + id="U0erlE1f_wHp"
# D for A_mod:
D_mod = np.zeros_like(A_mod)
np.fill_diagonal(D_mod, A_mod.sum(axis=1).flatten())
# Inverse square root of D:
D_mod_invroot = np.linalg.inv(sqrtm(D_mod))
# + id="zNkbY-df_wHp" outputId="de792dc9-9c3c-4d5f-e8b0-44d38c62b72e"
D_mod
# + id="CpeCM0EE_wHq" outputId="91ecf3fd-d6b0-4002-9b30-37f63175bb87"
D_mod_invroot
# + [markdown] id="rzfI6rMW_wHr"
# I.e.: $\frac{1}{\sqrt{2}}$, $\frac{1}{\sqrt{3}}$, $\frac{1}{\sqrt{4}}$, ...etc
# + id="C2le3Vc4_wHs"
node_labels = {i: i+1 for i in range(g.number_of_nodes())}
pos = nx.planar_layout(g)
# + id="GRYymwcM_wHs" outputId="a413e7d7-6b02-4c37-e672-ecebc7a94741"
fig, ax = plt.subplots(figsize=(10,10))
nx.draw(
g, pos, with_labels=True,
labels=node_labels,
node_color='#83C167',
ax=ax, edge_color='gray', node_size=1500, font_size=30, font_family='serif'
)
plt.savefig('simple_graph.png', bbox_inches='tight', transparent=True)
# + id="CYDhUiyg_wHu" outputId="65234fff-0166-4029-830f-c4ec1b1a9576"
pos
# + [markdown] id="Ir3SbSyr_wHu"
# Create $\hat{A}$:
#
# $$ \hat{A} = \tilde{D}^{-\frac{1}{2}} \tilde{A} \tilde{D}^{-\frac{1}{2}} $$
#
# $$ (\hat{A})_{i,j} = \frac{\tilde{A}_{i,j}}{\sqrt{\tilde{d_i} \tilde{d_j}}} $$
# + id="CDBaEX0j_wHv"
A_hat = D_mod_invroot @ A_mod @ D_mod_invroot
# + [markdown] id="RB1cKpes_wHv"
# # Water drop
# + id="Zdu5N-u-_wHv"
H = np.zeros((g.number_of_nodes(), 1))
H[0,0] = 1 # the "water drop"
iters = 10
results = [H.flatten()]
for i in range(iters):
H = A_hat @ H
results.append(H.flatten())
# + id="jZ4_eZ5L_wHw" outputId="e1272bcf-d308-47b8-89d9-2531e4fb5662"
print(f"Initial signal input: {results[0]}")
print(f"Final signal output after running {iters} steps of message-passing: {results[-1]}")
# + id="Zfgi0ids_wHw" outputId="cf0bd6a6-b2d3-4b3c-9112-a9cc77b97578"
fig, ax = plt.subplots(figsize=(10, 10))
kwargs = {'cmap': 'hot', 'node_size': 1500, 'edge_color': 'gray',
'vmin': np.array(results).min(), 'vmax': np.array(results).max()*1.1}
def update(idx):
ax.clear()
colors = results[idx]
nx.draw(g, pos, node_color=colors, ax=ax, **kwargs)
ax.set_title(f"Iter={idx}", fontsize=20)
anim = animation.FuncAnimation(fig, update, frames=len(results), interval=1000, repeat=True)
# + id="ZSJ4Ri3n_wHx"
anim.save(
'water_drop.mp4',
dpi=600, bitrate=-1,
savefig_kwargs={'transparent': True, 'facecolor': 'none'},
)
# + id="6VZZbf0q_wHy" outputId="78accd67-3db1-4579-a9d3-7f0414e46c71"
HTML(anim.to_html5_video())
# + id="Xrbw6OJL_wHz"
| _docs/nbs/T568177-GCN-Message-Passing.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
# ---
# # Learning a parametrized quantum circuit
#
# In this tutorial, we show how `qgrad` can be used
# to perform circuit learning as well, in that how
# it helps us to take gradients of circuits.
#
# For this example, we will train a simple
# variational quantum circuit. We shall apply
# rotations around $X, Y$ and $Z$ axes and
# shall use CNOT as an entangling gate. Note
# that `qgrad` was not motivated to be a circuit
# library, so one would have to define the gates
# themselves, which understandably creates some
# friction when working with quantum circuits.
# The goal of this tutorial, however, is to
# merely showcase that circuit learning is indeed
# _possible_ in `qgrad`
#
# We train a two-qubit circuit and measure
# the the first qubit and take the expectation
# with respect to the $\sigma_{z}$ operator. This
# serves as our cost function in this routine and
# the aim is to minimize this cost function
# using optimal rotation angles for the rotation
# gates.
#
#
# +
from functools import reduce
import jax.numpy as jnp
from jax.random import PRNGKey, uniform
from jax.experimental import optimizers
from jax import grad
from qutip import sigmaz
import matplotlib.pyplot as plt
from qgrad.qgrad_qutip import basis, expect, sigmaz, Unitary
# +
def rx(phi):
"""Rotation around x-axis
Args:
phi (float): rotation angle
Returns:
:obj:`jnp.ndarray`: Matrix
representing rotation around
the x-axis
"""
return jnp.array([[jnp.cos(phi / 2), -1j * jnp.sin(phi / 2)],
[-1j * jnp.sin(phi / 2), jnp.cos(phi / 2)]])
def ry(phi):
"""Rotation around y-axis
Args:
phi (float): rotation angle
Returns:
:obj:`jnp.ndarray`: Matrix
representing rotation around
the y-axis
"""
return jnp.array([[jnp.cos(phi / 2), -jnp.sin(phi / 2)],
[jnp.sin(phi / 2), jnp.cos(phi / 2)]])
def rz(phi):
"""Rotation around z-axis
Args:
phi (float): rotation angle
Returns:
:obj:`jnp.ndarray`: Matrix
representing rotation around
the z-axis
"""
return jnp.array([[jnp.exp(-1j * phi / 2), 0],
[0, jnp.exp(1j * phi / 2)]])
def cnot():
"""Returns a CNOT gate"""
return jnp.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]],)
# -
def circuit(params):
"""Returns the state evolved by
the parametrized circuit
Args:
params (list): rotation angles for
x, y, and z rotations respectively.
Returns:
:obj:`jnp.array`: state evolved
by a parametrized circuit
"""
thetax, thetay, thetaz = params
layer0 = jnp.kron(basis(2, 0), basis(2, 0))
layer1 = jnp.kron(ry(jnp.pi / 4), ry(jnp.pi / 4))
layer2 = jnp.kron(rx(thetax), jnp.eye(2))
layer3 = jnp.kron(ry(thetay), rz(thetaz))
layers = [layer1, cnot(), layer2, cnot(), layer3]
unitary = reduce(lambda x, y : jnp.dot(x, y), layers)
return jnp.dot(unitary, layer0)
# ## The Circuit
#
# Our 2 qubit circuit looks like follows
#
# <img src="images/circuit.jpg">
#
# We add constant $Y$ rotation of
# $\frac{\pi}{4}$ in the first
# layer to avoid any preferential
# gradient direction in the beginning.
# +
# pauli Z on the first qubit
op = jnp.kron(sigmaz(), jnp.eye(2))
def cost(params, op):
"""Cost function to optimize
Args:
params (list): rotation angles for
x, y, and z rotations respectively
op (:obj:`jnp.ndarray`): Operator
with respect to which the expectation
value is to be calculated
Returns:
float: Expectation value of the evloved
state w.r.t the given operator `op`
"""
state = circuit(params)
return jnp.real(expect(op, state))
# +
# fixed random parameter initialization
init_params = [0., 0., 0.]
opt_init, opt_update, get_params = optimizers.adam(step_size=1e-2)
opt_state = opt_init(init_params)
def step(i, opt_state, opt_update):
params = get_params(opt_state)
g = grad(cost)(params, op)
return opt_update(i, g, opt_state)
epochs = 400
loss_hist = []
for epoch in range(epochs):
opt_state = step(epoch, opt_state, opt_update)
params = get_params(opt_state)
loss = cost(params, op)
loss_hist.append(loss)
progress = [epoch+1, loss]
if (epoch % 50 == 49):
print("Epoch: {:2f} | Loss: {:3f}".format(*jnp.asarray(progress)))
# -
plt.plot(loss_hist)
plt.ylabel("Loss")
plt.xlabel("epochs")
# ## Conclusion
#
# Note that the value of the cost function
# is bounded between $-1$ and $1$ because
# we take the expectation value with
# respect to the Pauli-Z
# operator. This expectation
# value of a state $\psi$
# with respect to $\sigma_{z}$
# is
#
# \begin{equation}
# \langle \psi| \sigma_{z} |\psi\rangle
# \end{equation}
#
#
# And it is well-known that
#
# \begin{equation}
# \sigma_{z}|0\rangle = |0\rangle \\
# \sigma_{z} |1\rangle = -|1\rangle
# \end{equation}
#
# We see in the graph that the loss starts
# off bad from around $0.75$ (when the worse
# it could get was $1$). During the
# optimization routine, the loss progressively
# gets down in $400$ epochs to very close to
# $-1$. which was the best one could expect.
| examples/notebooks/Circuit-Learning.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/google/oculi/blob/master/colabs/CM360/%5Bcolab_3%5D_Feature_Extraction_and_Modeling.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="9mxCM0WQMmNs"
# # Setup
# + id="JvDepfrCNwFY"
import os
from google.cloud import bigquery
import pandas as pd
from google.colab import syntax
# + colab={"base_uri": "https://localhost:8080/"} id="IDajPVDxMz8G" outputId="45a698a8-c15d-411b-bcd6-d8b28f3c5048"
# %%writefile credentials.json
{
"type": "service_account",
"project_id": "[project_id]",
"private_key_id": "[private_key_id]",
"private_key": "[private_key]",
"client_email": "[client_email]",
"client_id": "[client_id]",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "[client_x509_cert_url]"
}
# + id="wxCgZb_6N7dS"
#@title Project Variables { run: "auto", display-mode: "form" }
project_id = 'oculi-v2-dev' #@param {type:"string"}
dataset_name = "demoverse" #@param {type:"string"}
#@markdown Enter a file path for the json key downloaded from GCP:
json_key_file = r'credentials.json' #@param {type:"string"}
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'credentials.json'
client = bigquery.Client(project=project_id)
# + [markdown] id="6Sxskl8PRnwD"
# # Helper Functions
# + id="G3Pj0PBeRqXN"
from IPython.display import Image, display, IFrame
from IPython.core.display import HTML
def display_creative(url):
extension = url.split('.')[-1]
if extension == 'html':
display(IFrame(src=url, width=300, height=250))
else:
display(Image(url=url))
def display_sample(subset, sample_size=5):
sample = subset.sample(sample_size)
sample_urls = sample['url'].tolist()
sample_cids = sample['creative_id'].tolist()
for i in range(sample_size):
print('Creative ID:', sample_cids[i])
print('URL:', sample_urls[i])
display_creative(sample_urls[i])
print()
def fill_sql(sql):
return sql.format(project=project_id, dataset=dataset_name)
def sql_to_df(sql):
sql = fill_sql(sql)
return client.query(sql).to_dataframe()
def sql_to_view(sql, view_name):
sql = fill_sql(sql)
view_id = '{project}.{dataset}.{view_name}'.format(
project=project_id, dataset=dataset_name,
view_name=view_name
)
view = bigquery.Table(view_id)
view.view_query = sql
client.delete_table(view, not_found_ok=True)
return client.create_table(view)
def sql_to_pivot_df(sql, col_name, view_name, prominence, limit='20'):
sql = sql.format(
project=project_id, dataset=dataset_name,
col_name=col_name, view_name=view_name,
prominence=prominence, limit=limit
)
df = sql_to_df(sql)
features = pd.pivot_table(
df, index='creative_id', values='prominence',
columns=col_name
)
features.reset_index(inplace=True)
features.fillna(0, inplace=True)
return features
# + [markdown] id="sLLB-PqQM8M9"
# # Flattening
# + [markdown] id="kOIYiYfaUmlw"
# ## Sizes
# + id="QrUR0SIXUpPR"
sql = syntax.sql('''
SELECT
creative_id,
full_url AS url,
CAST(SPLIT(creative_pixel_size, 'x')[OFFSET(0)] AS INT64) AS width,
CAST(SPLIT(creative_pixel_size, 'x')[OFFSET(1)] AS INT64) AS height
FROM `{project}.{dataset}.creative_urls`
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 142} id="n1UTUBCLUwdO" outputId="58b50912-4711-4032-aec7-6c11991f26a5"
sql_to_df(sql).head(3)
# + colab={"base_uri": "https://localhost:8080/"} id="8Xa8TVRuUyp_" outputId="fd1e4bd9-01e5-4d1b-cfb0-f0b3ef46c267"
sql_to_view(sql, 'creative_sizes')
# + [markdown] id="erW61ffJND7H"
# ## Labels
# + id="SyIm2wgoNBGj"
sql = syntax.sql('''
SELECT
creative_id,
frame_id,
description AS label,
score
FROM
`{project}.{dataset}.label_annotations`
JOIN UNNEST(frames)
JOIN UNNEST(label_annotations)
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 142} id="LGW861-jO6ys" outputId="c451b46f-6f25-4149-d8b4-7b367f8b3e13"
sql_to_df(sql).head(3)
# + colab={"base_uri": "https://localhost:8080/"} id="90nRZZ0FRgXh" outputId="d610d57b-01b5-4773-f031-e9586eb8461d"
sql_to_view(sql, 'flat_labels')
# + [markdown] id="s0k4mDojS6-8"
# ## Objects
# + id="cZy_HtDhTBsN"
sql = syntax.sql('''
SELECT
creative_id,
frame_id,
name AS object,
score,
(
(MAX(v.x) - MIN(v.x)) -- width of shape
*
(MAX(v.y) - MIN(v.y)) -- height of shape
) AS area_fraction
FROM
`{project}.{dataset}.localized_object_annotations`
JOIN UNNEST(frames)
JOIN UNNEST(localized_object_annotations)
JOIN UNNEST(boundingPoly.normalizedVertices) AS v
GROUP BY 1,2,3,4
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 142} id="N0l4i_ByTp_B" outputId="898a10e3-1d62-410e-d331-95ad06aaf6ce"
sql_to_df(sql).head(3)
# + colab={"base_uri": "https://localhost:8080/"} id="q0m_ilKxTrTE" outputId="8f63a3a1-8112-42fa-d042-473609e85b1e"
sql_to_view(sql, 'flat_objects')
# + [markdown] id="qVA4ezBrSkHn"
# ## Words
# + id="a_zf5xPUSo3v"
sql = syntax.sql('''
SELECT
creative_id,
frame_id,
LOWER(description) AS word,
(
(MAX(v.x) - MIN(v.x)) / ANY_VALUE(width)
*
(MAX(v.y) - MIN(v.y)) / ANY_VALUE(height)
) AS area_fraction
FROM
`{project}.{dataset}.text_annotations`
JOIN UNNEST(frames)
JOIN UNNEST(text_annotations)
JOIN UNNEST(boundingPoly.vertices) AS v
JOIN `{project}.{dataset}.creative_sizes` USING (creative_id)
WHERE
-- Exclude small and common words
LENGTH(description) > 2
AND LOWER(description) NOT IN ('for', 'the')
GROUP BY 1,2,3
''')
# + colab={"base_uri": "https://localhost:8080/"} id="vt4183uBS1V0" outputId="22b4cecc-b466-4e52-9af8-9968dbbd1f12"
sql_to_view(sql, 'flat_words')
# + colab={"base_uri": "https://localhost:8080/", "height": 142} id="e-VAzYEJS0EJ" outputId="40347249-728a-4a47-cc57-5f92c1adc364"
sql_to_df(sql).head(3)
# + [markdown] id="MRXMY0kxT0YU"
# ## Colors
# + id="-xvJjiM9T2Yw"
sql = syntax.sql('''
SELECT
creative_id,
frame_id,
ROW_NUMBER() OVER (PARTITION BY creative_id, frame_id) AS color,
color.red,
color.green,
color.blue,
score,
pixelFraction AS area_fraction
FROM
`{project}.{dataset}.image_properties_annotation`
JOIN UNNEST(frames)
JOIN UNNEST(image_properties_annotation.dominantColors.colors)
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 142} id="qzUM0QLcUj-4" outputId="1d9f8b65-fea4-4947-adf8-c9bfbda72cbb"
sql_to_df(sql).head(3)
# + colab={"base_uri": "https://localhost:8080/"} id="sniu1b1yVfhs" outputId="0346977a-4773-4cbb-c234-d88b3596c9d9"
sql_to_view(sql, 'flat_colors')
# + [markdown] id="bc4eADSXVjzl"
# ## Faces
# + id="el5-1p5gVn7i"
sql = syntax.sql('''
SELECT
creative_id,
frame_id,
ROW_NUMBER() OVER (PARTITION BY creative_id, frame_id) AS face,
headwearLikelihood,
angerLikelihood,
surpriseLikelihood,
sorrowLikelihood,
joyLikelihood,
panAngle,
rollAngle,
tiltAngle,
detectionConfidence AS score,
(
(MAX(v.x) - MIN(v.x)) / ANY_VALUE(width)
*
(MAX(v.y) - MIN(v.y)) / ANY_VALUE(height)
) AS area_fraction
FROM
`{project}.{dataset}.face_annotations`
JOIN UNNEST(frames)
JOIN UNNEST(face_annotations)
JOIN UNNEST(boundingPoly.vertices) AS v
JOIN `{project}.{dataset}.creative_sizes` USING (creative_id)
GROUP BY 1,2,4,5,6,7,8,9,10,11,12
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 162} id="n96cVnwaVrxF" outputId="76725d46-d353-4c3e-d852-490ef564431d"
sql_to_df(sql).head(3)
# + colab={"base_uri": "https://localhost:8080/"} id="23By1EAIVtB7" outputId="9163c660-e97e-4c00-a141-5e5176d55114"
sql_to_view(sql, 'flat_faces')
# + [markdown] id="DqrdA2fZV8O8"
# ## Logos
# + id="Y8C083x5V9Cp"
sql = syntax.sql('''
SELECT
creative_id,
frame_id,
description AS logo,
score,
(
(MAX(v.x) - MIN(v.x)) / ANY_VALUE(width)
*
(MAX(v.y) - MIN(v.y)) / ANY_VALUE(height)
) AS area_fraction,
(MAX(v.x) + MIN(v.x)) / 2 / ANY_VALUE(width) AS x_fraction,
(MAX(v.y) + MIN(v.y)) / 2 / ANY_VALUE(height) AS y_fraction,
FROM
`{project}.{dataset}.logo_annotations`
JOIN UNNEST(frames)
JOIN UNNEST(logo_annotations)
JOIN UNNEST(boundingPoly.vertices) AS v
JOIN `{project}.{dataset}.creative_sizes` USING (creative_id)
GROUP BY 1,2,3,4
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 142} id="aXIyjl3tXJbt" outputId="a454ed79-c050-48f0-f8f3-02f12ec4779e"
sql_to_df(sql).head(3)
# + colab={"base_uri": "https://localhost:8080/"} id="oW7h7zEkXKkA" outputId="554067e4-43b7-4dbd-d3c7-056bd0039245"
sql_to_view(sql, 'flat_logos')
# + [markdown] id="bFJN9t5cX_zM"
# # Feature Extraction
# + [markdown] id="B7MalkKNYCZo"
# ## Colors
# + id="wcHuMBsBYGMH"
sql = syntax.sql('''
WITH scaled_colors AS (
SELECT
creative_id,
frame_id,
color,
red / 255.0 AS red,
green / 255.0 AS green,
blue / 255.0 AS blue,
-- definition of perceived brightness:
-- https://en.wikipedia.org/wiki/Relative_luminance
(0.2126*red + 0.7152*green + 0.0722*blue) / 255.0 AS brightness,
area_fraction
FROM `{project}.{dataset}.flat_colors`
)
SELECT
creative_id,
SUM(red * area_fraction) / COUNT(frame_id) AS avg_redness,
SUM(green * area_fraction) / COUNT(frame_id) AS avg_greenness,
SUM(blue * area_fraction) / COUNT(frame_id) AS avg_blueness,
SUM(brightness * area_fraction) / COUNT(frame_id) AS avg_brightness,
MAX(red * area_fraction) AS max_redness,
MAX(green * area_fraction) AS max_greenness,
MAX(blue * area_fraction) AS max_blueness,
MAX(brightness * area_fraction) AS max_brightness
FROM scaled_colors
GROUP BY 1
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 142} id="gPKOpW-Ue0BL" outputId="bf1292cd-9445-465c-a946-c7a812cdb19e"
df_colors = sql_to_df(sql)
df_colors.head(3)
# + [markdown] id="QtyHYZhTfgJ-"
# ## Faces
# + id="rD5ubfxAfhBv"
sql = syntax.sql('''
CREATE OR REPLACE FUNCTION `{project}.{dataset}.likelihoodToNumber`(likelihood STRING) AS (
CASE
WHEN likelihood = 'VERY_LIKELY' THEN 1.0
WHEN likelihood = 'LIKELY' THEN 0.7
WHEN likelihood = 'POSSIBLE' THEN 0.5
ELSE 0
END
);
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 32} id="-1pIMfxsfqQi" outputId="af9ff335-2741-487d-907e-6696af93aa8c"
sql_to_df(sql).head(3)
# + id="a7hJj-ZSfyI6"
sql = syntax.sql('''
WITH scaled_faces AS (
SELECT
creative_id,
frame_id,
face,
`{project}.{dataset}.likelihoodToNumber`(headwearLikelihood) AS headwear,
`{project}.{dataset}.likelihoodToNumber`(angerLikelihood) AS anger,
`{project}.{dataset}.likelihoodToNumber`(surpriseLikelihood) AS surprise,
`{project}.{dataset}.likelihoodToNumber`(sorrowLikelihood) AS sorrow,
`{project}.{dataset}.likelihoodToNumber`(joyLikelihood) AS joy,
ABS(panAngle) / 180.0 + ABS(rollAngle) / 180.0 + ABS(tiltAngle) / 180.0 AS angular_deviation,
score,
area_fraction
FROM `{project}.{dataset}.flat_faces`
)
SELECT
creative_id,
COUNT(face) AS num_faces,
MAX(headwear) AS has_headwear_face,
MAX(anger) AS has_angry_face,
MAX(surprise) AS has_surprised_face,
MAX(sorrow) AS has_sad_face,
MAX(joy) AS has_happy_face,
MAX(area_fraction) AS largest_face_area,
1 - MIN(angular_deviation) AS has_front_facing_face
FROM scaled_faces
GROUP BY 1
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 80} id="_R61o7ZZiqXR" outputId="823a536c-4722-41c7-fbbe-22b70c6422bb"
df_faces = sql_to_df(sql)
df_faces.head(3)
# + [markdown] id="gbEKnGDckW4P"
# ## Logos
# + id="6AphcgKckZAP"
sql = syntax.sql('''
WITH flat_logos_with_prominence AS (
SELECT
creative_id,
frame_id,
logo,
(score * area_fraction) AS prominence,
x_fraction,
y_fraction
FROM `{project}.{dataset}.flat_logos` LIMIT 1000
),
prominent_logos AS (
SELECT
creative_id,
logo,
ROW_NUMBER() OVER (PARTITION BY creative_id ORDER BY prominence DESC) AS rank,
x_fraction,
y_fraction
FROM flat_logos_with_prominence
)
SELECT
creative_id,
IF(x_fraction < 0.5 AND y_fraction < 0.5, 1, 0) AS has_logo_top_left,
IF(x_fraction > 0.5 AND y_fraction < 0.5, 1, 0) AS has_logo_top_right,
IF(x_fraction < 0.5 AND y_fraction > 0.5, 1, 0) AS has_logo_bottom_left,
IF(x_fraction > 0.5 AND y_fraction > 0.5, 1, 0) AS has_logo_bottom_right
FROM prominent_logos
WHERE rank = 1
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 142} id="36Fk-20uorGL" outputId="e06de4d3-ba0b-4466-c9d6-0fa417188bc6"
df_logos = sql_to_df(sql)
df_logos.head(3)
# + [markdown] id="jQjDkWIAoxRY"
# ## Labels (one-hot query)
# + id="Rg3Kg8rPp_qz"
one_hot_sql = syntax.sql('''
WITH
source AS (
SELECT
creative_id,
'has_{col_name}_' || LOWER(REGEXP_REPLACE(REPLACE({col_name},' ','_'), r'[;:*?#"<>|()&,\.]', ''))
AS col,
{prominence} AS prominence
FROM `{project}.{dataset}.{view_name}`
GROUP BY 1, 2
)
SELECT
creative_id,
col AS {col_name},
prominence
FROM
source
INNER JOIN
(
SELECT col, MAX(prominence)
FROM source
GROUP BY 1
ORDER BY MAX(prominence) DESC
LIMIT {limit}
)
USING (col)
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 162} id="aQ8lz3lHrTgd" outputId="36aa771f-9b28-4b86-997a-92fbd5d2f73c"
df_labels = sql_to_pivot_df(
one_hot_sql,
col_name='label',
view_name='flat_labels',
prominence='MAX(score)',
limit='20'
)
df_labels.head(3)
# + [markdown] id="i0wfWa7os7is"
# ## Words
# + colab={"base_uri": "https://localhost:8080/", "height": 196} id="YwU6peW9s-6O" outputId="89c34b35-85b8-4ef3-8b9f-cd1c407b3a38"
df_words = sql_to_pivot_df(
one_hot_sql,
col_name='word',
view_name='flat_words',
prominence='MAX(area_fraction)',
limit='30'
)
df_words.head(3)
# + [markdown] id="mjb6ToxytO8R"
# ## Objects
# + colab={"base_uri": "https://localhost:8080/", "height": 162} id="LX-NhMvbtcfc" outputId="0c667c8b-f91a-44bf-a6e9-748cc3d257b7"
df_objects = sql_to_pivot_df(
one_hot_sql,
col_name='object',
view_name='flat_objects',
prominence='SUM(score * area_fraction) / COUNT(DISTINCT frame_id)',
limit='30'
)
df_objects.head(3)
# + [markdown] id="IJAP5k3ASETy"
# ## Sizes
# + id="Y5E_AlmQtyCL"
sql = syntax.sql('''
SELECT * FROM `{project}.{dataset}.creative_sizes`
''')
# + colab={"base_uri": "https://localhost:8080/", "height": 142} id="ktnEx2_muTOt" outputId="cb98ff3d-1b59-4d57-cc1c-f59fddeddd6c"
df_all_creatives = sql_to_df(sql)
df_all_creatives.head(3)
# + [markdown] id="ZE2totgkttym"
# # Full Feature Table
# + colab={"base_uri": "https://localhost:8080/", "height": 225} id="dhTsFF4EujZb" outputId="dd468def-0a2b-46e1-c780-9974f3e19a52"
df_features = pd.merge(df_all_creatives,
df_colors, how='outer', on='creative_id')
df_features = pd.merge(df_features,
df_faces, how='outer', on='creative_id')
df_features = pd.merge(df_features,
df_logos, how='outer', on='creative_id')
df_features = pd.merge(df_features,
df_objects, how='outer', on='creative_id')
df_features = pd.merge(df_features,
df_words, how='outer', on='creative_id')
df_features = pd.merge(df_features,
df_labels, how='outer', on='creative_id')
df_features.fillna(0, inplace=True)
df_features.head(3)
# + [markdown] id="M5zx7ojSv43X"
# ## Exploration
# + id="88lsbJ25wfJe" colab={"base_uri": "https://localhost:8080/", "height": 322} outputId="5cc84de8-fb7a-42ac-e7f4-8b99d1f7c744"
subset = df_features[df_features['num_faces'] > 0]
display_sample(subset, 1)
# + [markdown] id="kCn-VKq7PjV7"
# ## Merge with Performance Data
# + [markdown] id="8HsLwKqOVY9U"
# Steps taken in the Campaign Manager UI:
# 1. Go to Campaign Manager > Reporting and Attribution > enter your account ID
# 2. Create a new Standard report including, at minimum, *Creative ID* and performance metrics (*Impressions, Clicks, Active View: Viewable Impressions, Active View: Measureable Impressions*)
# - Don't include *Date* as a dimension
# - Set the *Date Range* to the maximum allowed (24 months)
# 3. Run the report, download as CSV, and upload to BigQuery as a table called `performance` in the same dataset as the Oculi data
# - Set *Number of errors allowed* to 2
# - Set *Header rows to skip* to the line number of the column headers in the CSV (usually 11, but depends on report parameters)
# + id="JzN7TQH-V4qF"
sql = syntax.sql('''
SELECT
CAST(Creative_ID AS INT64) AS creative_id,
-- Metric we're using: adjusted viewable CTR
Clicks / (Impressions * (Active_View__Viewable_Impressions / Active_View__Measurable_Impressions)) AS av_ctr
FROM `{project}.{dataset}.performance`
WHERE
-- Hard Requirements
Impressions > 0
AND Active_View__Measurable_Impressions > 0
AND Active_View__Viewable_Impressions > 0
AND Creative_ID NOT LIKE "%Grand Total%"
-- Soft Requirements
AND Impressions > 1000
''')
# + id="Igd_DWOWnpW8"
df_performance = sql_to_df(sql)
# + id="S6MLSeXHnqeN"
df_master = pd.merge(df_features, df_performance, how='inner', on='creative_id')
df_master.head(3)
# + [markdown] id="Dfvs7N083XwQ"
# ## Performance Bucketing
# + id="yoksGLcR3c6B"
av_ctr_75 = df_master['av_ctr'].quantile(0.75)
av_ctr_75
# + id="f0k28oZ13nqU"
av_ctr_bucket = lambda x: 1 if x > av_ctr_75 else 0
df_master['high_perf'] = df_master['av_ctr'].apply(av_ctr_bucket)
# + [markdown] id="ICKHppDxsUES"
# # Analysis
# + [markdown] id="iJAgvRpXsVh6"
# ## Random Forest Classifier
# + id="UmsMDYT9zFjQ"
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn import metrics
df_raw = df_master.drop(columns=['creative_id', 'url', 'width', 'height', 'av_ctr'])
df_raw.reset_index(drop=True, inplace=True)
x = df_raw.loc[:, df_raw.columns != 'high_perf']
y = df_raw['high_perf']
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2)
# + id="LFzJ5B1szsQb"
rf = RandomForestClassifier(
n_estimators=100,
max_depth=5,
max_features=30,
min_samples_split=20,
bootstrap=True,
criterion='gini'
)
rf.fit(x_train, y_train.values.ravel())
# + id="jeXUCg_L1JOD"
threshold = 0.5
y_train_pred = rf.predict_proba(x_train)
y_train_pred = (y_train_pred[:,1] > threshold).astype(int)
y_test_pred = rf.predict_proba(x_test)
y_test_pred = (y_test_pred[:,1] > threshold).astype(int)
print('Train Accuracy :', metrics.accuracy_score(y_train, y_train_pred))
print('Test Accuracy :', metrics.accuracy_score(y_test, y_test_pred))
# + id="yojmR6qM2YL1"
feat_importances = pd.DataFrame(
rf.feature_importances_,
index=x_train.columns
).reset_index().sort_values(0, ascending=False)
feat_importances.columns = ['Feature', 'Importance']
feat_importances.reset_index(drop=True, inplace=True)
# + id="jwV6Rdu12gMu"
feat_importances.head(40)
# + [markdown] id="xtbQ7dLyBu_w"
# ## Hypothesis Testing
# + id="s08rqW_MBwms"
left = df_master[df_master['has_word_get'] == 0]
right = df_master[df_master['has_word_get'] > 0]
# + id="yibqDSgeEBq2"
display_sample(right)
# + id="Uq9ZOCL8CBXr"
left['av_ctr'].describe()
# + id="umYYjTIxCKCo"
right['av_ctr'].describe()
# + id="ymeK0HX5CO7T"
from scipy.stats import mannwhitneyu
mannwhitneyu(left['av_ctr'], right['av_ctr'], alternative='less')
| colabs/CM360/[colab_3]_Feature_Extraction_and_Modeling.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
# #### Importing dataset
# 1.Since data is in form of excel file we have to use pandas read_excel to load the data
# 2.After loading it is important to check null values in a column or a row
# 3.If it is present then following can be done,
# a.Filling NaN values with mean, median and mode using fillna() method
# b.If Less missing values, we can drop it as well
#
train_data=pd.read_excel('Data_Train.xlsx')
train_data.head()
train_data.info()
train_data.isnull().sum()
# #### as less missing values,I can directly drop these
train_data.dropna(inplace=True)
train_data.isnull().sum()
train_data.dtypes
# #### From description we can see that Date_of_Journey is a object data type,
# Therefore, we have to convert this datatype into timestamp so as to use this column properly for prediction,bcz our
# model will not be able to understand Theses string values,it just understand Time-stamp
# For this we require pandas to_datetime to convert object data type to datetime dtype.
#
#
# dt.day method will extract only day of that date
# dt.month method will extract only month of that date
def change_into_datetime(col):
train_data[col]=pd.to_datetime(train_data[col])
train_data.columns
for i in ['Date_of_Journey','Dep_Time', 'Arrival_Time']:
change_into_datetime(i)
train_data.dtypes
train_data['Journey_day']=train_data['Date_of_Journey'].dt.day
train_data['Journey_month']=train_data['Date_of_Journey'].dt.month
train_data.head()
## Since we have converted Date_of_Journey column into integers, Now we can drop as it is of no use.
train_data.drop('Date_of_Journey', axis=1, inplace=True)
train_data.head()
def extract_hour(df,col):
df[col+"_hour"]=df[col].dt.hour
def extract_min(df,col):
df[col+"_minute"]=df[col].dt.minute
def drop_column(df,col):
df.drop(col,axis=1,inplace=True)
# Departure time is when a plane leaves the gate.
# Similar to Date_of_Journey we can extract values from Dep_Time
extract_hour(train_data,'Dep_Time')
# Extracting Minutes
extract_min(train_data,'Dep_Time')
# Now we can drop Dep_Time as it is of no use
drop_column(train_data,'Dep_Time')
train_data.head()
# +
# Arrival time is when the plane pulls up to the gate.
# Similar to Date_of_Journey we can extract values from Arrival_Time
# Extracting Hours
extract_hour(train_data,'Arrival_Time')
# Extracting minutes
extract_min(train_data,'Arrival_Time')
# Now we can drop Arrival_Time as it is of no use
drop_column(train_data,'Arrival_Time')
# -
train_data.head()
# #### Applying pre-processing on duration column,Separate Duration hours and minute from duration
# +
duration=list(train_data['Duration'])
for i in range(len(duration)):
if len(duration[i].split(' '))==2:
pass
else:
if 'h' in duration[i]: # Check if duration contains only hour
duration[i]=duration[i] + ' 0m' # Adds 0 minute
else:
duration[i]='0h '+ duration[i] # if duration contains only second, Adds 0 hour
# -
train_data['Duration']=duration
train_data.head()
'2h 50m'.split(' ')[1][0:-1]
def hour(x):
return x.split(' ')[0][0:-1]
def min(x):
return x.split(' ')[1][0:-1]
train_data['Duration_hours']=train_data['Duration'].apply(hour)
train_data['Duration_mins']=train_data['Duration'].apply(min)
train_data.head()
train_data.drop('Duration',axis=1,inplace=True)
train_data.head()
train_data.dtypes
train_data['Duration_hours']=train_data['Duration_hours'].astype(int)
train_data['Duration_mins']=train_data['Duration_mins'].astype(int)
train_data.dtypes
train_data.head()
train_data.dtypes
cat_col=[col for col in train_data.columns if train_data[col].dtype=='O']
cat_col
cont_col=[col for col in train_data.columns if train_data[col].dtype!='O']
cont_col
# ### Handling Categorical Data
#
# #### We are using 2 main Encoding Techniques to convert Categorical data into some numerical format
# Nominal data --> data are not in any order --> OneHotEncoder is used in this case
# Ordinal data --> data are in order --> LabelEncoder is used in this case
categorical=train_data[cat_col]
categorical.head()
categorical['Airline'].value_counts()
# #### Airline vs Price Analysis
plt.figure(figsize=(15,5))
sns.boxplot(y='Price',x='Airline',data=train_data.sort_values('Price',ascending=False))
# ##### Conclusion--> From graph we can see that Jet Airways Business have the highest Price., Apart from the first Airline almost all are having similar median
# #### Perform Total_Stops vs Price Analysis
plt.figure(figsize=(15,5))
sns.boxplot(y='Price',x='Total_Stops',data=train_data.sort_values('Price',ascending=False))
len(categorical['Airline'].unique())
# As Airline is Nominal Categorical data we will perform OneHotEncoding
Airline=pd.get_dummies(categorical['Airline'], drop_first=True)
Airline.head()
categorical['Source'].value_counts()
# +
# Source vs Price
plt.figure(figsize=(15,5))
sns.catplot(y='Price',x='Source',data=train_data.sort_values('Price',ascending=False),kind='boxen')
# +
# As Source is Nominal Categorical data we will perform OneHotEncoding
Source=pd.get_dummies(categorical['Source'], drop_first=True)
Source.head()
# -
categorical['Destination'].value_counts()
# +
# As Destination is Nominal Categorical data we will perform OneHotEncoding
Destination=pd.get_dummies(categorical['Destination'], drop_first=True)
Destination.head()
# -
categorical['Route']
categorical['Route_1']=categorical['Route'].str.split('→').str[0]
categorical['Route_2']=categorical['Route'].str.split('→').str[1]
categorical['Route_3']=categorical['Route'].str.split('→').str[2]
categorical['Route_4']=categorical['Route'].str.split('→').str[3]
categorical['Route_5']=categorical['Route'].str.split('→').str[4]
categorical.head()
import warnings
from warnings import filterwarnings
filterwarnings('ignore')
categorical['Route_1'].fillna('None',inplace=True)
categorical['Route_2'].fillna('None',inplace=True)
categorical['Route_3'].fillna('None',inplace=True)
categorical['Route_4'].fillna('None',inplace=True)
categorical['Route_5'].fillna('None',inplace=True)
categorical.head()
#now extract how many categories in each cat_feature
for feature in categorical.columns:
print('{} has total {} categories \n'.format(feature,len(categorical[feature].value_counts())))
# +
### as we will see we have lots of features in Route , one hot encoding will not be a better option lets appply Label Encoding
# -
from sklearn.preprocessing import LabelEncoder
encoder=LabelEncoder()
categorical.columns
for i in ['Route_1', 'Route_2', 'Route_3', 'Route_4','Route_5']:
categorical[i]=encoder.fit_transform(categorical[i])
categorical.head()
# +
# Additional_Info contains almost 80% no_info,so we can drop this column
# we can drop Route as well as we have pre-process that column
drop_column(categorical,'Route')
drop_column(categorical,'Additional_Info')
# -
categorical.head()
categorical['Total_Stops'].value_counts()
categorical['Total_Stops'].unique()
# +
# As this is case of Ordinal Categorical type we perform LabelEncoder
# Here Values are assigned with corresponding key
dict={'non-stop':0, '2 stops':2, '1 stop':1, '3 stops':3, '4 stops':4}
# -
categorical['Total_Stops']=categorical['Total_Stops'].map(dict)
categorical.head()
train_data[cont_col]
# +
# Concatenate dataframe --> categorical + Airline + Source + Destination
data_train=pd.concat([categorical,Airline,Source,Destination,train_data[cont_col]],axis=1)
data_train.head()
# -
drop_column(data_train,'Airline')
drop_column(data_train,'Source')
drop_column(data_train,'Destination')
data_train.head()
pd.set_option('display.max_columns',35)
data_train.head()
data_train.columns
# ### outlier detection
def plot(df,col):
fig,(ax1,ax2)=plt.subplots(2,1)
sns.distplot(df[col],ax=ax1)
sns.boxplot(df[col],ax=ax2)
plt.figure(figsize=(30,20))
plot(data_train,'Price')
# #### dealing with Outliers
data_train['Price']=np.where(data_train['Price']>=40000,data_train['Price'].median(),data_train['Price'])
plt.figure(figsize=(30,20))
plot(data_train,'Price')
# +
### separate your independent & dependent data
# -
X=data_train.drop('Price',axis=1)
X.head()
y=data_train['Price']
y
# +
#### as now we dont have any missing value in data, we can definitely go ahead with Feature Selection
# -
# ### Feature Selection
# Finding out the best feature which will contribute and have good relation with target variable.
#
# ### Why to apply Feature Selection?
# To select important features to get rid of curse of dimensionality ie..to get rid of duplicate features
# +
###np.array(X)
# +
##np.array(y)
# -
# ### I wanted to find mutual information scores or matrix to get to know about the relationship between all features.
# #### Feature Selection using Information Gain,
from sklearn.feature_selection import mutual_info_classif
X.dtypes
mutual_info_classif(X,y)
imp=pd.DataFrame(mutual_info_classif(X,y),index=X.columns)
imp
imp.columns=['importance']
imp.sort_values(by='importance',ascending=False)
# #### split dataset into train & test
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)
from sklearn import metrics
##dumping model using pickle so that we will re-use
import pickle
def predict(ml_model,dump):
model=ml_model.fit(X_train,y_train)
print('Training score : {}'.format(model.score(X_train,y_train)))
y_prediction=model.predict(X_test)
print('predictions are: \n {}'.format(y_prediction))
print('\n')
r2_score=metrics.r2_score(y_test,y_prediction)
print('r2 score: {}'.format(r2_score))
print('MAE:',metrics.mean_absolute_error(y_test,y_prediction))
print('MSE:',metrics.mean_squared_error(y_test,y_prediction))
print('RMSE:',np.sqrt(metrics.mean_squared_error(y_test,y_prediction)))
sns.distplot(y_test-y_prediction)
if dump==1:
##dump your model using pickle so that we will re-use
file=open('E:\End-2-end Projects\Flight_Price/model.pkl','wb')
pickle.dump(model,file)
# #### import randomforest class
from sklearn.ensemble import RandomForestRegressor
predict(RandomForestRegressor(),1)
# #### play with multiple Algorithms
# +
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.tree import DecisionTreeRegressor
# -
predict(DecisionTreeRegressor(),0)
predict(LinearRegression(),0)
# #### Hyperparameter Tuning
# 1.Choose following method for hyperparameter tuning
# a.RandomizedSearchCV --> Fast way to Hypertune model
# b.GridSearchCV--> Slow way to hypertune my model
#
# 2.Assign hyperparameters in form of dictionary
# 3.Fit the model
# 4.Check best paramters and best score
from sklearn.model_selection import RandomizedSearchCV
# +
# Number of trees in random forest
n_estimators=[int(x) for x in np.linspace(start=100,stop=1200,num=6)]
# Number of features to consider at every split
max_features=['auto','sqrt']
# Maximum number of levels in tree
max_depth=[int(x) for x in np.linspace(5,30,num=4)]
# Minimum number of samples required to split a node
min_samples_split=[5,10,15,100]
# +
# Create the random grid
random_grid={
'n_estimators':n_estimators,
'max_features':max_features,
'max_depth':max_depth,
'min_samples_split':min_samples_split
}
# -
random_grid
### initialise your estimator
reg_rf=RandomForestRegressor()
# +
# Random search of parameters, using 3 fold cross validation
rf_random=RandomizedSearchCV(estimator=reg_rf,param_distributions=random_grid,cv=3,verbose=2,n_jobs=-1)
# -
rf_random.fit(X_train,y_train)
rf_random.best_params_
prediction=rf_random.predict(X_test)
sns.distplot(y_test-prediction)
metrics.r2_score(y_test,prediction)
print('MAE',metrics.mean_absolute_error(y_test,prediction))
print('MSE',metrics.mean_squared_error(y_test,prediction))
print('RMSE',np.sqrt(metrics.mean_squared_error(y_test,prediction)))
# ##### Saving the model to reuse it again
# !pip install pickle
import pickle
# open a file, where you want to store the data
file=open('rf_random.pkl','wb')
# dump information to that file
pickle.dump(rf_random,file)
model=open('rf_random.pkl','rb')
forest=pickle.load(model)
y_prediction=forest.predict(X_test)
y_prediction
metrics.r2_score(y_test,y_prediction)
| flight_price_deploy.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] pycharm={"name": "#%% md\n"}
# # Calling Model with Executor
# This tutorial shows training and evaluating model with `Executor` and `Loader`.
# - Training `model`
# - Feed `Loader` into `model`
#
# In the tutorial 1 we shows how to inference images via a specific model.
# But it seems a little complicated:
# - What's the argument of `eval` function?
# - What's the data type it returns?
#
# Therefore we provide an easier way to call models, as we named `Executor`.
# + pycharm={"name": "#%%\n", "is_executing": false}
from VSR.DataLoader import Dataset, Loader
from VSR.Model import get_model
srcnn_builder = get_model('srcnn')
srcnn = srcnn_builder(scale=3, channel=1)
try:
srcnn.load("srcnn.pth")
except FileNotFoundError:
pass
data = Dataset('../../Tests/data').include('*.png')
loader = Loader(data, scale=3, threads=8)
# convert to grayscale image
loader.set_color_space('hr', 'L')
loader.set_color_space('lr', 'L')
with srcnn.get_executor(root=None) as t:
config = t.query_config({})
print(list(config.keys()))
config.epochs = 1
config.steps = 10
config.batch_shape = [4, 1, 16, 16]
config.lr = 1e-3
t.fit([loader, None], config)
# + [markdown] pycharm={"name": "#%% md\n"}
# The method `get_executor(root)` builds an model executor with a working directory.
# If root is not set, the executor runs without saving models.
#
# Using `with` statement to construct a running environment for it.
#
# To config the executor, calling `query_config({})` to get the default configuration.
#
# To train the model, call `fit` method. The first argument is a list of two loaders,
# the first one is the loader for training and the second loader is for validating (can be None).
#
# To evaluate or inference the model, call `benchmark` or `infer` method.
# + pycharm={"name": "#%%\n", "is_executing": false}
from VSR.DataLoader import Dataset, Loader
from VSR.Model import get_model
def my_hook(outputs: list, names: list):
print(len(outputs), outputs[0].shape)
print(names)
srcnn_builder = get_model('srcnn')
srcnn = srcnn_builder(scale=3, channel=1)
try:
srcnn.load("srcnn.pth")
except FileNotFoundError:
pass
data = Dataset('../../Tests/data').include('*.png')
loader = Loader(data, scale=3, threads=8)
# convert to grayscale image
loader.set_color_space('hr', 'L')
loader.set_color_space('lr', 'L')
with srcnn.get_executor(root=None) as t:
config = t.query_config({})
config.inference_results_hooks = [my_hook]
# t.benchmark(loader, config)
t.infer(loader, config)
| Docs/CookBook/3. Calling model with executor.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
# ---
# ## Logistic Regression
#
# Here the goal is to show how an objective function can be decomposed and solved by ADMM.
#
# For this purpose, this notebook considers solving a classification problem with logistic regression.
# ### Loss function
# minimize: $\sum -[y\log(\hat{y}) + (1-y)\log(1-\hat{y})] + \lambda \|x\|_1$
# The problem can be decomposed using one of the approaches presented in __Example_LeastSquares__ notebook.
#
# This notebook shows how to decompose into minimization of cross-entropy and regularization term.
# ### Steps
#
# 1. Devise a computation graph representing the problem as a bipartite graph
# 2. Implement nodes as Java classes extending org.admm4j.core.Node
# 3. Create the JSON input defining the graph
# 4. Execute admm4j
# 5. Import and analyze results
import numpy as np
import matplotlib.pyplot as plt
import json
# ### Generate data
# +
np.random.seed(100)
data = np.random.normal(0, 4, (100,2))
target = np.dot(data, np.array([1,1]))
target[target<=0] = 0
target[target>0] = 1
# plot data
plt.plot(data[target==0,0], data[target==0,1], 'b.', markersize=10)
plt.plot(data[target==1,0], data[target==1,1], 'r.', markersize=10)
plt.xlabel('x1')
plt.ylabel('x2')
plt.title("Data")
plt.legend(['class 0', 'class 1'])
plt.show()
# -
# ### Step 1. Devise a computation graph representing the problem as a bipartite graph
#
# The graph shows that the original problem is decomposed into two separate tasks.
# <img src="images/optimizer-regularizer0.png" width="600" height="600" style="float: center"/>
# ### Step 2. Implement nodes as Java classes extending org.admm4j.core.Node
# The following classes are implemented
#
# 1. org.admm4j.demo.ml.linearmodel.LogisticRegressionNode.java
#
# 2. org.admm4j.demo.common.L1NormNode.java
# ### Step 3. Create the JSON input defining the graph
#
# The JSON input has a well-defined structure allowing to define an arbitrary bipartite graph.
#
# Here the JSON input is created in python.
# +
# add vector of ones representing bias
I = np.ones(data.shape[0]).reshape(-1,1)
X = np.concatenate((I, data), axis=1)
y = target
# number of variables and scaling parameter
nvar = X.shape[1]
rho = 1
# lambda regularization term
_lambda = 0.2 * np.ones(nvar)
_lambda[0] = 0 # we do not want regularize bias term
# init nodesI.
nodesI = []
# define node
node = {}
node['name'] = 'crossentropy'
node['class'] = 'org.admm4j.demo.ml.linearmodel.LogisticRegressionNode'
node['neighbors'] = ['regularization:{}:{}'.format(nvar, rho)] # n and rho are set here, alternatively command line can be used
node['input'] = {'data': X.tolist(), 'target': y.tolist()}
# add to the list of nodesI
nodesI.append(node)
# init nodesII
nodesII = []
node = {}
node['name'] = 'regularization'
node['class'] = 'org.admm4j.demo.common.L1NormNode'
node['neighbors'] = ['crossentropy:{}:{}'.format(nvar, rho)] # n and rho are set here, alternatively command line can be used
node['input'] = {'lambda': _lambda.tolist()}
# add to the list of nodesII
nodesII.append(node)
# init whole json model
graph = {'nodesI': nodesI, 'nodesII': nodesII}
# -
# #### Show JSON model
print(json.dumps(graph))
# #### Save JSON input file
filename = 'logistic_regression_input.json'
fout = open(filename, 'w')
json.dump(graph, fout, indent=4)
fout.close()
# ### Step 4. Execute admm4j
#
# #### Note: -nvar and -rho are not specified because they are set in json input
# !java -jar admm4j-demo/target/admm4j-demo-1.0-jar-with-dependencies.jar\
# -input logistic_regression_input.json\
# -output logistic_regression_output.json\
# -verbose 10
# ### Step 5. Import and analyze results
fin = open('logistic_regression_output.json', 'r')
res = json.loads(fin.read())
fin.close()
# #### Show results and evaluate performance
# +
coeff = res.get('nodesI')[0].get('variables').get('regularization')
print('Coefficients', coeff)
# +
w = np.array(coeff[1:])
b = coeff[0]
z = np.dot(data, w) + b
y_pred = 1. / (1. + np.exp(-z))
plt.plot(data[y_pred<=0.5,0], data[y_pred<=0.5,1], 'bx', markersize=10)
plt.plot(data[y_pred>0.5,0], data[y_pred>0.5,1], 'rx', markersize=10)
plt.plot(data[target==0,0], data[target==0,1], 'b.', markersize=8)
plt.plot(data[target==1,0], data[target==1,1], 'r.', markersize=8)
plt.xlabel('x1')
plt.ylabel('x2')
plt.title("Data")
plt.show()
# -
# The plot shows that the coefficients found for logistic regression model give a good fit to the data.
| Example_LogisticRegression.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
# ---
# # AdventureWorks: resit questions
# ## 1.
# **List the SalesOrderNumber for the customer 'Good Toys' 'Bike World'**
# ## 2.
# **List the ProductName and the quantity of what was ordered by 'Futuristic Bikes'**
# ## 3.
# **List the name and addresses of companies containing the word 'Bike' (upper or lower case) and companies containing 'cycle' (upper or lower case). Ensure that the 'bike's are listed before the 'cycles's.**
# ## 4.
# **Show the total order value for each CountryRegion. List by value with the highest first.**
# ## 5.
# **Find the best customer in each region.**
| Spark/14-4 AdventureWorks - Resit.ipynb |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Q#
# language: qsharp
# name: iqsharp
# ---
# # Quantum Katas and Tutorials as Jupyter Notebooks
#
# To run the katas and tutorials online, make sure you're viewing this file on Binder (if not, use [this link](https://mybinder.org/v2/gh/Microsoft/QuantumKatas/main?filepath=index.ipynb)).
#
# To run the katas and tutorials locally, follow [these installation instructions](https://github.com/microsoft/QuantumKatas/blob/main/README.md#kata-locally).
#
# > While running the Katas online is the easiest option to get started, if you want to save your progress and enjoy better performance, we recommend you to choose the local option.
# ## Learning path
#
# Here is the learning path we suggest you to follow if you are starting to learn quantum computing and quantum programming. Once you're comfortable with the basics, you're welcome to jump ahead to the topics that pique your interest!
#
# #### Quantum Computing Concepts: Qubits and Gates
#
# * **[Complex arithmetic (tutorial)](./tutorials/ComplexArithmetic/ComplexArithmetic.ipynb)**.
# Learn about complex numbers and the mathematics required to work with quantum computing.
# * **[Linear algebra (tutorial)](./tutorials/LinearAlgebra/LinearAlgebra.ipynb)**.
# Learn about vectors and matrices used to represent quantum states and quantum operations.
# * **[The qubit (tutorial)](./tutorials/Qubit/Qubit.ipynb)**.
# Learn what a qubit is.
# * **[Single-qubit gates (tutorial)](./tutorials/SingleQubitGates/SingleQubitGates.ipynb)**.
# Learn what a quantum gate is and about the most common single-qubit gates.
# * **[Basic quantum computing gates](./BasicGates/BasicGates.ipynb)**.
# Learn to apply the most common gates used in quantum computing.
# * **[Multi-qubit systems (tutorial)](./tutorials/MultiQubitSystems/MultiQubitSystems.ipynb)**.
# Learn to represent multi-qubit systems.
# * **[Multi-qubit gates (tutorial)](./tutorials/MultiQubitGates/MultiQubitGates.ipynb)**.
# Learn about the most common multi-qubit gates.
# * **[Superposition](./Superposition/Superposition.ipynb)**.
# Learn to prepare superposition states.
#
# #### Quantum Computing Concepts: Measurements
#
# * **[Single-qubit measurements (tutorial)](./tutorials/SingleQubitSystemMeasurements/SingleQubitSystemMeasurements.ipynb)**.
# Learn what quantum measurement is and how to use it for single-qubit systems.
# * **[Measurements](./Measurements/Measurements.ipynb)**.
# Learn to distinguish quantum states using measurements.
# * **[Distinguish unitaries](./DistinguishUnitaries/DistinguishUnitaries.ipynb)**\*.
# Learn to distinguish unitaries by designing and performing experiments with them.
# * **[Joint measurements](./JointMeasurements/JointMeasurements.ipynb)**\*.
# Learn about using joint (parity) measurements to distinguish quantum states and to perform state transformations.
#
# #### Q\# and Microsoft Quantum Development Kit Tools
#
# * **[Visualization tools (tutorial)](./tutorials/VisualizationTools/VisualizationTools.ipynb)**.
# Learn to use the various tools for visualizing elements of Q\# programs.
#
# #### Simple Algorithms
#
# * **[Random number generation (tutorial)](./tutorials/RandomNumberGeneration/RandomNumberGenerationTutorial.ipynb)**.
# Learn to generate random numbers using the principles of quantum computing.
# * **[Teleportation](./Teleportation/Teleportation.ipynb)**.
# Implement standard teleportation protocol and its variations.
# * **[Superdense coding](./SuperdenseCoding/SuperdenseCoding.ipynb)**.
# Implement the superdense coding protocol.
#
# #### Quantum Oracles and Simple Oracle Algorithms
#
# * **[Quantum oracles (tutorial)](./tutorials/Oracles/Oracles.ipynb)**.
# Learn to implement classical functions as equivalent quantum oracles.
# * **[Exploring Deutsch–Jozsa algorithm (tutorial)](./tutorials/ExploringDeutschJozsaAlgorithm/DeutschJozsaAlgorithmTutorial.ipynb)**.
# Learn to implement classical functions and equivalent quantum oracles,
# and compare the quantum solution to the Deutsch–Jozsa problem to a classical one.
# * **[Deutsch–Jozsa algorithm](./DeutschJozsaAlgorithm/DeutschJozsaAlgorithm.ipynb)**.
# Learn about quantum oracles which implement classical functions, and implement Bernstein–Vazirani and Deutsch–Jozsa algorithms.
#
# #### Grover's search algorithm
#
# * **[Implementing Grover's algorithm](./GroversAlgorithm/GroversAlgorithm.ipynb)**.
# Learn about Grover's search algorithm and how to write quantum oracles to use with it.
# * **[Exploring Grover's search algorithm (tutorial)](./tutorials/ExploringGroversAlgorithm/ExploringGroversAlgorithmTutorial.ipynb)**.
# Learn more about Grover's search algorithm, picking up where the [Grover's algorithm kata](./GroversAlgorithm/GroversAlgorithm.ipynb) left off.
# * **[Solving SAT problems using Grover's algorithm](./SolveSATWithGrover/SolveSATWithGrover.ipynb)**.
# Explore Grover's search algorithm, using SAT problems as an example.
# Learn to implement quantum oracles based on the problem description instead of a hard-coded answer.
# Use Grover's algorithm to solve problems with an unknown number of solutions.
# * **[Solving graph coloring problems using Grover's algorithm](./GraphColoring/GraphColoring.ipynb)**.
# Continue the exploration of Grover's search algorithm, using graph coloring problems as an example.
# * **[Solving bounded knapsack problem using Grover's algorithm](./BoundedKnapsack/BoundedKnapsack.ipynb)**.
# Learn how solve the variants of knapsack problem with Grover's search.
#
# #### Tools and libraries/Building up to Shor's algorithm
#
# * **[Quantum Fourier transform](./QFT/QFT.ipynb)**.
# Learn to implement quantum Fourier transform and to use it to perform simple state transformations.
# * **[Phase estimation](./PhaseEstimation/PhaseEstimation.ipynb)**.
# Learn about phase estimation algorithms.
#
# #### Entanglement games
#
# * **[CHSH game](./CHSHGame/CHSHGame.ipynb)**.
# * **[GHZ game](./GHZGame/GHZGame.ipynb)**.
# * **[Mermin-Peres magic square game](./MagicSquareGame/MagicSquareGame.ipynb)**.
#
# #### Reversible computing
#
# * **[Truth tables](./TruthTables/TruthTables.ipynb)**.
# Learn to represent and manipulate Boolean functions as truth tables and to implement them as quantum operations.
# * **[Ripple-carry adder](./RippleCarryAdder/RippleCarryAdder.ipynb)**.
# Build a ripple-carry adder on a quantum computer.
#
# #### Miscellaneous
#
# * **[BB84 protocol](./KeyDistribution_BB84/KeyDistribution_BB84.ipynb)**.
# Implement the BB84 key distribution algorithm.
# * **[Bit-flip error correcting code](./QEC_BitFlipCode/QEC_BitFlipCode.ipynb)**.
# Learn about a 3-qubit error correcting code for protecting against bit-flip errors.
# * **[Unitary patterns](./UnitaryPatterns/UnitaryPatterns.ipynb)**.
# Learn to implement unitaries with matrices that follow certain patterns of zero and non-zero elements.
# * **[Quantum classification (tutorial)](./tutorials/QuantumClassification/ExploringQuantumClassificationLibrary.ipynb)**.
# Learn about circuit-centric classifiers and the quantum machine learning library included in the QDK.
#
# For a full list of Quantum Katas available as Q# projects instead of Jupyter Notebooks, see the [QuantumKatas repository](https://github.com/Microsoft/QuantumKatas#learning-path).
# ## Getting Started with Kata Notebooks and Tutorials
#
# Each kata notebook presents the tasks of the respective kata (Q# project) in Jupyter Notebook format. This makes getting started with the katas a lot easier - you don't need to install anything locally to try them out!
#
# Notebook tutorials are designed with Notebook format in mind - in addition to programming exercises they include a lot of theoretical explanations and code samples for you to learn from.
#
# Make sure you're viewing this file when running Jupyter notebooks on your machine or on Binder (for running on Binder, use [this link](https://mybinder.org/v2/gh/Microsoft/QuantumKatas/main?filepath=index.ipynb)). From here you can navigate to the individual kata or tutorial notebooks using the links above.
#
# * Each tutorial or kata notebook contains a sequence of tasks on the topic, progressing from trivial to challenging.
# * Each task is defined in a separate code cell, preceded by the description of the task in a Markdown cell.
# Your goal is to fill in the blanks in the code (marked with `// ...` comments) with some Q# code that solves the task.
# * To verify your solution, run the code cell using Ctrl + Enter (or ⌘ + Enter on macOS). This will invoke the test covering the task and let you know whether it passes or fails, and if it fails, what the error is.
# * You can find pointers to reference materials you might need to solve the tasks, both on quantum computing and on Q#, either in the beginning of the tutorial or the kata or next to the task to which they are relevant.
# * You can find reference solutions in `ReferenceImplementation.qs` files of the corresponding katas or tutorials.
# * A lot of katas and tutorials have *workbooks* - detailed explanations of task solutions. Feel free to look them up if you're stuck!
| index.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import cv2
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
def display_img(img):
fig = plt.figure(figsize=(12,10))
ax = fig.add_subplot(111)
ax.imshow(img,cmap='gray')
img = cv2.imread('test images/sudoku.png')
display_img(img)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5) #for x axis
display_img(sobelx)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5) #for y axis
display_img(sobely)
laplacian = cv2.Laplacian(img,cv2.CV_64F) #for x and y axis
display_img(laplacian)
blended = cv2.addWeighted(src1=sobelx,alpha=0.5,src2=sobely,beta=0.5,gamma=0)
display_img(blended)
ret,th1 = cv2.threshold(img,100,255,cv2.THRESH_BINARY)
display_img(th1)
kernel = np.ones((4,4),np.uint8)
gradient = cv2.morphologyEx(blended,cv2.MORPH_GRADIENT,kernel) ##Edge detection
display_img(gradient)
| Gradients.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:ani36]
# language: python
# name: conda-env-ani36-py
# ---
# ## Imports
# +
from simtk.openmm import app
from simtk import openmm as mm
from simtk import unit
from autograd import grad
from autograd import numpy as np
# -
# ## Load system
# +
from openmmtools.testsystems import AlanineDipeptideVacuum
testsystem = AlanineDipeptideVacuum(constraints=None)
integrator = mm.VerletIntegrator(1*unit.femtosecond)
platform = mm.Platform.getPlatformByName("Reference")
simulation = app.Simulation(testsystem.topology, testsystem.system, integrator, platform)
xyz = testsystem.positions
simulation.context.setPositions(testsystem.positions)
flat_xyz = (xyz / unit.nanometer).flatten()
# -
torsion_indices = [ 4, 6, 8, 14]
# ## Geometric functions
def compute_dihedral(xyz, indices):
"""Copied from mdtraj, except without calls to a non-python distance library,
and assuming we dont have to deal with periodic stuff"""
a,b,c,d = indices
b1 = xyz[b] - xyz[a]
b2 = xyz[c] - xyz[b]
b3 = xyz[d] - xyz[c]
c1 = np.cross(b2, b3) # bc x cd
c2 = np.cross(b1, b2) # ab x bc
p1 = np.sum(b1 * c1)
p1 *= np.sum(b2 * b2) ** 0.5
p2 = np.sum(c1 * c2)
return np.arctan2(p1, p2)
compute_dihedral(xyz, indices=torsion_indices)
# ## OpenMM utilities
# +
def unflatten(flat_xyz):
N = int(len(flat_xyz) / 3)
return np.reshape(flat_xyz, (N, 3))
def set_positions(xyz):
simulation.context.setPositions(xyz)
E_unit = simulation.context.getState(getEnergy=True).getPotentialEnergy().unit
F_unit = simulation.context.getState(getForces=True).getForces(asNumpy=True).unit
def get_energy(xyz):
set_positions(xyz)
return simulation.context.getState(getEnergy=True).getPotentialEnergy() / E_unit
def get_forces(xyz):
set_positions(xyz)
return simulation.context.getState(getForces=True).getForces(asNumpy=True) / F_unit
def fxn_to_minimize(flat_xyz):
return get_energy(unflatten(flat_xyz))
def jacobian_of_fxn(flat_xyz):
return - get_forces(unflatten(flat_xyz))
# -
fxn_to_minimize(flat_xyz), jacobian_of_fxn(flat_xyz)
# ## Constrained optimization using scipy
# +
from functools import partial
def dihedral_constraint(flat_xyz, target_dihedral=0.0):
"""equality constraint: want the output of this function to be 0"""
xyz = unflatten(flat_xyz)
return compute_dihedral(xyz, torsion_indices) - target_dihedral
# +
from scipy.optimize import minimize
def form_eq_constraint(target_dihedral):
"""adapted from scipy documentation
https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#sequential-least-squares-programming-slsqp-algorithm-method-slsqp
"""
fun = partial(dihedral_constraint, target_dihedral=target_dihedral)
eq_cons = {'type': 'eq',
'fun' : fun,
'jac' : grad(fun)}
return eq_cons
# -
target_dihedral = - 0.5 * np.pi
target_dihedral
eq_cons = form_eq_constraint(target_dihedral)
eq_cons['jac'](flat_xyz)
from scipy.optimize import show_options
show_options('minimize', method='SLSQP')
result = minimize(fxn_to_minimize, flat_xyz, method='SLSQP', jac=jacobian_of_fxn,
constraints=[eq_cons], options={'ftol': 1e-9, 'disp': True, 'maxiter': 1000})
compute_dihedral(unflatten(result.x), torsion_indices), target_dihedral
# # Do a torsion scan
# TODO: may have to define constraint not in terms of angle (skip arctan2)
torsion_grid = np.linspace(-np.pi, np.pi, 101)[1:]
from tqdm import tqdm
results = []
for theta in tqdm(torsion_grid):
results.append(minimize(fxn_to_minimize, flat_xyz, method='SLSQP', jac=jacobian_of_fxn,
constraints=[form_eq_constraint(theta)],
options={'ftol': 1e-9, 'disp': True, 'maxiter': 1000}))
energies = np.array([r.fun for r in results])
# +
import matplotlib.pyplot as plt
# %matplotlib inline
plt.plot(torsion_grid, energies)
plt.scatter(torsion_grid, energies, s=3)
plt.xlabel('$\phi$ torsion angle')
plt.xticks([-np.pi, 0, np.pi], ['$-\pi$', '$0$', '$+\pi$'])
plt.ylabel('potential energy (kJ/mol)')
# -
| MM torsion scan.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 sys
sys.path.append(r'C:\Users\moallemie\EMAworkbench-master')
sys.path.append(r'C:\Users\moallemie\EM_analysis')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from ema_workbench import load_results, ema_logging
from ema_workbench.em_framework.salib_samplers import get_SALib_problem
from SALib.analyze import morris
# +
import multiprocessing
multiprocessing.cpu_count()
# -
# ## Loading the model, uncertainities, and outcomes
# +
# Here we only generate experiments for loading the necessary components.
#The actual results will be loaded in the next cell.
# Open Excel input data from the notebook directory before runnign the code in multi-processing.
# Close the folder where the results will be saved in multi-processing.
# This line must be at the beginning for multi processing.
if __name__ == '__main__':
ema_logging.log_to_stderr(ema_logging.INFO)
#The model must be imoorted as .py file in parallel processing.
from Model_init import vensimModel
from ema_workbench import (TimeSeriesOutcome,
perform_experiments,
RealParameter,
CategoricalParameter,
ema_logging,
save_results,
load_results)
directory = 'C:/Users/moallemie/EM_analysis/Model/'
df_unc = pd.read_excel(directory+'ScenarioFramework.xlsx', sheet_name='Uncertainties')
# 0.5/1.5 multiplication is added to previous Min/Max cells for parameters with Reference values 0
#or min/max manually set in the spreadsheet
df_unc['Min'] = df_unc['Min'] + df_unc['Reference'] * 0.75
df_unc['Max'] = df_unc['Max'] + df_unc['Reference'] * 1.25
vensimModel.uncertainties = [RealParameter(row['Uncertainty'], row['Min'], row['Max']) for index, row in df_unc.iterrows()]
df_out = pd.read_excel(directory+'ScenarioFramework.xlsx', sheet_name='Outcomes')
vensimModel.outcomes = [TimeSeriesOutcome(out) for out in df_out['Outcome']]
from ema_workbench import MultiprocessingEvaluator
from ema_workbench.em_framework.evaluators import (MC, LHS, FAST, FF, PFF, SOBOL, MORRIS)
import time
start = time.time()
with MultiprocessingEvaluator(vensimModel, n_processes=230) as evaluator:
results = evaluator.perform_experiments(scenarios=5000, uncertainty_sampling=MORRIS)
end = time.time()
print("took {} seconds".format(end-start))
fn = 'D:/moallemie/EM_analysis/Data/SDG_experiments_sc5000.tar.gz'
save_results(results, fn)
# -
experiments, outcomes = results
# ## Calculating SA (Morris) metrics
# +
#Sobol indice calculation as a function of number of scenarios and time
def make_morris_df(scores, problem, outcome_var, sc, t):
scores_filtered = {k:scores[k] for k in ['mu_star','mu_star_conf','mu','sigma']}
Si_df = pd.DataFrame(scores_filtered, index=problem['names'])
sa_dir='C:/Users/moallemie/EM_analysis/Data/'
Si_df.to_csv(sa_dir+"MorrisIndices_{}_sc{}_t{}.csv".format(outcome_var, sc, t))
Si_df.sort_values(by=['mu_star'], ascending=False, inplace=True)
Si_df = Si_df.head(20)
Si_df = Si_df.iloc[::-1]
indices = Si_df[['mu_star','mu']]
errors = Si_df[['mu_star_conf','sigma']]
return indices, errors
# +
# Set the outcome variable, number of scenarios generated, and the timeslice you're interested in for SA
sc = 5000
t = 2100
outcome_vars = list(outcomes.keys())[1:]
inds ={}
errs = {}
problem = get_SALib_problem(vensimModel.uncertainties)
for i, outcome_var in enumerate(outcome_vars):
X = experiments.iloc[:, :-3].values
Y = outcomes[outcome_var][:,-1]
scores = morris.analyze(problem, X, Y, print_to_console=False)
inds[outcome_var], errs[outcome_var] = make_morris_df(scores, problem, outcome_var, sc, t)
# -
errs['Total Population Indicator'].iloc[:,0]
# ## Plotting SA results
# +
# define the ploting function
def plot_scores(inds, errs, outcome_var, sc):
sns.set_style('white')
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(3, 6))
ind = inds[outcome_var].iloc[:,0]
err = errs[outcome_var].iloc[:,0]
ind.plot.barh(xerr=err.values.T,ax=ax, color = ['#8980D4'], width=.9)
ax.set_ylabel('')
ax.legend().set_visible(False)
ax.set_xlabel('mu_star index', fontsize=14)
ylabels = ax.get_yticklabels()
ylabels = [item.get_text()[:-10] for item in ylabels]
ax.set_yticklabels(ylabels, fontsize=10)
#ax.set_title("2100", fontsize=12)
plt.suptitle("{} in 2100".format(outcome_var), y=0.94, fontsize=12)
plt.rcParams["figure.figsize"] = [7.08,7.3]
plt.savefig('{}/Morris_{}_sc{}.png'.format(r'C:/Users/moallemie/EM_analysis/Fig/sa_ranking', outcome_var, sc), dpi=300, bbox_inches='tight')
return fig
# -
sc = 5000
for out, outcome_var in enumerate(outcome_vars):
plot_scores(inds, errs, outcome_var, sc)
plt.close()
| Notebook/.ipynb_checkpoints/Morris_ranking_sc5000-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
# ---
# # Space-time visualisations (giddy)
# +
from libpysal.weights.contiguity import Queen
from libpysal import examples
import geopandas as gpd
import pandas as pd
import numpy as np
from giddy.directional import Rose
import matplotlib.pyplot as plt
import esda
from splot.esda import lisa_cluster
from ipywidgets import interact, fixed
import ipywidgets as widgets
# %matplotlib inline
# -
# ## Data prepration
# get csv and shp and merge
shp_link = examples.get_path('us48.shp')
df = gpd.read_file(shp_link)
income_table = pd.read_csv(examples.get_path("usjoin.csv"))
# calculate relative values
for year in range(1969, 2010):
income_table[str(year) + '_rel'] = income_table[str(year)] / income_table[str(year)].mean()
# merge
gdf = df.merge(income_table,left_on='STATE_NAME',right_on='Name')
#retrieve spatial weights and data for two points in time
w = Queen.from_dataframe(gdf)
w.transform = 'r'
y1 = gdf['1969_rel'].values
y2 = gdf['2000_rel'].values
# create rose object
Y = np.array([y1, y2]).T
rose = Rose(Y, w, k=5)
# calculate Moran_Local
moran_loc1 = esda.moran.Moran_Local(y1, w)
moran_loc2 = esda.moran.Moran_Local(y2, w)
# ## Plotting
# +
from splot.giddy import (dynamic_lisa_heatmap,
dynamic_lisa_rose,
dynamic_lisa_vectors,
dynamic_lisa_composite,
dynamic_lisa_composite_explore)
import splot
from importlib import reload
reload(splot.giddy)
# -
fig, ax = dynamic_lisa_heatmap(rose)
ax.set_ylabel(1996)
ax.set_xlabel(2006)
plt.show()
fig, ax = dynamic_lisa_rose(rose, attribute=y1)
plt.show()
fig, ax = dynamic_lisa_vectors(rose)
dynamic_lisa_composite(rose, gdf)
plt.show()
dynamic_lisa_composite_explore(rose, gdf, pattern='rel')
plt.show()
| notebooks/giddy_space_time.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 models import UMNNMAFFlow
import torch
from torch.utils.data import DataLoader
from torch.distributions.multivariate_normal import MultivariateNormal
import lib.toy_data as toy_data
import numpy as np
import matplotlib.pyplot as plt
from timeit import default_timer as timer
import os
import lib.utils as utils
import lib.visualize_flow as vf
device = "cpu"
# # Dataset
toy_dataset = "8gaussians"
# +
batch_size = 100
num_data = 10000
x_train = torch.tensor(toy_data.inf_train_gen(toy_dataset, batch_size=num_data)).to(device)
x_test = torch.tensor(toy_data.inf_train_gen(toy_dataset, batch_size=1000)).to(device)
x_train = DataLoader(x_train, batch_size=batch_size)
x_test = DataLoader(x_test, batch_size=batch_size)
# -
# # Model
# +
nb_steps=20
nb_flow=1
model = UMNNMAFFlow(nb_flow=nb_flow,
nb_in=2,
hidden_derivative=[100, 100, 100, 100],
hidden_embedding=[100, 100, 100, 100],
embedding_s=10,
nb_steps=nb_steps,
device=device).to(device)
# -
# # Training
opt = torch.optim.Adam(model.parameters(), 1e-3, weight_decay=1e-5)
# +
print_every = 10
nb_epoch = 100
training_loss = []
testing_loss = []
for epoch in range(nb_epoch):
# Training
train_loss = 0
for batch in x_train:
ll, z = model.compute_ll(batch)
ll = -ll.mean()
train_loss += ll.detach()/(batch_size/batch.shape[0])/len(x_train)
loss = ll
opt.zero_grad()
loss.backward()
opt.step()
# Compute Test Loss
test_loss = 0
for batch in x_test:
ll_test, _ = model.compute_ll(batch)
ll_test = -ll_test.mean()
test_loss += ll_test.detach()/(batch_size/batch.shape[0])/len(x_test)
training_loss.append(train_loss)
testing_loss.append(test_loss)
if (epoch % print_every) == 0:
print("epoch: {:d} - Train loss: {:4f} - Test loss: {:4f}".
format(epoch, train_loss.item(), test_loss.item()))
fig = plt.figure(figsize=(7, 7))
ax = plt.subplot(1, 1, 1, aspect="equal")
vf.plt_flow(model.compute_ll, ax)
plt.show()
# -
plt.plot(training_loss, label='Training Loss')
plt.plot(testing_loss, label='Test Loss')
plt.legend()
# # Sample from the model
def sample_p_z(size, dim=2):
means = torch.zeros(size, dim)
cov = torch.eye(dim)
m = MultivariateNormal(means, cov)
return m.sample()
z1 = sample_p_z(1000)
z2 = sample_p_z(1000)
x = model.invert(z)
plt.scatter(x[:, 0], x[:, 1], alpha=0.2);
plt.title('Data sampled from the trained model');
| 8gaussians.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: LEAP_venv
# language: python
# name: leap_venv
# ---
# # Asynchronous parallel evaluation
#
# This demonstrates an asynchronous evaluation model, or as is known more formally, an asynchronous steady-state evolutionary algorithm (ASEA). We will demonstrate two approaches. The first shows a detailed implementation suitable for practitioners that like to have full control of their implementations. The second shows a more accessible approach using a single, monolithic function that implements a full ASEA.
# +
import multiprocessing.popen_spawn_posix # Python 3.9 workaround for Dask. See https://github.com/dask/distributed/issues/4168
from distributed import Client, LocalCluster
import toolz
from leap_ec import Representation, context
from leap_ec import ops
from leap_ec.decoder import IdentityDecoder
from leap_ec.binary_rep.problems import MaxOnes
from leap_ec.binary_rep.initializers import create_binary_sequence
from leap_ec.binary_rep.ops import mutate_bitflip
from leap_ec.distrib import asynchronous
from leap_ec.distrib import evaluate
from leap_ec.distrib.individual import DistributedIndividual
# -
# First, let's set up `dask` to run on local pretend "cluster" on your machine.
cluster = LocalCluster()
client = Client(cluster)
# Now create an initial random population of five individuals that use a binary representation of four bits for solving the MAX ONES problem.
parents = DistributedIndividual.create_population(5,
initialize=create_binary_sequence(4),
decoder=IdentityDecoder(), problem=MaxOnes())
# To get things started, we send the entire randomly generated initial population to dask to start getting evaluated asynchronously. We do this by calling `asynchronous.eval_population()`, which returns a distributed dask `as_completed` iterator. Essentially running `next()` on that iterator will iterate to the next completed individual.
as_completed_iter = asynchronous.eval_population(parents, client=client)
# We create a "bag" that will contain the evaluated individuals. This bag will initially be an empty list.
bag = []
# Then we fall into a loop where we insert individuals into a bag with an arbitrary capacity of three. That means the first three individuals will just be inserted into the bag. However, the fourth and fifth individual will have to fight it out to be inserted. We chose the greedy insertion function that means new individuals fight it out with the current *weakest* individual in the bag; there is an alternative function, `tournament_insert_into_pop()` that just randomly selects an opponent from the current bag.
#
# To make things more interesting, we will create up to four *new* offspring from the bag. In later, more complex examples, we'll implement a proper births budget to limit the total number of evaluated individuals.
# +
num_offspring = 0
for i, evaluated_future in enumerate(as_completed_iter):
evaluated = evaluated_future.result()
print(i, ', evaluated: ', evaluated.genome, evaluated.fitness)
asynchronous.greedy_insert_into_pop(evaluated, bag, 3)
if num_offspring < 4:
# Only create offspring if we have the budget for one
offspring = toolz.pipe(bag,
ops.random_selection,
ops.clone,
mutate_bitflip(expected_num_mutations=1),
ops.pool(size=1))
print('created offspring:', offspring[0].genome)
# Now asyncrhonously submit to dask
as_completed_iter.add(client.submit(evaluate.evaluate(context=context), offspring[0]))
num_offspring += 1
# -
# Now `bag` should contain the final population of the seven total individuals cooked down to the three best. Note that there are nine total "evaluated" lines that correspond to the original five randomly generated individuals plus the four new ones we added inside the loop.
[print(i, ind.genome, ind.fitness) for i, ind in enumerate(bag)]
# ## Using convenience function `steady_state`
#
# However, if you are comfortable with relinquishing control over implementation details, you might find it easier to use `leap.distributed.steady_state`. Under the hood it essentially does everything above, plus a few other things, such as allowing you to decide if non-viable individuals count towards the birth budget, or not. You can also specify the strategy for inserting new individuals into the bag.
#
# ### A note about non-viable individuals
#
# A non-viable individual is one that didn't get a chance to get evaluated because, say, an exception was thrown during the evaluation process. For example, if you were tuning deep-learner (DL) hyper-parameters, it may be that a given DL configuration an individual represents doesn't make sense such that it caused pytorch or tensorflow to throw an exception. That individual would be "non-viable" because the corresponding DL hyper-parameter set didn't even get a chance to be trained.
#
# Essentially, any exception thrown during an individual's evaluation will cause `leap.distributed` to deem that individual to be non-viable. It will see the `is_viable` to `False`, set the fitness to `math.nan`, and set the attribute `exception` to the thrown exception. This should hopefully make it easier to track such individuals and to provide a diagnostic to how and when individuals are marked non-viable during runs. `leap.core.context['leap']['distributed']['non_viable']` is incremented to keep a running total of non-viable individuals during a run; you will need to manually reset this counter between runs.
#
# Both `leap.distributed.synchronous` and `leap.distributed.asynchronous` use `leap.distributed.evaluate` to implement this functionality.
#
# ### `steady_state()` example
#
# The following example uses `steady_state()` to do what we did above, though we go with the default inserter, `tournament_insert_into_pop()` that is less greedy that what we used earlier. Note that we didn't specify the `individual_cls` argument since the default already uses `core.Individual`.
# + pycharm={"name": "#%%\n"}
final_pop = asynchronous.steady_state(client, births=9, init_pop_size=5, pop_size=3,
representation=Representation(
decoder=IdentityDecoder(),
initialize=create_binary_sequence(4),
individual_cls=DistributedIndividual),
problem=MaxOnes(),
offspring_pipeline=[ops.random_selection,
ops.clone,
mutate_bitflip(expected_num_mutations=1),
ops.pool(size=1)])
# + pycharm={"name": "#%%\n"}
[print(i, ind.genome, ind.fitness) for i, ind in enumerate(final_pop)]
# + pycharm={"name": "#%%\n"}
context
# -
final_pop = asynchronous.steady_state(client, births=9, init_pop_size=5, pop_size=3,
representation=Representation(
decoder=IdentityDecoder(),
initialize=create_binary_sequence(4),
individual_cls=DistributedIndividual),
problem=MaxOnes(),
offspring_pipeline=[ops.random_selection,
ops.clone,
mutate_bitflip(expected_num_mutations=1),
ops.pool(size=1)])
[print(i, ind.genome, ind.fitness) for i, ind in enumerate(final_pop)]
context
| examples/distributed/simple_async_distributed.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/litfung/100-Days-Of-ML-Code/blob/master/iris.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="OmHe5nTZFLNW" colab_type="text"
# **1. Import necessary library.**
# + id="88cjNKQ7FVEH" colab_type="code" colab={}
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn import metrics
# %matplotlib inline
# + [markdown] id="MfCJIoAHBBqr" colab_type="text"
# **2. Import dataset into dataframe.**
#
# + id="IWPsUp4XBIdT" colab_type="code" outputId="e832c9bd-7747-448f-8e56-535d67ffc4a5" colab={"base_uri": "https://localhost:8080/", "height": 195}
url = 'https://raw.githubusercontent.com/meiyeeyip/iris/master/IRIS.csv'
data = pd.read_csv(url)
data.head()
# + [markdown] id="k3pVDqMpFVp2" colab_type="text"
# **3. Exploratory data analysis --> important to understand the data.**
#
# + [markdown] id="7wBZ9Q4xAlWs" colab_type="text"
# 3.1 check shape of the data to know the number of row and columns.
# + id="FN49wiHhB8tI" colab_type="code" outputId="4faa02bd-3077-44a0-a300-d290dba252fa" colab={"base_uri": "https://localhost:8080/", "height": 34}
data.shape
# + [markdown] id="w_TGemaeCbMB" colab_type="text"
# 3.2 Check first few rows of the dataframe.
# + id="_yVpmLLLFZUP" colab_type="code" outputId="a0040ff2-1ce5-4aa6-bcd4-0dbcab6bb8e4" colab={"base_uri": "https://localhost:8080/", "height": 204}
data.head()
# + [markdown] id="aZMozBauDITI" colab_type="text"
# 3.3 Check for null values.
# + id="a0mApJIMDTux" colab_type="code" outputId="b1b6a19e-6ac2-4df7-acdc-546fc300158a" colab={"base_uri": "https://localhost:8080/", "height": 119}
data.isnull().sum()
# + [markdown] id="dPYLqcgwEqtP" colab_type="text"
# 4. **Transformation**
# + [markdown] id="r2G0IO1_DUTR" colab_type="text"
# 4.1 There are columns that contains string which will need to be transformed into integer so that the data can be fitted into our model.
#
# Please convert all the column that contains string into integer.
#
#
#
# + id="aUaiHDpfEvUW" colab_type="code" colab={}
labelencoder=LabelEncoder()
data['species'] = labelencoder.fit_transform(data['species'])
# + [markdown] id="Y9WqqLOMA2q6" colab_type="text"
# 4.2 Check encoded column. Make sure it is all integer!
# + id="nvgy3j0AGToW" colab_type="code" outputId="82246931-aa4d-42b6-9078-bbab4ad6a7e6" colab={"base_uri": "https://localhost:8080/", "height": 204}
data.head()
# + [markdown] id="IPpNERbw33P2" colab_type="text"
# Data Visualization
# + id="5NHg26B739ni" colab_type="code" outputId="5c8bd070-9e6a-454b-fd36-ca2071caf187" colab={"base_uri": "https://localhost:8080/", "height": 977}
tmp = data.drop('species', axis=1)
g = sns.pairplot(data, hue='species', markers='+')
plt.show()
# + [markdown] id="_8m8sak3FaNf" colab_type="text"
# 4.3 Check the information on the transformed data.
# + id="g6s769xfFeJH" colab_type="code" outputId="90683416-53e9-4150-e1f6-d33ec7baa7b1" colab={"base_uri": "https://localhost:8080/", "height": 284}
data.describe()
# + [markdown] id="cX5mjnGlF9OS" colab_type="text"
# 4.4 Check the correlation between each columns.
# + id="-NlIRwAGGA8-" colab_type="code" outputId="60e68ecc-839e-4a46-ae2f-22116440319d" colab={"base_uri": "https://localhost:8080/", "height": 204}
data.corr()
# + [markdown] id="PXKgFC9tJ8Le" colab_type="text"
# **5. Data Normalization**
# + [markdown] id="dXNvwy1FKAbF" colab_type="text"
# 5.1 Split Features column and Target column separately into "X" and "y".
#
# + id="7RkzO6A9J_cu" colab_type="code" colab={}
X = data.iloc[:,0:4]
y = data.iloc[:, 4]
# + id="FV95Yg6htOum" colab_type="code" outputId="b7ca854d-16f7-4db0-e588-12da57febdc4" colab={"base_uri": "https://localhost:8080/", "height": 195}
X.head()
# + id="rEbD5biutQdb" colab_type="code" outputId="0d6321b6-7abb-4fd2-ac59-7da8d81c2d7f" colab={"base_uri": "https://localhost:8080/", "height": 121}
y.head()
# + [markdown] id="EOfooa9GKTel" colab_type="text"
# 5.2 Normalise the Feature column only (X).
# + id="q0NfJigiKjg0" colab_type="code" outputId="b6305bb0-1664-4b40-ddc4-a6101fd27e4a" colab={"base_uri": "https://localhost:8080/", "height": 1000}
scaler = StandardScaler()
X=scaler.fit_transform(X)
X
# + [markdown] id="wLTpzdAMGBan" colab_type="text"
# **6.Split Data**
# + [markdown] id="hB1AqJZVIG5s" colab_type="text"
# 6.1 Split data set into training: 80% and test: 20%: random_state = 4.
#
# + id="PSmb8Xq8GERX" colab_type="code" colab={}
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=4)
# + [markdown] id="dzqtIryEGE1G" colab_type="text"
# **7. Training**
# + [markdown] id="Mp6dRPv8Lje8" colab_type="text"
# 7.1 Instantiate a Decision Tree model.
# + id="SXTOtm3eGHa-" colab_type="code" colab={}
model_tree = DecisionTreeClassifier()
# + [markdown] id="IyobCicrLx28" colab_type="text"
# 7.2 Fit the model with X_train and y_train.
#
# + id="pBnseKHpL6W-" colab_type="code" outputId="c00f8f03-c743-48b6-8e1e-32696e5676fa" colab={"base_uri": "https://localhost:8080/", "height": 118}
model_tree.fit(X_train, y_train)
# + [markdown] id="-uhEMe2vL66c" colab_type="text"
# **8. Predict**
# + [markdown] id="_4uOMYwjM5bl" colab_type="text"
# 8.1 Predict with X_test and output it as y_pred
# + id="C047K3nuM8fV" colab_type="code" colab={}
y_pred = model_tree.predict(X_test)
# + [markdown] id="dXPiZVFXM9C1" colab_type="text"
# **9. Result Evaluation**
#
# + [markdown] id="ImLSemmLNO20" colab_type="text"
# 9.1 Display the confusion matric for y_test and y_pred.
# + id="e0Z2ZE1TPYRZ" colab_type="code" outputId="113d0ece-bf61-4261-f8ed-bd5a0ec3c463" colab={"base_uri": "https://localhost:8080/", "height": 67}
confusion_matrix=metrics.confusion_matrix(y_test,y_pred)
confusion_matrix
# + [markdown] id="tUrrZ_7SPYoI" colab_type="text"
# 9.2 Display classification reports for y_test and y_pred.
# + id="jjMWpD7rPlSo" colab_type="code" outputId="8be9925f-59b1-427e-ea83-c886b795c676" colab={"base_uri": "https://localhost:8080/", "height": 54}
auc_roc=metrics.classification_report(y_test,y_pred)
auc_roc
# + id="T9eiiNm786_b" colab_type="code" colab={}
# + id="gyopPE00zFL3" colab_type="code" colab={}
| iris.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
fn = '../src/data/raw/2005-2015_Greenhouse_Gas_Emissions.csv'
emissions = pd.read_csv(fn)
trunc_emissions = emissions.iloc[5:13]
trunc_emissions.loc[5:13, 'id'] = np.array(np.arange(len(trunc_emissions)))
trunc_emissions
# -
year_str = [str(int(blah)) for blah in np.linspace(2005, 2015, 11)]
year_str
# +
# trunc_long = pd.wide_to_long(trunc_emissions, ['20'], i="id", j="year")
# trunc_long.rename(index = int)
# trunc_long
# Remove totals and add leveled indices
#see https://pandas.pydata.org/pandas-docs/version/0.22/groupby.html#grouping-dataframe-with-index-levels-and-columns
idx_list = np.linspace(5, 13, 9)[:-1]
#non_totals = emissions['Emission Source'][idx_list]
non_totals = trunc_emissions['Emission Source']
type_list = [list(non_totals.values),
[non_totals.str.split('-')[i][-1].strip().capitalize() for i in idx_list],
[non_totals.str.split('-')[i][0].strip().capitalize() for i in idx_list]]
idx = pd.MultiIndex.from_arrays(type_list, names=['original', 'source', 'use'])
len_columns = [len(emissions.columns)]
#emissions_lvld = pd.DataFrame(emissions.iloc[idx_list,1:], index = idx)
emissions_lvld = emissions.iloc[idx_list, 1:].copy()
emissions_lvld.index = idx
#emissions.iloc[idx_list,1:]
#emissions_lvld
emissions_lvld.loc[:, 'id'] = np.array(np.arange(len(emissions_lvld)))
emissions_lvld.loc[:, 'source'] = type_list[1]
emissions_lvld.loc[:, 'use'] = type_list[2]
emissions_long = emissions_lvld.melt(col_level=0, id_vars=['id', 'source', 'use'], value_vars=year_str, var_name='year')
#emissions_long = trunc_emissions.melt(col_level=0, id_vars=['id'], value_vars=year_str, var_name='year')
emissions_long['id'] = emissions_long.index
#emissions_long = emissions_long.melt(id_vars = ['id'], value_vars = 'Emission Source')
emissions_long
# -
len_data = len(emissions_long)
interval = 8
# link_data = np.array([[int(blah) for blah in np.linspace(0,len_data-interval,len_data-interval+1)],
# [int(blah) for blah in np.linspace(interval,len_data,len_data-interval+1)],
# emissions_long['value'].values[0:len_data-interval]]).T
link_data = np.transpose([emissions_long['id'].values[0:len_data-interval],
emissions_long['id'].values[interval:len_data],
emissions_long['value'].values[interval:len_data]])
link_df = pd.DataFrame(link_data, columns = ['source_id','target_id', 'strength'], dtype=object)
link_df
emissions_long.to_csv('emissions_long.csv')
link_df.to_csv('emissions_link.csv')
| notebooks/Emissions2015_charticulator.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import csv
import cv2
import os
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
import sklearn.utils
samples = []
with open('challenge_data/driving_log.csv') as csvfile:
reader = csv.reader(csvfile)
for line in reader:
samples.append(line)
from sklearn.model_selection import train_test_split
train_samples, validation_samples = train_test_split(samples, test_size=0.2)
images = []
measurements = []
def generator(samples, batch_size):
num_samples = len(samples)
while 1:
sklearn.utils.shuffle(samples)
for offset in range(0,num_samples, batch_size):
batch_samples = samples[offset:offset+batch_size]
images =[]
angles =[]
for batch_sample in batch_samples:
# Center Camera
filename_c = 'challenge_data/IMG/'+batch_sample[0].split('\\')[-1]
image_c = cv2.imread(filename_c)
image_center = cv2.cvtColor(image_c, cv2.COLOR_BGR2RGB)
image_flipped = np.fliplr(image_center)
images.append(image_center)
images.append(image_flipped)
measurement_center = np.float64(batch_sample[3])
measurement_center_flipped = -np.copy(measurement_center)
angles.append(measurement_center)
angles.append(measurement_center_flipped)
# Correction
correction = 0.09
#Left Camera
filename_l = 'challenge_data/IMG/'+batch_sample[1].split('\\')[-1]
image_l = cv2.imread(filename_l)
image_left = cv2.cvtColor(image_l, cv2.COLOR_BGR2RGB)
images.append(image_left)
measurement_left = np.float64(batch_sample[3]) + correction
angles.append(measurement_left)
#Right Camera
filename_r = 'challenge_data/IMG/'+batch_sample[2].split('\\')[-1]
image_r = cv2.imread(filename_r)
image_right = cv2.cvtColor(image_r, cv2.COLOR_BGR2RGB)
images.append(image_right)
measurement_right = np.float64(batch_sample[3]) - correction
angles.append(measurement_right)
X_train = np.array(images)
y_train = np.array(angles)
yield sklearn.utils.shuffle (X_train, y_train)
# -
train_generator = generator(train_samples, batch_size=10)
validation_generator = generator(validation_samples, batch_size=10)
print(len(train_samples))
print(len(validation_samples))
# +
from keras.models import Sequential
from keras.layers import Flatten, Dense, Activation, Lambda, Dropout, Convolution2D, MaxPooling2D, Cropping2D
import warnings
warnings.filterwarnings('ignore')
model = Sequential()
model.add(Lambda(lambda x: x / 255.0 - 0.5, input_shape=(160,320,3)))
model.add(Cropping2D(cropping=((70,25),(0,0))))
model.add(Convolution2D(24,5,5,subsample=(2,2), activation="relu"))
model.add(Dropout(0.2))
model.add(Convolution2D(36,5,5,subsample=(2,2), activation="relu"))
model.add(Dropout(0.2))
model.add(Convolution2D(48,5,5,subsample=(2,2), activation="relu"))
model.add(Dropout(0.2))
model.add(Convolution2D(64,3,3, activation="relu"))
model.add(Dropout(0.2))
model.add(Convolution2D(64,3,3, activation="relu"))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(100))
model.add(Dense(50))
model.add(Dense(10))
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')
#model.fit(X_train,y_train,validation_split=0.2, shuffle=True, nb_epoch=5)
model.fit_generator(train_generator, samples_per_epoch= len(train_samples),validation_data=validation_generator,nb_val_samples=len(validation_samples), nb_epoch=5)
model.save('model_challenge.h5')
# -
| Beh_Clon-Challenge.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] toc=true
# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#Finding-Outliers" data-toc-modified-id="Finding-Outliers-1"><span class="toc-item-num">1 </span>Finding Outliers</a></span></li><li><span><a href="#Exercise" data-toc-modified-id="Exercise-2"><span class="toc-item-num">2 </span>Exercise</a></span></li><li><span><a href="#Demo:-2-Dimensional-Analysis" data-toc-modified-id="Demo:-2-Dimensional-Analysis-3"><span class="toc-item-num">3 </span>Demo: 2-Dimensional Analysis</a></span></li><li><span><a href="#Conclusion" data-toc-modified-id="Conclusion-4"><span class="toc-item-num">4 </span>Conclusion</a></span></li></ul></div>
# -
# # Finding Outliers
#
# In this exercise, you'll practice looking for outliers. You'll look at the World Bank GDP and population data sets. First, you'll look at the data from a one-dimensional perspective and then a two-dimensional perspective.
#
# Run the code below to import the data sets and prepare the data for analysis. The code:
# * reads in the data sets
# * reshapes the datasets to a long format
# * uses back fill and forward fill to fill in missing values
# * merges the gdp and population data together
# * shows the first 10 values in the data set
# +
import pandas as pd
import numpy as np
# read in the projects data set and do basic wrangling
gdp = pd.read_csv('../data/gdp_data.csv', skiprows=4)
gdp.drop(['Unnamed: 62', 'Country Code', 'Indicator Name', 'Indicator Code'], inplace=True, axis=1)
population = pd.read_csv('../data/population_data.csv', skiprows=4)
population.drop(['Unnamed: 62', 'Country Code', 'Indicator Name', 'Indicator Code'], inplace=True, axis=1)
# Reshape the data sets so that they are in long format
gdp_melt = gdp.melt(id_vars=['Country Name'],
var_name='year',
value_name='gdp')
# Use back fill and forward fill to fill in missing gdp values
gdp_melt['gdp'] = gdp_melt.sort_values('year').groupby('Country Name')['gdp'].fillna(method='ffill').fillna(method='bfill')
population_melt = population.melt(id_vars=['Country Name'],
var_name='year',
value_name='population')
# Use back fill and forward fill to fill in missing population values
population_melt['population'] = population_melt.sort_values('year').groupby('Country Name')['population'].fillna(method='ffill').fillna(method='bfill')
# merge the population and gdp data together into one data frame
df_country = gdp_melt.merge(population_melt, on=('Country Name', 'year'))
# filter data for the year 2016
df_2016 = df_country[df_country['year'] == '2016']
# see what the data looks like
df_2016.head(10)
# -
# # Exercise
#
# Explore the data set to identify outliers using the Tukey rule. Follow the TODOs.
# +
import matplotlib.pyplot as plt
# %matplotlib inline
# TODO: Make a boxplot of the population data for the year 2016
df_2016.plot('population', kind='box')
# TODO: Make a boxplot of the gdp data for the year 2016
df_2016.plot('gdp', kind='box')
# -
# Use the Tukey rule to determine what values of the population data are outliers for the year 2016. The Tukey rule finds outliers in one-dimension. The steps are:
#
# * Find the first quartile (ie .25 quantile)
# * Find the third quartile (ie .75 quantile)
# * Calculate the inter-quartile range (Q3 - Q1)
# * Any value that is greater than Q3 + 1.5 * IQR is an outlier
# * Any value that is less than Qe - 1.5 * IQR is an outlier
# +
# TODO: Filter the data for the year 2016 and put the results in the population_2016 variable. You only need
# to keep the Country Name and population columns
population_2016 = df_2016[['Country Name','population']]
# TODO: Calculate the first quartile of the population values
# HINT: you can use the pandas quantile method
Q1 = population_2016['population'].quantile(0.25)
# TODO: Calculate the third quartile of the population values
Q3 = population_2016['population'].quantile(0.75)
# TODP: Calculate the interquartile range Q3 - Q1
IQR = Q3 - Q1
# TODO: Calculate the maximum value and minimum values according to the Tukey rule
# max_value is Q3 + 1.5 * IQR while min_value is Q1 - 1.5 * IQR
max_value = Q3 + 1.5 * IQR
min_value = Q1 - 1.5 * IQR
# TODO: filter the population_2016 data for population values that are greater than max_value or less than min_value
population_outliers = population_2016[(population_2016['population'] > max_value) | (population_2016['population'] < min_value)]
population_outliers
# -
# Many of these aren't countries at all but rather aggregates of various countries. Notice as well that the min_value calculated above was negative. According to the Tukey rule, there are no minimum population outliers in this data set. If you were going to study how population and gdp correlate, you might want to remove these aggregated regions from the data set.
#
# Next, use the Tukey method to do the same analysis for gdp.
# +
# TODO: Filter the data for the year 2016 and put the results in the population_2016 variable. You only need
# to keep the Country Name and population columns
gdp_2016 = df_2016[['Country Name','gdp']]
# TODO: Calculate the first quartile of the population values
# HINT: you can use the pandas quantile method
Q1 = gdp_2016['gdp'].quantile(0.25)
# TODO: Calculate the third quartile of the population values
Q3 = gdp_2016['gdp'].quantile(0.75)
# TODP: Calculate the interquartile range Q3 - Q1
IQR = Q3 - Q1
# TODO: Calculate the maximum value and minimum values according to the Tukey rule
# max_value is Q3 + 1.5 * IQR while min_value is Q1 - 1.5 * IQR
max_value = Q3 + 1.5 * IQR
min_value = Q1 - 1.5 * IQR
# TODO: filter the population_2016 data for population values that are greater than max_value or less than min_value
gdp_outliers = gdp_2016[(gdp_2016['gdp'] > max_value) | (gdp_2016['gdp'] < min_value)]
gdp_outliers
# -
# Clearly many of these outliers are due to regional data getting aggregated together.
#
# Remove these data points and redo the analysis. There's a list provided below of the 'Country Name' values that are not actually countries.
# +
# TODO: remove the rows from the data that have Country Name values in the non_countries list
# Store the filter results back into the df_2016 variable
non_countries = ['World',
'High income',
'OECD members',
'Post-demographic dividend',
'IDA & IBRD total',
'Low & middle income',
'Middle income',
'IBRD only',
'East Asia & Pacific',
'Europe & Central Asia',
'North America',
'Upper middle income',
'Late-demographic dividend',
'European Union',
'East Asia & Pacific (excluding high income)',
'East Asia & Pacific (IDA & IBRD countries)',
'Euro area',
'Early-demographic dividend',
'Lower middle income',
'Latin America & Caribbean',
'Latin America & the Caribbean (IDA & IBRD countries)',
'Latin America & Caribbean (excluding high income)',
'Europe & Central Asia (IDA & IBRD countries)',
'Middle East & North Africa',
'Europe & Central Asia (excluding high income)',
'South Asia (IDA & IBRD)',
'South Asia',
'Arab World',
'IDA total',
'Sub-Saharan Africa',
'Sub-Saharan Africa (IDA & IBRD countries)',
'Sub-Saharan Africa (excluding high income)',
'Middle East & North Africa (excluding high income)',
'Middle East & North Africa (IDA & IBRD countries)',
'Central Europe and the Baltics',
'Pre-demographic dividend',
'IDA only',
'Least developed countries: UN classification',
'IDA blend',
'Fragile and conflict affected situations',
'Heavily indebted poor countries (HIPC)',
'Low income',
'Small states',
'Other small states',
'Not classified',
'Caribbean small states',
'Pacific island small states']
# remove non countries from the data
df_2016 = df_2016[~df_2016['Country Name'].isin(non_countries)]
# +
# TODO: Re-rerun the Tukey code with this filtered data to find population outliers
# TODO: Filter the data for the year 2016 and put the results in the population_2016 variable. You only need
# to keep the Country Name and population columns
population_2016 = df_2016[['Country Name','population']]
# TODO: Calculate the first quartile of the population values
# HINT: you can use the pandas quantile method
Q1 = population_2016['population'].quantile(0.25)
# TODO: Calculate the third quartile of the population values
Q3 = population_2016['population'].quantile(0.75)
# TODO: Calculate the interquartile range Q3 - Q1
IQR = Q3 - Q1
# TODO: Calculate the maximum value and minimum values according to the Tukey rule
# max_value is Q3 + 1.5 * IQR while min_value is Q1 - 1.5 * IQR
max_value = Q3 + 1.5 * IQR
min_value = Q1 - 1.5 * IQR
# TODO: filter the population_2016 data for population values that are greater than max_value or less than min_value
population_outliers = population_2016[(population_2016['population'] > max_value) | (population_2016['population'] < min_value)]
population_outliers
# +
# TODO: Filter the data for the year 2016 and put the results in the population_2016 variable. You only need
# to keep the Country Name and population columns
gdp_2016 = df_2016[['Country Name','gdp']]
# TODO: Calculate the first quartile of the population values
# HINT: you can use the pandas quantile method
Q1 = gdp_2016['gdp'].quantile(0.25)
# TODO: Calculate the third quartile of the population values
Q3 = gdp_2016['gdp'].quantile(0.75)
# TODO: Calculate the interquartile range Q3 - Q1
IQR = Q3 - Q1
# TODO: Calculate the maximum value and minimum values according to the Tukey rule
# max_value is Q3 + 1.5 * IQR while min_value is Q1 - 1.5 * IQR
max_value = Q3 + 1.5 * IQR
min_value = Q1 - 1.5 * IQR
# TODO: filter the population_2016 data for population values that are greater than max_value or less than min_value
gdp_outliers = gdp_2016[(gdp_2016['gdp'] > max_value) | (gdp_2016['gdp'] < min_value)]
gdp_outliers
# -
# Next, write code to determine which countries are in the population_outliers array and in the gdp_outliers array.
# TODO: Find country names that are in both the population_outliers and the gdp_outliers
list(set(population_outliers['Country Name']).intersection(gdp_outliers['Country Name']))
# These countries have both relatively high populations and high GDPs. That might be an indication that although these countries have high values for both gdp and population, they're not true outliers when looking at these values from a two-dimensional perspective.
#
# Now write code to find countries in population_outliers but not in the gdp_outliers.
# +
# TODO: Find country names that are in the population outliers list but not the gdp outliers list
# HINT: Python's set() and list() methods should be helpful
list(set(population_outliers['Country Name']) - set(gdp_outliers['Country Name']))
# -
# These countries are population outliers but not GDP outliers. If looking at outliers from a two-dimensional perspective, there's some indication that these countries might be outliers.
#
# And finally, write code to find countries that are in the gdp_outliers array but not the population_outliers array.
# +
# TODO: Find country names that are in the gdp outliers list but not the population outliers list
# HINT: Python's set() and list() methods should be helpful
list(set(gdp_outliers['Country Name']) - set(population_outliers['Country Name']))
# -
# On the other hand, these countries have high GDP but are not population outliers.
#
#
# # Demo: 2-Dimensional Analysis
#
# Next, look at the data from a two-dimensional perspective. You don't have to do anything in this section other than run the code cells below. This gives a basic example of how outlier removal affects machine learning algorithms.
#
# The next code cell plots the GDP vs Population data including the country name of each point.
# +
# run the code cell below
x = list(df_2016['population'])
y = list(df_2016['gdp'])
text = df_2016['Country Name']
fig, ax = plt.subplots(figsize=(15,10))
ax.scatter(x, y)
plt.title('GDP vs Population')
plt.xlabel('population')
plt.ylabel('GDP')
for i, txt in enumerate(text):
ax.annotate(txt, (x[i],y[i]))
# -
# The United States, China, and India have such larger values that it's hard to see this data. Let's take those countries out for a moment and look at the data again.
# +
# Run the code below to see the results
df_no_large = (df_2016['Country Name'] != 'United States') & (df_2016['Country Name'] != 'India') & (df_2016['Country Name'] != 'China')
x = list(df_2016[df_no_large]['population'])
y = list(df_2016[df_no_large]['gdp'])
text = df_2016[df_no_large]['Country Name']
fig, ax = plt.subplots(figsize=(15,10))
ax.scatter(x, y)
plt.title('GDP vs Population')
plt.xlabel('population')
plt.ylabel('GDP')
for i, txt in enumerate(text):
ax.annotate(txt, (x[i],y[i]))
# -
# Run the code below to build a simple linear regression model with the population and gdp data for 2016.
# +
from sklearn.linear_model import LinearRegression
# fit a linear regression model on the population and gdp data
model = LinearRegression()
model.fit(df_2016['population'].values.reshape(-1, 1), df_2016['gdp'].values.reshape(-1, 1))
# plot the data along with predictions from the linear regression model
inputs = np.linspace(1, 2000000000, num=50)
predictions = model.predict(inputs.reshape(-1,1))
df_2016.plot('population', 'gdp', kind='scatter')
plt.plot(inputs, predictions)
print(model.predict(1000000000))
# -
# Notice that the code ouputs a GDP value of 6.54e+12 when population equals 1e9. Now run the code below when the United States is taken out of the data set.
# Remove the United States to see what happens with the linear regression model
df_2016[df_2016['Country Name'] != 'United States'].plot('population', 'gdp', kind='scatter')
# plt.plot(inputs, predictions)
model.fit(df_2016[df_2016['Country Name'] != 'United States']['population'].values.reshape(-1, 1),
df_2016[df_2016['Country Name'] != 'United States']['gdp'].values.reshape(-1, 1))
inputs = np.linspace(1, 2000000000, num=50)
predictions = model.predict(inputs.reshape(-1,1))
plt.plot(inputs, predictions)
print(model.predict(1000000000))
# Notice that the code now ouputs a GDP value of 5.26e+12 when population equals 1e9. In other words, removing the United States shifted the linear regression line down.
#
# # Conclusion
#
# Data scientists sometimes have the task of creating an outlier removal model. In this exercise, you've used the Tukey rule. There are other one-dimensional models like eliminating data that is far from the mean. There are also more sophisticated models that take into account multi-dimensional data.
#
# Remember, however, that this is a course on data engineering. As a data engineer, your job will be to remove outliers using code based on whatever model you're given.
#
# If you were using the Tukey rule, for example, you'd calculate Q1, Q3, and IQR on your training data. You'd need to store these results. Then as new data comes in, you'd use these stored values to eliminate any outliers.
| lessons/ETLPipelines/13_outlierspart1_exercise/.ipynb_checkpoints/13_outliers_exercise-solution-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
# ---
# # How to Scrape Tweets of Twitter Users (Handles) and Get Around Twitter API Limits
# ### Objective: Get entire history of tweets for particular Twitter users using their handles. Avoid any limits put in place by the Twitter API.
# In the previous step I compiled a list of all the Twitter handles from colleges in our sample on Twitter. The next step is to obtain all tweets created by each handle. This is tricky because the Twitter API [limits the number of Tweets you can pull](https://developer.twitter.com/en/docs/basics/rate-limiting.html). Thankfully, the developers of the [twint](https://github.com/twintproject/twint) Python package have figured out how to circumvent these limits by not using the API at all!
#
# All tweets are output to a .json file for each college's main handle and admissions handle.
# ## Set Up
import pandas as pd
import numpy as np
import os, requests, re, time
import twint
# #### File Locations
base_path = r"C:\Users\laure\Dropbox\!research\20181026_ihe_diversity"
tw_path = os.path.join(base_path,'data','twitter_handles')
# #### Import handles
ihe_handles = pd.read_pickle(os.path.join(tw_path, "tw_df_final"))
ihe_handles[ihe_handles.adm_handle == ''].head(2)
# ## Scrape All Tweets from Username with Twint
def scrape_tweets(username, csv_name):
# Configure
c = twint.Config()
c.Username = username
c.Custom = ['id', 'date', 'time', 'timezone', 'user_id', 'username', 'tweet', 'replies',
'retweets', 'likes', 'hashtags', 'link', 'retweet', 'user_rt', 'mentions']
c.Store_csv = True
c.Output = os.path.join(tw_path, csv_name)
# Start search
twint.run.Profile(c)
for index, row in ihe_handles.iterrows():
# CSV file names
main_f_name = os.path.join(tw_path, str(index) + '_main.csv')
adm_f_name = os.path.join(tw_path, str(index) + '_adm.csv')
# Handles
main_handle = row['main_handle']
adm_handle = row['adm_handle']
if main_handle != '':
scrape_tweets(main_handle, main_f_name)
if adm_handle != '':
scrape_tweets(adm_handle, adm_f_name)
| Notebooks/03_scrape_tweets_final.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/FairozaAmira/basic_algorithms_a/blob/master/Lecture04.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="T6UuzVPzv4p5" colab_type="text"
# # 変数
#
# **変数を導入する**
#
# 1. `2`を`x`の変数に導入する
# + id="S8m3_u7kv4p9" colab_type="code" outputId="dc87de83-d6a3-4abb-8061-2020c022c724" colab={"base_uri": "https://localhost:8080/", "height": 35}
x = 2
print(x)
# + [markdown] id="QjHGCYHxv4qD" colab_type="text"
# 2. 整数、文字列とリストを変数`x`に導入する
# + id="CyaD2kgPv4qE" colab_type="code" outputId="316f868d-11b7-49d3-843c-35051432818e" colab={"base_uri": "https://localhost:8080/", "height": 71}
x = 1 #xは整数
print(x)
x = "hello" #xは文字列
print(x)
x = [1, 2, 3] #xは1,2,3のリスト
print(x)
# + [markdown] id="xhc6xgnXv4qG" colab_type="text"
# 3. `y`を`x`に導入する
# + id="WNZp8nbDv4qH" colab_type="code" outputId="e8f5e396-2277-4fe2-b0f6-3dd92e0a608f" colab={"base_uri": "https://localhost:8080/", "height": 35}
y = x
print(y)
# + [markdown] id="6Q--BLU1v4qK" colab_type="text"
# 4. `append()`を使って、`x`の変数に`4`を追加する
# + id="B4Uv0R3wv4qK" colab_type="code" outputId="c0859c29-af66-4499-9cdc-9e39ebd66806" colab={"base_uri": "https://localhost:8080/", "height": 35}
x.append(4)
print(y)
# + [markdown] id="PDPcLCEFv4qM" colab_type="text"
# 5. `x`に他のものに導入し、`y`を出力してみる
# + id="bamfbFlNv4qN" colab_type="code" outputId="0133a578-0ce8-4285-d4ac-6d7221c9af0c" colab={"base_uri": "https://localhost:8080/", "height": 35}
x = "something else"
print(y)
# + [markdown] id="6G2AS-7zv4qP" colab_type="text"
# 6. `4`を`x`に導入し、`type()`を使って、`x`の種類を見せてください。
# + id="e7IZkEokv4qQ" colab_type="code" outputId="80e3f75b-9b61-4e7e-a25c-338d01fe9814" colab={"base_uri": "https://localhost:8080/", "height": 35}
x = 4
type(x)
# + [markdown] id="-FHoiF54v4qS" colab_type="text"
# 7. `hello`を`x`に導入し、`type()`を使って、`x`の種類を見せてください。
# + id="sze7caNdv4qT" colab_type="code" outputId="f8f38976-9f14-41b0-fdd7-6cbbf72e41c7" colab={"base_uri": "https://localhost:8080/", "height": 35}
x = "hello"
type(x)
# + [markdown] id="GcO9PBmdv4qV" colab_type="text"
# 8. `3.14159`を`x`に導入し、`type()`を使って、`x`の種類を見せてください。
# + id="N7Ap1zSZv4qV" colab_type="code" outputId="3e5042c0-de0d-41e6-9f9f-2e708503b345" colab={"base_uri": "https://localhost:8080/", "height": 35}
x = 3.14159
type(x)
# + [markdown] id="wU4zu934v4qY" colab_type="text"
# # 算術演算
# + [markdown] id="PMvp-yR7v4qa" colab_type="text"
# 1. $(5+2) \times (12 \div 4)$ を計算して、出力してください。
# + id="DzuVRAnPv4qc" colab_type="code" outputId="2cb15012-4409-45ec-f2f8-ed39a9648052" colab={"base_uri": "https://localhost:8080/", "height": 35}
(5 + 2) * (12 / 4)
# + [markdown] id="mL27jt8Yv4qf" colab_type="text"
# 2. 以下の出力は何ですか?
#
# a. `print (11 /3)`
#
# b. `print (11//3)`
# + id="gPX5px3Gv4qg" colab_type="code" outputId="251992f1-743e-4239-91f2-7538ed237724" colab={"base_uri": "https://localhost:8080/", "height": 35}
print(11/3)
# + id="sJpzS4aEv4qj" colab_type="code" outputId="f2dbb5ac-e764-49ab-938f-5478f3c3a759" colab={"base_uri": "https://localhost:8080/", "height": 35}
print(11//3)
# + [markdown] id="uhBEFlRlv4ql" colab_type="text"
# 3. $2^5$を計算してください
# + id="mS0WeWLhv4qm" colab_type="code" outputId="5f6c85f0-89b9-43f5-b7d6-27c37bc737bf" colab={"base_uri": "https://localhost:8080/", "height": 35}
2**5
# + [markdown] id="9KLzGHrjv4qo" colab_type="text"
# # ビット算術
# + [markdown] id="9EGCtcbpv4qp" colab_type="text"
# 1. 12の2進数を計算してください。
# + id="AQabN9Btv4qq" colab_type="code" outputId="88f5a5ca-73cd-49e0-fc6f-1ba82f4bfc9c" colab={"base_uri": "https://localhost:8080/", "height": 35}
bin(12)
# + [markdown] id="HIpAii_Wv4qs" colab_type="text"
# 2. `4`の2進数を計算してください
# + id="KiNBkpGSv4qt" colab_type="code" outputId="a93940a5-62d2-4d02-8feb-1ef48ba8be8d" colab={"base_uri": "https://localhost:8080/", "height": 35}
bin(4)
# + [markdown] id="pwWe_Toqv4qw" colab_type="text"
# 3. 12と4のOR演算を計算し、その2進数も計算してください。
# + id="R8hTCID0v4qx" colab_type="code" outputId="a30dec99-19e5-4f9a-beb9-8b6d599020d8" colab={"base_uri": "https://localhost:8080/", "height": 35}
12 | 4
# + id="zpjcQULQv4qz" colab_type="code" outputId="ce3c2648-5437-44d9-f338-b924f44b35c1" colab={"base_uri": "https://localhost:8080/", "height": 35}
bin (12|4)
# + id="Xos8AU3bv4q3" colab_type="code" outputId="f03c5d26-0bf0-472b-8a4a-6fb5cb2a6c69" colab={"base_uri": "https://localhost:8080/", "height": 35}
bin(1)
# + [markdown] id="hSuHqKbLBlrO" colab_type="text"
# 4. `a=5`, `b=67`とすると、`a`と`b`のビットAND、ビットOR,ビットXOR,`a<<b`, `a>>b`とビットNOTを計算しなさい。
# + id="1GrS9UrbCNkG" colab_type="code" outputId="533b3f12-0fda-4030-de80-2fb8efe1b2e0" colab={"base_uri": "https://localhost:8080/", "height": 35}
a = 5
a_bin = bin(a)
print(a)
# + id="ZHkVg4lkCTIN" colab_type="code" outputId="d247be86-5ae7-48f2-9cc1-eb429acb36df" colab={"base_uri": "https://localhost:8080/", "height": 35}
b = 67
b_bin = bin(b)
print(b)
# + id="n0TaAoGACX04" colab_type="code" outputId="9bbff104-6936-4eed-b3cf-386a59725d86" colab={"base_uri": "https://localhost:8080/", "height": 35}
print(a & b)
# + id="ym9h1Mb7CfeH" colab_type="code" outputId="aa27e241-81ee-4272-99d8-50a561226c00" colab={"base_uri": "https://localhost:8080/", "height": 35}
print (a | b)
# + id="FcFioPhECjSc" colab_type="code" outputId="b26c0b0a-552d-4d5b-afcf-ab1362e2b59c" colab={"base_uri": "https://localhost:8080/", "height": 35}
print( a << b)
# + id="_J0_qsTjDQkL" colab_type="code" outputId="82c0c3e7-09f5-44cd-a8a0-38727660df7b" colab={"base_uri": "https://localhost:8080/", "height": 35}
print( a >> b)
# + id="hU48EK12DVh1" colab_type="code" outputId="230705e4-1152-4e2e-c216-5c2520e09c3b" colab={"base_uri": "https://localhost:8080/", "height": 35}
print(~ a)
# + id="CJr-Jvr3D2cy" colab_type="code" outputId="ebb55f7f-6757-49a8-d694-f7c456678666" colab={"base_uri": "https://localhost:8080/", "height": 35}
print (~ b)
| Lecture04.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
# ---
# # 17L-5509 CS 5102 - Deep Learning Part A
# Convolutional Neural Network using Keras with Tensorflow backend
# #### Import libraries
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
# #### Set parameters, learning rate is set while compiling the model below
batch_size = 128
num_classes = 10
epochs = 12
# #### Load mnist data
# +
# input image dimensions
img_rows, img_cols = 28, 28
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# -
# #### Reshape and normalize data , also convert the classes to binary class vectors
# +
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# -
# #### Build squential model with following architecture
# Input layer
# 2D Convolutional layer with filter size of 3x3 and depth of = 32 (# of filters) and activation function 'relu'
# 2D Convolutional layer with filter size of 3x3 and depth = 64 and activation function 'relu'
# MaxPooling layer with pool size 2x2
# 2D Convolutional layer with filter size of 3x3 and depth = 64 and activation function 'relu'
# MaxPooling layer with pool size 2x2
# Dropout 25%
# Flatten
# Fully connected layer with 128 neurons and activation function 'relu'
# Dropout 25%
# Output layer with sofmax activation function for class probabilities
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(num_classes, activation='softmax'))
# #### Commpile and fit the model
# Set Adadelta as optimizer. It is an adaptive learning method. Default value of learning rate is 1.0
# +
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
# -
# #### The training accuracy is over 99%, now evaluate test score
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# ### The test accuraccy is also more than 99%
# # 17L-5509 CS 5102 - Deep Learning Part B
# #### Initial part is reused from Part A
# +
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from keras.callbacks import TensorBoard
from time import time
import matplotlib.pyplot as plt
K.clear_session()
batch_size = 128
num_classes = 10
epochs = 12
# input image dimensions
img_rows, img_cols = 28, 28
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
#model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
# -
# #### Define tensorboard callback for collecting loss, accuracy and weights data
tensorboard = TensorBoard(log_dir="logs/{}".format(time()),
histogram_freq = 1,
write_graph = True,
write_images = True)
# #### Save history from model.fit for later visualization of the accuracy and loss graphs
start_time = time()
history = model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
callbacks=[tensorboard],
validation_data=(x_test, y_test))
elapsed_time = time() - start_time
print(elapsed_time)
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# #### Plot loss and accuracy for training and validation vs epochs
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# #### Tensorboard accuracy and loss graphs
# <img src="logs\accuracy_loss_tensorboard.PNG">
# #### Tensorboard network graph - complete
# <img src="logs\graph_tensorboard.PNG">
# #### Tensorboard network graph - simple
# <img src="logs\graph_simple_tensorboard.PNG">
# #### Tensorboard weights visualization of convolational and fully connected layers
# <img src="logs\weights_conv_dense_tensorboard.PNG">
| Project 1 - Part B Submission Files/Project 1 - Part B - L17-5509.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
# ---
# +
# Print the first Armstrong number in the range of 1042000 to 702648265 and exit the loop as soon as you encounter the first
# armstrong number.
# Use while loop
# -
s=0
p=1
q=0
for n in range(1042000,702648265):
s=0
q=n
while q>0:
p=q%10
s+=p*p*p*p*p*p*p
q=q/10
q=int(q)
if(s==n):
print("The first armstrong number is:",s)
break
| Day 4 - Assignment.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <NAME>. 2019 г.
#
# # Естественная сепарация
#
# Источники:
#
# <NAME>. Modeling downhole natural separation : дис. – The University of Tulsa, 2004.
#
# Естественная сепарация на приеме погружного оборудования играет существенную роль в работе скважины. За счет того, что часть свободного газа удаляется в затрубное пространство, плотность ГЖС в НКТ возрастает, и следовательно снижается газлифтный эффект. С другой стороны, сепарация газа позволяет нормально работать погружному оборудованию, например, создавать больший перепад давления.
#
# Как и гидравлические корреляции, модели естественной сепарации деляться на экспериментальные корреляции и механистические модели. Новая корреляция Marquez относится к первому типу.
#
# В данном методике приняты следующие допущения:
# 1. Объемное содержание газа поступившее в насос определяется как:
# $$\alpha_p (1 - \alpha_p)^{n-1} = \frac{V_{Sgz}^i}{V_{\infty z}}$$
# 2. Учитываются скорости проскальзывания газа, как в вертикальном, так и в радиальном направлении;
# 3. Для пробкового и эмульсионного режимов течения автор пренебрегает эффектом воздействия с другими пузырьками газа и на основе анализа экспериментальных данных принимает значение $n$ равным нулю.
#
# Коэффициент естественной сепарации рассчитывается по формуле
#
# $$E = 1 -[-\frac{V_{\infty r}}{V_{\infty z}}(\frac{A_p}{A_a}) + \frac{V_{SLz}^i}{V_{\infty z}}] $$
#
# где отношение скоростей проскальзывания в вертикальном и радиальном направлении
#
# $$\frac{V_{\infty r}}{V_{\infty z}} = \frac{\rho_L}{(\rho_L + \rho_g)g} (V_{Lr} \frac{dV_{Lr}}{dr})$$
#
# а $V_{SLz}^i, V_{Sgz}^i$ - приведенные скорости жидкости и газа вдоль оси насоса
#
# Автор ввел параметр M в виде
#
# $$M = -\frac{V_{\infty r}}{V_{\infty z}}\frac{A_p}{A_a} $$
#
# или
#
# $$M = -[\frac{ab+c(\frac{V_{SLz}^i}{V_{\infty z}})^d}{b+(\frac{V_{SLz}^i}{V_{\infty z}})^d}]$$
#
# где а = -0,0093 ; b = 57,758 ; c = 34,4 ; d = 1,308 – коэффициенты М параметра определялись из экспериментальных данных
#
# $A_p, A_a$ - площади поперечного сечения приема насоса и эксплуатационной колонны.
#
# Итоговая упрощенная формула:
#
# $$E = ([1 + [\frac{ab+c(\frac{V_{SLz}^i}{V_{\infty z}})^d}{b+(\frac{V_{SLz}^i}{V_{\infty z}})^d}]]^{272} + [\frac{V_{SLz}^i}{V_{\infty z}}]^{272} )^{1/272} - \frac{V_{SLz}^i}{V_{\infty z}}$$
#
#
# Перед расчетом необходимо воспользоваться механистической моделью Caetano (1992) для определения режимов течения в затрубном пространстве вертикальной скважины и для вычисления $V_{\infty z}$ - скорости проскальзывания пузырьков газа в вертикальном направлении
#
#
# +
import sys
sys.path.append('../')
import uniflocpy.uTools.uconst as uc
import uniflocpy.uTools.data_workflow as tool
import uniflocpy.uMultiphaseFlow.flow_pattern_annulus_Caetano as FPA
import uniflocpy.uPVT.PVT_fluids as PVT
import uniflocpy.uMultiphaseFlow.natural_separation as nat_sep
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly import tools
init_notebook_mode(connected=True)
# -
# Создание необходимых экземляров для работы
# +
annular = FPA.flow_pattern_annulus_Caetano()
fluid_flow = PVT.FluidFlow()
flow_data = tool.Data()
pattern_data = tool.Data()
separation = nat_sep.new_correlation_Marquez()
annular_data = tool.Data()
fluid_flow_data = tool.Data()
separation_data = tool.Data()
# -
# Задание термобарических условий на приеме погружного оборудования, конструкцию приема
#
# Расчет параметров по кольцевому пространству проиизводится исходя из того, что площадь поперечного сечения кольцевого пространства равна площади трубы при расчете многофазного потока. Возможно вместо этого подхода требуется применение гидравлического диаметра
# +
p_bar = 40
t_c = 60
annular.d_cas_in_m = 0.140
annular.d_tube_out_m = 0.100
d_annular_hydr_m = annular.d_cas_in_m - annular.d_tube_out_m #TODO какой диаметр при расчетах потока использовать?
Ap = uc.pi / 4 * (annular.d_cas_in_m ** 2 - annular.d_tube_out_m ** 2)
fluid_flow.d_m = (Ap * 4 / uc.pi) ** (1 / 2)
# -
# Здесь производится расчет. Расчитанные параметры многофазного потока вливаются в расчет режима течения
# в кольцевом пространстве, а затем необходимые параметры передаются модулю расчета естественной сепарации
#
# +
separation_data.clear_data()
fluid_flow_data.clear_data()
annular_data.clear_data()
for i in range(1,200):
fluid_flow.qliq_on_surface_m3day = i
fluid_flow.calc(p_bar, t_c)
annular.surface_tension_gl_Nm = fluid_flow.sigma_liq_Nm
annular.rho_liq_kgm3 = fluid_flow.rho_liq_kgm3
annular.rho_gas_kgm3 = fluid_flow.fl.rho_gas_kgm3
annular.rho_mix_kgm3 = fluid_flow.rhon_kgm3
annular.mu_mix_pasec = fluid_flow.mun_cP / 10 ** 3
vs_gas_msec = fluid_flow.vsg_msec
vs_liq_msec = fluid_flow.vsl_msec
annular.calc_pattern(vs_liq_msec, vs_gas_msec)
separation.v_infinite_z_msec = annular.v_infinite_z_msec
separation.vs_liq_z_msec = annular.vs_liq_msec
value_of_natural_separation_Marquez = separation.calc()
separation_data.get_data(separation)
fluid_flow_data.get_data(fluid_flow)
annular_data.get_data(annular)
# +
def trace(data, number_param):
tracep = go.Scattergl(
x = fluid_flow_data.get_values(1),
y = data.get_values(number_param),
name = data.get_name(number_param),
mode = 'markers'
)
return tracep
def plot():
layout = dict(title = 'Естественная сепарация по новой корреляции Marquez',
yaxis = dict(range=[0,1], title = 'Коэффициент естественной сепарации, д.ед.'),
xaxis = dict(title = 'Дебит жидкости в поверхностных условиях, м3/сут'))
fig = dict(data=data, layout=layout)
iplot(fig, filename='basic-scatter')
# -
separation_data.print_all_names()
fluid_flow_data.print_all_names()
# +
trace1 = trace(separation_data, 4)
data = [trace1]
plot()
| notebooks/uMultiphaseFlow. Natural separation.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
# ---
# # Association Rule Mining
from IPython.display import Image
Image(filename='pseudocode.png')
Image(filename='image.png')
Image(filename='advantages&disadvantages.png')
# # Demo:
#
#
# ## Apriori
# ! pip install mlxtend
def loadDataSet():
return [[1,3,4],[2,3,5],[1,2,3,5],[2,5]]
# ### Apriori Algorithm from scratch
def createC1(dataSet):
C1 = []
for transaction in dataSet:
for item in transaction:
if not [item] in C1:
C1.append([item])
C1.sort()
return list(map(frozenset, C1))
def scanD(D, Ck, minSupport):
ssCnt = {}
for tid in D:
for can in Ck:
if can.issubset(tid):
if not can in ssCnt: ssCnt[can] = 1
else: ssCnt[can] += 1
numItems = float(len(D))
retList = []
supportData = {}
for key in ssCnt:
support = ssCnt[key]/numItems
supportData[key] = support
if support >= minSupport:
retList.insert(0,key)
return retList,supportData
dataSet = loadDataSet()
dataSet
C1 = createC1(dataSet)
C1
D = list(map(set,dataSet))
D
L1,suppDat0 = scanD(D,C1,0.6)
L1
suppDat0
def aprioriGen(Lk, k):
retList = []
lenLk = len(Lk)
for i in range(lenLk):
for j in range(i+1,lenLk):
L1 = list(Lk[i])[:k-2]
L2 = list(Lk[j])[:k-2]
L1.sort(); L2.sort()
if L1 == L2:
retList.append(Lk[i] | Lk[j]) # set union
return retList
def apriori(dataSet, minSupport):
C1 = createC1(dataSet)
D = list(map(set,dataSet))
L1, supportData = scanD(D,C1,minSupport)
L = [L1]
k = 2
while (len(L[k-2]) > 0):
Ck = aprioriGen(L[k-2],k)
Lk, supK = scanD(D, Ck, minSupport)
supportData.update(supK)
L.append(Lk)
k += 1
return L, supportData
def generateRules(L, supportData, minConf):
bigRuleList = []
for i in range(1,len(L)):
for freqSet in L[i]:
H1 = [frozenset([item]) for item in freqSet]
if i>1:
rulesFromConseq(freqSet, H1, supportData, bigRuleList,minConf)
else:
prunedH = calcConf(freqSet,H1,supportData,bigRuleList,minConf)
return bigRuleList
def calcConf(freqSet, H, supportData,brl,minConf):
prunedH = []
for conseq in H:
conf = supportData[freqSet]/supportData[freqSet - conseq]
if conf >= minConf:
print(freqSet-conseq, " --> ", conseq, "conf: ", conf)
brl.append((freqSet-conseq , conseq, conf))
prunedH.append(conseq)
return prunedH
def rulesFromConseq(freqSet, H, supportData, brl, minConf):
m = len(H[0])
if (len(freqSet) > (m+1)):
Hmp1 = aprioriGen(H,m+1)
Hmp1 = calcConf(freqSet, Hmp1, supportData,brl,minConf)
if (len(Hmp1) > 1):
rulesFromConseq(freqSet, Hmp1, supportData,brl,minConf)
L, suppData = apriori(dataSet,minSupport=0.5)
rules = generateRules(L, suppData, minConf = 0.6)
rules
# ## Apriori Algorithm on Bread-Basket Data Set
import pandas as pd
import numpy as np
df = pd.read_csv("C:/Users/<NAME>/Downloads/All/Association-Rule-Mining-master/Basketdataset.csv",delimiter=',')
df.head()
df.info()
df.columns
df.loc[df['Item_Name']=='NONE',:]
df.drop(df.loc[df['Item_Name']=='NONE',:].index,axis=0,inplace=True)
hot_encoded_df = df.groupby(['Transaction','Item_Name'])['Item_Name'].count().unstack().reset_index().fillna(0).set_index('Transaction')
hot_encoded_df.head()
def encode_units(x):
if x <= 0:
return 0
else:
return 1
hot_encoded_df = hot_encoded_df.applymap(encode_units)
hot_encoded_df.head()
from mlxtend.frequent_patterns import apriori, association_rules
freq_itemsets = apriori(hot_encoded_df, min_support=0.01,use_colnames = True)
rules = association_rules(freq_itemsets, metric='lift')
rules.head(10)
rules[ (rules['lift'] > 1.1) & (rules['confidence'] > 0.6)]
| Association_Rule_Mining_Vibhooti.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
# ---
# # Correspondence of precursor emissions to ozone forcing
#
# Theme Song: The Bell<br>
# Artist: iamthemorning<br>
# Album: The Bell<br>
# Released: 2019
#
# In AR6, we do not separate tropospheric and stratospheric ozone.
#
# Coefficients provided by AerChemMIP models contributing to Thornhill et al. (2021a), and historical time series from Skeie et al. 2020. The forcing dependence on temperature is from Thornhill et al. (2021b)
#
# Use this tuning in FaIRv1.6.2 to run WG1 and WG3 assessment pathways
#
# - Skeie et al. 2020 https://www.nature.com/articles/s41612-020-00131-0
# - Thornhill et al. 2021a https://acp.copernicus.org/preprints/acp-2019-1205/acp-2019-1205.pdf
# - Thornhill et al. 2021b https://acp.copernicus.org/preprints/acp-2019-1207/acp-2019-1207.pdf
# +
import fair
import numpy as np
import pandas as pd
import matplotlib.pyplot as pl
from fair.constants import molwt
from fair.forcing.ozone_tr import stevenson
from scipy.interpolate import interp1d
from scipy.optimize import curve_fit
import copy
from ar6.forcing.ozone import eesc
from ar6.constants.gases import rcmip_to_ghg_names
# -
# ## The historcial forcing time series
#
# Follow Skeie et al., 2020 exclusively for the historical (1850-2010)
#
# Update 18.01.2020: 0.47 1750-2019 - the foot has come down<br>
# Update 20.06.2021: Save split into trop and strat for John Fyfe
good_models = ['BCC-ESM1', 'CESM2(WACCM6)', 'GFDL-ESM4', 'GISS-E2-1-H', 'MRI-ESM2-0', 'OsloCTM3']
skeie_trop = pd.read_csv('../data_input/Skeie_et_al_npj_2020/skeie_ozone_trop.csv', index_col=0)
skeie_trop = skeie_trop.loc[good_models]
skeie_trop.insert(0, 1850, 0)
skeie_trop.columns = pd.to_numeric(skeie_trop.columns)
skeie_trop.interpolate(axis=1, method='values', limit_area='inside', inplace=True)
skeie_trop
skeie_strat = pd.read_csv('../data_input/Skeie_et_al_npj_2020/skeie_ozone_strat.csv', index_col=0)
skeie_strat = skeie_strat.loc[good_models]
skeie_strat.insert(0, 1850, 0)
skeie_strat.columns = pd.to_numeric(skeie_strat.columns)
skeie_strat.interpolate(axis=1, method='values', limit_area='inside', inplace=True)
skeie_strat
skeie_total = skeie_trop + skeie_strat
#skeie_total.drop([2014,2017,2020], inplace=True, axis=1)
skeie_total
skeie_trop_est = skeie_trop.mean()
skeie_trop_est[1750] = -0.03
skeie_trop_est.sort_index(inplace=True)
skeie_trop_est = skeie_trop_est + 0.03
skeie_trop_est.drop([2014,2017,2020], inplace=True)
skeie_trop_est = skeie_trop_est.append(skeie_trop.loc['OsloCTM3',2014:]-skeie_trop.loc['OsloCTM3',2010]+skeie_trop_est[2010])
f = interp1d(skeie_trop_est.index, skeie_trop_est, bounds_error=False, fill_value='extrapolate')
years = np.arange(1750,2021)
o3trop = f(years)
pl.plot(years, o3trop)
print("2014-1750 trop. ozone ERF from Skeie:", o3trop[264])
print("2019-1750 trop. ozone ERF from Skeie:", o3trop[269])
# +
skeie_strat_est = skeie_strat.mean()
skeie_strat_est_min = skeie_strat.min()
skeie_strat_est_max = skeie_strat.max()
skeie_strat_est[1750] = 0.00
skeie_strat_est_min[1750] = 0.00
skeie_strat_est_max[1750] = 0.00
skeie_strat_est.sort_index(inplace=True)
skeie_strat_est_min.sort_index(inplace=True)
skeie_strat_est_max.sort_index(inplace=True)
skeie_strat_est.drop([2014,2017,2020], inplace=True)
skeie_strat_est_min.drop([2014,2017,2020], inplace=True)
skeie_strat_est_max.drop([2014,2017,2020], inplace=True)
years = np.arange(1750,2021)
skeie_strat_est = skeie_strat_est.append(skeie_strat.loc['OsloCTM3',2014:]-skeie_strat.loc['OsloCTM3',2010]+skeie_strat_est[2010])
f = interp1d(skeie_strat_est.index, skeie_strat_est, bounds_error=False, fill_value='extrapolate')
o3strat = f(years)
skeie_strat_est_min = skeie_strat_est_min.append(skeie_strat.loc['OsloCTM3',2014:]-skeie_strat.loc['OsloCTM3',2010]+skeie_strat_est_min[2010])
f = interp1d(skeie_strat_est_min.index, skeie_strat_est_min, bounds_error=False, fill_value='extrapolate')
o3strat_min = f(years)
skeie_strat_est_max = skeie_strat_est_max.append(skeie_strat.loc['OsloCTM3',2014:]-skeie_strat.loc['OsloCTM3',2010]+skeie_strat_est_max[2010])
f = interp1d(skeie_strat_est_max.index, skeie_strat_est_max, bounds_error=False, fill_value='extrapolate')
o3strat_max = f(years)
pl.fill_between(years, o3strat_min, o3strat_max)
pl.plot(years, o3strat, color='k')
print("2014-1750 strat. ozone ERF from Skeie:", o3strat[264])
print("2019-1750 strat. ozone ERF from Skeie:", o3strat[269])
# -
df = pd.DataFrame(
np.array([o3strat_min, o3strat, o3strat_max]).T,
columns=['min','mean','max'],
index=np.arange(1750,2021)
)
df.index.name = 'year'
df.to_csv('../data_output/o3strat_erf.csv')
skeie_ssp245 = skeie_total.mean()
skeie_ssp245[1750] = -0.03
skeie_ssp245.sort_index(inplace=True)
skeie_ssp245 = skeie_ssp245 + 0.03
skeie_ssp245.drop([2014,2017,2020], inplace=True)
skeie_ssp245 = skeie_ssp245.append(skeie_total.loc['OsloCTM3',2014:]-skeie_total.loc['OsloCTM3',2010]+skeie_ssp245[2010])
skeie_ssp245
f = interp1d(skeie_ssp245.index, skeie_ssp245, bounds_error=False, fill_value='extrapolate')
years = np.arange(1750,2021)
o3total = f(years)
pl.plot(years, o3total)
print("2014-1750 ozone ERF from Skeie:", o3total[264])
print("2019-1750 ozone ERF from Skeie:", o3total[269])
df = pd.DataFrame(np.array([o3total, o3trop, o3strat]).T, columns=['o3_erf','o3_trop','o3_strat'], index=np.arange(1750,2021))
df.index.name = 'year'
df.to_csv('../data_output/o3_erf.csv')
# ## Tuning to emissions for projections: NO TEMPERATURE FEEDBACK
# Thornhill et al (2020) contributions to 2014-1850 ozone forcing:
#
# |species | best | unc |
# |---------|-------|--------|
# |CH4 | +0.14 | (0.05) |
# |NOx | +0.20 | (0.11) |
# |CO + VOC | +0.11 | (0.07) |
# |N2O | +0.03 | (0.02) |
# |ODS | -0.11 | (0.10) |
# |Sum | +0.37 | (0.18) |
#
# Uncertainties, in brackets, taken to be 5-95%.
#
# Here we will define ODS as the Velders EESC definition.
# +
emissions = pd.read_csv('../data_input_large/rcmip-emissions-annual-means-v5-1-0.csv')
concentrations = pd.read_csv('../data_input_large/rcmip-concentrations-annual-means-v5-1-0.csv')
scenario = 'ssp245'
ch4 = concentrations.loc[(concentrations['Scenario']==scenario)&(concentrations['Region']=='World')&(concentrations.Variable.str.endswith('|CH4')),'1750':'2020'].values.squeeze()
n2o = concentrations.loc[(concentrations['Scenario']==scenario)&(concentrations['Region']=='World')&(concentrations.Variable.str.endswith('|N2O')),'1750':'2020'].values.squeeze()
ods = {}
ods_species = [
'CCl4',
'CFC11',
'CFC113',
'CFC114',
'CFC115',
'CFC12',
'CH2Cl2',
'CH3Br',
'CH3CCl3',
'CH3Cl',
'CHCl3',
'HCFC141b',
'HCFC142b',
'HCFC22',
'Halon1211',
'Halon1301',
'Halon2402',
]
for specie in ods_species:
ods[specie] = concentrations.loc[(concentrations['Scenario']==scenario)&(concentrations['Region']=='World')&(concentrations.Variable.str.endswith('|%s' % specie)),'1750':'2020'].values.squeeze()
co = emissions.loc[(emissions['Scenario']==scenario)&(emissions['Region']=='World')&(emissions.Variable.str.endswith('|CO')),'1750':'2020'].interpolate(axis=1).values.squeeze()
nox = emissions.loc[(emissions['Scenario']==scenario)&(emissions['Region']=='World')&(emissions.Variable.str.endswith('|NOx')),'1750':'2020'].interpolate(axis=1).values.squeeze()
voc = emissions.loc[(emissions['Scenario']==scenario)&(emissions['Region']=='World')&(emissions.Variable.str.endswith('|VOC')),'1750':'2020'].interpolate(axis=1).values.squeeze()
# -
pl.plot(voc)
nox.shape
eesc_total = np.zeros((271))
for specie in ods_species:
eesc_total = eesc_total + eesc(ods[specie], specie)
pl.plot(np.arange(1750,2021), eesc_total)
delta_Cch4 = ch4[264] - ch4[0]
delta_Cn2o = n2o[264] - n2o[0]
delta_Cods = eesc_total[264] - eesc_total[0]
delta_Eco = co[264] - co[0]
delta_Evoc = voc[264] - voc[0]
delta_Enox = nox[264] - nox[0]
# +
# best estimate radiative efficienices from 2014 - 1850
radeff_ch4 = 0.14/delta_Cch4
radeff_n2o = 0.03/delta_Cn2o
radeff_ods = -0.11/delta_Cods
radeff_co = 0.067/delta_Eco # stevenson rescaled
radeff_voc = 0.043/delta_Evoc # stevenson rescaled
radeff_nox = 0.20/delta_Enox
# -
fac_cmip6_skeie = (
(
radeff_ch4 * delta_Cch4 +
radeff_n2o * delta_Cn2o +
radeff_ods * delta_Cods +
radeff_co * delta_Eco +
radeff_voc * delta_Evoc +
radeff_nox * delta_Enox
) / (o3total[264]-o3total[0])
)
ts = np.vstack((ch4, n2o, eesc_total, co, voc, nox)).T
ts
# +
def fit_precursors(x, rch4, rn2o, rods, rco, rvoc, rnox):
return rch4*x[0] + rn2o*x[1] + rods*x[2] + rco*x[3] + rvoc*x[4] + rnox*x[5]
p, cov = curve_fit(
fit_precursors,
ts[:271,:].T - ts[0:1, :].T,
o3total[:271]-o3total[0],
bounds=(
(
0.09/delta_Cch4/fac_cmip6_skeie,
0.01/delta_Cn2o/fac_cmip6_skeie,
-0.21/delta_Cods/fac_cmip6_skeie,
0.010/delta_Eco/fac_cmip6_skeie,
0/delta_Evoc/fac_cmip6_skeie,
0.09/delta_Enox/fac_cmip6_skeie
), (
0.19/delta_Cch4/fac_cmip6_skeie,
0.05/delta_Cn2o/fac_cmip6_skeie,
-0.01/delta_Cods/fac_cmip6_skeie,
0.124/delta_Eco/fac_cmip6_skeie,
0.086/delta_Evoc/fac_cmip6_skeie,
0.31/delta_Enox/fac_cmip6_skeie
)
)
)
forcing = (
p[0] * (ch4 - ch4[0]) +
p[1] * (n2o - n2o[0]) +
p[2] * (eesc_total - eesc_total[0]) +
p[3] * (co - co[0]) +
p[4] * (voc - voc[0]) +
p[5] * (nox - nox[0])
)
pl.plot(np.arange(1750,2021), forcing)
# -
pl.plot(np.arange(1750,2021), forcing, label='Precursor fit')
pl.plot(np.arange(1750,2021), o3total, label='Skeie et al. 2020 mean')
pl.legend()
print(p) # these coefficients we export to the ERF time series
print(radeff_ch4, radeff_n2o, radeff_ods, radeff_co, radeff_voc, radeff_nox)
# ## Tuning to emissions for projections: INCLUDING TEMPERATURE FEEDBACK
#
# Skeie et al. 2020 analyses CMIP6 historical coupled models, so it should include a temperature feedback on total ozone forcing for all models except Oslo-CTM3.
#
# 1. Get observed 1850-2014 warming from AR6 (use 1850-1900 to 2009-19)
# 2. Calculate temperature-ozone feedback at -0.037 W/m2/K
# 3. Subtract this feedback from all model results except Oslo-CTM3, which was run with fixed-SST, and take average of the forcing
# 4. recalibrate Thornhill coefficients
# 5. grab a beer, you deserve it
xl = pd.read_excel('../data_input/observations/AR6 FGD assessment time series - GMST and GSAT.xlsx', skiprows=1, skipfooter=28)
Tobs=xl['4-set mean'].values
years=xl['Unnamed: 0'].values
pl.plot(years, Tobs)
Tobs[:51].mean() # already normalised to 1850-1900 anyway - from plot above, looks stable
Tobs[161:171].mean() # 2011-2020 mean
# +
delta_gmst = pd.DataFrame(
{
1850: 0,
1920: Tobs[65:76].mean(),
1930: Tobs[75:86].mean(),
1940: Tobs[85:96].mean(),
1950: Tobs[95:106].mean(),
1960: Tobs[105:116].mean(),
1970: Tobs[115:126].mean(),
1980: Tobs[125:136].mean(),
1990: Tobs[135:146].mean(),
2000: Tobs[145:156].mean(),
2007: Tobs[152:163].mean(),
2010: Tobs[155:166].mean(),
2014: Tobs[159:170].mean(),
2017: Tobs[167], # we don't use this
2020: Tobs[168] # or this
}, index=[0])
delta_gmst
delta_gmst=[
0,
Tobs[65:76].mean(),
Tobs[75:86].mean(),
Tobs[85:96].mean(),
Tobs[95:106].mean(),
Tobs[105:116].mean(),
Tobs[115:126].mean(),
Tobs[125:136].mean(),
Tobs[135:146].mean(),
Tobs[145:156].mean(),
Tobs[152:163].mean(),
Tobs[155:166].mean(),
Tobs[159:170].mean(),
Tobs[167], # we don't use this
Tobs[168]
]
delta_gmst
# -
warming_pi_pd = Tobs[159:170].mean()
skeie_trop = pd.read_csv('../data_input/Skeie_et_al_npj_2020/skeie_ozone_trop.csv', index_col=0)
skeie_trop = skeie_trop.loc[good_models]
skeie_trop.insert(0, 1850, 0)
skeie_trop.columns = pd.to_numeric(skeie_trop.columns)
skeie_trop.interpolate(axis=1, method='values', limit_area='inside', inplace=True)
skeie_strat = pd.read_csv('../data_input/Skeie_et_al_npj_2020/skeie_ozone_strat.csv', index_col=0)
skeie_strat = skeie_strat.loc[good_models]
skeie_strat.insert(0, 1850, 0)
skeie_strat.columns = pd.to_numeric(skeie_strat.columns)
skeie_strat.interpolate(axis=1, method='values', limit_area='inside', inplace=True)
skeie_total = skeie_strat + skeie_trop
skeie_total
coupled_models = copy.deepcopy(good_models)
coupled_models.remove('OsloCTM3')
skeie_total.loc[coupled_models] = skeie_total.loc[coupled_models] - (-0.037) * np.array(delta_gmst)
skeie_ssp245 = skeie_total.mean()
skeie_ssp245[1750] = -0.03
skeie_ssp245.sort_index(inplace=True)
skeie_ssp245 = skeie_ssp245 + 0.03
skeie_ssp245.drop([2014,2017,2020], inplace=True)
skeie_ssp245 = skeie_ssp245.append(skeie_total.loc['OsloCTM3',2014:]-skeie_total.loc['OsloCTM3',2010]+skeie_ssp245[2010])
skeie_ssp245 # this is what the ozone forcing would be, in the absence of any feedbacks
f = interp1d(skeie_ssp245.index, skeie_ssp245, bounds_error=False, fill_value='extrapolate')
years = np.arange(1750,2021)
o3total = f(years)
pl.plot(years, o3total)
print("2014-1750 ozone ERF from Skeie:", o3total[264])
print("2019-1750 ozone ERF from Skeie:", o3total[269])
print("2014-1850 ozone ERF from Skeie:", o3total[264] - o3total[100])
# +
# best estimate radiative efficienices from 2014 - 1850
radeff_ch4 = 0.14/delta_Cch4
radeff_n2o = 0.03/delta_Cn2o
radeff_ods = -0.11/delta_Cods
radeff_co = 0.067/delta_Eco # stevenson rescaled
radeff_voc = 0.043/delta_Evoc # stevenson rescaled
radeff_nox = 0.20/delta_Enox
# -
fac_cmip6_skeie = (
(
radeff_ch4 * delta_Cch4 +
radeff_n2o * delta_Cn2o +
radeff_ods * delta_Cods +
radeff_co * delta_Eco +
radeff_voc * delta_Evoc +
radeff_nox * delta_Enox
) / (o3total[264]-o3total[0])
)
ts = np.vstack((ch4, n2o, eesc_total, co, voc, nox)).T
# +
def fit_precursors(x, rch4, rn2o, rods, rco, rvoc, rnox):
return rch4*x[0] + rn2o*x[1] + rods*x[2] + rco*x[3] + rvoc*x[4] + rnox*x[5]
p, cov = curve_fit(
fit_precursors,
ts[:271,:].T - ts[0:1, :].T,
o3total[:271]-o3total[0],
bounds=(
(
0.09/delta_Cch4/fac_cmip6_skeie,
0.01/delta_Cn2o/fac_cmip6_skeie,
-0.21/delta_Cods/fac_cmip6_skeie,
0.010/delta_Eco/fac_cmip6_skeie,
0/delta_Evoc/fac_cmip6_skeie,
0.09/delta_Enox/fac_cmip6_skeie
), (
0.19/delta_Cch4/fac_cmip6_skeie,
0.05/delta_Cn2o/fac_cmip6_skeie,
-0.01/delta_Cods/fac_cmip6_skeie,
0.124/delta_Eco/fac_cmip6_skeie,
0.086/delta_Evoc/fac_cmip6_skeie,
0.31/delta_Enox/fac_cmip6_skeie
)
)
)
forcing = (
p[0] * (ch4 - ch4[0]) +
p[1] * (n2o - n2o[0]) +
p[2] * (eesc_total - eesc_total[0]) +
p[3] * (co - co[0]) +
p[4] * (voc - voc[0]) +
p[5] * (nox - nox[0])
)
pl.plot(np.arange(1750,2021), forcing)
# -
o3_aerchemmip = (
radeff_ch4 * (ch4 - ch4[0]) +
radeff_n2o * (n2o - n2o[0]) +
radeff_ods * (eesc_total - eesc_total[0]) +
radeff_co * (co - co[0]) +
radeff_voc * (voc - voc[0]) +
radeff_nox * (nox - nox[0])
)
# +
delta_Cch4_1850 = ch4[264] - ch4[100]
delta_Cn2o_1850 = n2o[264] - n2o[100]
delta_Cods_1850 = eesc_total[264] - eesc_total[100]
delta_Eco_1850 = co[264] - co[100]
delta_Evoc_1850 = voc[264] - voc[100]
delta_Enox_1850 = nox[264] - nox[100]
radeff_ch4_1850 = 0.14/delta_Cch4_1850
radeff_n2o_1850 = 0.03/delta_Cn2o_1850
radeff_ods_1850 = -0.11/delta_Cods_1850
radeff_co_1850 = 0.067/delta_Eco_1850 # stevenson rescaled
radeff_voc_1850 = 0.043/delta_Evoc_1850 # stevenson rescaled
radeff_nox_1850 = 0.20/delta_Enox_1850
o3_aerchemmip = (
radeff_ch4_1850 * (ch4 - ch4[0]) +
radeff_n2o_1850 * (n2o - n2o[0]) +
radeff_ods_1850 * (eesc_total - eesc_total[0]) +
radeff_co_1850 * (co - co[0]) +
radeff_voc_1850 * (voc - voc[0]) +
radeff_nox_1850 * (nox - nox[0])
)
# -
default_to_skeie = forcing[269]/o3_aerchemmip[269]
default_to_skeie
default_to_skeie*o3_aerchemmip[269]
#o3total[269]
#forcing[269]
# scale everything up to be exactly equal in 2014
#ratio = forcing[170]/(o3total[270]-o3total[100])
ratio=1
print(ratio)
pl.plot(np.arange(1750,2021), forcing/ratio, label='Precursor fit')
pl.plot(np.arange(1750,2021), o3total, label='Skeie et al. 2020 mean')
pl.plot(np.arange(1750,2021), default_to_skeie*o3_aerchemmip, label='Default coefficients')
#pl.xlim(2000,2020)
#pl.ylim(0.4,0.5)
pl.legend()
# ## these are the coefficients to use (first line)
# +
p # these coefficients we export to the ERF time series
#print(radeff_ch4/ratio, radeff_n2o/ratio, radeff_ods/ratio, radeff_co/ratio, radeff_voc/ratio, radeff_nox/ratio)
mean = np.array([default_to_skeie*radeff_ch4_1850, default_to_skeie*radeff_n2o_1850, default_to_skeie*radeff_ods_1850, default_to_skeie*radeff_co_1850, default_to_skeie*radeff_voc_1850, default_to_skeie*radeff_nox_1850])
unc = np.array([47/37*radeff_ch4_1850*5/14, 47/37*radeff_n2o_1850*2/3, 47/37*radeff_ods_1850*10/11, 47/37*radeff_co_1850*57/67, 47/37*radeff_voc_1850*43/43, 47/37*radeff_nox_1850*11/20])
df = pd.DataFrame(data={'mean': mean, 'u90': unc})
df.index = ['CH4','N2O','ODS','CO','VOC','NOx']
df.index.name='species'
df.to_csv('../data_input/tunings/cmip6_ozone_skeie_fits.csv')
df
#pl.savetxt('../data_input/ozone_coeffici')
# -
print(p[0] * (ch4[264] - ch4[100]))
print(p[1] * (n2o[264] - n2o[100]))
print(p[2] * (eesc_total[264] - eesc_total[100]))
print(p[3] * (co[264] - co[100]))
print(p[4] * (voc[264] - voc[100]))
print(p[5] * (nox[264] - nox[100]))
print(radeff_ch4 * (ch4[264] - ch4[100]))
print(radeff_n2o * (n2o[264] - n2o[100]))
print(radeff_ods * (eesc_total[264] - eesc_total[100]))
print(radeff_co * (co[264] - co[100]))
print(radeff_voc * (voc[264] - voc[100]))
print(radeff_nox * (nox[264] - nox[100]))
47/37*radeff_ch4_1850, 47/37*radeff_n2o_1850, 47/37*radeff_ods_1850, 47/37*radeff_co_1850, 47/37*radeff_voc_1850, 47/37*radeff_nox_1850
47/37*radeff_ch4_1850*5/14, 47/37*radeff_n2o_1850*2/3, 47/37*radeff_ods_1850*10/11, 47/37*radeff_co_1850*57/67, 47/37*radeff_voc_1850*43/43, 47/37*radeff_nox_1850*11/20
| notebooks/070_chapter7_ozone_emissions_to_forcing.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import numpy as np
import matplotlib as mpl
#mpl.use('pdf')
import matplotlib.pyplot as plt
import numpy as np
plt.rc('font', family='serif', serif='Times')
plt.rc('text', usetex=True)
plt.rc('xtick', labelsize=6)
plt.rc('ytick', labelsize=6)
plt.rc('axes', labelsize=6)
#axes.linewidth : 0.5
plt.rc('axes', linewidth=0.5)
#ytick.major.width : 0.5
plt.rc('ytick.major', width=0.5)
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
plt.rc('ytick.minor', visible=True)
#plt.style.use(r"..\..\styles\infocom.mplstyle") # Insert your save location here
# width as measured in inkscape
fig_width = 3.487
#height = width / 1.618 / 2
fig_height = fig_width / 1.3 / 2
# -
cc_folder_list = ["SF_new_results/", "capacity_results/", "BF_new_results/"]
nc_folder_list = ["SF_new_results_NC/", "capacity_resultsNC/", "BF_new_results_NC/"]
cc_folder_list = ["failure20stages-new-rounding-capacity/" + e for e in cc_folder_list]
nc_folder_list = ["failure20stages-new-rounding-capacity/" + e for e in nc_folder_list]
file_list = ["no-reconfig120.csv", "Link-reconfig120.csv", "LimitedReconfig120.csv", "Any-reconfig120.csv"]
print(cc_folder_list)
print(nc_folder_list)
nc_objective_data = np.full((5, 3), 0)
max_stage = 20
selected_stage = 10
for i in range(3):
for j in range(4):
with open(nc_folder_list[i]+file_list[j], "r") as f:
if j != 2:
f1 = f.readlines()
start_line = 0
for line in f1:
if line.find("%Stage") >= 0:
break
else:
start_line = start_line + 1
#print(start_line)
#print(len(f1))
line = f1[selected_stage+start_line]
line = line.split(",")
if j == 0:
nc_objective_data[0, i] = float(line[2])
if j == 1:
nc_objective_data[1, i] = float(line[2])
if j == 3:
nc_objective_data[4, i] = float(line[2])
else:
f1 = f.readlines()
start_line = 0
start_line1 = 0
for line in f1:
if line.find("%Stage") >= 0:
break
else:
start_line = start_line + 1
for index in range(start_line+max_stage+1, len(f1)):
if f1[index].find("%Stage") >= 0:
start_line1 = index
break
else:
start_line1 = start_line1 + 1
line = f1[selected_stage+start_line]
line = line.split(",")
nc_objective_data[2, i] = float(line[2])
#mesh3data[2, index] = int(line[1])
line = f1[selected_stage+start_line1]
line = line.split(",")
nc_objective_data[3, i] = float(line[2])
print(nc_objective_data)
cc_objective_data = np.full((5, 3), 0)
max_stage = 20
selected_stage = 10
for i in range(1):
for j in range(4):
with open(cc_folder_list[i]+file_list[j], "r") as f:
if j != 2:
f1 = f.readlines()
start_line = 0
for line in f1:
if line.find("%Stage") >= 0:
break
else:
start_line = start_line + 1
#print(start_line)
#print(len(f1))
line = f1[selected_stage+start_line]
line = line.split(",")
if j == 0:
cc_objective_data[0, i] = float(line[2])
if j == 1:
cc_objective_data[1, i] = float(line[2])
if j == 3:
cc_objective_data[4, i] = float(line[2])
else:
f1 = f.readlines()
start_line = 0
start_line1 = 0
for line in f1:
if line.find("%Stage") >= 0:
break
else:
start_line = start_line + 1
for index in range(start_line+max_stage+1, len(f1)):
if f1[index].find("%Stage") >= 0:
print(f1[index])
start_line1 = index
break
else:
start_line1 = start_line1 + 1
line = f1[selected_stage+start_line]
line = line.split(",")
cc_objective_data[2, i] = float(line[2])
#mesh3data[2, index] = int(line[1])
line = f1[selected_stage+start_line1]
line = line.split(",")
cc_objective_data[3, i] = float(line[2])
print(cc_objective_data)
max_stage = 20
selected_stage = 10
for i in range(1, 3):
for j in range(4):
with open(cc_folder_list[i]+file_list[j], "r") as f:
if j != 2:
f1 = f.readlines()
start_line = 0
for line in f1:
if line.find("%Stage") >= 0:
break
else:
start_line = start_line + 1
#print(start_line)
#print(len(f1))
line = f1[selected_stage+start_line]
line = line.split(",")
if j == 0:
cc_objective_data[0, i] = float(line[2])
if j == 1:
cc_objective_data[1, i] = float(line[2])
if j == 3:
cc_objective_data[4, i] = float(line[2])
else:
f1 = f.readlines()
start_line = 0
start_line1 = 0
for line in f1:
if line.find("%Stage") >= 0:
break
else:
start_line = start_line + 1
for index in range(start_line+max_stage+1, len(f1)):
if f1[index].find("%Stage") >= 0:
start_line1 = index
break
else:
start_line1 = start_line1 + 1
line = f1[selected_stage+start_line]
line = line.split(",")
cc_objective_data[2, i] = float(line[2])
#mesh3data[2, index] = int(line[1])
line = f1[selected_stage+start_line1]
line = line.split(",")
cc_objective_data[3, i] = float(line[2])
print(cc_objective_data)
print((cc_objective_data-nc_objective_data)/nc_objective_data)
# +
import numpy as np
N = 3
ind = np.arange(N)
width = 1 / 6
x = [0, '20', '30', '40']
x_tick_label_list = ['20', '30', '40']
fig, (ax1, ax2) = plt.subplots(1, 2)
#ax1.bar(x, objective)
#ax1.bar(x, objective[0])
label_list = ['No-rec', 'Link-rec', 'Lim-rec(3, 0)', 'Lim-rec(3, 1)', 'Any-rec']
patterns = ('//////','\\\\\\','---', 'ooo', 'xxx', '\\', '\\\\','++', '*', 'O', '.')
plt.rcParams['hatch.linewidth'] = 0.25 # previous pdf hatch linewidth
#plt.rcParams['hatch.linewidth'] = 1.0 # previous svg hatch linewidth
#plt.rcParams['hatch.color'] = 'r'
for i in range(5):
ax1.bar(ind + width * (i-2), nc_objective_data[i], width, label=label_list[i],
#alpha=0.7)
hatch=patterns[i], alpha=0.7)
#yerr=error[i], ecolor='black', capsize=1)
ax1.grid(lw = 0.25)
ax2.grid(lw = 0.25)
ax1.set_xticklabels(x)
ax1.set_ylabel('Objective value for NC')
ax1.set_xlabel('Percentage of substrate failures (\%)')
#ax1.set_ylabel('Objective value')
#ax1.set_xlabel('Recovery Scenarios')
ax1.xaxis.set_label_coords(0.5,-0.17)
ax1.yaxis.set_label_coords(-0.17,0.5)
#ax1.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
# ncol=3, fancybox=True, shadow=True, fontsize='small')
for i in range(5):
ax2.bar(ind + width * (i-2), cc_objective_data[i], width, label=label_list[i],
#alpha=0.7)
hatch=patterns[i], alpha=0.7)
ax2.set_xticklabels(x)
ax2.set_ylabel('Objective value for CC')
ax2.set_xlabel('Percentage of substrate failures (\%)')
ax2.xaxis.set_label_coords(0.5,-0.17)
ax2.yaxis.set_label_coords(-0.17,0.5)
ax1.legend(loc='upper center', bbox_to_anchor=(1.16, 1.2),
ncol=5, prop={'size': 5})
fig.set_size_inches(fig_width, fig_height)
mpl.pyplot.subplots_adjust(wspace = 0.3)
fig.subplots_adjust(left=.10, bottom=.20, right=.97, top=.85)
#ax1.grid(color='b', ls = '-.', lw = 0.25)
plt.show()
fig.savefig('test-heuristic-failure-cc-nc.pdf')
| python-plot/slice-restoration/compare-heuristic-failure-nc-cc-capacity.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Let's figure out these freaking learning rates
# %load_ext autoreload
# %autoreload 2
import re, os
import numpy as np
import xarray as xr
import tensorflow.keras as keras
import datetime
import pdb
import matplotlib.pyplot as plt
from src.utils import *
from src.score import *
from src.data_generator import *
from src.networks import *
from src.train import *
from src.clr import LRFinder, OneCycleLR
import matplotlib.ticker as ticker
os.environ["CUDA_VISIBLE_DEVICES"]=str(0)
limit_mem()
policy = mixed_precision.Policy('mixed_float16')
mixed_precision.set_policy(policy)
# +
class RunLRFind():
def __init__(self, exp_id, train_years=['2014', '2015'],
ext_exp_id='81-resnet_d3_dr_0.1'):
self.train_years = train_years
self.args = load_args(f'../nn_configs/B/{exp_id}.yml')
self.ext_exp_id = ext_exp_id
self.load_data()
self.build_model()
def build_model(self):
args = self.args
dg_train = self.dg_train
if args['network_type'] == 'resnet':
model = build_resnet(
**args, input_shape=dg_train.shape,
)
elif args['network_type'] == 'uresnet':
model = build_uresnet(
**args, input_shape=dg_train.shape,
)
if args['loss'] == 'lat_mse':
loss = create_lat_mse(dg_train.data.lat)
if args['loss'] == 'lat_rmse':
loss = create_lat_rmse(dg_train.data.lat)
if args['optimizer'] == 'adam':
opt = keras.optimizers.Adam(args['lr'])
elif args['optimizer'] =='adadelta':
opt = keras.optimizers.Adadelta(args['lr'])
elif args['optimizer'] =='sgd':
opt = keras.optimizers.SGD(args['lr'], momentum=args['momentum'], nesterov=True)
elif optimizer == 'rmsprop':
opt = keras.optimizers.RMSprop(lr, momentum=momentum)
model.compile(opt, loss, metrics=['mse'])
self.model = model
def load_data(self):
if self.ext_exp_id is None:
self.args['train_years'] = self.train_years
dg_train, dg_valid, dg_test = load_data(**self.args)
self.dg_train, self.dg_valid = dg_train, dg_test
else:
mean = xr.open_dataarray(f"{self.args['model_save_dir']}/{self.ext_exp_id}_mean.nc")
std = xr.open_dataarray(f"{self.args['model_save_dir']}/{self.ext_exp_id}_std.nc")
self.args['ext_mean'] = mean
self.args['ext_std'] = std
dg_test = load_data(**self.args, only_test=True)
self.dg_train = dg_test
def find_lr(self, minimum_lr=1e-6, maximum_lr=1e-3, lr_scale='exp'):
self.lrf = LRFinder(
self.dg_train.n_samples, self.dg_train.batch_size,
minimum_lr=minimum_lr, maximum_lr=maximum_lr,
lr_scale=lr_scale, save_dir='./', verbose=0,
validation_data=self.dg_valid if self.ext_exp_id is None else None,
stopping_criterion_factor=100
)
self.model.fit(self.dg_train, epochs=1, callbacks=[self.lrf])
return self.lrf
def plot(self, xlim=None, ylim=None, log=False):
fig, ax = plt.subplots(figsize=(8, 8))
plt.plot(10**self.lrf.lrs, self.lrf.losses)
plt.xlabel('lr'); plt.ylabel('loss')
if log: plt.yscale('log')
if ylim is not None: plt.ylim(ylim)
if xlim is not None: plt.xlim(xlim)
x_labels = ax.get_xticks()
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.0e'))
def plot_lrfs(lrfs, xlim=None, ylim=None, log=False, labels=None, smooth = False):
fig, ax = plt.subplots(figsize=(15, 8))
for i, lrf in enumerate(lrfs):
lrs = lrf.lrs
if lrf.lr_scale == 'exp': lrs = 10** lrs
losses = lrf.losses
if smooth: losses = np.convolve(losses, np.ones(5)/5, 'same')
ax.plot(lrs, losses, label=labels[i] if not labels is None else None)
plt.xlabel('lr'); plt.ylabel('loss')
if log: plt.yscale('log')
if ylim is not None: plt.ylim(ylim)
if xlim is not None: plt.xlim(xlim)
x_labels = ax.get_xticks()
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.0e'))
if labels is not None: plt.legend()
# -
lrf = RunLRFind('81-resnet_d3_dr_0.1')
lrfs[0].use_validation_set
lrfs = []
lrf.build_model()
lrfs.append(lrf.find_lr(lr_scale='exp', minimum_lr=1e-5, maximum_lr=1e-1))
lrf.dg_train.lead_time = 6
lrf.build_model(); lrf.dg_train.on_epoch_end()
lrfs.append(lrf.find_lr(lr_scale='exp', minimum_lr=1e-5, maximum_lr=1e-1))
lrf.dg_train.lead_time = 120
lrf.build_model(); lrf.dg_train.on_epoch_end()
lrfs.append(lrf.find_lr(lr_scale='exp', minimum_lr=1e-5, maximum_lr=1e-1))
plot_lrfs(lrfs, log=True, ylim=(1e-1, 100), labels = ['72', '6', '120'])
plt.axvline(5e-5)
lrf.dg_train.lead_time = 6
lrf.args['loss'] = 'lat_rmse'
lrf.build_model(); lrf.dg_train.on_epoch_end()
lrfs.append(lrf.find_lr(lr_scale='exp', minimum_lr=1e-5, maximum_lr=1e-1))
lrf.dg_train.lead_time = 72
lrf.args['loss'] = 'lat_rmse'
lrf.build_model(); lrf.dg_train.on_epoch_end()
lrfs.append(lrf.find_lr(lr_scale='exp', minimum_lr=1e-5, maximum_lr=1e-1))
lrf.dg_train.lead_time = 120
lrf.args['loss'] = 'lat_rmse'
lrf.build_model(); lrf.dg_train.on_epoch_end()
lrfs.append(lrf.find_lr(lr_scale='exp', minimum_lr=1e-5, maximum_lr=1e-1))
plot_lrfs(lrfs[:3], log=False, ylim=(5e-1, 500), labels = ['72', '6', '120', '6_rmse', '72_rmse', '120_rmse'], xlim=(0, 5e-2), smooth=True)
plt.axvline(2e-5)
plt.xscale('log'); plt.xlim(1e-5, 1e-1)
plot_lrfs(lrfs[3:], log=True, ylim=(5e-1, 20), labels = ['72', '6', '120', '6_rmse', '72_rmse', '120_rmse'][3:], xlim=(0, 5e-2), smooth=True)
plt.axvline(5e-5)
lrf.dg_train.lead_time = 72
lrf.args['loss'] = 'lat_mse'
lrf.args['optimizer'] = 'sgd'
lrf.args['momentum'] = 0.9
lrf.build_model(); lrf.dg_train.on_epoch_end()
lrfs.append(lrf.find_lr(lr_scale='exp', minimum_lr=1e-5, maximum_lr=1e-1))
lrf.dg_train.lead_time = 72
lrf.args['loss'] = 'lat_mse'
lrf.args['optimizer'] = 'rmsprop'
lrf.args['momentum'] = 0.9
lrf.build_model(); lrf.dg_train.on_epoch_end()
lrfs.append(lrf.find_lr(lr_scale='exp', minimum_lr=1e-5, maximum_lr=1e-1))
lrf.dg_train.lead_time = 72
lrf.args['optimizer'] = 'adam'
lrf.build_model(); lrf.dg_train.on_epoch_end()
lrfs.append(lrf.find_lr(lr_scale='linear', minimum_lr=1e-5, maximum_lr=5e-3))
plot_lrfs(lrfs[-1:], log=False, ylim=(5e-1, 100), xlim=(0, 5e-3), smooth=False)
plt.axvline(5e-5)
plot_lrfs(lrfs[:1], log=True, ylim=(5e-1, 100), xlim=(0, 5e-3), smooth=True)
plot_losses('/home/rasp/data/myWeatherBench/predictions/saved_models/',
[81, 99, 101], log=False, ylim=(0.01, 0.3)
)
max_lr=2e-5
??OneCycleLR
one_cycle = OneCycleLR(max_lr,
end_percentage=0.1, verbose=0)
# +
NUM_SAMPLES = 2000
NUM_EPOCHS = 100
BATCH_SIZE = 500
MAX_LR = 0.1
# Data
X = np.random.rand(NUM_SAMPLES, 10)
Y = np.random.randint(0, 2, size=NUM_SAMPLES)
# Model
inp = Input(shape=(10,))
x = Dense(5, activation='relu')(inp)
x = Dense(1, activation='sigmoid')(x)
model = keras.models.Model(inp, x)
# -
optimizer = keras.optimizers.SGD()
optimizer.
model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
model.optimizer
# +
model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X, Y, batch_size=BATCH_SIZE, epochs=NUM_EPOCHS, callbacks=[one_cycle], verbose=0)
# -
plt.plot(one_cycle.history['lr'])
plot_losses('/home/rasp/data/myWeatherBench/predictions/saved_models/',
['81.1', 103], log=False, ylim=(0.005, 0.02)
)
| devlog/23-lrs_again.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
# ---
# # FTE/BTE Experiment for DTD
#
# The progressive learning package utilizes representation ensembling algorithms to sequentially learn a representation for each task and ensemble both old and new representations for all future decisions.
#
# Here, a representation ensembling algorithm based on decision forests (Odif) and an algorithm based on neural networks (Odin) demonstrate forward and backward knowledge transfer of tasks on the Describable Textures Dataset (DTD). The original dataset can be found at https://www.robots.ox.ac.uk/~vgg/data/dtd/.
#
# ### Import necessary packages and modules
# +
import numpy as np
import os
import matplotlib.pyplot as plt
from multiprocessing import Pool
import seaborn as sns
from matplotlib import rcParams
rcParams.update({"figure.autolayout": True})
# -
# ### Experimental Set-up
#
# DTD has 47 classes of food with 120 images each. For the purposes of this experiment, only 40 of those classes are used. The dataset is split into 10 tasks with 4 classes each.
#
# Each class is then split into 4 batches of 30 images each. Every time the experiment is repeated, the batch used as the test set is shifted.
#
# The remaining 90 images in each class are used for training each task.
#
# With 4 batches of test sets and 1 batch of training sets, the number of permutations comes out to 4, so the final errors are averaged across 4 trials and then used to calculate FTE and BTE
# ### DTD Data Generation
#
# DTD was downloaded and preprocessed (images were padded and resized) by running the algorithms found in https://github.com/neurodata/LLF_tidy_images. This sectipn of the notebook serves to take those processed images and convert them into numpy arrays that can be read and used by the progressive learning algorithms.
# Load data set
data_dir = "../../../datasets_resized_wLabels/dtd/images" # replace with the path name for wherever the downloaded dtd images have been stored
textures_sorted = sorted(os.listdir(data_dir))
# Start reading the image data into numpy arrays. Only the first 40 out of the 47 sorted texture classes will be used in order to make it easier to split up the samples into tasks later on.
#
# This process of initializing each x data array with some images and then concatenating to get the next batch of 1200 images is repeated 4 times, resulting in 4 numpy arrays each containing all the images from 10 of the dtd classes.
dict_x = {}
for k in range(4):
# Initialize data_x* with the first image in the first class, then concatenate to acquire all images from the first class
texture_class = os.listdir(os.path.join(data_dir, textures_sorted[10 * k]))
data_xk = [
plt.imread(os.path.join(data_dir, textures_sorted[10 * k], texture_class[0]))
]
for i in range(1, 120):
data_xk = np.concatenate(
[
data_xk,
[
(
plt.imread(
os.path.join(
data_dir, textures_sorted[10 * k], texture_class[i]
)
)
)
],
]
)
# Add to the initialized data_x* array until it contains all images from the 10 classes
# Concatenating more than 1200 images per batch increases the run time by a lot
for j in range(((k * 10) + 1), (10 * (k + 1))):
texture_class = os.listdir(os.path.join(data_dir, textures_sorted[j]))
for i in range(0, 120):
data_xk = np.concatenate(
[
data_xk,
[
(
plt.imread(
os.path.join(
data_dir, textures_sorted[j], texture_class[i]
)
)
)
],
]
)
dict_x["data_x" + str(k + 1)] = data_xk
# Combine individual numpy arrays for x data for each batch of 10 classes all into one big numpy array
data_x = np.concatenate([dict_x["data_x1"], dict_x["data_x2"], dict_x["data_x3"]])
data_x = np.concatenate([data_x, dict_x["data_x4"]])
# Create y data containing 40 class labels
data_y = np.full((120), 0, dtype=int)
for i in range(1, 40):
data_y = np.concatenate([data_y, np.full((120), i, dtype=int)])
# ### Train the model and perform validation
#
# `which_task`: The task number for which BTE should be calculated
#
# #### run_parallel_exp:
# Wrapper method for the `run_bte_exp` function which declares and trains the model, and performs validation with respect to the test data to compute the error of the model at a particular iteration
# Choose algorithm (odif or odin)
model = "odin"
# +
from functions.fte_bte_dtd_functions import run_fte_bte_exp
fte = []
bte = []
te = []
accuracies = []
for which_task in range(1, 11):
def run_parallel_exp(shift):
df_list = run_fte_bte_exp(data_x, data_y, which_task, model, shift=shift)
return df_list
shifts = np.arange(0, 4, 1) # Number of test set batches
acc = []
for shift in shifts:
acc.append(run_parallel_exp(shift))
# Average forward transfer accuracies accross all permutations of testing and training batches for each task
acc_x = []
acc_y = []
acc_z = []
for z in range(which_task):
for y in range(1):
for x in range(4):
if model == "odin":
acc_x.append(acc[x][y]["task_accuracy"][z])
elif model == "odif":
acc_x.append(acc[0][x][y]["task_accuracy"][z])
acc_y.append(np.mean(acc_x))
acc_x = []
acc_z.append(np.mean(acc_y))
acc_y = []
# Calculate and store FTE
fte.append((1 - acc_z[0]) / (1 - acc_z[-1]))
# Average backward transfer accuracies accross all permutations of testing and training batches for each task
acc_x = []
acc_y = []
acc_z = []
for z in range((which_task - 1), 10):
for y in range(1):
for x in range(4):
if model == "odin":
acc_x.append(acc[x][y]["task_accuracy"][z])
elif model == "odif":
acc_x.append(acc[0][x][y]["task_accuracy"][z])
acc_y.append(np.mean(acc_x))
acc_x = []
acc_z.append(np.mean(acc_y))
acc_y = []
# Calculate and store accuracies, BTE, and TE
accuracies.append(acc_z)
calc_bte = (1 - acc_z[0]) / ([1 - a for a in acc_z])
bte.append(calc_bte)
te.append([fte[(which_task - 1)] * a for a in calc_bte])
# -
# ### Calculating FTE, BTE, TE, and Accuracy
#
# The forward transfer efficiency of $f$ for task $t$ given $n$ samples is
# $$FTE_n^t (f) := \mathbb{E} [R^t (f(D_n^{t}) )] / \mathbb{E} [R^t (f(D_n^{<t}))]$$
#
# We say an algorithm achieves forward transfer for task $t$ if and only if $FTE_n^t(f) > 1$. Intuitively, this means that the progressive learner has used data associated with past tasks to improve performance on task $t$.
#
# The backward transfer efficiency of $f$ for task $t$ given $n$ samples is
# $$BTE_n^t (f) := \mathbb{E} [R^t (f(D_n^{<t}) )] / \mathbb{E} [R^t (f(D_n))]$$
#
# We say an algorithm achieves backward transfer for task $t$ if and only if $BTE_n^t(f) > 1$. Intuitively, this means that the progressive learner has used data associated with new tasks to improve performance on previous tasks.
#
# The transfer efficiency of $f$ for task $t$ given $n$ samples is
# $$TE_n^t (f) := \mathbb{E} [R^t (f(D_n^{t}) )] / \mathbb{E} [R^t (f(D_n))]$$
#
# We say an algorithm has transfer learned for task $t$ with data $D_n$ if and only if $TE_n^t(f) > 1$.
# ### Plotting FTE, BTE, TE, and Accuracy
# Run cell to generate a figure containing 4 plots of the forward transfer efficiency, backward transfer efficiency, transfer efficiency, and accuracy of the Odif/Odin algorithms.
# +
sns.set(style="ticks")
sns.despine
n_tasks = 10
# clr = ["#e41a1c", "#a65628", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00", "#CCCC00"]
# c = sns.color_palette(clr, n_colors=len(clr))
if model == "odin":
c = "blue"
elif model == "odif":
c = "red"
fontsize = 28
ticksize = 23
# Plot FTE
fig, ax = plt.subplots(2, 2, figsize=(16, 11.5))
# fig.suptitle('ntrees = '+str(ntrees),fontsize=25)
ax[0][0].plot(np.arange(1, n_tasks + 1), fte, c, marker="v", markersize=12, linewidth=3)
ax[0][0].hlines(1, 1, n_tasks, colors="grey", linestyles="dashed", linewidth=1.5)
ax[0][0].tick_params(labelsize=ticksize)
ax[0][0].set_xlabel("Number of tasks seen", fontsize=fontsize)
ax[0][0].set_ylabel("log Forward TE", fontsize=fontsize)
right_side = ax[0][0].spines["right"]
right_side.set_visible(False)
top_side = ax[0][0].spines["top"]
top_side.set_visible(False)
# Plot BTE
for i in range(n_tasks):
et = np.asarray(bte[i])
ns = np.arange(i + 1, n_tasks + 1)
ax[0][1].plot(ns, et, c, linewidth=2.6)
ax[0][1].set_xlabel("Number of tasks seen", fontsize=fontsize)
ax[0][1].set_ylabel("log Backward TE", fontsize=fontsize)
# ax[0][1].set_xticks(np.arange(1,10))
ax[0][1].tick_params(labelsize=ticksize)
ax[0][1].hlines(1, 1, n_tasks, colors="grey", linestyles="dashed", linewidth=1.5)
right_side = ax[0][1].spines["right"]
right_side.set_visible(False)
top_side = ax[0][1].spines["top"]
top_side.set_visible(False)
# Plot TE
for i in range(n_tasks):
et = np.asarray(te[i])
ns = np.arange(i + 1, n_tasks + 1)
ax[1][0].plot(ns, et, c, linewidth=2.6)
ax[1][0].set_xlabel("Number of tasks seen", fontsize=fontsize)
ax[1][0].set_ylabel("log TE", fontsize=fontsize)
# ax[1][0].set_xticks(np.arange(1,10))
ax[1][0].tick_params(labelsize=ticksize)
ax[1][0].hlines(1, 1, n_tasks, colors="grey", linestyles="dashed", linewidth=1.5)
right_side = ax[1][0].spines["right"]
right_side.set_visible(False)
top_side = ax[1][0].spines["top"]
top_side.set_visible(False)
# Plot accuracy
for i in range(n_tasks):
acc_p = np.asarray(accuracies[i])
ns = np.arange(i + 1, n_tasks + 1)
ax[1][1].plot(ns, acc_p, c, linewidth=2.6)
# ax[1][1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=22)
ax[1][1].set_xlabel("Number of tasks seen", fontsize=fontsize)
ax[1][1].set_ylabel("Accuracy", fontsize=fontsize)
ax[1][1].tick_params(labelsize=ticksize)
right_side = ax[1][1].spines["right"]
right_side.set_visible(False)
top_side = ax[1][1].spines["top"]
top_side.set_visible(False)
fig = plt.gcf()
fig.canvas.draw()
# Update fig to make into log-scale
labels = [float(item.get_text()) for item in ax[0][0].get_yticklabels()]
log_lbl = np.round(np.log(labels), 2)
ax[0][0].set_yticklabels(log_lbl)
labels = [float(item.get_text()) for item in ax[0][1].get_yticklabels()]
log_lbl = np.round(np.log(labels), 2)
ax[0][1].set_yticklabels(log_lbl)
labels = [float(item.get_text()) for item in ax[1][0].get_yticklabels()]
log_lbl = np.round(np.log(labels), 2)
ax[1][0].set_yticklabels(log_lbl)
| docs/experiments/fte_bte_dtd.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
# language: python
# name: python37464bitfbfa7aceeafb4dfc937102a23a64f667
# ---
# Install package
# %pip install --upgrade portfoliotools
from portfoliotools.screener.stock_screener import StockScreener
from portfoliotools.screener.utility.util import get_ticker_list, getHistoricStockPrices, get_nse_index_list, get_port_ret_vol_sr
from portfoliotools.screener.stock_screener import PortfolioStrategy, ADF_Reg_Model
from tqdm import tqdm
import pandas as pd
import numpy as np
import seaborn as sns
import plotly.graph_objects as go
import matplotlib.pyplot as plt
from IPython.display import display_html
from pandas.plotting import register_matplotlib_converters
from plotly.subplots import make_subplots
from datetime import datetime
import warnings
warnings.filterwarnings("ignore")
register_matplotlib_converters()
# %matplotlib inline
sns.set()
pd.options.display.max_columns = None
pd.options.display.max_rows = None
# ### <font color = 'red'>USER INPUT</font>
# +
tickers = get_ticker_list()
asset_list = [ticker['Ticker'] for ticker in tickers]
#asset_list.remove("GAIL")
#asset_list = ['ICICIBANK', 'HDFC', 'HDFCBANK', 'INFY', 'RELIANCE', 'ASIANPAINT', 'TCS', 'MARUTI', 'TATAMOTORS', 'CIPLA']
#asset_list = ['DMART', 'BAJFINANCE', 'KOTAKBANK', 'BAJAJFINSV','TCS', 'PIDILITIND', 'HDFCBANK', 'SUPREMEIND', 'NAUKRI', 'ASIANPAINT', 'HDFC', 'MARUTI', 'SHREECEM', 'RELIANCE', 'DIVISLAB', 'ICICIBANK', 'BHARTIARTL',
# 'WABCOINDIA', 'VGUARD', 'CUMMINSIND']
cob = None #datetime(2020,2,1) # COB Date
# -
tickers
# ### <font color = 'blue'>Portfolio Strategy Tools</font>
strat = PortfolioStrategy(asset_list, period = 1000, cob = cob)
# #### Correlation Matrix
fig = strat.plot_correlation_matrix()
fig.show()
# #### Correlated Stocks
corr_pair = strat.get_correlation_pair()
print("Highly Correlated:")
display_html(corr_pair[corr_pair['Correlation'] > .95])
print("\nInversely Correlated:")
display_html(corr_pair[corr_pair['Correlation'] < -.90])
# #### <font color = 'black'>Efficient Frontier</font>
market_portfolio = strat.get_efficient_market_portfolio(plot = True, num_ports = 500, show_frontier =True) #plot =True to plot Frontier
# #### Market Portfolio
market_portfolio = market_portfolio.T
market_portfolio = market_portfolio[market_portfolio['MP'] != 0.00]
plt.pie(market_portfolio.iloc[:-3,0], labels=market_portfolio.index.tolist()[:-3])
market_portfolio
# **Ticker Performance**
strat.calcStat(format_result = True)
| jupyter notebooks/Analysis/Stocks/.ipynb_checkpoints/Portfolio Analysis-checkpoint 4.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
# ---
# # Create ScMags Object
#
# Creating the ScMags object is very simple.\
# Data matrix and labels are mandatory gene names are optional.
# * In the data matrix, rows must correspond to cells, columns must correspond to genes, and must be in one of three formats: `numpy.ndarry`, `scipy.sparse.csr_matrix`, or `scipy.sparse.csc_matrix`.
#
# * Labels and gene names should be in numpy.ndarray format
# An example for the pollen dataset\
# In any location in the folder named pollen the data matrix get the labels and gene names.
# + language="bash"
# ls Pollen
# -
# Let's read the data and convert it to numpy.ndarray format
# +
import pandas as pd
pollen_data = pd.read_csv('Pollen/Pollen_Data.csv',sep=',', header = 0, index_col = 0).to_numpy().T
pollen_labels = pd.read_csv('Pollen/Pollen_Labels.csv', sep=',', header = 0, index_col = 0).to_numpy()
gene_names = pd.read_csv('Pollen/Pollen_Gene_Ann.csv', sep=',', header = 0, index_col = 0).to_numpy()
pollen_labels = pollen_labels.reshape(pollen_data.shape[0])
gene_names = gene_names.reshape(pollen_data.shape[1])
# -
# * Sizes of data labels and gene names must match.
# * In addition, labels and gene names must be a one-dimensional array.
print(pollen_data.shape)
print(type(pollen_data))
print(pollen_labels.shape)
print(type(pollen_labels))
print(pollen_data.shape)
print(type(pollen_labels))
# Now let's create the `ScMags` object
import scmags as sm
pollen = sm.ScMags(data=pollen_data, labels=pollen_labels, gene_ann=gene_names)
# Then the desired operations can be performed.
pollen.filter_genes()
pollen.sel_clust_marker()
pollen.get_markers()
# * If gene names are not given, they are created from indexes inside.
pollen = sm.ScMags(data=pollen_data, labels=pollen_labels)
pollen.filter_genes()
pollen.sel_clust_marker()
pollen.get_markers()
# * These names are actually indices of genes in the data matrix.
pollen.get_markers(ind_return=True)
# Data matrix can be in sparse matrix other than `numpy.ndarray` For example:
from scipy import sparse
pollen_data = sparse.csr_matrix(pollen_data)
print(pollen_data.shape)
print(type(pollen_data))
pollen_data
pollen = sm.ScMags(data=pollen_data, labels=pollen_labels, gene_ann=gene_names)
pollen.filter_genes()
pollen.sel_clust_marker()
pollen.get_markers()
| docs/source/cr_scmags.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
# ---
# # FMRI Analysis
#
# In this notebook, we analyze the incongruent-congruent MSIT contrast in the fMRI. To do so we use a standard analysis approach of first fitting an individual GLM to each subject (first levels) and then performing group statistics on these individual subject maps. This is done separately for the left and right cortical surfaces as well as the subcortical volume in a standardized fsaverage space to facilitate comparison across subjects. The goal with this analysis is to spatially localize areas of the brain that are differentially involved in incongruent compared to congruent trials in the MSIT task.
# # First Levels
#
# First levels involves fitting a GLM and computing incongruent-congruent contrast maps for each subject invidually. These maps are then passed to group level statistics. This two step process serves as a computationally feasible approximation to a hierarchical model.
#
# The first level GLM is fit individually for every voxel for each subject. We use a separate regressor for incongruent and congruent trials as well as multiple nuisance regressors. The incongruent and congruent regressors are convolved with a canonical hemodynamic response function (SPM no derivatives) in order to account for the delayed shape of the BOLD response. Additionally, the GLM is corrected for auto-correlated residuals due to the fact that the BOLD response from a previous trial sustains through the presentation of the next trial.
# ## Make Task Paradigm Files
#
# Here I make regressors for the congruent and incongruent conditions. I make both full duration boxcar regressors and variable RT epoch regressors to look at RT independent and dependent effects. Methods and considerations based on the following papers:
#
# - <NAME>'s Blog Post on time on task implications: https://www.talyarkoni.org/blog/2010/06/16/time-on-task-effects-in-fmri-research-why-you-should-care/
# - Yarkoni paper related to above blog post: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2622763/
# - Grinbad Paper explaining variable RT epoch method as most ideal method for accounting for time on task effects: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2654219/
#
# It is especially important to control for RT effects in this task because there is such a large difference in response time between the two conditions. Controlling for RT removes regions of different amplitude where the difference was simply due to longer BOLD accumulation due to the increased response times. See the above references for more information.
# +
import sys
sys.path.append('../src')
from utils import select_subjects
import pandas as pd
# load and clean behavior
behavior = pd.read_csv('../data/derivatives/behavior/group_data.tsv',
sep='\t', na_values='n/a')
behavior = behavior[behavior.modality == 'fmri']
exclusions = ['error', 'post_error', 'no_response', 'fast_rt']
behavior = behavior[behavior[exclusions].sum(axis=1) == 0]
# output directory
fsfast_path = '../data/derivatives/fsfast'
subjects = select_subjects('both')
for subject in subjects:
sub_behavior = behavior[behavior.participant_id == subject]
sub_behavior['tt'] = sub_behavior.trial_type.astype('category').cat.codes + 1
sub_behavior['weight'] = 1.0
# extract behavior information
for typ in ['base', 'rt']:
if typ == 'base':
columns = ['onset', 'tt', 'duration', 'weight', 'trial_type']
else:
columns = ['onset', 'tt', 'response_time', 'weight', 'trial_type']
df = sub_behavior[columns]
# save the regressors
f = '%s/%s/msit/001/%s.par'
df.to_csv(f % (fsfast_path, subject, typ), header=False, sep='\t',
index=False)
print('Done!')
# -
# ## Make Motion Timepoint Censors
#
# Controlling for motion is important to ensure that our results are not biased by motion artifacts. We use only functional displacement based motion timepoint censoring (and no motion regressors) as determined in <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3895106/"> Siegel 2013</a>. We use their threshold of 0.9 mm though we recognize this was not a global recommendation, but it is used here as a reasonable value without further investigation.
# +
import sys
sys.path.append('../src')
from utils import select_subjects
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# %matplotlib inline
fd = 0.9
fmriprep_path = '../data/derivatives/fmriprep'
fsfast_path = '../data/derivatives/fsfast'
subjects = select_subjects('both')
fds = []
for i, subject in enumerate(subjects):
f = '%s/%s/func/%s_task-msit_bold_confounds.tsv'
confounds = pd.read_csv(f % (fmriprep_path, subject, subject),
sep='\t', na_values='n/a')
# determine fd censor indices
fd_ix = np.array(confounds.FramewiseDisplacement >= fd).astype(int)
fds.append(fd_ix)
# save censor indices
f = '%s/%s/msit/001/fd_censor.par'
np.savetxt(f % (fsfast_path, subject), fd_ix, fmt='%d')
# Plot censor heatmap
fds = np.array(fds)
plt.figure(figsize=(14, 10))
sns.heatmap(fds, cbar=False)
plt.xticks(())
plt.yticks(np.arange(len(subjects)) + .5, subjects, rotation=0)
plt.xlabel('TR')
plt.ylabel('Subject')
plt.show()
# -
# ## Run 1st Levels
#
# The following cells actually run the first level GLMs. To do so, we make use of Freesurfer's <a href="https://surfer.nmr.mgh.harvard.edu/fswiki/FsFast">fsfast fMRI analysis package</a>.
#
# ### Set up the analysis
#
# This cell configures the analysis. It does many things including determining the space to do the analysis in, the form of the hemodynamic response kernel that will be convolved with the design matrix, and what additional nuiscance regressors to add to the design matrix.
# + language="bash"
#
# # Source freesurfer v6
# export FREESURFER_HOME=/usr/local/freesurfer/stable6_0_0
# . /usr/local/freesurfer/stable6_0_0/SetUpFreeSurfer.sh
# export SUBJECTS_DIR=/autofs/space/cassia_001/users/matt/msit/data/derivatives/freesurfer
#
# # get into fsfast directory
# export FSFAST=../data/derivatives/fsfast
# cd $FSFAST
#
# # set up the analyses
# types="base rt"
# hemis="lh rh"
# fwhm=4
#
# for type in $types
# do
# for hemi in $hemis
# do
# mkanalysis-sess -analysis $type.$hemi \
# -surface fsaverage $hemi \
# -event-related \
# -fsd msit \
# -fwhm $fwhm \
# -per-run \
# -TR 1.75 \
# -refeventdur 1.75 \
# -paradigm $type.par \
# -nconditions 2 \
# -spmhrf 0 \
# -polyfit 0 \
# -hpf 0.01 \
# -nskip 4 \
# -tpexclude fd_censor.par \
# -no-mask \
# -force
# done
#
# mkanalysis-sess -analysis $type.mni305 \
# -mni305 \
# -event-related \
# -fsd msit \
# -fwhm $fwhm \
# -per-run \
# -TR 1.75 \
# -refeventdur 1.75 \
# -paradigm $type.par \
# -nconditions 2 \
# -spmhrf 0 \
# -polyfit 0 \
# -hpf 0.01 \
# -nskip 4 \
# -tpexclude fd_censor.par \
# -force
# done
# -
# ### Compute Contrast Matrices
#
# This cell pre-computes the incongruent-congruent contrast matrices that we will use to get the contrast estimate from the GLM.
# + language="bash"
#
# # Source freesurfer v6
# export FREESURFER_HOME=/usr/local/freesurfer/stable6_0_0
# . /usr/local/freesurfer/stable6_0_0/SetUpFreeSurfer.sh
# export SUBJECTS_DIR=/autofs/space/cassia_001/users/matt/msit/data/derivatives/freesurfer
#
# # get into fsfast directory
# export FSFAST=../data/derivatives/fsfast
# cd $FSFAST
#
# types="base rt"
# spaces="lh rh mni305"
#
# for type in $types
# do
# for space in $spaces
# do
# mkcontrast-sess -analysis $type.$space \
# -contrast incongruent \
# -a 2
#
# mkcontrast-sess -analysis $type.$space \
# -contrast congruent \
# -a 1
#
# mkcontrast-sess -analysis $type.$space\
# -contrast incongruent-congruent \
# -a 2 -c 1
#
# done
#
# done
# -
# ### Fit the GLMs
#
# This cell actually fits the GLM for each subject.
# + language="bash"
#
# # Source freesurfer v6
# export FREESURFER_HOME=/usr/local/freesurfer/stable6_0_0
# . /usr/local/freesurfer/stable6_0_0/SetUpFreeSurfer.sh
# export SUBJECTS_DIR=/autofs/space/cassia_001/users/matt/msit/data/derivatives/freesurfer
#
# # get into fsfast directory
# export FSFAST=../data/derivatives/fsfast
# cd $FSFAST
#
# # set up the analyses
# types="base rt"
# spaces="lh rh mni305"
#
# for type in $types
# do
# for space in $spaces
# do
# selxavg3-sess -analysis $type.$space -sf subjects -no-preproc \
# -overwrite
# done
#
# done
# -
# ### Visualize the Design Matrices
#
# This cell produces a summary plot of each subject's design matrix. The design matrix only gets saved out after the GLM fit command which is why we visualize after fitting.
#
# Our design matrix consists of the following regressors:
# - incongruent and congruent response times convolved with the BOLD HRF function
# - two highpass filter nuisance regressors to account for scanner drift and other low frequency artifacts
# - four censor nuisance regressors to exclude the first 4 acquisitions to account for the scanner settling
# - any additional motion nuisance censor regressors that exceed the 0.9 mm threshold
#
# This cell produces a separate plot for both the RT-controlled and non-RT-controlled design matrix including:
# - a heatmap of the design matrix
# - plots of the incongruent and congruent response times convolved with the HRF kernel
# - Plots of the highpass filter nuiscance regressors to account for scanner drift and other low frequency artifacts
# - A barplot of the variance inflation factor (VIF) scores for each regressor. The VIF is a measure of the collinearity of a regressor with the other regressors. We want these scores to prevent issues with fitting the GLM.
# +
import sys
sys.path.append('../src')
from utils import select_subjects
from fmri import plot_design_matrix
import matplotlib.pyplot as plt
fsfast_path = '../data/derivatives/fsfast'
subjects = select_subjects('both')
for subject in subjects:
for typ in ['base', 'rt']:
fig = plot_design_matrix(fsfast_path, subject, typ)
f = '%s/%s/msit/%s_design_matrix.png'
fig.savefig(f % (fsfast_path, subject, typ))
plt.close(fig)
print('Done!')
# -
# ## Visualize 1st Level Results
#
# The following cell will create significance maps for the first level incongruent-congruent contrast maps for each subject.
# +
from surfer import Brain
import sys
sys.path.append('../src')
from utils import select_subjects
fsfast_path = '../data/derivatives/fsfast'
SUBJECTS_DIR = '/autofs/space/cassia_001/users/matt/msit/data/derivatives/freesurfer'
subjects = select_subjects('both')
for subject in subjects:
for typ in ['base', 'rt']:
# plot sig
brain = Brain('fsaverage', 'split', 'inflated', views=['lat', 'med'],
subjects_dir=SUBJECTS_DIR)
for hemi in ['lh', 'rh']:
f = '%s/%s/msit/%s.%s/incongruent-congruent/sig.nii.gz' % (fsfast_path, subject,
typ, hemi)
brain.add_overlay(f, hemi=hemi, min=1.3, max=5)
f = '%s/%s/msit/%s_sig.png' % (fsfast_path, subject, typ)
brain.save_image(f)
print('Done!')
# -
# # Group Levels
#
# The next stage is to find spatial clusters where there is a significant difference between the incongruent and congruent conditions across subjects. To do so, we compute a GLM over the first level contrast maps from each subject.
# ## Collect Data & Compute Connectivity
#
# This is a convenience cell that collects all of the needed data for the statistics into a single file. This includes:
# - fMRI first levels maps: We collect the incongruent - congruent contrast effect sizes from each subject for each voxel to get a # subjects x # voxels data array (Y).
# - Design matrix: We are simply interested in whether the contrast estimates are different from 0. This could be done with a simple t-test. However, our subjects were collected across multiple different scanners so we include this as a nuisance regressor (technically regressors using one hot encoding). This gives us a # subjects x 3 array (X, 3 = intercept + 2 scanner type nuisance regressors).
# - Weight matrix: We collect the inverse contrast effect variances to be used as weights for a weighted GLM. This gives us a # subjects x # voxels array (W)
# - Permuted sign flips: We pre-compute the sign flip permutations (sign flipping is equivalent to permuting the incongruent and congruent labels in random subsets of the subjects). This provides a # permutations x # subjects matrix
# - Connectivity matrix: A sparse matrix containing the connected vertices and voxels for the given space.
# - Include: A boolean mask denoting which voxels had non-zero variance across subjects
#
# These all get saved in a compressed numpy file separately for each space and design type.
# +
import sys
sys.path.append('../src')
from utils import select_subjects
from fmri import compute_connectivity
import numpy as np
import nibabel as nib
import os
import pandas as pd
deriv_dir = '../data/derivatives/fmri_group_levels'
if not os.path.exists(deriv_dir):
os.makedirs(deriv_dir)
with open('experiment_config.json', 'r') as fid:
config = json.load(fid)
typs = config['fmri_types']
spaces = config['fmri_spaces']
np.random.seed(10)
subjects = select_subjects('both')
fsfast_dir = '../data/derivatives/fsfast'
subjects_dir = '../data/derivatives/freesurfer'
# create scanner type nuisance regressors
demo = pd.read_csv('../data/participants.tsv', sep='\t', na_values='n/a')
demo = demo[demo.participant_id.isin(subjects)]
sc = demo.scanner.astype('category').cat.codes
Z = np.array(pd.get_dummies(sc))[:, 1:]
# compute the subcortical mask
tmp = config['subcort_roi']
roi_dict = dict()
for key in tmp:
roi_dict[int(key)] = tmp[key]
aseg = '%s/fsaverage/mri.2mm/aseg.mgz' % subjects_dir
aseg = nib.load(aseg).get_data()
subcort_mask = np.in1d(aseg, roi_dict.keys()).reshape(aseg.shape)
voxels = np.vstack(np.where(subcort_mask)).T
print(voxels.shape)
for typ in typs:
print(typ)
for space in spaces:
print(space)
# compute connectivity
coo = compute_connectivity(space, subjects_dir, voxels)
# load data + weights
Ws = []
Ys = []
for subject in subjects:
analysis_folder = '%s/%s/msit/%s.%s/incongruent-congruent'
analysis_folder = analysis_folder % (fsfast_dir, subject,
typ, space)
f = '%s/ces.nii.gz' % analysis_folder
Ys.append(nib.load(f).get_data())
f = '%s/cesvar.nii.gz' % analysis_folder
Ws.append(nib.load(f).get_data())
# weights = inverse variance
W = np.array(Ws).squeeze()
W = np.abs(1 / W)
Y = np.array(Ys).squeeze()
# 1d the subcortical data and reduce to rois
if space == 'mni305':
W = W[:, subcort_mask]
Y = Y[:, subcort_mask]
# only include voxels that had non-zero variance for every subject
include = ~np.isinf(W).sum(axis=0).astype(bool)
# compute sign flips
sign_flips = np.random.choice([1, -1],
size=(config['num_fmri_perm'],
Y.shape[0]),
replace=True)
np.savez_compressed('%s/%s_%s_data.npz' % (deriv_dir, typ, space),
Y=Y, W=W, Z=Z, sign_flips=sign_flips,
include=include, conn=coo.data, col=coo.col,
shape=coo.shape, row=coo.row,
subcort_mask=subcort_mask, voxel_ix=voxels)
print('Done!')
# -
# ## Compute TFCE Permutation P-Values
#
# Here we actually compute the group statistics. We use a relatively new and robust technique known as <a href="https://www.ncbi.nlm.nih.gov/pubmed/18501637"> threshold free cluster enhancement (TFCE)</a>. TFCE is an improvement over spatial cluster permutation testing. It works by first scaling the image to enhance spatially contiguous clusters. One then does their permutations using this TFCE enhanced map rather than the original. So the algorithm becomes:
#
# 1. Compute the WLS F-statistic for the intercept testing whether the contrast effect is different from 0 separately for each voxel/vertex
# 2. TFCE enhance the F-statistic map
# 3. Permute the data. In our case, since we are looking at a simple within subjects two condition contrast, this is equivalent to doing sign flips on random subsets of the subject's contrast effect size estimates. We also ensure to <a href="https://www.sciencedirect.com/science/article/pii/S1053811914000913"> control for nuisance regressors by sign flipping just the residuals after the nuisance regressors estimates have been subtracted out</a>.
# 4. Compute the WLS F-statistic and TFCE enhance the permuted data. Select out the maximum TFCE value across all voxels to correct for the vast number of tests across voxels.
# 5. Repeat 3 and 4 1000 times to build a permutation null distribution.
# 6. Compute the p-value at each voxel as the fraction of permuted max TFCE values whose absolute magnitude are larger than the TFCE value at each voxel in the unpermuted data.
# +
import sys
sys.path.append('../src')
from fmri import wls
import nibabel as nib
import os
os.environ['OMP_NUM_THREADS'] = '1'
import numpy as np
import pandas as pd
from mne.stats.cluster_level import _find_clusters
import statsmodels.api as sm
from mne import set_log_level
from joblib import Parallel, delayed
from scipy.sparse import coo_matrix
import json
set_log_level('critical')
def perm_tfce_glm(i):
"""
Computes and returns the maximum threshold free cluster enhanced
fmap value for a randomly permuted sample of the data. Serves as a
wrapper for joblib parallelize by making use of other globally defined
variables in the cell.
Parameters
----------
i: int
The permutation index
Returns
-------
float
The maximum tfce f value for the given permutation
"""
print(i)
sf = sign_flips[i, :]
fs = []
for j in range(Y.shape[1]):
if include[j]:
Z = X[:, 1:]
w = np.diag(W[:, j])
# permute only the residuals
y = Y[:, j][:, np.newaxis]
ZZ = Z.dot(np.linalg.inv(Z.T.dot(w).dot(Z))).dot(Z.T).dot(w)
Rz = np.identity(Y.shape[0]) - ZZ
y_perm = np.diag(sf).dot(Rz).dot(y)
# compute wls f-statistic
beta, f = wls(X, y_perm, w)
fs.append(f[0])
else:
fs.append(0)
fs = np.array(fs)
# compute tfce
_, tfce = _find_clusters(fs, threshold, tail=0,
connectivity=coo, include=include,
max_step=1, show_info=False)
return np.max(np.abs(tfce))
with open('experiment_config.json', 'r') as fid:
config = json.load(fid)
typs = config['fmri_types']
spaces = config['fmri_spaces']
deriv_dir = '../data/derivatives/fmri_group_levels'
subjects_dir = '../data/derivatives/freesurfer/fsaverage'
np.random.seed(10)
for typ in typs:
print(typ)
for space in spaces:
print(space)
# extract data
data = np.load('%s/%s_%s_data.npz' % (deriv_dir, typ, space))
Z = data['Z']
X = np.hstack((np.ones((Z.shape[0], 1)), Z))
W = data['W']
Y = data['Y']
sign_flips = data['sign_flips']
include = data['include']
num_perm = sign_flips.shape[0]
# extract connectivity
coo = coo_matrix((data['conn'], (data['row'], data['col'])),
data['shape'])
# compute the un-permuted fmap
betas = []
fs = []
for i in range(Y.shape[1]):
if include[i]:
beta, f = wls(X, Y[:, i][:, np.newaxis],
np.diag(W[:, i]))
fs.append(f[0])
betas.append(beta[0])
else:
fs.append(0)
betas.append(0)
betas = np.array(betas)
fs = np.array(fs)
# threshold fre cluster enhance the un-permuted fmap
_, tfce = _find_clusters(fs, threshold, tail=0,
connectivity=coo, include=include,
max_step=1, show_info=False)
# compute permuted tfce maps in parallel
perm_dist = Parallel(n_jobs=10)(delayed(perm_tfce_glm)(i)
for i in range(num_perm))
perm_dist = np.array(perm_dist)
# compute the permutation p-values
tmp = np.tile(perm_dist[:, np.newaxis], (1, tfce.shape[0]))
p = (np.sum(np.abs(tmp) >= np.abs(tfce),
axis=0) + 1.) / (num_perm + 1.)
np.savez_compressed('%s/%s_%s_stats.npz' % (deriv_dir, typ, space),
pvals=p, perm_dist=perm_dist, beta=betas,
fmap=fs, tfce=tfce, include=include)
print('Done!')
# -
# ## Screen Clusters & Save Maps
#
# In this cell, we take the computed p-values and effect sizes and convert them into nifti brain maps that can then be visualized. Additionally we screen out spurious clusters that are smaller than pre-defined cluster sizes (100 mm^2 for the surface data and 20 voxels for the subcortical areas).
# +
import nibabel as nib
import numpy as np
import json
from mne.stats.cluster_level import _find_clusters as find_clusters
from mne import read_surface, spatial_tris_connectivity
from scipy.sparse import coo_matrix
deriv_dir = '../data/derivatives/fmri_group_levels'
fsfast_dir = '../data/derivatives/fsfast'
subjects_dir = '../data/derivatives/freesurfer'
np.random.seed(10)
with open('experiment_config.json', 'r') as fid:
config = json.load(fid)
typs = config['fmri_types']
spaces = config['fmri_spaces']
for typ in typs:
print(typ)
for space in spaces:
print(space)
stats = np.load('%s/%s_%s_stats.npz' % (deriv_dir, typ, space))
stats = {'pvals': stats['pvals'],
'tfce': stats['tfce'],
'beta': stats['beta'],
'include': stats['include'],
'perm_dist': stats['perm_dist']}
# log transform and sign the p-values
stats['pvals'] = -np.log10(stats['pvals']) * np.sign(stats['beta'])
stats['tfce'] = stats['tfce'] * np.sign(stats['beta'])
# load connectivity
data = np.load('%s/%s_%s_data.npz' % (deriv_dir, typ, space))
coo = coo_matrix((data['conn'], (data['row'], data['col'])),
data['shape'])
# extract clusters
threshold = -np.log10(0.05)
clusters, sums = find_clusters(stats['pvals'].squeeze(), threshold,
tail=0, connectivity=coo,
include=stats['include'],
t_power=0)
# compute mm cluster size for cortical surface
if space != 'mni305':
f = '%s/fsaverage/surf/%s.white.avg.area.mgh'
avg_area = nib.load(f % (subjects_dir, space)).get_data().squeeze()
sums = np.array([avg_area[c].sum() for c in clusters])
# threshold clusters by size
stats['mask'] = np.zeros_like(stats['pvals'])
min_cluster = {'lh': 100, 'rh': 100, 'mni305': 20}
good_ix = []
new_clusters = []
new_sums = []
for c, s in zip(clusters, sums):
if s > min_cluster[space]:
new_clusters.append(c)
new_sums.append(s)
good_ix.append(c)
print('%d clusters found' % len(good_ix))
if len(good_ix) > 0:
good_ix = np.concatenate(good_ix)
stats['mask'][good_ix] = 1
# reshape and save maps
for mapp in ['pvals', 'beta', 'tfce']:
stats[mapp] *= stats['mask']
if space == 'mni305':
aseg = '%s/fsaverage/mri.2mm/aseg.mgz' % subjects_dir
aseg = nib.load(aseg)
affine = aseg.affine
voxel_ix = data['voxel_ix']
mapp_data = np.zeros(aseg.get_data().shape)
x, y, z = voxel_ix[:, 0], voxel_ix[:, 1], voxel_ix[:, 2]
mapp_data[x, y, z] += stats[mapp].astype(float)
else:
f = '%s/sub-hc005/msit/%s.%s/incongruent-congruent/ces.nii.gz'
holder = nib.load(f % (fsfast_dir, typ, space))
affine = holder.affine
mapp_data = stats[mapp].astype(float)
# extend to full range
for i in range(4 - len(mapp_data.shape)):
mapp_data = np.expand_dims(mapp_data, -1)
img = nib.Nifti1Image(mapp_data, affine)
nib.save(img, '%s/%s_%s_%s.nii' % (deriv_dir, typ, space, mapp))
# save out clusters + cluster mask
np.savez_compressed('%s/%s_%s_clusters.npz' % (deriv_dir, typ, space),
clusters=new_clusters, sums=new_sums,
cluster_ix=good_ix)
print('Done!')
# -
# ## Visualize Results
# ### Cortical Results
#
# We use <a href="https://pysurfer.github.io/"> pysurfer</a> to visualize the results on the cortical surface. The cell below will plot the effect size estimates and the significance values (-log10(p-values)) on the inflated cortical surface for each hemisphere. They are thresholded at a p < .05 value.
# +
from surfer import Brain
import json
subjects_dir = '../data/derivatives/freesurfer'
deriv_dir = '../data/derivatives/fmri_group_levels'
with open('experiment_config.json', 'r') as fid:
config = json.load(fid)
typs = config['fmri_types']
spaces = config['fmri_spaces']
for typ in typs:
for space in spaces[:2]:
for mapp in ['pvals', 'beta']:
brain = Brain('fsaverage', space, surf,
subjects_dir=subjects_dir, views=['lat', 'med'])
if mapp == 'pvals':
mi = -np.log10(.05)
ma = 3 * mi
else:
mi, ma = 0.0001, 0.5
overlay = '%s/%s_%s_%s.nii' % (deriv_dir, typ, space, mapp)
brain.add_overlay(overlay, min=mi, max=ma)
brain.save_image('%s/%s_%s_%s.png' % (deriv_dir, typ,
space, mapp))
# -
# ### Subcortical Results
#
# The following bash cell uses freesurfer to load the subcortical maps over the fsaverage MRI in freeview.
# + language="bash"
#
# # Source freesurfer v6
# export FREESURFER_HOME=/usr/local/freesurfer/stable6_0_0
# . /usr/local/freesurfer/stable6_0_0/SetUpFreeSurfer.sh
# export SUBJECTS_DIR=/autofs/space/cassia_001/users/matt/msit/data/derivatives/freesurfer
#
# # base or rt
# typ=rt
# # beta or pvals
# map=pvals
#
# cd ../data/derivatives/fmri_group_levels
#
# tkmeditfv fsaverage orig.mgz -aseg -overlay ${typ}_mni305_${map}.nii
# -
# # Summary of Results
#
# ## Cortical
#
# We generally see consistent results with the <a href="https://www.nature.com/articles/nprot.2006.48"> original MSIT validation paper</a>. This includes the dACC (only left hemisphere), the DLPFC, VLPFC, and Superior Parietal. Additionally, we also see incredibly robust and widespread visual/parietal cortex activation.
#
# Two major trends stand out as well:
# - We see much more activation in the left hemsiphere
# - The RT-controlled activation is as widespread, if not more so, than the non-RT controlled activation. This is very counterinuitive and a bit of a cause for concern (see issues section below).
#
# ## Sub-Cortical
#
# We don't see any significant clusters... I am not sure if this is due to issues with the approach or just a facet of MSIT. My concerns about the global TFCE approach below may be relevant here as well.
#
# ## Concerns
#
# 1. The RT-controlled activation should be more restricted than the non-RT controlled activation. Seeing almost the opposite is alarming and suggests that something is not quite right.
# 2. The size and magnitude of the visual activation may be disrupting TFCE. TFCE is sensitive to the cluster size. This large visual cluster could be swamping out the smaller clusters. In fact, it looks as if all of our regions are often being lumped into a single connected cluster which allows them to survive (they get extra magnified in the TFCE due to the size of this cluster). This could also explain why the RT-control doesn't actually reduce the activation very much. Two options for alleviating this could be to split TFCE up into separate larger ROI's. One could also try starting the enhancement at a higher level to prevent bridging. This may just drown out the frontal regions however.
# 3. No subcortical activation. Not sure if this is due to a design flaw or reasonable.
#
# I would hesitate to interpret these results further without investigating and alleviating the concerns above. Encouragingly, we do see the expected regions showing up on the cortex, which suggests the core statistical approach is likely right. The TFCE process may just need appropriate tweaking.
#
# ## Potential Future Directions
#
# - Correct the TFCE method or figure out a more appropriate ROI approach.
# - Look at correlations with different RT model parameters (drift rate, decision boundary, etc.)
# - Use fmri spatial localization to seed EEG source space analyses and compare with source space EEG.
# - See if fmri spatial cluster activation predicts psychiatric dysfunction or questionnaires related to the task (cognitive flexibility, impulsivity).
| notebooks/F2-fmri_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
# ---
# +
# learn the states of a double dot
import numpy as np
import tensorflow as tf
import glob
import os
from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
tf.logging.set_verbosity(tf.logging.INFO)
# application logic will be added here
def cnn_model_fn(features,labels,mode):
'''Model function for CNN'''
#input layer
input_layer = tf.cast(tf.reshape(features,[-1,100,100,1]),tf.float32)
# Concolutional layer1
conv1 = tf.layers.conv2d(
inputs=input_layer,
filters=32,
kernel_size=[10,10],
padding="same",
activation=tf.nn.relu)
# Pooling layer1
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=[5,5],strides=5)
# Dense layer
pool2_flat = tf.contrib.layers.flatten(pool1)
dense0 = tf.layers.dense(inputs=pool2_flat,units=512,activation=tf.nn.relu)
dropout0 = tf.layers.dropout(inputs=dense0,rate=0.5,training=mode == learn.ModeKeys.TRAIN)
dense1 = tf.layers.dense(inputs=dropout0,units=256,activation=tf.nn.relu)
dropout1 = tf.layers.dropout(inputs=dense1,rate=0.5,training=mode == learn.ModeKeys.TRAIN)
dense2 = tf.layers.dense(inputs=dropout1,units=128,activation=tf.nn.relu)
dropout2 = tf.layers.dropout(inputs=dense2,rate=0.5,training=mode == learn.ModeKeys.TRAIN)
# encode layer
encode = tf.layers.dense(inputs=dropout2,units=8)
# dense output layer
out_layer = tf.layers.dense(inputs=encode,units=10000)
loss = None
train_op = None
# Calculate loss( for both TRAIN AND EVAL modes)
if mode != learn.ModeKeys.INFER:
loss = tf.losses.mean_squared_error(labels=labels, predictions=out_layer)
# Configure the training op (for TRAIN mode)
if mode == learn.ModeKeys.TRAIN:
train_op = tf.contrib.layers.optimize_loss(
loss=loss,
global_step=tf.contrib.framework.get_global_step(),
learning_rate=0.01,
optimizer="Adam")
# Generate predictions
predictions= {
"states" : tf.rint(out_layer),
}
# Returna ModelFnOps object
return model_fn_lib.ModelFnOps(mode=mode,predictions=predictions,loss=loss, train_op=train_op)
def get_train_inputs():
n_batch = 50
index = np.random.choice(np.arange(train_data.shape[0]),n_batch,replace=False)
x = tf.constant(train_data[index])
y = tf.constant(train_labels[index])
return x,y
def get_test_inputs():
x = tf.constant(test_data)
y = tf.constant(test_labels)
return x,y
# get the data
data_files = glob.glob(os.path.expanduser('~/dataproc/*100*.npy'))
inp = []
oup = []
for file in data_files:
data_dict = np.load(file).item()
inp += [data_dict['current_map']]
oup += [data_dict['state_map'].flatten()]
inp = np.array(inp)
oup = np.array(oup)
n_samples = inp.shape[0]
train_sample_ratio = 0.9
n_train = int(train_sample_ratio * n_samples)
print("Total number of samples :",n_samples)
print("Training samples :",n_train)
print("Test samples :",n_samples - n_train)
train_data = inp[:n_train]
train_labels = oup[:n_train]
test_data = inp[n_train:]
test_labels = oup[n_train:]
# create the estimator
dd_classifier = learn.Estimator(model_fn=cnn_model_fn)
# set up logging for predictions
tensors_to_log = {}
logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=100)
metrics = {
"accuracy" : learn.MetricSpec(metric_fn=tf.metrics.accuracy, prediction_key="states"),
}
for _ in range(1):
dd_classifier.fit(
input_fn=get_train_inputs,
steps=1000,
monitors=[logging_hook])
eval_results=dd_classifier.evaluate(input_fn=get_train_inputs,metrics=metrics,steps=1)
print("Train accuracy",eval_results)
eval_results=dd_classifier.evaluate(input_fn=get_test_inputs,metrics=metrics,steps=1)
print("Validation accuracy",eval_results)
print("Total number of samples :",n_samples)
print("Training samples :",n_train)
print("Test samples :",n_samples - n_train)
eval_results=dd_classifier.evaluate(input_fn=get_test_inputs,metrics=metrics,steps=1)
print("Test accuracy",eval_results)
# -
res_list = []
for i,p in enumerate(predictions):
res_list += [p['states'].reshape((100,100))]
import matplotlib.pyplot as plt
# %matplotlib inline
plt.subplot(2,1,1)
plt.pcolor(res_list[0])
plt.subplot(2,1,2)
plt.pcolor(test_labels[0].reshape((100,100)))
res_list
predictions = dd_classifier.predict(x=test_data)
sub_image = np.zeros((100,100))
sub_image[50:90,50:90] = test_data[23][20:60,20:60]
sub_image_res = dd_classifier.predict(x=sub_image)
sub_res_list = []
for i,p in enumerate(sub_image_res):
sub_res_list += [p['states'].reshape((100,100))]
plt.pcolor(sub_res_list[0][50:90,50:90])
plt.pcolor(test_labels[23].reshape((100,100))[20:60,20:60])
diff = test_labels[23].reshape((100,100))[20:60,20:60] - sub_res_list[0][20:60,20:60]
np.sum(np.abs(diff))/1600
# +
# animation
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
import matplotlib.animation as animation
plt.rcParams['animation.ffmpeg_path'] ='/usr/local/bin/ffmpeg'
# %matplotlib
fig, ax = plt.subplots(1,2)
XX,YY = np.meshgrid(np.linspace(50e-3,500e-3,100),np.linspace(50e-3,500e-3,100))
def fixed_aspect_ratio(ax,ratio):
'''
Set a fixed aspect ratio on matplotlib plots
regardless of axis units
'''
xvals,yvals = ax.axes.get_xlim(),ax.axes.get_ylim()
xrange = xvals[1]-xvals[0]
yrange = yvals[1]-yvals[0]
ax.set_aspect(ratio*(xrange/yrange), adjustable='box')
def animate(i):
my_cmap = mpl.colors.ListedColormap([[0., .4, 1.], [0., .8, 1.],
[1., .8, 0.], [1., .4, 0.]])
line = ax[0].pcolor(XX,YY,predictions_list[i][0],vmin=-1,vmax=2,cmap = my_cmap,alpha=0.9)
fixed_aspect_ratio(ax[0],1.0)
ax[0].set_title(r'Predicted $n_{iter} = $' + str(i*500))
return line,
# Init only required for blitting to give a clean slate.
def init():
my_cmap = mpl.colors.ListedColormap([[0., .4, 1.], [0., .8, 1.],
[1., .8, 0.], [1., .4, 0.]])
line = ax[0].pcolor(XX,YY,predictions_list[0][0],vmin=-1,vmax=2,cmap = my_cmap,alpha=0.9)
fixed_aspect_ratio(ax[0],1.0)
cbar_0 = plt.colorbar(line,ax=ax[0],cmap=my_cmap,ticks=[-1,0,1,2],fraction=0.046, pad=0.04)
cbar_0.set_ticklabels(["SC","QPC","1Dot","2Dot"])
cbar_0.set_ticks([-0.5,0.5,1.5,2.5])
ax[0].set_xlabel(r'$V_{d1} (V)$',fontsize=12)
ax[0].set_ylabel(r'$V_{d2} (V)$',fontsize=12)
ax[0].set_title(r'Expected $n_{iter} = $' + str(0))
ax[0].set_title('Predicted')
line2 = ax[1].pcolor(XX,YY,test_labels[0].reshape((100,100)),vmin=-1,vmax=2,cmap = my_cmap,alpha=0.9)
fixed_aspect_ratio(ax[1],1.0)
cbar_1 = plt.colorbar(line2,ax=ax[1],cmap=my_cmap,ticks=[-1,0,1,2],fraction=0.046, pad=0.04)
cbar_1.set_ticklabels(["SC","QPC","1Dot","2Dot"])
cbar_1.set_ticks([-0.5,0.5,1.5,2.5])
ax[1].set_xlabel(r'$V_{d1} (V)$',fontsize=12)
ax[1].set_ylabel(r'$V_{d2} (V)$',fontsize=12)
ax[1].set_title('Expected')
plt.tight_layout()
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(100) , init_func=init,
interval=500, blit=True)
mywriter = animation.FFMpegWriter()
ani.save('dd_learning.mp4',writer=mywriter)
plt.show()
# -
test_labels[0]
predictions_list[0][18]
| machine_learning/cnn/image_learning.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# ---
# # Part 16 of Recipes: Automating Heatmaps
#
# This page is primarily based on the following page at the Circos documentation site:
#
#
#
# - [16. Automating Heatmaps](????????????)
#
#
#
# That page is found as part number 4 of the ??? part ['Recipes' section](http://circos.ca/documentation/tutorials/quick_start/) of [the larger set of Circos tutorials](http://circos.ca/documentation/tutorials/).
#
#
#
# Go back to Part 15 by clicking [here ←](Recipes_Part16.ipynb).
#
#
#
# ----
#
#
#
# 8 --- Recipes
# =============
#
# 16. Automating Heatmaps
# -----------------------
#
# ::: {#menu4}
# [[Lesson](/documentation/tutorials/recipes/automating_heatmaps/lesson){.clean}]{.active}
# [Images](/documentation/tutorials/recipes/automating_heatmaps/images){.normal}
# [Configuration](/documentation/tutorials/recipes/automating_heatmaps/configuration){.normal}
# :::
#
# Before reading this tutorial, make sure that you understand how dynamic
# configuration parameters work (see [Configuration Files
# Tutorial](/documentation/tutorials/configuration/configuration_files/))
# and have read through the [Automating Tracks
# Tutorial](/documentation/tutorials/recipes/automating_tracks/).
#
# For this tutorial, I have created an image with 100 heat map tracks. The
# data for these tracks are gene densities computed across differently
# sized windows (0.5-50 Mb). The higest resolution file is
# `data/8/17/genes.0.txt` which samples density every 500kb. The lowest
# resolution file is `data/8/17/genes.99.txt` which samples density every
# 50,000kb (1/100th resolution of `genes.0.txt`).
#
# The gene densities were designed so that each heat map interval occupies
# the same number of pixels along the map\'s circumference.
#
# ### changing heat map color
#
# The color of the heat map is specified using a list of colors
# ```ini
# color = red,green,blue
# ```
#
# or a color list
# ```ini
# color = spectral-11-div
# ```
#
# For more about color lists, see the [Configuration Files
# Tutorial](/documentation/tutorials/configuration/configuration_files/).
#
# The track counter can be used to dynamically change the color scheme.
# For example, as the track counter increases from 0 to 99, the definition
# ```ini
# color = eval(sprintf("spectral-%d-div",remap_round(counter(plot),0,99,11,3)))
# ```
#
# will assign a list to a track based on the counter. The assignment will
# range from `spectral-11-div` for the outer-most track, progressing
# through `spectral-10-div`, \..., and end at `spectral-3-div` for the
# inner-most track.
#
# You can combine multiple color maps. Here, an orange sequential color
# list is added to a reversed blue sequential one.
# ```ini
# color = eval(sprintf("blues-%d-seq-rev,oranges-%d-seq-rev",
# remap_round(counter(plot),0,99,9,3),
# remap_round(counter(plot),0,99,9,3)))
# ```
#
# Given the reduced resolution of the inner-most track, reducing the
# number of colors in its heat map can make the figure more legible.
#
# ### adjusting log scaling
#
# The `scale_log_base` parameter controls how heat map values are mapped
# onto colors. The default value of this parameter is
# `scale_log_base = 1`, which corresponds to a linear mapping. For more
# details about this parameter, see the [Heat Map
# Tutorial](/documentation/tutorials/2d_tracks/heat_maps/).
#
# Keeping the color list constant, but varying the `scale_log_base`, you
# can increase the dynamic range of color sampling for small values (if
# `log_scale_base < 1`) or large values (if `log_scale_base > 1`).
# ```ini
# color = spectral-11-div
# # 0.05, 0.10, 0.15, ..., 5.00
# scale_log_base = eval(0.05*(1+counter(plot)))
# ```
#
# ----
#
# ### Generating the plot produced by this example code
#
#
# The following two cells will generate the plot. The first cell adjusts the current working directory.
# %cd ../circos-tutorials-0.67/tutorials/8/16/
# + language="bash"
# ../../../../circos-0.69-6/bin/circos -conf circos.conf
# -
# View the plot in this page using the following cell.
from IPython.display import Image
Image("circos.png")
# ----
#
# Continue on to the next part of the Recipes series by clicking [here ➡](Recipes_Part18.ipynb).
#
# ----
| notebooks/Recipes_Part17.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"}
# # **Least squares regression**
#
# Notebook version: 1.4 (Sep 26, 2019)
#
# Author: <NAME> (<EMAIL>)
# + [markdown] slideshow={"slide_type": "notes"}
# Changes: v.1.0 - First version
# v.1.1 - UTAD version
# v.1.2 - Minor corrections
# v.1.3 - Python 3 compatibility
# v.1.4 - Revised notation
#
# Pending changes: *
# + slideshow={"slide_type": "skip"}
# Import some libraries that will be necessary for working with data and displaying plots
# To visualize plots in the notebook
# %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.io # To read matlab files
import pylab
# For the student tests (only for python 2)
import sys
if sys.version_info.major==2:
from test_helper import Test
# + [markdown] slideshow={"slide_type": "slide"}
# This notebook covers the problem of fitting parametric regression models with a minimum least-squares criterion. The material presented here is based on the first lectures of this <a haref=http://mlg.eng.cam.ac.uk/teaching/4f13/1415/>Machine Learning course</a>. In particular, you can refer to the following presentation: <a href=http://mlg.eng.cam.ac.uk/teaching/4f13/1415/lect0102.pdf> Probabilistic Regression</a>.
#
#
# ## 1. A parametric approach to the regression problem
#
# We have already presented the goal of regression. Given that we have access to a set of training points, $\{{\bf x}_k, s_k\}_{k=0}^{K-1}$, the goal is to learn a function $f({\bf x})$ that we can use to make good predictions for an arbitrary input vector.
#
# The following plot illustrates a regression example for unidimensional input data. We have also generated three different regression curves corresponding to polynomia of degrees 1, 2, and 3 with random coefficients.
# + slideshow={"slide_type": "slide"}
K = 35
n_grid = 200
frec = 3
std_n = 0.3
# Location of the training points
X_tr = (3 * np.random.random((K, 1)) - 0.5)
# Labels are obtained from a sinusoidal function, and contaminated by noise
S_tr = np.cos(frec*X_tr) + std_n * np.random.randn(K, 1)
# Equally spaced points in the X-axis
X_grid = np.linspace(np.min(X_tr),np.max(X_tr),n_grid)
# Gererate random prediction curves
f1 = np.random.random() + np.random.random()*X_grid
f2 = np.random.random() + np.random.random()*X_grid + \
np.random.random()*(X_grid**2)
f3 = np.random.random() + np.random.random()*X_grid + \
np.random.random()*(X_grid**2) + np.random.random()*(X_grid**3)
plt.plot(X_tr,S_tr,'b.')
plt.plot(X_grid,f1.T,'g-',label='Arbitrary Linear function')
plt.plot(X_grid,f2.T,'r-',label='Arbitrary Quadratic function')
plt.plot(X_grid,f3.T,'m-',label='Arbitrary Cubic function')
plt.legend(loc='best')
plt.show()
# + [markdown] slideshow={"slide_type": "slide"}
# ### 1.1. Parametric model
#
# Parametric regression models assume a parametric expression for the regression curve, adjusting the free parameters according to some criterion that measures the quality of the proposed model.
#
# - For a unidimensional case like the one in the previous figure, a convenient approach is to recur to polynomial expressions:
#
# $${\hat s}(x) = f(x) = w_0 + w_1 x + w_2 x^2 + \dots + w_{m-1} x^{m-1}$$
# + [markdown] slideshow={"slide_type": "slide"}
# - For multidimensional regression, polynomial expressions can include cross-products of the variables. For instance, for a case with two input variables, the degree 2 polynomial would be given by
#
# $${\hat s}({\bf x}) = f({\bf x}) = w_0 + w_1 x_1 + w_2 x_2 + w_3 x_1^2 + w_4 x_2^2 + w_5 x_1 x_2$$
# + [markdown] slideshow={"slide_type": "fragment"}
#
# - A linear model for multidimensional regression can be expressed as
#
# $${\hat s}({\bf x}) = f({\bf x}) = w_0 + {\bf w}^\top {\bf x}$$
#
# + [markdown] slideshow={"slide_type": "fragment"}
# When we postulate such models, the regression model is reduced to finding the most appropriate values of the parameters ${\bf w} = [w_i]$.
#
# All the previous models have in common the fact that they are linear in the parameters, even though they can implement highly non-linear functions. All the derivations in this notebook are equally valid for other non-linear transformations of the input variables, as long as we keep linear-in-the-parameters models.
# + slideshow={"slide_type": "slide"}
## Next, we represent some random polynomial functions for degrees between 0 and 14
max_degree = 15
K = 200
#Values of X to evaluate the function
X_grid = np.linspace(-1.5, 1.5, K)
for idx in range(max_degree):
x1 = plt.subplot(3,5, idx+1)
x1.get_xaxis().set_ticks([])
x1.get_yaxis().set_ticks([])
for kk in range(5):
#Random generation of coefficients for the model
we = np.random.randn(idx+1, 1)
#Evaluate the polynomial with previous coefficients at X_grid values
fout = np.polyval(we, X_grid)
x1.plot(X_grid,fout,'g-')
x1.set_ylim([-5,5])
# + [markdown] slideshow={"slide_type": "slide"}
# - Should we choose a polynomial?
#
# - What degree should we use for the polynomial?
#
# - For a given degree, how do we choose the weights?
#
# For now, we will find the single "best" polynomial. In a future session, we will see how we can design methods that take into account different polynomia simultaneously.
#
# Next, we will explain how to choose optimal weights according to Least-Squares criterion.
# + [markdown] slideshow={"slide_type": "slide"}
# ## 2. Least squares regression
#
# ### 2.1. Problem definition
#
# - The goal is to learn a (possibly non-linear) regression model from a set of $K$ labeled points, $\{{\bf x}_k,s_k\}_{k=0}^{K-1}$.
#
# - We assume a parametric function of the form:
#
# $${\hat s}({\bf x}) = f({\bf x}) = w_0 z_0({\bf x}) + w_1 z_1({\bf x}) + \dots w_{m-1} z_{m-1}({\bf x})$$
#
# where $z_i({\bf x})$ are particular transformations of the input vector variables.
# + [markdown] slideshow={"slide_type": "slide"}
# Some examples are:
#
# - If ${\bf z} = {\bf x}$, the model is just a linear combination of the input variables
# + [markdown] slideshow={"slide_type": "fragment"}
# - If ${\bf z} = \left[\begin{array}{c}1\\{\bf x}\end{array}\right]$, we have again a linear combination with the inclusion of a constant term.
#
# + [markdown] slideshow={"slide_type": "fragment"}
# - For unidimensional input $x$, ${\bf z} = [1, x, x^2, \dots,x^{m-1}]^\top$ would implement a polynomia of degree $m-1$.
#
# + [markdown] slideshow={"slide_type": "fragment"}
# - Note that the variables of ${\bf z}$ could also be computed combining different variables of ${\bf x}$. E.g., if ${\bf x} = [x_1,x_2]^\top$, a degree-two polynomia would be implemented with
# $${\bf z} = \left[\begin{array}{c}1\\x_1\\x_2\\x_1^2\\x_2^2\\x_1 x_2\end{array}\right]$$
# + [markdown] slideshow={"slide_type": "fragment"}
# - The above expression does not assume a polynomial model. For instance, we could consider ${\bf z} = [\log(x_1),\log(x_2)]$
# + [markdown] slideshow={"slide_type": "slide"}
# Least squares (LS) regression finds the coefficients of the model with the aim of minimizing the square of the residuals. If we define ${\bf w} = [w_0,w_1,\dots,w_{m-1}]^\top$, the LS solution would be defined as
#
# \begin{equation}
# {\bf w}_{LS} = \arg \min_{\bf w} \sum_{k=0}^{K-1} [e_k]^2 = \arg \min_{\bf w} \sum_{k=0}^{K-1} \left[s_k - {\hat s}_k \right]^2
# \end{equation}
# + [markdown] slideshow={"slide_type": "slide"}
# ### 2.2. Vector Notation
#
# In order to solve the LS problem it is convenient to define the following vectors and matrices:
#
# - We can group together all available target values to form the following vector
#
# $${\bf s} = \left[s_0, s_1, \dots, s_{K-1} \right]^\top$$
#
# + [markdown] slideshow={"slide_type": "fragment"}
#
# - The estimation of the model for a single input vector ${\bf z}_k$ (which would be computed from ${\bf x}_k$), can be expressed as the following inner product
#
# $${\hat s}_k = {\bf z}_k^\top {\bf w}$$
# + [markdown] slideshow={"slide_type": "fragment"}
# - If we now group all input vectors into a matrix ${\bf Z}$, so that each row of ${\bf Z}$ contains the transpose of the corresponding ${\bf z}_k$, we can express
#
# $$\hat{{\bf s}} = \left[{\hat s}_0, {\hat s}_1, \dots, {\hat s}_{K-1} \right]^\top =
# {\bf Z} {\bf w}, \;\;\;\;
# \text{with} \;\;
# {\bf Z} = \left[\begin{array}{c} {\bf z}_0^\top \\ {\bf z}_1^\top\\ \vdots \\ {\bf z}_{K-1}^\top
# \end{array}\right]$$
#
# + [markdown] slideshow={"slide_type": "slide"}
# ### 2.3. Least-squares solution
#
# - Using the previous notation, the cost minimized by the LS model can be expressed as
#
# $$
# C({\bf w}) = \sum_{k=0}^{K-1} \left[s_0 - {\hat s}_{K-1} \right]^2
# = \|{\bf s} - {\hat{\bf s}}\|^2 = \|{\bf s} - {\bf Z}{\bf w}\|^2
# $$
#
# + [markdown] slideshow={"slide_type": "slide"}
# - Since the above expression depends quadratically on ${\bf w}$ and is non-negative, we know that there is only one point where the derivative of $C({\bf w})$ becomes zero, and that point is necessarily a minimum of the cost
#
# $$\nabla_{\bf w} \|{\bf s} - {\bf Z}{\bf w}\|^2\Bigg|_{{\bf w} = {\bf w}_{LS}} = {\bf 0}$$
# + [markdown] slideshow={"slide_type": "slide"}
# <b>Exercise:</b>
# Solve the previous problem to show that
# $${\bf w}_{LS} = \left( {\bf Z}^\top{\bf Z} \right)^{-1} {\bf Z}^\top{\bf s}$$
# + [markdown] slideshow={"slide_type": "slide"}
# The next fragment of code adjusts polynomia of increasing order to randomly generated training data. To illustrate the composition of matrix ${\bf Z}$, we will avoid using functions $\mbox{np.polyfit}$ and $\mbox{np.polyval}$.
# + slideshow={"slide_type": "fragment"}
n_points = 20
n_grid = 200
frec = 3
std_n = 0.2
max_degree = 20
colors = 'brgcmyk'
#Location of the training points
X_tr = (3 * np.random.random((n_points,1)) - 0.5)
#Labels are obtained from a sinusoidal function, and contaminated by noise
S_tr = np.cos(frec*X_tr) + std_n * np.random.randn(n_points,1)
#Equally spaced points in the X-axis
X_grid = np.linspace(np.min(X_tr),np.max(X_tr),n_grid)
#We start by building the Z matrix
Z = []
for el in X_tr.tolist():
Z.append([el[0]**k for k in range(max_degree+1)])
Z = np.matrix(Z)
Z_grid = []
for el in X_grid.tolist():
Z_grid.append([el**k for k in range(max_degree+1)])
Z_grid = np.matrix(Z_grid)
plt.plot(X_tr,S_tr,'b.')
for k in [1, 2, n_points]: # range(max_degree+1):
Z_iter = Z[:,:k+1]
# Least square solution
#w_LS = (np.linalg.inv(Z_iter.T.dot(Z_iter))).dot(Z_iter.T).dot(S_tr)
# Least squares solution, with leass numerical errors
w_LS, resid, rank, s = np.linalg.lstsq(Z_iter, S_tr, rcond=None)
#estimates at all grid points
fout = Z_grid[:,:k+1].dot(w_LS)
fout = np.array(fout).flatten()
plt.plot(X_grid,fout,colors[k%len(colors)]+'-',label='Degree '+str(k))
plt.legend(loc='best')
plt.ylim(1.2*np.min(S_tr), 1.2*np.max(S_tr))
plt.show()
# + [markdown] slideshow={"slide_type": "slide"}
# ### 2.4. Overfitting the training data
#
# It may seem that increasing the degree of the polynomia is always beneficial, as we can implement a more expressive function. A polynomia of degree $M$ would include all polynomia of lower degrees as particular cases. However, if we increase the number of parameters without control, the polynomia would eventually get expressive enough to adjust any given set of training points to arbitrary precision, what does not necessarily mean that the solution is obtaining a model that can be extrapolated to new data, as we show in the following example:
#
# + slideshow={"slide_type": "slide"}
n_points = 35
n_test = 200
n_grid = 200
frec = 3
std_n = 0.7
max_degree = 25
colors = 'brgcmyk'
#Location of the training points
X_tr = (3 * np.random.random((n_points,1)) - 0.5)
#Labels are obtained from a sinusoidal function, and contaminated by noise
S_tr = np.cos(frec*X_tr) + std_n * np.random.randn(n_points,1)
#Test points to validate the generalization of the solution
X_tst = (3 * np.random.random((n_test,1)) - 0.5)
S_tst = np.cos(frec*X_tst) + std_n * np.random.randn(n_test,1)
#Equally spaced points in the X-axis
X_grid = np.linspace(np.min(X_tr),np.max(X_tr),n_grid)
#We start by building the Z matrix
def extend_matrix(X,max_degree):
Z = []
X = X.reshape((X.shape[0],1))
for el in X.tolist():
Z.append([el[0]**k for k in range(max_degree+1)])
return np.matrix(Z)
Z = extend_matrix(X_tr,max_degree)
Z_grid = extend_matrix(X_grid,max_degree)
Z_test = extend_matrix(X_tst,max_degree)
#Variables to store the train and test errors
tr_error = []
tst_error = []
for k in range(max_degree):
Z_iter = Z[:,:k+1]
#Least square solution
#w_LS = (np.linalg.inv(Z_iter.T.dot(Z_iter))).dot(Z_iter.T).dot(S_tr)
# Least squares solution, with leass numerical errors
w_LS, resid, rank, s = np.linalg.lstsq(Z_iter, S_tr)
#estimates at traint and test points
f_tr = Z_iter.dot(w_LS)
f_tst = Z_test[:,:k+1].dot(w_LS)
tr_error.append(np.array((S_tr-f_tr).T.dot(S_tr-f_tr)/len(S_tr))[0,0])
tst_error.append(np.array((S_tst-f_tst).T.dot(S_tst-f_tst)/len(S_tst))[0,0])
plt.stem(range(max_degree),tr_error,'b-',label='Train error')
plt.stem(range(max_degree),tst_error,'r-o',label='Test error')
plt.legend(loc='best')
plt.show()
# -
# #### 2.4.1 Limitations of the LS approach. The need for assumptions
#
# Another way to visualize the effect of overfiting is to analyze the effect of variations o a single sample. Consider a training dataset consisting of 15 points which are given, and depict the regression curves that would be obtained if adding an additional point at a fixed location, depending on the target value of that point:
#
# (You can run this code fragment several times, to check also the changes in the regression curves between executions, and depending also on the location of the training points)
# +
n_points = 15
n_grid = 200
frec = 3
std_n = 0.2
n_val_16 = 5
degree = 18
X_tr = 3 * np.random.random((n_points,1)) - 0.5
S_tr = - np.cos(frec*X_tr) + std_n * np.random.randn(n_points,1)
X_grid = np.linspace(-.5,2.5,n_grid)
S_grid = - np.cos(frec*X_grid) #Noise free for the true model
X_16 = .3 * np.ones((n_val_16,))
S_16 = np.linspace(np.min(S_tr),np.max(S_tr),n_val_16)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(X_tr,S_tr,'b.',markersize=10)
ax.plot(X_16,S_16,'ro',markersize=6)
ax.plot(X_grid,S_grid,'r-',label='True model')
for el in zip(X_16,S_16):
#Add point to the training set
X_tr_iter = np.append(X_tr,el[0])
S_tr_iter = np.append(S_tr,el[1])
#Obtain LS regression coefficients and evaluate it at X_grid
w_LS = np.polyfit(X_tr_iter, S_tr_iter, degree)
S_grid_iter = np.polyval(w_LS,X_grid)
ax.plot(X_grid,S_grid_iter,'g-')
ax.set_xlim(-.5,2.5)
ax.set_ylim(S_16[0]-2,S_16[-1]+2)
ax.legend(loc='best')
plt.show()
# + [markdown] slideshow={"slide_type": "slide"}
# ### Exercise
#
# Analyze the performance of LS regression on the `Advertising` dataset. You can analyze:
#
# - The performance of linear regression when using just one variable, or using all of them together
# - The performance of different non-linear methods (e.g., polynomial or logarithmic transformations)
# - Model selection using CV strategies
| R3.Least_Squares/.ipynb_checkpoints/regresion_LS-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
# ---
# # Multilayer Perceptron from raw data
# This notebook will guide you through the use of the `keras` package to train a multilayer perceptron for handwritten digits classification. You are going to use the `mnist` dataset from LeCun et al. 1998
# ## Loading the packages
# +
import numpy as np
from matplotlib import pyplot as pl
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout
from keras.optimizers import RMSprop
from keras.utils import np_utils
from sklearn import metrics as me
# %matplotlib inline
# -
# ## Using raw data to train a MLP
# First load the `mnist` dataset and normalize it to be in the range [0, 1]
# +
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print X_train.shape[0], 'train samples'
print X_test.shape[0], 'test samples'
n_classes = 10
# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, n_classes)
Y_test = np_utils.to_categorical(y_test, n_classes)
# -
# Create the MLP
# +
model = Sequential()
model.add(Dense(300, input_shape=(784,), activation='relu'))
#model.add(Dropout(0.5))
model.add(Dense(n_classes, activation='softmax'))
model.summary()
# -
# Define some constants and train the MLP
# +
batch_size = 128
n_epoch = 10
model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'])
history = model.fit(X_train, Y_train,
batch_size=batch_size, epochs=n_epoch,
verbose=1, validation_data=(X_test, Y_test))
# -
# Show the performance of the model
# +
pl.plot(history.history['loss'], label='Training')
pl.plot(history.history['val_loss'], label='Testing')
pl.legend()
pl.grid()
score = model.evaluate(X_test, Y_test, verbose=0)
print 'Test score:', score[0]
print 'Test accuracy:', score[1]
# -
# Confusion matrix
pred = model.predict_classes(X_test)
me.confusion_matrix(y_test, pred)
| Other/2.FromMLP_to_CNN/ML-PW-09/MLP_and_CNN_notebooks/MLP_from_raw_data.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import os
from shutil import copyfile
from PIL import Image, ImageDraw,ImageFont
import matplotlib.pyplot as plt
path = 'scd_addit'
my_list = os.listdir(path)
for i in range(50):
directory_path=path+'_sam/'+str(i)
if not os.path.exists(directory_path):
os.makedirs(directory_path)
for j,dir in enumerate(my_list):
source = path+'/'+dir+'/'+str(i)+'.png'
print (source)
dest = directory_path+'/'+str(j)+'.png'
print (dest)
copyfile(source, dest)
path = 'soc_addit'
my_list = os.listdir(path)
for i in range(50):
directory_path=path+'_sam/'+str(i)
if not os.path.exists(directory_path):
os.makedirs(directory_path)
for j,dir in enumerate(my_list):
source = path+'/'+dir+'/'+str(i)+'.png'
print (source)
dest = directory_path+'/'+str(j)+'.png'
print (dest)
copyfile(source, dest)
path = 'scd_exclud'
my_list = os.listdir(path)
for i in range(50):
directory_path=path+'_sam/'+str(i)
if not os.path.exists(directory_path):
os.makedirs(directory_path)
for j,dir in enumerate(my_list):
source = path+'/'+dir+'/'+str(i)+'.png'
print (source)
dest = directory_path+'/'+str(j)+'.png'
print (dest)
copyfile(source, dest)
path = 'soc_exclud'
my_list = os.listdir(path)
for i in range(50):
directory_path=path+'_sam/'+str(i)
if not os.path.exists(directory_path):
os.makedirs(directory_path)
for j,dir in enumerate(my_list):
source = path+'/'+dir+'/'+str(i)+'.png'
print (source)
dest = directory_path+'/'+str(j)+'.png'
print (dest)
copyfile(source, dest)
def add_margin(pil_img, top, right, bottom, left, color):
width, height = pil_img.size
new_width = width + right + left
new_height = height + top + bottom
result = Image.new(pil_img.mode, (new_width, new_height), color)
result.paste(pil_img, (left, top))
return result
path = 'scd_addit_sam'
my_list = os.listdir(path)
print (my_list)
for fol in my_list:
image_list=[]
max_height = 0
for i in range(12):
image_path = path+'/'+fol+'/'+str(i)+'.png'
im = Image.open(image_path)
width, height = im.size
max_height = max(max_height,height)
image_list.append(im)
new_image_list=[]
for i,im in enumerate(image_list):
width, height = im.size
new_im = add_margin(im,max_height-height,0,0,0,(255,255,255))
draw = ImageDraw.Draw(new_im)
font = ImageFont.truetype("Arial.ttf", 100)
draw.text((0, 0),str(i+1),(0,0,0),font=font)
new_image_list.append(new_im)
save_path = path+'/'+fol+'/'+'animated.gif'
new_image_list[0].save(save_path,save_all=True, append_images=new_image_list[1:], optimize=False, duration=1500, loop=0)
path = 'scd_exclud_sam'
my_list = os.listdir(path)
print (my_list)
for fol in my_list:
image_list=[]
max_height = 0
for i in range(12):
image_path = path+'/'+fol+'/'+str(i)+'.png'
im = Image.open(image_path)
width, height = im.size
max_height = max(max_height,height)
image_list.append(im)
new_image_list=[]
for i,im in enumerate(image_list):
width, height = im.size
new_im = add_margin(im,max_height-height,0,0,0,(255,255,255))
draw = ImageDraw.Draw(new_im)
font = ImageFont.truetype("Arial.ttf", 100)
draw.text((0, 0),str(i+1),(0,0,0),font=font)
new_image_list.append(new_im)
save_path = path+'/'+fol+'/'+'animated.gif'
new_image_list[0].save(save_path,save_all=True, append_images=new_image_list[1:], optimize=False, duration=1500, loop=0)
path = 'soc_addit_sam'
my_list = os.listdir(path)
print (my_list)
for fol in my_list:
image_list=[]
max_height = 0
for i in range(12):
image_path = path+'/'+fol+'/'+str(i)+'.png'
im = Image.open(image_path)
width, height = im.size
max_height = max(max_height,height)
image_list.append(im)
new_image_list=[]
for i,im in enumerate(image_list):
width, height = im.size
new_im = add_margin(im,max_height-height,0,0,0,(255,255,255))
draw = ImageDraw.Draw(new_im)
font = ImageFont.truetype("Arial.ttf", 100)
draw.text((0, 0),str(i+1),(0,0,0),font=font)
new_image_list.append(new_im)
save_path = path+'/'+fol+'/'+'animated.gif'
new_image_list[0].save(save_path,save_all=True, append_images=new_image_list[1:], optimize=False, duration=1500, loop=0)
path = 'soc_exclud_sam'
my_list = os.listdir(path)
print (my_list)
for fol in my_list:
image_list=[]
max_height = 0
for i in range(12):
image_path = path+'/'+fol+'/'+str(i)+'.png'
im = Image.open(image_path)
width, height = im.size
max_height = max(max_height,height)
image_list.append(im)
new_image_list=[]
for i,im in enumerate(image_list):
width, height = im.size
new_im = add_margin(im,max_height-height,0,0,0,(255,255,255))
draw = ImageDraw.Draw(new_im)
font = ImageFont.truetype("Arial.ttf", 100)
draw.text((0, 0),str(i+1),(0,0,0),font=font)
new_image_list.append(new_im)
save_path = path+'/'+fol+'/'+'animated.gif'
new_image_list[0].save(save_path,save_all=True, append_images=new_image_list[1:], optimize=False, duration=1500, loop=0)
"""path = 'scd_addit_sam'
my_list = os.listdir(path)
print (my_list)
for fol in my_list:
image_list=[]
for i in range(1,12):
image_path = path+'/'+fol+'/'+str(i)+'.png'
im = Image.open(image_path)
draw = ImageDraw.Draw(im)
font = ImageFont.truetype("Arial.ttf", 100)
draw.text((0, 0),str(i),(0,0,0),font=font)
image_list.append(im)
save_path = path+'/'+fol+'/'+'animated.gif'
image_list[0].save(save_path,save_all=True, append_images=image_list[1:], optimize=False, duration=1000, loop=0)
"""
| figs/.ipynb_checkpoints/order_samples_gif_maker-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.6.8 64-bit
# name: python36864bit02660a26c7e04cbba91a433884a017aa
# ---
from sympy.physics.mechanics import *
from sympy import symbols, atan, cos, Matrix
q = dynamicsymbols('q:3')
qd = dynamicsymbols('q:3', level=1)
l = symbols('l:3')
m = symbols('m:3')
g, t = symbols('g, t')
# +
# Compose World Frame
N = ReferenceFrame('N')
A = N.orientnew('A', 'axis', [q[0], N.z])
B = N.orientnew('B', 'axis', [q[1], N.z])
C = N.orientnew('C', 'axis', [q[2], N.z])
A.set_ang_vel(N, qd[0] * N.z)
B.set_ang_vel(N, qd[1] * N.z)
C.set_ang_vel(N, qd[2] * N.z)
# -
O = Point('O')
P = O.locatenew('P', l[0] * A.x)
R = P.locatenew('R', l[1] * B.x)
S = R.locatenew('S', l[2] * C.x)
O.set_vel(N, 0)
P.v2pt_theory(O, N, A)
R.v2pt_theory(P, N, B)
S.v2pt_theory(R, N, C)
ParP = Particle('ParP', P, m[0])
ParR = Particle('ParR', R, m[1])
ParS = Particle('ParS', S, m[2])
FL = [(P, m[0] * g * N.x), (R, m[1] * g * N.x), (S, m[2] * g * N.x)]
# Calculate the lagrangian, and form the equations of motion
Lag = Lagrangian(N, ParP, ParR, ParS)
LM = LagrangesMethod(Lag, q, forcelist=FL, frame=N)
lag_eqs = LM.form_lagranges_equations()
lag_eqs.simplify()
lag_eqs
| InvertedPendulumCart/triplePendulum/triple_pendulum.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
# ---
# + dc={"key": "3"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 1. Inspecting transfusion.data file
# <p><img src="https://assets.datacamp.com/production/project_646/img/blood_donation.png" style="float: right;" alt="A pictogram of a blood bag with blood donation written in it" width="200"></p>
# <p>Blood transfusion saves lives - from replacing lost blood during major surgery or a serious injury to treating various illnesses and blood disorders. Ensuring that there's enough blood in supply whenever needed is a serious challenge for the health professionals. According to <a href="https://www.webmd.com/a-to-z-guides/blood-transfusion-what-to-know#1">WebMD</a>, "about 5 million Americans need a blood transfusion every year".</p>
# <p>Our dataset is from a mobile blood donation vehicle in Taiwan. The Blood Transfusion Service Center drives to different universities and collects blood as part of a blood drive. We want to predict whether or not a donor will give blood the next time the vehicle comes to campus.</p>
# <p>The data is stored in <code>datasets/transfusion.data</code> and it is structured according to RFMTC marketing model (a variation of RFM). We'll explore what that means later in this notebook. First, let's inspect the data.</p>
# + dc={"key": "3"} tags=["sample_code"]
# Print out the first 5 lines from the transfusion.data file
# !head -n 5 datasets/transfusion.data
# + dc={"key": "10"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 2. Loading the blood donations data
# <p>We now know that we are working with a typical CSV file (i.e., the delimiter is <code>,</code>, etc.). We proceed to loading the data into memory.</p>
# + dc={"key": "10"} tags=["sample_code"]
# Import pandas
import pandas as pd
# Read in dataset
transfusion = pd.read_csv("datasets/transfusion.data")
# Print out the first rows of our dataset
transfusion.head()
# + dc={"key": "17"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 3. Inspecting transfusion DataFrame
# <p>Let's briefly return to our discussion of RFM model. RFM stands for Recency, Frequency and Monetary Value and it is commonly used in marketing for identifying your best customers. In our case, our customers are blood donors.</p>
# <p>RFMTC is a variation of the RFM model. Below is a description of what each column means in our dataset:</p>
# <ul>
# <li>R (Recency - months since the last donation)</li>
# <li>F (Frequency - total number of donation)</li>
# <li>M (Monetary - total blood donated in c.c.)</li>
# <li>T (Time - months since the first donation)</li>
# <li>a binary variable representing whether he/she donated blood in March 2007 (1 stands for donating blood; 0 stands for not donating blood)</li>
# </ul>
# <p>It looks like every column in our DataFrame has the numeric type, which is exactly what we want when building a machine learning model. Let's verify our hypothesis.</p>
# + dc={"key": "17"} tags=["sample_code"]
# Print a concise summary of transfusion DataFrame
transfusion.info()
# + dc={"key": "24"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 4. Creating target column
# <p>We are aiming to predict the value in <code>whether he/she donated blood in March 2007</code> column. Let's rename this it to <code>target</code> so that it's more convenient to work with.</p>
# + dc={"key": "24"} tags=["sample_code"]
# Rename target column as 'target' for brevity
transfusion.rename(
columns={'whether he/she donated blood in March 2007': 'target'},
inplace=True
)
# Print out the first 2 rows
transfusion.head(2)
# + dc={"key": "31"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 5. Checking target incidence
# <p>We want to predict whether or not the same donor will give blood the next time the vehicle comes to campus. The model for this is a binary classifier, meaning that there are only 2 possible outcomes:</p>
# <ul>
# <li><code>0</code> - the donor will not give blood</li>
# <li><code>1</code> - the donor will give blood</li>
# </ul>
# <p>Target incidence is defined as the number of cases of each individual target value in a dataset. That is, how many 0s in the target column compared to how many 1s? Target incidence gives us an idea of how balanced (or imbalanced) is our dataset.</p>
# + dc={"key": "31"} tags=["sample_code"]
# Print target incidence proportions, rounding output to 3 decimal places
transfusion.target.value_counts(normalize=True).round(3)
# + dc={"key": "38"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 6. Splitting transfusion into train and test datasets
# <p>We'll now use <code>train_test_split()</code> method to split <code>transfusion</code> DataFrame.</p>
# <p>Target incidence informed us that in our dataset <code>0</code>s appear 76% of the time. We want to keep the same structure in train and test datasets, i.e., both datasets must have 0 target incidence of 76%. This is very easy to do using the <code>train_test_split()</code> method from the <code>scikit learn</code> library - all we need to do is specify the <code>stratify</code> parameter. In our case, we'll stratify on the <code>target</code> column.</p>
# + dc={"key": "38"} tags=["sample_code"]
# Import train_test_split method
from sklearn.model_selection import train_test_split
# Split transfusion DataFrame into
# X_train, X_test, y_train and y_test datasets,
# stratifying on the `target` column
X_train, X_test, y_train, y_test = train_test_split(
transfusion.drop(columns='target'),
transfusion.target,
test_size=0.25,
random_state=42,
stratify=transfusion.target
)
# Print out the first 2 rows of X_train
X_train.head(2)
# + dc={"key": "45"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 7. Selecting model using TPOT
# <p><a href="https://github.com/EpistasisLab/tpot">TPOT</a> is a Python Automated Machine Learning tool that optimizes machine learning pipelines using genetic programming.</p>
# <p><img src="https://assets.datacamp.com/production/project_646/img/tpot-ml-pipeline.png" alt="TPOT Machine Learning Pipeline"></p>
# <p>TPOT will automatically explore hundreds of possible pipelines to find the best one for our dataset. Note, the outcome of this search will be a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html">scikit-learn pipeline</a>, meaning it will include any pre-processing steps as well as the model.</p>
# <p>We are using TPOT to help us zero in on one model that we can then explore and optimize further.</p>
# + dc={"key": "45"} tags=["sample_code"]
import warnings
warnings.filterwarnings("ignore")
# Import TPOTClassifier and roc_auc_score
from tpot import TPOTClassifier
from sklearn.metrics import roc_auc_score
# Instantiate TPOTClassifier
tpot = TPOTClassifier(
generations=5,
population_size=20,
verbosity=2,
scoring='roc_auc',
random_state=42,
disable_update_check=True,
config_dict='TPOT light'
)
tpot.fit(X_train, y_train)
# AUC score for tpot model
tpot_auc_score = roc_auc_score(y_test, tpot.predict_proba(X_test)[:, 1])
print(f'\nAUC score: {tpot_auc_score:.4f}')
# Print best pipeline steps
print('\nBest pipeline steps:', end='\n')
for idx, (name, transform) in enumerate(tpot.fitted_pipeline_.steps, start=1):
# Print idx and transform
print(f'{idx}. {transform}')
# + dc={"key": "52"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 8. Checking the variance
# <p>TPOT picked <code>LogisticRegression</code> as the best model for our dataset with no pre-processing steps, giving us the AUC score of 0.7850. This is a great starting point. Let's see if we can make it better.</p>
# <p>One of the assumptions for linear regression models is that the data and the features we are giving it are related in a linear fashion, or can be measured with a linear distance metric. If a feature in our dataset has a high variance that's an order of magnitude or more greater than the other features, this could impact the model's ability to learn from other features in the dataset.</p>
# <p>Correcting for high variance is called normalization. It is one of the possible transformations you do before training a model. Let's check the variance to see if such transformation is needed.</p>
# + dc={"key": "52"} tags=["sample_code"]
# X_train's variance, rounding the output to 3 decimal places
print(X_train.var().round(3).to_string())
# + dc={"key": "59"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 9. Log normalization
# <p><code>Monetary (c.c. blood)</code>'s variance is very high in comparison to any other column in the dataset. This means that, unless accounted for, this feature may get more weight by the model (i.e., be seen as more important) than any other feature.</p>
# <p>One way to correct for high variance is to use log normalization.</p>
# + dc={"key": "59"} tags=["sample_code"]
# Import numpy
import numpy as np
# Copy X_train and X_test into X_train_normed and X_test_normed
X_train_normed, X_test_normed = X_train.copy(), X_test.copy()
# Specify which column to normalize
col_to_normalize = X_train_normed.var().idxmax(axis=1)
# Log normalization
for df_ in [X_train_normed, X_test_normed]:
# Add log normalized column
df_['monetary_log'] = np.log(df_[col_to_normalize])
# Drop the original column
df_.drop(columns=col_to_normalize, inplace=True)
# Check the variance for X_train_normed
print(X_train_normed.var().round(3).to_string())
# + dc={"key": "66"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 10. Training the linear regression model
# <p>The variance looks much better now. Notice that now <code>Time (months)</code> has the largest variance, but it's not the <a href="https://en.wikipedia.org/wiki/Order_of_magnitude">orders of magnitude</a> higher than the rest of the variables, so we'll leave it as is.</p>
# <p>We are now ready to train the linear regression model.</p>
# + dc={"key": "66"} tags=["sample_code"]
# Importing modules
from sklearn import linear_model
# Instantiate LogisticRegression
logreg = linear_model.LogisticRegression(
solver='liblinear',
random_state=42
)
# Train the model
logreg.fit(X_train_normed, y_train)
# AUC score for tpot model
logreg_auc_score = roc_auc_score(y_test, logreg.predict_proba(X_test_normed)[:, 1])
print(f'\nAUC score: {logreg_auc_score:.4f}')
# + dc={"key": "73"} deletable=false editable=false run_control={"frozen": true} tags=["context"]
# ## 11. Conclusion
# <p>The demand for blood fluctuates throughout the year. As one <a href="https://www.kjrh.com/news/local-news/red-cross-in-blood-donation-crisis">prominent</a> example, blood donations slow down during busy holiday seasons. An accurate forecast for the future supply of blood allows for an appropriate action to be taken ahead of time and therefore saving more lives.</p>
# <p>In this notebook, we explored automatic model selection using TPOT and AUC score we got was 0.7850. This is better than simply choosing <code>0</code> all the time (the target incidence suggests that such a model would have 76% success rate). We then log normalized our training data and improved the AUC score by 0.5%. In the field of machine learning, even small improvements in accuracy can be important, depending on the purpose.</p>
# <p>Another benefit of using logistic regression model is that it is interpretable. We can analyze how much of the variance in the response variable (<code>target</code>) can be explained by other variables in our dataset.</p>
# + dc={"key": "73"} tags=["sample_code"]
# Importing itemgetter
from operator import itemgetter
# Sort models based on their AUC score from highest to lowest
sorted(
[('tpot', tpot_auc_score.round(4)), ('logreg', logreg_auc_score.round(4))],
key=itemgetter(1),
reverse=True
)
| Predict Blood Donations.ipynb |