text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
# eICU Collaborative Research Database
# Notebook 3: Severity of illness
This notebook introduces high level admission details relating to a single patient stay, using the following tables:
- patient
- admissiondx
- apacheapsvar
- apachepredvar
- apachepatientresult
## Load libraries and connect to the database
```
# Import libraries
import numpy as np
import os
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
# Make pandas dataframes prettier
from IPython.display import display, HTML
# Access data using Google BigQuery.
from google.colab import auth
from google.cloud import bigquery
# authenticate
auth.authenticate_user()
# Set up environment variables
project_id='hst-953-2019'
os.environ["GOOGLE_CLOUD_PROJECT"]=project_id
# Helper function to read data from BigQuery into a DataFrame.
def run_query(query):
return pd.io.gbq.read_gbq(query, project_id=project_id, dialect="standard")
```
## Selecting a single patient stay¶
As we have seen, the patient table includes general information about the patient admissions (for example, demographics, admission and discharge details). See: http://eicu-crd.mit.edu/eicutables/patient/
## Questions
Use your knowledge from the previous notebook and the online documentation (http://eicu-crd.mit.edu/) to answer the following questions:
- Which column in the patient table is distinct for each stay in the ICU (similar to `icustay_id` in MIMIC-III)?
- Which column is unique for each patient (similar to `subject_id` in MIMIC-III)?
```
# view distinct ids
query = """
SELECT DISTINCT(patientunitstayid)
FROM `physionet-data.eicu_crd_demo.patient`
"""
run_query(query)
# select a single ICU stay
patientunitstayid = <your_id_here>
# set the where clause to select the stay of interest
query = """
SELECT *
FROM `physionet-data.eicu_crd_demo.patient`
WHERE patientunitstayid = {}
""".format(patientunitstayid)
patient = run_query(query)
patient
```
## Questions
- Which type of unit was the patient admitted to? Hint: Try `patient['unittype']` or `patient.unittype`
- What year was the patient discharged from the ICU? Hint: You can view the table columns with `patient.columns`
- What was the status of the patient upon discharge from the unit?
## The admissiondx table
The `admissiondx` table contains the primary diagnosis for admission to the ICU according to the APACHE scoring criteria. For more detail, see: http://eicu-crd.mit.edu/eicutables/admissiondx/
```
# set the where clause to select the stay of interest
query = """
SELECT *
FROM `physionet-data.eicu_crd_demo.admissiondx`
WHERE patientunitstayid = {}
""".format(patientunitstayid)
admissiondx = run_query(query)
# View the columns in this data
admissiondx.columns
# View the data
admissiondx.head()
# Set the display options to avoid truncating the text
pd.set_option('display.max_colwidth', -1)
admissiondx.admitdxpath
```
## Questions
- What was the primary reason for admission?
- How soon after admission to the ICU was the diagnoses recorded in eCareManager? Hint: The `offset` columns indicate the time in minutes after admission to the ICU.
## The apacheapsvar table
The apacheapsvar table contains the variables used to calculate the Acute Physiology Score (APS) III for patients. APS-III is an established method of summarizing patient severity of illness on admission to the ICU, taking the "worst" observations for a patient in a 24 hour period.
The score is part of the Acute Physiology Age Chronic Health Evaluation (APACHE) system of equations for predicting outcomes for ICU patients. See: http://eicu-crd.mit.edu/eicutables/apacheApsVar/
```
# set the where clause to select the stay of interest
query = """
SELECT *
FROM `physionet-data.eicu_crd_demo.apacheapsvar`
WHERE patientunitstayid = {}
""".format(patientunitstayid)
apacheapsvar = run_query(query)
apacheapsvar.head()
```
## Questions
- What was the 'worst' heart rate recorded for the patient during the scoring period?
- Was the patient oriented and able to converse normally on the day of admission? (hint: the verbal element refers to the Glasgow Coma Scale).
# apachepredvar table
The apachepredvar table provides variables underlying the APACHE predictions. Acute Physiology Age Chronic Health Evaluation (APACHE) consists of a groups of equations used for predicting outcomes in critically ill patients. See: http://eicu-crd.mit.edu/eicutables/apachePredVar/
```
# set the where clause to select the stay of interest
query = """
SELECT *
FROM `physionet-data.eicu_crd_demo.apachepredvar`
WHERE patientunitstayid = {}
""".format(patientunitstayid)
apachepredvar = run_query(query)
apachepredvar.columns
```
## Questions
- Was the patient ventilated during (APACHE) day 1 of their stay?
- Is the patient recorded as having diabetes?
# `apachepatientresult` table
The `apachepatientresult` table provides predictions made by the APACHE score (versions IV and IVa), including probability of mortality, length of stay, and ventilation days. See: http://eicu-crd.mit.edu/eicutables/apachePatientResult/
```
# set the where clause to select the stay of interest
query = """
SELECT *
FROM `physionet-data.eicu_crd_demo.apachepatientresult`
WHERE patientunitstayid = {}
""".format(patientunitstayid)
apachepatientresult = run_query(query)
apachepatientresult
```
## Questions
- What versions of the APACHE score are computed?
- How many days during the stay was the patient ventilated?
- How long was the patient predicted to stay in hospital?
- Was this prediction close to the truth?
| github_jupyter |
# Polychromatic Propagations
Prysm has a long heritage solving the monochromatic problem very quickly. However, it used a brute force 'propagate and interpolate' approach to solving the polychromatic problem. v0.19 offers large speedup by using matrix triple product DFTs to perform polychromatic propagations. This results in forward model times that are significantly faster, and clearer code when propagating to a grid for a detector.
This notebook shows in the fewest possible lines the speedup by using a zero OPD circular pupil under nine discrete wavelengths. It also shows propagating to a detector grid.
```
from operator import add
from functools import reduce
import numpy as np
from matplotlib import pyplot as plt
from prysm import Pupil, PSF
from prysm.propagation import focus_units, Wavefront
wvls = np.linspace(.4, .7, 9) # 400 to 900 nm, 9 wavelengths
pups = [Pupil(wavelength=w, samples=512) for w in wvls]
```
## The old way
```
%%timeit
psfs = [PSF.from_pupil(pup, efl=1, Q=2) for pup in pups]
poly_psf = PSF.polychromatic(psfs)
# the new way - setup for equivalence of output
x, y = focus_units(pups[0].fcn, pups[0].sample_spacing, 1, wvls[0], 2)
sample_spacing = x[1] - x[0]
```
## The new way
```
%%timeit
psf_fields = [p.astype(Wavefront)\
.focus_fixed_sampling(efl=1, sample_spacing=sample_spacing, samples=1024) for p in pups]
psf_intensities = [abs(w.fcn)**2 for w in psf_fields]
poly_psf2 = PSF(x=x, y=y, data=reduce(add, psf_intensities))
```
In this simple example, the new way is about **4x** faster. In this case, the simulation was done at Q=2 for all colors in the 'old' polychromatic way. This results in some numerical errors, where the new way is error free. At larger Qs the old way will have improved accuracy, but also increased computation time. To show the true power of the new way, we will compare old and new for Q=8, and use the flexibility of the matrix triple product to compute a smaller output domain:
## the old (high oversampling):
```
%%timeit
psfs = [PSF.from_pupil(pup, efl=1, Q=8) for pup in pups]
poly_psf3 = PSF.polychromatic(psfs)
# the new way - setup for equivalence of output
x, y = focus_units(pups[0].fcn, pups[0].sample_spacing, 1, wvls[0], 8)
sample_spacing = x[1] - x[0]
```
## the new (high oversampling)
```
%%timeit
psf_fields = [p.astype(Wavefront)\
.focus_fixed_sampling(efl=1, sample_spacing=sample_spacing, samples=256) for p in pups]
psf_intensities = [abs(w.fcn)**2 for w in psf_fields]
poly_psf4 = PSF(x=x, y=y, data=reduce(add, psf_intensities))
```
The parameters of this second example are not particularly relevant outside coronagraphy or simulation study of astronomical instrumentation due to the large Q, but we see a **nearly 500x** speedup for use of the matrix triple product.
While the output data is not strictly the same since the matrix triple product is computed over a smaller domain, their _value_ is the same since we do not care about the region far from the core of the PSF. This speedup allows computations that may require a supercomputer to be done on a laptop.
| github_jupyter |
# React
- [https://reactjs.org/](https://reactjs.org/)
- JavaScript library for building user interfaces
- `declarative` views make code more predictable and easier to debug
- `component-based` UI makes it easier to compose and manage complex UIs with their own state (data)
- since component logic is written in JS, instead of templates, you can easily pass rich data through your app and keep state out of the DOM
- `learn once, write anywhere` feature doesn't make any assumptions about the technology stack
- can be rendered on the server using Node and power mobile apps using React Native
## Main Concepts
- go through the main concepts from reactjs.org docs page:
- [https://reactjs.org/docs/hello-world.html](https://reactjs.org/docs/hello-world.html)
## JSX - (Syntax Extension to JavaScript)
- Use JSX to describe what the UI should look like
- [https://reactjs.org/docs/introducing-jsx.html](https://reactjs.org/docs/introducing-jsx.html)
- JSX represents Objects
- JSX supports embedding expressions and data within `{ }`
- JSX prevents Injection Attacks - such as Cross-site Scripting (XSS) attack
- React DOM escapes any values embedded in JSX before rendering them
- JSX is JavaScript and XML/HTML syntax combined as Javascript
- convert any XML/HTML attributes with hyphen to camelCase
- e.g.: data-toggle needs to be dataToggle
- class needs to be className
- inline HTML style needs to be in {{ "key":"value" }} format
- e.g.: style={{"width":"100%"}}
## React Developer tools
- addons/extensions for Chrome, Edge, Firefox - https://reactjs.org/blog/2015/09/02/new-react-developer-tools.html#installation
## On VS Code install Live Server extension
- let's you change the html contents and automatically reloads the updated content after each save
- right click on an HTML file and click "Open with Live Server"
## JSX demos using standalone html files
- see `ReactDemos/react-jsx-intro` folder
- see the content on any editor to go through the React JSX code
- open the file in browser to execute the JSX using standalone babel compiler
## Add React to an existing static website
- React components can be gradually added to an existing site
- use it as little or as much as you need
- see `ReactDemos/homepage-v0` demo
### Homepage v0
- a very basic demo
- static pages with some react components
- uses JavaScript libraries downloaded on the browser itself
- nothing needs to be installed just run index.html file on the browser and start navigating
- repeated components are added in each page
- can't import or add component as an external JS file
### Homepage v1
- see `ReactDemos/homepage-v2`
```bash
cd React-Demos/homepage-v1
npm install
npm update
```
- this project uses express backend and some react components
- must add the following line in your package.json under scripts key
```json
"compile": "webpack"
```
- create components scripts under public folder
- add the required script tags in html pages
- NOTE type="text/jsx" attribute to each UI component file
```html
<!-- Load React -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
<script type="text/jsx" src="ui/header.js"></script>
```
- run the express server
```bash
cd ReactDemos/homepage-v1
npm start
```
- point browswer to http://localhost:3000
### Notes
- the site uses Express server to serve the pages (more on Express later)
- the website uses mix of complete static HTML tags and React components
- React components have data/state hard-coded within each component class
- html pages are in views folder
- react components are in public/ui folder
## Create React Single-page App
- react is typically used for single-page app
- learn in depth about single-page app: [https://blog.pshrmn.com/how-single-page-applications-work/](https://blog.pshrmn.com/how-single-page-applications-work/)
- first install Facebook's `create-react-app` and use to create a react app with boilder plate code
- on a terminal change your working directory where you want to create the react app
```bash
npm install create-react-app
npx create-react-app AppName
cd AppName
npm start
```
## React App with Router
- see a simple demo app with react router for web site that mimics multiple pages
- in order to create multiple routes and associated pages/views, we'll use react router app - [https://reactrouter.com/web/guides/quick-start](https://reactrouter.com/web/guides/quick-start)
- test React UI Components using https://testing-library.com/docs/
- see `ReactDemos/route-testing-demo` app
```bash
npm install react-router-dom --save
```
```bash
cd ReactDemos/route-testing-demo
npm install
npm start
```
## React Testing
- documentation - https://testing-library.com/docs/queries/about/
- install Chrome Plugin - Testing Playground
- online Testing Playground - https://testing-playground.com/
- see `ReactDemos/route-testing-demo` application for react testing demo
```bash
cd ReactDemos/route-testing-demo
npm install
npm test
```
- see tests folder for test scripts examples
- run npm test from within the React project from terminal
- you'll see the following result

## Homepage v2 - a complete react app
- install `create-react-app` framework if it's not installed already
- a react application now runs on localhost:3000; just navigate to it on a browser
- if all is ok, you'll see a react welcome page
- if a window pops up regarding access control and permission, just allow it
- see `ReactDemos/homepage-v2` which is completely react-based single-page site
```bash
cd ReactDemos/homepage-v2
npm install
npm start
```
### Notes
- there's only one index.hml public page
- each locallay routed component's content goes in index.html page:
```html
<div id="content" class="container">
<!-- CONTENT OF EACH PAGE GOES HERE-->
</div>
```
- `src/components/navbar.js` file has the client-side navigation
- app doesn't display updated contents/components at times (not sure why!)
- if that happens, I'm not sure how to debug it but try these copule of techniques that have worked for me:
1. restart the server manually to compile jsx
2. embed that component in App.js's App function
#### Demo
- create Research component class in research.js module
- include Publications component in Research component
## Deploy React App to Github.io
- step by step instructions: [https://github.com/gitname/react-gh-pages](https://github.com/gitname/react-gh-pages)
- Facebook's instructions: [https://create-react-app.dev/docs/deployment/#github-pages-https-pagesgithubcom](https://create-react-app.dev/docs/deployment/#github-pages-https-pagesgithubcom)
- create a react app using `create-react-app`
- install gh-pages using npm inside the react app
```bash
npx create-react-app homepage
cd hompage
npm install gh-pages --save
npm install react-router-dom --save
```
- make sure repository setting->Pages->Source branch is set to gh-pages as shown in the following figure

### See deployed single-page homepage
- See Demo app - https://github.com/rambasnet/rambasnet.github.io
| github_jupyter |
# A stylized New Keynesian Model
This notebook is part of a computational appendix that accompanies the paper.
> MATLAB, Python, Julia: What to Choose in Economics?
>
> Coleman, Lyon, Maliar, and Maliar (2017)
In this notebook we summarize the key equations for the stylized New Keynesian model we solved in the paper.
For more information on the model itself see section 5 of
> Maliar, L., & Maliar, S. (2015). Merging simulation and projection approaches to solve high-dimensional problems with an application to a new Keynesian model. Quantitative Economics, 15(7), 424. http://doi.org/10.1186/s13059-014-0424-0
The model features Calvo-type price frictions and a
Taylor (1993) rule. The economy is populated by households, final-good
firms, intermediate-good firms, a monetary authority and government.
In the equations below, the following variables appear:
- $\pi$: profit of intermediate good firms
- $S$, $F$: intermediate variables introduced to help notation below
- $C$: Consumption
- $G$: Level of government spending
- $Y$: Final goods production
- $L$: Labor supply
- $\Delta$: measure of price dispersion across firms (also referred to as efficiency distortion)
- $Y_N$: Natural level of final goods production -- it is the level of $Y$ in the planner's solution, or the level of $Y$ in the model without distorting taxes.
- $\bar{G}$: steady-state share of government spendint in output
- $R$: gross nominal interest rate
- $\eta_u$: exogenous preference shock to utility
- $\eta_L$: exogenous preference shock to labor dis-utility
- $\eta_B$: exogenous premium on bond returns
- $\eta_a$: log of productivity of intermediate goods firms
- $\eta_G$: government spending shock
- $\eta_R$: monetary shock to interest rate
We also see the following parameters:
- $\beta$: discount factor
- $\varepsilon$: Parameter in Dixit-Stiglitz aggregator over intermediate goods
- $\theta$: Calvo-parameter -- a fraction (1-$\theta$) of firms set prices optimally each period.
- $\gamma$, $\vartheta$: utility function parameters
- $\pi^*$: target inflation
- $\phi_y$, $\phi_{\pi}$, $\mu$: Taylor rule parameters
In our computation we will approximate $S_t$, $F_t$ and $C_t$ using a complete monomial of degree N. Given these three variables, we express the equilibrium conditions of the model in the following way:
\begin{eqnarray}
\pi_{t} &=& \left(\frac{1-(1-\theta)}{\theta}\left(\frac{S_t}{F_t}\right)^{1- \varepsilon}\right)^{\frac{1}{\varepsilon-1}} \\
\Delta _{t} &=&\left[ \left( 1-\theta \right) \left[ \frac{1-\theta \pi
_{t}^{\varepsilon -1}}{1-\theta }\right] ^{\frac{\varepsilon }{\varepsilon -1%
}}+\theta \frac{\pi _{t}^{\varepsilon }}{\Delta _{t-1}}\right] ^{-1} \\
Y_t &=& \frac{C_t}{1-\frac{\bar{G}}{\exp\left(\eta_{G,t}\right)}} \\
L_t &=& \frac{Y_t }{\exp\left(\eta_{a,t}\right) \Delta_t} \\
Y_{N,t} &=& \left[ \frac{\exp \left( \eta _{a,t}\right) ^{1+\vartheta }\left[1- \frac{\bar{G}}{\exp \left( \eta _{G,t}\right)} \right] ^{-\gamma}}{\exp \left( \eta_{L,t}\right) }\right] ^{\frac{1}{\vartheta +\gamma }}\\
R_{t} &=& \max \left\{1, \frac{\pi^*}{\beta} \left(R_{t-1} \frac{\beta}{\pi^*} \right)^{\mu} \left(\left(\frac{\pi_t}{\pi^*}\right)^{\phi_{\pi}} \left(\frac{Y_t}{Y_{N,t}} \right)^{\phi_y} \right)^{1-\mu}\exp\left(\eta_{R,t}\right) \right\}.
\end{eqnarray}
The Euler equations are given by
\begin{eqnarray}
S_{t} &=&\frac{\exp \left( \eta _{u,t}+\eta _{L,t}\right) }{\left[ \exp
\left( \eta _{a,t}\right) \right] ^{\vartheta +1}}\frac{\left(
G_{t}^{-1}C_{t}\right) ^{1+\vartheta }}{\left( \Delta _{t}\right)
^{\vartheta }}+\beta \theta E_{t}\left \{ \pi _{t+1}^{\varepsilon
}S_{t+1}\right \} \\
F_{t} &=&\exp \left( \eta _{u,t}\right) C_{t}^{1-\gamma }G_{t}^{-1}+\beta
\theta E_{t}\left \{ \pi _{t+1}^{\varepsilon -1}F_{t+1}\right \} \\
C_{t}^{-\gamma } &=&\beta \frac{\exp \left( \eta _{B,t}\right) }{\exp \left(
\eta _{u,t}\right) }R_{t}E_{t}\left[ \frac{C_{t+1}^{-\gamma }\exp \left(
\eta _{u,t+1}\right) }{\pi _{t+1}}\right]
\end{eqnarray}
| github_jupyter |
# Dataset Distribution
```
import numpy as np
import math
from torch.utils.data import random_split
```
## Calculating Mean & Std
Calculates mean and std of dataset.
```
def get_norm(dataset):
mean = dataset.data.mean(axis=(0, 1, 2)) / 255.
std = dataset.data.std(axis=(0, 1, 2)) / 255.
return mean, std
```
## Split Dataset
Splits dataset into multiple subsets.
### TODO
- [ ] bias
```
def random_split_by_dist(
dataset,
size: int,
dist: callable = None,
**params
):
"""Split `dataset` into subsets by distribution function.
Parameters
----------
dataset : datasets
See `torchvision.datasets` .
size : int
Number (Length) of subsets.
dist : function
Distribution function which retures np.array.
Sum of returned array SHOULD be 1.
Returns
-------
out : subsets
Of `dataset`.
"""
assert size != 0, "`size` > 0"
dist = dist or uniform # default value
# calculates distribution `dist_val`
dist_val = dist(size, **params) # dist_val: np.array
assert math.isclose(sum(dist_val), 1.), "sum of `dist` SHOULD be 1."
N = len(dataset)
result = np.full(size, N) * dist_val
result = np.around(result).astype('int') # to integers
result = result.clip(1, None) # to positive integers
# adjustment for that summation of `result` SHOULD be `N`
result[-1] = N - sum(result[:-1])
while True:
if result[-1] < 1:
result[result.argmax()] -= 1
result[-1] += 1
else:
break
return random_split(dataset, sorted(result))
def uniform(
size: int,
**params # no longer needed
):
assert len(params) == 0, \
"uniform() got an unexpected keyword argument {}".format(
', '.join(["""\'""" + k + """\'""" for k in params.keys()])
)
return np.ones(size) / size
def normal(
size: int,
loc: float = 0.,
scale: float = 1.,
lower: float = 0.,
upper: float = None
):
"""Calculate normal (Gaussian) distribution.
Uses `abs` to restrict to non-zeros.
In fact, it is not a normal distribution because there are only
positive elements in `result`.
See https://numpy.org/doc/stable/reference/random/generated/numpy.random.normal.html .
Parameters
----------
size : int
Number (Length) of chunks.
Same as length of returned np.array.
loc : float
Mean (“centre”) of the distribution.
scale : float
Standard deviation (spread or “width”) of the distribution.
MUST be non-negative.
lower : float
Lower-bound before applying scaling.
upper : float
Upper-bound before applying scaling.
Returns
-------
out : np.array
Returns normal (Gaussian) distribution.
"""
result = np.random.normal(loc, scale, size)
result = abs(result) # `result` SHOULD be only positive.
result = result.clip(lower, upper)
return result / sum(result)
def pareto(
size: int,
alpha: float = 1.16, # by 80-20 rule, log(5)/log(4)
lower: float = 0.,
upper: float = None
):
"""Calculate Pareto distribution.
See https://numpy.org/doc/stable/reference/random/generated/numpy.random.pareto.html .
Parameters
----------
size : int
Number (Length) of chunks.
Same as length of returned np.array.
alpha : float
Shape of the distribution.
Must be positive.
lower : float
Lower-bound before applying scaling.
upper : float
Upper-bound before applying scaling.
Returns
-------
out : np.array
Returns Pareto distribution.
"""
result = np.random.pareto(alpha, size)
result = result.clip(lower, upper)
return result / sum(result)
```
# main
```
if __name__ == "__main__":
from pprint import pprint
import torchvision.datasets as dset
import torchvision.transforms as transforms
"""Test `get_norm`"""
transform = transforms.Compose([
transforms.ToTensor()
])
trainDataset = dset.CIFAR10(root='cifar', train=True, download=True, transform=transform)
pprint(get_norm(trainDataset))
"""Test `adv_random_split`"""
pprint([len(subset) for subset in random_split_by_dist(
trainDataset,
size=10,
dist=pareto,
alpha=2.
)])
```
| github_jupyter |
# `nnetsauce` Examples
Examples of:
- Multitask, AdaBoost, Deep, Random Bag, Ridge2, Ridge2 Multitask, Nonlinear GLM __classifiers__
- Nonlinear GLM model for __regression__
```
!pip install git+https://github.com/techtonique/nnetsauce.git@cythonize --upgrade
```
Multitask Classifier
```
import nnetsauce as ns
import numpy as np
from sklearn.datasets import load_breast_cancer, load_wine, load_iris, make_classification
from sklearn.linear_model import ElasticNet, LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics
from time import time
# dataset no. 1 ----------
breast_cancer = load_breast_cancer()
Z = breast_cancer.data
t = breast_cancer.target
np.random.seed(123)
X_train, X_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
# Linear Regression is used
regr = LinearRegression()
fit_obj = ns.MultitaskClassifier(regr, n_hidden_features=5,
n_clusters=2, type_clust="gmm")
start = time()
fit_obj.fit(X_train, y_train)
print(time() - start)
print(fit_obj.score(X_test, y_test))
print(fit_obj.score(X_test, y_test, scoring="roc_auc"))
start = time()
preds = fit_obj.predict(X_test)
print(time() - start)
print(metrics.classification_report(preds, y_test))
```
AdaBoost
```
import nnetsauce as ns
import numpy as np
from sklearn.datasets import load_breast_cancer, load_wine, load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics
from time import time
# dataset no. 1 ----------
# logistic reg
breast_cancer = load_breast_cancer()
Z = breast_cancer.data
t = breast_cancer.target
np.random.seed(123)
X_train, X_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
# SAMME
clf = LogisticRegression(solver='liblinear', multi_class = 'ovr',
random_state=123)
fit_obj = ns.AdaBoostClassifier(clf,
n_hidden_features=np.int(56.13806152),
direct_link=True,
n_estimators=1000, learning_rate=0.09393372,
col_sample=0.52887573, row_sample=0.87781372,
dropout=0.10216064, n_clusters=2,
type_clust="gmm",
verbose=1, seed = 123,
method="SAMME")
start = time()
fit_obj.fit(X_train, y_train)
print(time() - start)
# 29.34
print(fit_obj.score(X_test, y_test))
preds = fit_obj.predict(X_test)
print(fit_obj.score(X_test, y_test, scoring="roc_auc"))
print(metrics.classification_report(preds, y_test))
# SAMME.R
clf = LogisticRegression(solver='liblinear', multi_class = 'ovr',
random_state=123)
fit_obj = ns.AdaBoostClassifier(clf,
n_hidden_features=np.int(11.22338867),
direct_link=True,
n_estimators=250, learning_rate=0.01126343,
col_sample=0.72684326, row_sample=0.86429443,
dropout=0.63078613, n_clusters=2,
type_clust="gmm",
verbose=1, seed = 123,
method="SAMME.R")
start = time()
fit_obj.fit(X_train, y_train)
print(time() - start)
# 6.906151294708252
print(fit_obj.score(X_test, y_test))
preds = fit_obj.predict(X_test)
print(fit_obj.score(X_test, y_test, scoring="roc_auc"))
print(metrics.classification_report(preds, y_test))
# dataset no. 2 ----------
wine = load_wine()
Z = wine.data
t = wine.target
np.random.seed(123)
Z_train, Z_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
# SAMME
clf = LogisticRegression(solver='liblinear', multi_class = 'ovr',
random_state=123)
fit_obj = ns.AdaBoostClassifier(clf,
n_hidden_features=np.int(8.21154785e+01),
direct_link=True,
n_estimators=1000, learning_rate=2.96252441e-02,
col_sample=4.22766113e-01, row_sample=7.87268066e-01,
dropout=1.56909180e-01, n_clusters=3,
type_clust="gmm",
verbose=1, seed = 123,
method="SAMME")
start = time()
fit_obj.fit(Z_train, y_train)
print(time() - start)
# 22.685115098953247
print(fit_obj.score(Z_test, y_test))
preds = fit_obj.predict(Z_test)
print(metrics.classification_report(preds, y_test))
# dataset no. 3 ----------
iris = load_iris()
Z = iris.data
t = iris.target
np.random.seed(123)
Z_train, Z_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
# SAMME.R
clf = LogisticRegression(solver='liblinear', multi_class = 'ovr',
random_state=123)
fit_obj = ns.AdaBoostClassifier(clf,
n_hidden_features=np.int(19.66918945),
direct_link=True,
n_estimators=250, learning_rate=0.28534302,
col_sample=0.45474854, row_sample=0.87833252,
dropout=0.15603027, n_clusters=0,
verbose=1, seed = 123,
method="SAMME.R")
start = time()
fit_obj.fit(Z_train, y_train)
print(time() - start)
# 1.413327932357788
print(fit_obj.score(Z_test, y_test))
preds = fit_obj.predict(Z_test)
print(metrics.classification_report(preds, y_test))
```
Deep Classifier
```
import nnetsauce as ns
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_digits
digits = load_digits()
X = digits.data
y = digits.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=123)
# layer 1 (base layer) ----
layer1_regr = RandomForestClassifier(n_estimators=10, random_state=123)
layer1_regr.fit(X_train, y_train)
# Accuracy in layer 1
print(layer1_regr.score(X_test, y_test))
# layer 2 using layer 1 ----
layer2_regr = ns.CustomClassifier(obj = layer1_regr, n_hidden_features=5,
direct_link=True, bias=True,
nodes_sim='uniform', activation_name='relu',
n_clusters=2, seed=123)
layer2_regr.fit(X_train, y_train)
# Accuracy in layer 2
print(layer2_regr.score(X_test, y_test))
# layer 3 using layer 2 ----
layer3_regr = ns.CustomClassifier(obj = layer2_regr, n_hidden_features=10,
direct_link=True, bias=True, dropout=0.7,
nodes_sim='uniform', activation_name='relu',
n_clusters=2, seed=123)
layer3_regr.fit(X_train, y_train)
# Accuracy in layer 3
print(layer3_regr.score(X_test, y_test))
```
Random Bag Classifier
```
import nnetsauce as ns
import numpy as np
from sklearn.datasets import load_breast_cancer, load_wine, load_iris, make_classification
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics
from time import time
# dataset no. 1 ----------
breast_cancer = load_breast_cancer()
Z = breast_cancer.data
t = breast_cancer.target
np.random.seed(123)
X_train, X_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
# decision tree
clf = DecisionTreeClassifier(max_depth=2, random_state=123)
fit_obj = ns.RandomBagClassifier(clf, n_hidden_features=2,
direct_link=True,
n_estimators=100,
col_sample=0.9, row_sample=0.9,
dropout=0.3, n_clusters=0, verbose=0)
start = time()
fit_obj.fit(X_train, y_train)
print(time() - start)
#0.8955960273742676
print(fit_obj.score(X_test, y_test))
print(fit_obj.score(X_test, y_test, scoring="roc_auc"))
start = time()
[fit_obj.fit(X_train, y_train) for _ in range(10)]
print(time() - start)
start = time()
preds = fit_obj.predict(X_test)
print(time() - start)
print(metrics.classification_report(preds, y_test))
# dataset no. 2 ----------
wine = load_wine()
Z = wine.data
t = wine.target
np.random.seed(123)
Z_train, Z_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
clf = DecisionTreeClassifier(max_depth=2, random_state=123)
fit_obj = ns.RandomBagClassifier(clf, n_hidden_features=5,
direct_link=True,
n_estimators=100,
col_sample=0.5, row_sample=0.5,
dropout=0.1, n_clusters=3,
type_clust="gmm", verbose=1)
start = time()
fit_obj.fit(Z_train, y_train)
print(time() - start)
# 1.8651049137115479
print(fit_obj.score(Z_test, y_test))
preds = fit_obj.predict(Z_test)
print(metrics.classification_report(preds, y_test))
# dataset no. 3 ----------
iris = load_iris()
Z = iris.data
t = iris.target
np.random.seed(123)
Z_train, Z_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
clf = LogisticRegression(solver='liblinear', multi_class = 'ovr',
random_state=123)
fit_obj = ns.RandomBagClassifier(clf, n_hidden_features=5,
direct_link=False,
n_estimators=100,
col_sample=0.5, row_sample=0.5,
dropout=0.1, n_clusters=0, verbose=0,
n_jobs=1)
start = time()
fit_obj.fit(Z_train, y_train)
print(time() - start)
# 0.4114112854003906
print(fit_obj.score(Z_test, y_test))
# dataset no. 4 ----------
X, y = make_classification(n_samples=2500, n_features=20,
random_state=783451)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=351452)
clf = DecisionTreeClassifier(max_depth=1, random_state=123)
fit_obj = ns.RandomBagClassifier(clf, n_hidden_features=5,
direct_link=True,
n_estimators=100,
col_sample=0.5, row_sample=0.5,
dropout=0.1, n_clusters=3,
type_clust="gmm", verbose=1)
start = time()
fit_obj.fit(X_train, y_train)
print(time() - start)
# 5.983736038208008
print(fit_obj.score(X_test, y_test))
preds = fit_obj.predict(X_test)
print(metrics.classification_report(preds, y_test))
```
Ridge2 Classifier
```
import nnetsauce as ns
import numpy as np
from sklearn.datasets import load_digits, load_breast_cancer, load_wine, load_iris
from sklearn.model_selection import train_test_split
from time import time
# dataset no. 1 ----------
breast_cancer = load_breast_cancer()
X = breast_cancer.data
y = breast_cancer.target
# split data into training test and test set
np.random.seed(123)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# create the model with nnetsauce
fit_obj = ns.Ridge2Classifier(lambda1 = 6.90185578e+04,
lambda2 = 3.17392781e+02,
n_hidden_features=95,
n_clusters=2,
row_sample = 4.63427734e-01,
dropout = 3.62817383e-01,
type_clust = "gmm")
# fit the model on training set
start = time()
fit_obj.fit(X_train, y_train)
print(time() - start)
# get the accuracy on test set
start = time()
print(fit_obj.score(X_test, y_test))
print(time() - start)
# get area under the curve on test set (auc)
print(fit_obj.score(X_test, y_test, scoring="roc_auc"))
# dataset no. 2 ----------
wine = load_wine()
Z = wine.data
t = wine.target
np.random.seed(123)
Z_train, Z_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
# create the model with nnetsauce
fit_obj = ns.Ridge2Classifier(lambda1 = 8.64135756e+04,
lambda2 = 8.27514666e+04,
n_hidden_features=109,
n_clusters=3,
row_sample = 5.54907227e-01,
dropout = 1.84484863e-01,
type_clust = "gmm")
# fit the model on training set
fit_obj.fit(Z_train, y_train)
# get the accuracy on test set
print(fit_obj.score(Z_test, y_test))
# dataset no. 3 ----------
iris = load_iris()
Z = iris.data
t = iris.target
np.random.seed(123)
Z_train, Z_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
# create the model with nnetsauce
fit_obj = ns.Ridge2Classifier(lambda1 = 1.87500081e+04,
lambda2 = 3.12500069e+04,
n_hidden_features=47,
n_clusters=3,
row_sample = 7.37500000e-01,
dropout = 1.31250000e-01,
type_clust = "gmm")
# fit the model on training set
start = time()
fit_obj.fit(Z_train, y_train)
print(time() - start)
# get the accuracy on test set
start = time()
print(fit_obj.score(Z_test, y_test))
print(time() - start)
# dataset no. 4 ----------
digits = load_digits()
Z = digits.data
t = digits.target
np.random.seed(123)
Z_train, Z_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
# create the model with nnetsauce
fit_obj = ns.Ridge2Classifier(lambda1 = 7.11914091e+04,
lambda2 = 4.63867241e+04,
n_hidden_features=13,
n_clusters=0,
row_sample = 7.65039063e-01,
dropout = 5.21582031e-01,
type_clust = "gmm")
# fit the model on training set
fit_obj.fit(Z_train, y_train)
# get the accuracy on test set
print(fit_obj.score(Z_test, y_test))
```
Ridge2 Multitask Classifier
```
import nnetsauce as ns
import numpy as np
from sklearn.datasets import load_breast_cancer, load_wine, load_iris, load_digits, make_classification
from sklearn.model_selection import train_test_split
from sklearn import metrics
from time import time
# dataset no. 1 ----------
breast_cancer = load_breast_cancer()
Z = breast_cancer.data
t = breast_cancer.target
np.random.seed(123)
X_train, X_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
print(Z.shape)
fit_obj = ns.Ridge2MultitaskClassifier(n_hidden_features=np.int(9.83730469e+01),
dropout=4.31054687e-01,
n_clusters=np.int(1.71484375e+00),
lambda1=1.24023438e+01, lambda2=7.30263672e+03)
start = time()
fit_obj.fit(X_train, y_train)
print(time() - start)
print(fit_obj.score(X_test, y_test))
print(fit_obj.score(X_test, y_test, scoring="roc_auc"))
start = time()
preds = fit_obj.predict(X_test)
print(time() - start)
print(metrics.classification_report(preds, y_test))
# dataset no. 2 ----------
wine = load_wine()
Z = wine.data
t = wine.target
np.random.seed(123)
Z_train, Z_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
fit_obj = ns.Ridge2MultitaskClassifier(n_hidden_features=15,
dropout=0.1, n_clusters=3,
type_clust="gmm")
start = time()
fit_obj.fit(Z_train, y_train)
print(time() - start)
print(fit_obj.score(Z_test, y_test))
preds = fit_obj.predict(Z_test)
print(metrics.classification_report(preds, y_test))
# dataset no. 3 ----------
iris = load_iris()
Z = iris.data
t = iris.target
np.random.seed(123)
Z_train, Z_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
fit_obj = ns.Ridge2MultitaskClassifier(n_hidden_features=10,
dropout=0.1, n_clusters=2)
start = time()
fit_obj.fit(Z_train, y_train)
print(time() - start)
print(fit_obj.score(Z_test, y_test))
# dataset no. 4 ----------
X, y = make_classification(n_samples=2500, n_features=20,
random_state=783451)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=351452)
fit_obj = ns.Ridge2MultitaskClassifier(n_hidden_features=5,
dropout=0.1, n_clusters=3,
type_clust="gmm")
start = time()
fit_obj.fit(X_train, y_train)
print(time() - start)
print(fit_obj.score(X_test, y_test))
preds = fit_obj.predict(X_test)
print(metrics.classification_report(preds, y_test))
# dataset no. 5 ----------
digits = load_digits()
X = digits.data
y = digits.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=123)
fit_obj = ns.Ridge2MultitaskClassifier(n_hidden_features=25,
dropout=0.1, n_clusters=3,
type_clust="gmm")
start = time()
fit_obj.fit(X_train, y_train)
print(time() - start)
print(fit_obj.score(X_test, y_test))
start = time()
preds = fit_obj.predict(X_test)
print(time() - start)
print(metrics.classification_report(preds, y_test))
```
GLM Regressor with __loss function plot__
```
import numpy as np
import nnetsauce as ns
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from time import time
import matplotlib.pyplot as plt
boston = load_boston()
X = boston.data
y = boston.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=2020)
print(f"\n Example 1 -----")
obj2 = ns.GLMRegressor(n_hidden_features=3,
lambda1=1e-2, alpha1=0.5,
lambda2=1e-2, alpha2=0.5,
optimizer=ns.optimizers.Optimizer(type_optim="sgd"))
start = time()
obj2.fit(X_train, y_train, learning_rate=0.1, batch_prop=0.25, verbose=1)
print(f"\n Elapsed: {time() - start}")
plt.plot(obj2.optimizer.results[2])
print(obj2.beta)
print("RMSE: ")
print(np.sqrt(obj2.score(X_test, y_test))) # RMSE
print(f"\n Example 2 -----")
obj2.optimizer.type_optim = "scd"
start = time()
obj2.fit(X_train, y_train, learning_rate=0.01, batch_prop=0.8, verbose=1)
print(f"\n Elapsed: {time() - start}")
plt.plot(obj2.optimizer.results[2])
print(obj2.beta)
print("RMSE: ")
print(np.sqrt(obj2.score(X_test, y_test))) # RMSE
print(f"\n Example 3 -----")
obj2.optimizer.type_optim = "sgd"
obj2.set_params(lambda1=1e-2, alpha1=0.1,
lambda2=1e-1, alpha2=0.9)
start = time()
obj2.fit(X_train, y_train, batch_prop=0.25, verbose=1)
print(f"\n Elapsed: {time() - start}")
plt.plot(obj2.optimizer.results[2])
print(obj2.beta)
print("RMSE: ")
print(np.sqrt(obj2.score(X_test, y_test))) # RMSE
print(f"\n Example 4 -----")
obj2.optimizer.type_optim = "scd"
start = time()
obj2.fit(X_train, y_train, learning_rate=0.01, batch_prop=0.8, verbose=1)
print(f"\n Elapsed: {time() - start}")
plt.plot(obj2.optimizer.results[2])
print(obj2.beta)
print("RMSE: ")
print(np.sqrt(obj2.score(X_test, y_test))) # RMSE
print(f"\n Example 5 -----")
obj2.optimizer.type_optim = "sgd"
obj2.set_params(lambda1=1, alpha1=0.5,
lambda2=1e-2, alpha2=0.1)
start = time()
obj2.fit(X_train, y_train, learning_rate=0.1, batch_prop=0.5, verbose=1)
print(f"\n Elapsed: {time() - start}")
plt.plot(obj2.optimizer.results[2])
print(obj2.beta)
print("RMSE: ")
print(np.sqrt(obj2.score(X_test, y_test))) # RMSE
print(f"\n Example 6 -----")
obj2.optimizer.type_optim = "scd"
start = time()
obj2.fit(X_train, y_train, learning_rate=0.1, batch_prop=0.5, verbose=1)
print(f"\n Elapsed: {time() - start}")
plt.plot(obj2.optimizer.results[2])
print(obj2.beta)
print("RMSE: ")
print(np.sqrt(obj2.score(X_test, y_test))) # RMSE
```
GLM Classifier with __loss function plot__
```
import numpy as np
from sklearn.datasets import load_breast_cancer, load_wine, load_iris, make_classification, load_digits
from sklearn.model_selection import train_test_split
from sklearn import metrics
from time import time
import matplotlib.pyplot as plt
print(f"\n method = 'momentum' ----------")
# dataset no. 1 ----------
breast_cancer = load_breast_cancer()
Z = breast_cancer.data
t = breast_cancer.target
np.random.seed(123)
X_train, X_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
print(f"\n 1 - breast_cancer dataset ----------")
fit_obj = ns.GLMClassifier(n_hidden_features=5,
n_clusters=2, type_clust="gmm")
start = time()
fit_obj.fit(X_train, y_train, verbose=1)
print(time() - start)
plt.plot(fit_obj.optimizer.results[2])
print(fit_obj.score(X_test, y_test))
print(fit_obj.score(X_test, y_test, scoring="roc_auc"))
start = time()
preds = fit_obj.predict(X_test)
print(time() - start)
print(metrics.classification_report(preds, y_test))
# dataset no. 2 ----------
wine = load_wine()
Z = wine.data
t = wine.target
np.random.seed(123575)
X_train, X_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
print(f"\n 2 - wine dataset ----------")
fit_obj = ns.GLMClassifier(n_hidden_features=3,
n_clusters=2, type_clust="gmm")
start = time()
fit_obj.fit(X_train, y_train, verbose=1)
print(time() - start)
plt.plot(fit_obj.optimizer.results[2])
print(fit_obj.score(X_test, y_test))
start = time()
preds = fit_obj.predict(X_test)
print(time() - start)
print(metrics.classification_report(preds, y_test))
# dataset no. 3 ----------
iris = load_iris()
Z = iris.data
t = iris.target
np.random.seed(123575)
X_train, X_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
print(f"\n 3 - iris dataset ----------")
fit_obj = ns.GLMClassifier(n_hidden_features=3,
n_clusters=2, type_clust="gmm")
start = time()
fit_obj.fit(X_train, y_train, verbose=1)
print(time() - start)
plt.plot(fit_obj.optimizer.results[2])
print(fit_obj.score(X_test, y_test))
start = time()
preds = fit_obj.predict(X_test)
print(time() - start)
print(metrics.classification_report(preds, y_test))
# dataset no. 4 ----------
X, y = make_classification(n_samples=2500, n_features=20,
random_state=783451)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=351452)
print(f"\n 4 - make_classification dataset ----------")
fit_obj = ns.GLMClassifier(n_hidden_features=5,
dropout=0.1, n_clusters=3,
type_clust="gmm")
start = time()
fit_obj.fit(X_train, y_train, verbose=1)
print(time() - start)
print(fit_obj.score(X_test, y_test))
preds = fit_obj.predict(X_test)
print(metrics.classification_report(preds, y_test))
# dataset no. 5 ----------
digits = load_digits()
X = digits.data
y = digits.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=123)
print(f"\n 5 - digits dataset ----------")
fit_obj = ns.GLMClassifier(n_hidden_features=25,
dropout=0.1, n_clusters=3,
type_clust="gmm")
start = time()
fit_obj.fit(X_train, y_train, verbose=1)
print(time() - start)
print(fit_obj.score(X_test, y_test))
start = time()
preds = fit_obj.predict(X_test)
print(time() - start)
print(metrics.classification_report(preds, y_test))
print(f"\n method = 'exp' ----------")
# dataset no. 1 ----------
breast_cancer = load_breast_cancer()
Z = breast_cancer.data
t = breast_cancer.target
np.random.seed(123)
X_train, X_test, y_train, y_test = train_test_split(Z, t, test_size=0.2)
print(f"\n 1 - breast_cancer dataset ----------")
opt = ns.Optimizer()
opt.set_params(learning_method = "exp")
fit_obj = ns.GLMClassifier(optimizer=opt)
fit_obj.set_params(lambda1=1e-5, lambda2=100)
fit_obj.optimizer.type_optim = "scd"
start = time()
fit_obj.fit(X_train, y_train, verbose=1, learning_rate=0.01, batch_prop=0.5)
print(time() - start)
plt.plot(fit_obj.optimizer.results[2])
print(fit_obj.score(X_test, y_test))
print(fit_obj.score(X_test, y_test, scoring="roc_auc"))
start = time()
preds = fit_obj.predict(X_test)
print(time() - start)
print(metrics.classification_report(preds, y_test))
print(f"\n method = 'poly' ----------")
# dataset no. 1 ----------
print(f"\n 1 - breast_cancer dataset ----------")
opt = ns.Optimizer()
opt.set_params(learning_method = "poly")
fit_obj = ns.GLMClassifier(optimizer=opt)
fit_obj.set_params(lambda1=1, lambda2=1)
fit_obj.optimizer.type_optim = "scd"
start = time()
fit_obj.fit(X_train, y_train, verbose=1, learning_rate=0.001, batch_prop=0.5)
print(time() - start)
plt.plot(fit_obj.optimizer.results[2])
print(fit_obj.score(X_test, y_test))
print(fit_obj.score(X_test, y_test, scoring="roc_auc"))
start = time()
preds = fit_obj.predict(X_test)
print(time() - start)
print(metrics.classification_report(preds, y_test))
```
| github_jupyter |
## Model Components
The 5 main components of a `WideDeep` model are:
1. `wide`
2. `deeptabular`
3. `deeptext`
4. `deepimage`
5. `deephead`
The first 4 of them will be collected and combined by `WideDeep`, while the 5th one can be optionally added to the `WideDeep` model through its corresponding parameters: `deephead` or alternatively `head_layers`, `head_dropout` and `head_batchnorm`.
Through the development of the package, the `deeptabular` component became one of the core values of the package. Currently `pytorch-widedeep` offers three models that can be passed as the `deeptabular` components. The possibilities are numerous, and therefore, that component will be discussed on its own in a separated notebook.
### 1. `wide`
The `wide` component is a Linear layer "plugged" into the output neuron(s). This can be implemented in `pytorch-widedeep` via the `Wide` model.
The only particularity of our implementation is that we have implemented the linear layer via an Embedding layer plus a bias. While the implementations are equivalent, the latter is faster and far more memory efficient, since we do not need to one hot encode the categorical features.
Let's assume we the following dataset:
```
import torch
import pandas as pd
import numpy as np
from torch import nn
df = pd.DataFrame({"color": ["r", "b", "g"], "size": ["s", "n", "l"]})
df.head()
```
one hot encoded, the first observation would be
```
obs_0_oh = (np.array([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])).astype("float32")
```
if we simply numerically encode (label encode or `le`) the values:
```
obs_0_le = (np.array([0, 3])).astype("int64")
```
Note that in the functioning implementation of the package we start from 1, saving 0 for padding, i.e. unseen values.
Now, let's see if the two implementations are equivalent
```
# we have 6 different values. Let's assume we are performing a regression, so pred_dim = 1
lin = nn.Linear(6, 1)
emb = nn.Embedding(6, 1)
emb.weight = nn.Parameter(lin.weight.reshape_as(emb.weight))
lin(torch.tensor(obs_0_oh))
emb(torch.tensor(obs_0_le)).sum() + lin.bias
```
And this is precisely how the linear model `Wide` is implemented
```
from pytorch_widedeep.models import Wide
# ?Wide
wide = Wide(wide_dim=10, pred_dim=1)
wide
```
Note that even though the input dim is 10, the Embedding layer has 11 weights. Again, this is because we save `0` for padding, which is used for unseen values during the encoding process.
As I mentioned, `deeptabular` has enough complexity on its own and it will be described in a separated notebook. Let's then jump to `deeptext`.
### 3. `deeptext`
`pytorch-widedeep` offers one model that can be passed to `WideDeep` as the `deeptext` component, `DeepText`, which is a standard and simple stack of LSTMs on top of word embeddings. You could also add a FC-Head on top of the LSTMs. The word embeddings can be pre-trained. In the future I aim to include some simple pretrained models so that the combination between text and images is fair.
*While I recommend using the `wide` and `deeptabular` models within this package when building the corresponding wide and deep model components, it is very likely that the user will want to use custom text and image models. That is perfectly possible. Simply, build them and pass them as the corresponding parameters. Note that the custom models MUST return a last layer of activations (i.e. not the final prediction) so that these activations are collected by `WideDeep` and combined accordingly. In addition, the models MUST also contain an attribute `output_dim` with the size of these last layers of activations.*
Let's have a look to the `DeepText` class within `pytorch-widedeep`
```
import torch
from pytorch_widedeep.models import DeepText
# ?DeepText
X_text = torch.cat((torch.zeros([5, 1]), torch.empty(5, 4).random_(1, 4)), axis=1)
deeptext = DeepText(vocab_size=4, hidden_dim=4, n_layers=1, padding_idx=0, embed_dim=4)
deeptext
```
You could, if you wanted, add a Fully Connected Head (FC-Head) on top of it
```
deeptext = DeepText(
vocab_size=4,
hidden_dim=8,
n_layers=1,
padding_idx=0,
embed_dim=4,
head_hidden_dims=[8, 4],
)
deeptext
```
Note that since the FC-Head will receive the activations from the last hidden layer of the stack of RNNs, the corresponding dimensions must be consistent.
### 4. DeepImage
Similarly to `deeptext`, `pytorch-widedeep` offers one model that can be passed to `WideDeep` as the `deepimage` component, `DeepImage`, which iseither a pretrained ResNet (18, 34, or 50. Default is 18) or a stack of CNNs, to which one can add a FC-Head. If is a pretrained ResNet, you can chose how many layers you want to defrost deep into the network with the parameter `freeze_n`
```
from pytorch_widedeep.models import DeepImage
# ?DeepImage
X_img = torch.rand((2, 3, 224, 224))
deepimage = DeepImage(head_hidden_dims=[512, 64, 8], head_activation="leaky_relu")
deepimage
deepimage(X_img)
```
if `pretrained=False` then a stack of 4 CNNs are used
```
deepimage = DeepImage(pretrained=False, head_hidden_dims=[512, 64, 8])
deepimage
```
### 5. deephead
The `deephead` component is not defined outside `WideDeep` as the rest of the components.
When defining the `WideDeep` model there is a parameter called `head_layers_dim` (and the corresponding related parameters. See the package documentation) that define the FC-head on top of `DeeDense`, `DeepText` and `DeepImage`.
Of course, you could also chose to define it yourself externally and pass it using the parameter `deephead`. Have a look
```
from pytorch_widedeep.models import WideDeep
# ?WideDeep
```
| github_jupyter |
```
import math, json, os, sys
import keras
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.layers import Dense
from keras.models import Model
from keras.optimizers import Adam
from keras.preprocessing import image
DATA_DIR = 'data'
TRAIN_DIR = os.path.join(DATA_DIR, 'train')
VALID_DIR = os.path.join(DATA_DIR, 'valid')
SIZE = (224, 224)
BATCH_SIZE = 16
num_train_samples = sum([len(files) for r, d, files in os.walk(TRAIN_DIR)])
num_valid_samples = sum([len(files) for r, d, files in os.walk(VALID_DIR)])
num_train_steps = math.floor(num_train_samples/BATCH_SIZE)
num_valid_steps = math.floor(num_valid_samples/BATCH_SIZE)
gen = keras.preprocessing.image.ImageDataGenerator()
val_gen = keras.preprocessing.image.ImageDataGenerator(horizontal_flip=True, vertical_flip=True)
batches = gen.flow_from_directory(TRAIN_DIR, target_size=SIZE, class_mode='categorical', shuffle=True, batch_size=BATCH_SIZE)
val_batches = val_gen.flow_from_directory(VALID_DIR, target_size=SIZE, class_mode='categorical', shuffle=True, batch_size=BATCH_SIZE)
model = keras.applications.resnet50.ResNet50()
classes = list(iter(batches.class_indices))
model.layers.pop()
for layer in model.layers:
layer.trainable=False
last = model.layers[-1].output
x = Dense(len(classes), activation="softmax")(last)
finetuned_model = Model(model.input, x)
finetuned_model.compile(optimizer=Adam(lr=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
for c in batches.class_indices:
classes[batches.class_indices[c]] = c
finetuned_model.classes = classes
early_stopping = EarlyStopping(patience=10)
checkpointer = ModelCheckpoint('resnet50_best.h5', verbose=1, save_best_only=True)
finetuned_model.fit_generator(batches, steps_per_epoch=num_train_steps, epochs=1000, callbacks=[early_stopping, checkpointer], validation_data=val_batches, validation_steps=num_valid_steps)
# finetuned_model.save('resnet50_final.h5')
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout
# Generate dummy data
x_train = np.random.random((1000, 20))
y_train = np.random.randint(2, size=(1000, 1))
x_test = np.random.random((100, 20))
y_test = np.random.randint(2, size=(100, 1))
model = Sequential()
model.add(Dense(64, input_dim=20, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.fit(x_train, y_train,
epochs=20,
batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)
model.predict()
```
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
import os
from hydra.experimental import initialize, initialize_config_module, initialize_config_dir, compose
from omegaconf import OmegaConf
```
# Initializing Hydra
There are several ways to initialize. See the [API docs](https://hydra.cc/docs/next/experimental/compose_api/#api-documentation) for full details.
All methods support both a function call style that changes the global state, and a context style that cleans up when the scope exits.
## initialize()
Initializes Hydra and add the config_path to the config search path.
config_path is relative to the parent of the caller, in this case it is realtive to the directory containing
this Notebook.
```
with initialize(config_path="cloud_app/conf"):
cfg = compose(overrides=["+db=mysql"])
print(cfg)
```
## initialize_config_module()
Initializes Hydra and add the config_module to the config search path.
The config module must be importable (an `__init__.py` must exist at its top level)
```
with initialize_config_module(config_module="cloud_app.conf"):
cfg = compose(overrides=["+db=mysql"])
print(cfg)
```
## initialize_config_dir()
Initializes Hydra and add the config_path to the config search path.
The config_path must be an absolute path on the file system.
```
abs_config_dir=os.path.abspath("cloud_app/conf")
with initialize_config_dir(config_dir=abs_config_dir):
cfg = compose(overrides=["+db=mysql"])
print(cfg)
```
## Global initialization
Calling each of the initilizaiton methods outside of a context changes the global state.
```
initialize(config_path="cloud_app/conf")
compose(overrides=["+db=mysql"])
```
# Config composition
Below are some more interesting demonstrations of config composition
## Config Structure
The `__init__.py` file is needed is needed to help Python find the config files in some scenarios (It can be empty).
```
conf/
├── application
│ ├── bananas.yaml
│ └── donkey.yaml
├── cloud_provider
│ ├── aws.yaml
│ └── local.yaml
├── db
│ ├── mysql.yaml
│ └── sqlite.yaml
├── environment
│ ├── production.yaml
│ └── testing.yaml
├── config.yaml
└── __init__.py
```
```
# compose application specific config (in this case the applicaiton is "donkey")
cfg=compose(overrides= ["+db=mysql", "+environment=production", "+application=donkey"])
print(OmegaConf.to_yaml(cfg))
# compose from config.yaml, this composes a bunch of defaults in:
cfg=compose(config_name="config.yaml")
print(OmegaConf.to_yaml(cfg))
import os
os.environ["AWS_API_KEY"] = "__SOMETHING_FROM_AN_ENV_VARIABLE__"
# compose from config.yaml and override from the default testing
# environment to production and cloud provider to aws.
# Also override the ami id
cfg=compose(
config_name="config.yaml",
overrides=[
"cloud_provider=aws",
"environment=production",
"cloud.ami_id=MY_AMI_ID",
]
)
print(OmegaConf.to_yaml(cfg, resolve=True))
```
| github_jupyter |
# ResNet50 for Species without detritus
```
# License: BSD
# Author: Sasank Chilamkurthy
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
import time
import os
import copy
plt.ion() # interactive mode
DATA_ROOT = "/scratch/robertblackwell/label3a/train/"
DATA_ROOT_TEST = "/scratch/robertblackwell/label3a/test/"
transforms = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Resize((256,256))
])
dataset = torchvision.datasets.ImageFolder(DATA_ROOT, transforms)
dataset_test = torchvision.datasets.ImageFolder(DATA_ROOT_TEST, transforms)
class_names = dataset.classes
class_names, len(class_names)
dataset_sizes = {'train': 15000, 'val': 309, 'test': 1682}
train_set, val_set = torch.utils.data.random_split(dataset, [dataset_sizes['train'], dataset_sizes['val']])
dataloaders = {
'train': torch.utils.data.DataLoader(train_set, batch_size=16, shuffle=True, num_workers=4),
'val': torch.utils.data.DataLoader(val_set, batch_size=16, shuffle=True, num_workers=4),
'test': torch.utils.data.DataLoader(dataset_test, batch_size=16, shuffle=True, num_workers=4),
}
def imshow(inp, title=None):
"""Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0))
# mean = np.array([0.485, 0.456, 0.406])
# std = np.array([0.229, 0.224, 0.225])
# inp = std * inp + mean
inp = np.clip(inp, 0, 1)
plt.imshow(inp)
# if title is not None:
# plt.title(title)
plt.pause(0.001) # pause a bit so that plots are updated
# Get a batch of training data
inputs, classes = next(iter(dataloaders['train']))
# Make a grid from batch
out = torchvision.utils.make_grid(inputs)
plt.figure(figsize=(20, 20))
imshow(out, title=[dataset.classes[x] for x in classes])
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
if phase == 'train':
scheduler.step()
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print('{} Loss: {:.4f} Acc: {:.4f}'.format(
phase, epoch_loss, epoch_acc))
# deep copy the model
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
print()
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60, time_elapsed % 60))
print('Best val Acc: {:4f}'.format(best_acc))
# load best model weights
model.load_state_dict(best_model_wts)
return model
def visualize_model(model, num_images=6):
was_training = model.training
model.eval()
images_so_far = 0
fig = plt.figure()
with torch.no_grad():
for i, (inputs, labels) in enumerate(dataloaders['val']):
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
for j in range(inputs.size()[0]):
images_so_far += 1
ax = plt.subplot(num_images//2, 2, images_so_far)
ax.axis('off')
ax.set_title('predicted: {}/{}'.format(class_names[preds[j]],class_names[labels[j]]))
imshow(inputs.cpu().data[j])
if images_so_far == num_images:
model.train(mode=was_training)
return
model.train(mode=was_training)
model_ft = torchvision.models.resnet50(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = torch.nn.Linear(num_ftrs, 38)
model_ft = model_ft.to(device)
criterion = torch.nn.CrossEntropyLoss()
# Observe that all parameters are being optimized
optimizer_ft = torch.optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)
# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)
model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,
num_epochs=25)
visualize_model(model_ft,10)
def evaluate(model,dataloader,dataset_size):
since = time.time()
model.eval()
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs, labels in dataloader:
inputs = inputs.to(device)
labels = labels.to(device)
# forward
# track history if only in train
with torch.set_grad_enabled(False):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
test_loss = running_loss / dataset_size
test_acc = running_corrects.double() / dataset_size
print()
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60, time_elapsed % 60))
print('Test Loss: {:.4f} Acc: {:.4f}'.format(
test_loss, test_acc))
evaluate(model_ft, dataloaders['test'], dataset_sizes['test'])
nb_classes = 38
confusion_matrix = torch.zeros(nb_classes, nb_classes)
with torch.no_grad():
for i, (inputs, classes) in enumerate(dataloaders['test']):
inputs = inputs.to(device)
classes = classes.to(device)
outputs = model_ft(inputs)
_, preds = torch.max(outputs, 1)
for t, p in zip(classes.view(-1), preds.view(-1)):
confusion_matrix[t.long(), p.long()] += 1
print(confusion_matrix.double())
torch.set_printoptions(sci_mode=False)
print(confusion_matrix.tolist())
import seaborn as sn
import pandas as pd
df_cm = pd.DataFrame(confusion_matrix.numpy().astype(np.int32), index = [i for i in class_names],
columns = [i for i in class_names])
plt.figure(figsize = (15,15))
sn.set(font_scale=1.4) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 8},fmt='g') # font size
torch.save(model_ft.state_dict(), "/scratch/models/torch_resnet50_label3a.pth")
! pwd
def evaluate(confusion_matrix, classes):
true_pos = np.diag(confusion_matrix)
false_pos = np.sum(confusion_matrix, axis=0) - true_pos
false_neg = np.sum(confusion_matrix, axis=1) - true_pos
accuracy = sum(true_pos) / np.sum(confusion_matrix)
precision = (true_pos / (true_pos + false_pos))
recall = (true_pos / (true_pos + false_neg))
f1 = 2*precision*recall / (precision + recall)
print(precision)
print(recall)
precision = np.mean(precision)
recall = np.mean(recall)
f1 = np.mean(f1)
return precision, recall, accuracy, f1
evaluate(confusion_matrix.numpy(),39)
```
| github_jupyter |
reduce
```
from functools import reduce
a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]
reduce(lambda x,y:x+y,a+b)
reduce(lambda x,y:x+y,a+c)
reduce(lambda x,y:x+y,c+b)
reduce(lambda x,y:x+y,a)
reduce(lambda x,y:x+y,b)
reduce(lambda x,y:x+y,c)
reduce(lambda x,y:x+y,a+b+c)
max_find = lambda a,b: a if (a>b) else b
max_find(5,6)
max_find(9,5)
max_find(a,b)
max_find(b,c)
max_find(c,a)
a = [1,2,3,99]
b = [5,6,7,8]
c = [9,10,11,12]
max_find(c,a)
a = [19,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]
max_find(c,a)
reduce(max_find,a)
reduce(max_find,c)
k =range(4)
k
print(k)
for i in k:
print(i)
```
## filter
```
def even_check(num):
if num%2 ==0:
return True
x = filter(even_check,k)
x
for i in x:
print(i)
tuple(x)
list(x)
x
```
## ZIP
```
a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]
x1 = zip(a,b)
print(x1)
for i in x1:
print(i)
x2 = list(zip(c,a))
x2
d1 = {'a':1,'b':2}
d2 = {'c':4,'d':5}
dir1 = zip(d1,d2)
dir1
for i in dir1:
print(i)
dir2 = zip(d1.values(),d2)
for i in dir2:
print(i)
dir3 = zip(d1.values(),d2.values())
for i in dir3:
print(i)
def switcharoo(d1,d2):
dout = {}
for d1key,d2val in zip(d1,d2.values()):
dout[d1key] = d2val
return dout
switcharoo(d1,d2)
```
## Enumerate
```
a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]
for number,item in enumerate(b):
print (f"The position is {number}:")
print(item)
for number,item in enumerate(a):
print (f"The position is {number}:")
print(item)
```
## Any and All
```
makes = [True,True,False,True]
all(makes)
any(makes)
makes2 = [False,False,False,False]
all(makes2)
any(makes2)
makes3 = [True,True,True,True]
all(makes3)
any(makes3)
```
COMPLEX
```
complex(45,2)
```
# TEST
```
def word_lengths(phrase):
return list(map(len, phrase.split()))
word_lengths('How long are the words in this phrase')
k = "Hello world "
k.split()
len(k.split())
m = "How long are the words in this phrase"
m.split()
len(m.split())
pixel = map(len,m.split())
for a in pixel:
print(a)
x = list[lambda x,y:x*10 + y,[3,4,3,2,1]]
print(x)
for i in x:
print(x)
def filter_words(word_list, letter):
return list(filter(lambda word:word[0]==letter,word_list))
words = ['hello','are','cat','dog','ham','hi','go','to','heart']
filter_words(words,'h')
m = "How long are the words in this phrase"
filter_words(m,'o')
def concatenate(L1, L2, connector):
return [word1+connector+word2 for (word1,word2) in zip(L1,L2)]
concatenate(['A','B'],['a','b'],'&&&&&')
def count_match_index(L):
return len([num for count,num in enumerate(L) if num==count])
count_match_index([0,2,2,1,5,5,6,10])
```
| github_jupyter |
# MNIST - Lightning ⚡️ Syft Duet - Data Scientist 🥁
## PART 1: Connect to a Remote Duet Server
As the Data Scientist, you want to perform data science on data that is sitting in the Data Owner's Duet server in their Notebook.
In order to do this, we must run the code that the Data Owner sends us, which importantly includes their Duet Session ID. The code will look like this, importantly with their real Server ID.
```
import syft as sy
duet = sy.duet('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
```
This will create a direct connection from my notebook to the remote Duet server. Once the connection is established all traffic is sent directly between the two nodes.
Paste the code or Server ID that the Data Owner gives you and run it in the cell below. It will return your Client ID which you must send to the Data Owner to enter into Duet so it can pair your notebooks.
```
import torch
import torchvision
import syft as sy
from torch import nn
from pytorch_lightning import Trainer
from pytorch_lightning.experimental.plugins.secure.pysyft import SyLightningModule
from pytorch_lightning.utilities.imports import is_syft_initialized
from pytorch_lightning.metrics import Accuracy
from syft.util import get_root_data_path
duet = sy.join_duet(loopback=True)
sy.client_cache["duet"] = duet
assert is_syft_initialized()
```
## PART 2: Setting up a Model and our Data
The majority of the code below has been adapted closely from the original PyTorch MNIST example which is available in the `original` directory with these notebooks.
The `duet` variable is now your reference to a whole world of remote operations including supported libraries like torch.
Lets take a look at the duet.torch attribute.
```
duet.torch
```
Lets create a model just like the one in the MNIST example. We do this in almost the exact same way as in PyTorch. The main difference is we inherit from sy.Module instead of nn.Module and we need to pass in a variable called torch_ref which we will use internally for any calls that would normally be to torch.
```
class SyNet(sy.Module):
def __init__(self, torch_ref) -> None:
super(SyNet, self).__init__(torch_ref=torch_ref)
self.conv1 = self.torch_ref.nn.Conv2d(1, 32, 3, 1)
self.conv2 = self.torch_ref.nn.Conv2d(32, 64, 3, 1)
self.dropout1 = self.torch_ref.nn.Dropout2d(0.25)
self.dropout2 = self.torch_ref.nn.Dropout2d(0.5)
self.fc1 = self.torch_ref.nn.Linear(9216, 128)
self.fc2 = self.torch_ref.nn.Linear(128, 10)
self.train_acc = Accuracy()
self.test_acc = Accuracy()
def forward(self, x):
x = self.conv1(x)
x = self.torch_ref.nn.functional.relu(x)
x = self.conv2(x)
x = self.torch_ref.nn.functional.relu(x)
x = self.torch_ref.nn.functional.max_pool2d(x, 2)
x = self.dropout1(x)
x = self.torch_ref.flatten(x, 1)
x = self.fc1(x)
x = self.torch_ref.nn.functional.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = self.torch_ref.nn.functional.log_softmax(x, dim=1)
return output
class LiftSyLightningModule(SyLightningModule):
def __init__(self, module, duet):
super().__init__(module, duet)
def train(self, mode: bool = True):
if self.is_remote:
return self.remote_model.train(mode)
else:
return self.module.train(mode)
def eval(self):
return self.train(False)
def training_step(self, batch, batch_idx):
data_ptr, target_ptr = batch[0], batch[1] # batch is list so no destructuring
output = self.forward(data_ptr)
loss = self.torch.nn.functional.nll_loss(output, target_ptr)
target = target_ptr.get(delete_obj=False)
real_output = output.get(delete_obj=False)
self.log("train_acc", self.module.train_acc(real_output.argmax(-1), target), on_epoch=True, prog_bar=True)
return loss
def test_step(self, batch, batch_idx):
data, target = batch[0], batch[1] # batch is list so no destructuring
output = self.forward(data)
loss = self.torch.nn.functional.nll_loss(output, target)
self.log("test_loss", loss, on_step=True, on_epoch=True, prog_bar=True)
def configure_optimizers(self):
optimizer = self.torch.optim.SGD(self.model.parameters(), lr=0.1)
return optimizer
@property
def torchvision(self):
tv = duet.torchvision if self.is_remote() else torchvision
return tv
def get_transforms(self):
current_list = duet.python.List if self.is_remote() else list
transforms = current_list()
transforms.append(self.torchvision.transforms.ToTensor())
transforms.append(self.torchvision.transforms.Normalize(0.1307, 0.3081))
transforms_compose = self.torchvision.transforms.Compose(transforms)
return transforms_compose
def train_dataloader(self):
transforms_ptr = self.get_transforms()
train_dataset_ptr = self.torchvision.datasets.MNIST(
str(get_root_data_path()),
train=True,
download=True,
transform=transforms_ptr,
)
train_loader_ptr = self.torch.utils.data.DataLoader(
train_dataset_ptr, batch_size=500
)
return train_loader_ptr
def test_dataloader(self):
transforms = self.get_transforms()
test_dataset = self.torchvision.datasets.MNIST(
str(get_root_data_path()),
train=False,
download=True,
transform=transforms,
)
test_loader = self.torch.utils.data.DataLoader(test_dataset, batch_size=1)
return test_loader
module = SyNet(torch)
model = LiftSyLightningModule(module=module, duet=duet)
limit_train_batches = 1.0 # 1.0 is 100% of data
trainer = Trainer(
default_root_dir="./",
max_epochs=1,
limit_train_batches=limit_train_batches
)
trainer.fit(model)
model = LiftSyLightningModule.load_from_checkpoint(
trainer.checkpoint_callback.best_model_path, module=module, duet=duet
)
if not model.module.is_local:
local_model = model.module.get(
request_block=True,
reason="test evaluation",
timeout_secs=5
)
else:
local_model = model
torch.save(local_model.state_dict(), "weights.pt")
from torch import nn
class NormalModel(nn.Module):
def __init__(self) -> None:
super(NormalModel, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = nn.functional.relu(x)
x = self.conv2(x)
x = nn.functional.relu(x)
x = nn.functional.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = nn.functional.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = nn.functional.log_softmax(x, dim=1)
return output
torch_model = NormalModel()
saved_state_dict = torch.load("weights.pt")
torch_model.load_state_dict(saved_state_dict)
# TorchVision hotfix https://github.com/pytorch/vision/issues/3549
from syft.util import get_root_data_path
from torchvision import datasets
import torch.nn.functional as F
datasets.MNIST.resources = [
(
"https://ossci-datasets.s3.amazonaws.com/mnist/train-images-idx3-ubyte.gz",
"f68b3c2dcbeaaa9fbdd348bbdeb94873",
),
(
"https://ossci-datasets.s3.amazonaws.com/mnist/train-labels-idx1-ubyte.gz",
"d53e105ee54ea40749a09fcbcd1e9432",
),
(
"https://ossci-datasets.s3.amazonaws.com/mnist/t10k-images-idx3-ubyte.gz",
"9fb629c4189551a2d022fa330f9573f3",
),
(
"https://ossci-datasets.s3.amazonaws.com/mnist/t10k-labels-idx1-ubyte.gz",
"ec29112dd5afa0611ce80d1b7f02629c",
),
]
batch_size_test = 100
test_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST(
get_root_data_path(),
train=False, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.1307,), (0.3081,))
])
),
batch_size=batch_size_test, shuffle=True
)
def test(network, test_loader):
network.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
output = network(data)
test_loss += F.nll_loss(output, target, size_average=False).item()
pred = output.data.max(1, keepdim=True)[1]
correct += pred.eq(target.data.view_as(pred)).sum()
test_loss /= len(test_loader.dataset)
accuracy = 100. * correct / len(test_loader.dataset)
print('\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(test_loss, correct, len(test_loader.dataset), accuracy))
return accuracy.item()
result = test(torch_model, test_loader)
expected_accuracy = 93.0
assert result > expected_accuracy
```
| github_jupyter |
# 8 Benefis of Unit Testing
[8 benefits of unit testing](https://dzone.com/articles/top-8-benefits-of-unit-testing)
The goal of unit testing is to segregate each part of the program and test that the individual parts are working correctly.
1. It isolates the smallest piece of testable software from the remainder of the code and determines whether it behaves exactly as you expect.
1. Unit testing has proven its value in that a large percentage of defects are identified during its use.
1. It allows automation of the testing process, reduces difficulties of discovering errors contained in more complex pieces of the application, and enhances test coverage because attention is given to each unit.
## 1. Makes the Process Agile
One of the main benefits of unit testing is that it makes the coding process more Agile. When you add more and more features to a software, you sometimes need to change old design and code. However, changing already-tested code is both risky and costly. If we have unit tests in place, then we can proceed for refactoring confidently.
Unit testing really goes hand-in-hand with agile programming of all flavors because it builds in tests that allow you to make changes more easily. In other words, unit tests facilitate safe refactoring.
## 2. Quality of Code
Unit testing improves the quality of the code. It identifies every defect that may have come up before code is sent further for integration testing. Writing tests before actual coding makes you think harder about the problem. It exposes the edge cases and makes you write better code.
## 3. Finds Software Bugs Early
Issues are found at an early stage. Since unit testing is carried out by developers who test individual code before integration, issues can be found very early and can be resolved then and there without impacting the other pieces of the code. This includes both bugs in the programmer’s implementation and flaws or missing parts of the specification for the unit.
## 4. Facilitates Changes and Simplifies Integration
Unit testing allows the programmer to refactor code or upgrade system libraries at a later date and make sure the module still works correctly. Unit tests detect changes that may break a design contract. They help with maintaining and changing the code.
Unit testing reduces defects in the newly developed features or reduces bugs when changing the existing functionality.
Unit testing verifies the accuracy of the each unit. Afterward, the units are integrated into an application by testing parts of the application via unit testing. Later testing of the application during the integration process is easier due to the verification of the individual units.
## 5. Provides Documentation
Unit testing provides documentation of the system. Developers looking to learn what functionality is provided by a unit and how to use it can look at the unit tests to gain a basic understanding of the unit’s interface (API).
## 6. Debugging Process
Unit testing helps simplify the debugging process. If a test fails, then only the latest changes made in the code need to be debugged.
## 7. Design
Writing the test first forces you to think through your design and what it must accomplish before you write the code. This not only keeps you focused; it makes you create better designs. Testing a piece of code forces you to define what that code is responsible for. If you can do this easily, that means the code’s responsibility is well-defined and therefore that it has high cohesion.
## 8. Reduce Costs
Since the bugs are found early, unit testing helps reduce the cost of bug fixes. Just imagine the cost of a bug found during the later stages of development, like during system testing or during acceptance testing. Of course, bugs detected earlier are easier to fix because bugs detected later are usually the result of many changes, and you don’t really know which one caused the bug.
# Getting Started With Testing in Python
[Getting Started With Testing in Python
](https://realpython.com/python-testing/)
## Automated vs. Manual Testing
* To have a complete set of manual tests, all you need to do is make a list of all the features your application has, the different types of input it can accept, and the expected results. Now, every time you make a change to your code, you need to go through every single item on that list and check it.
* Automated testing is the execution of your test plan (the parts of your application you want to test, the order in which you want to test them, and the expected responses) by a script instead of a human. Python already comes with a set of tools and libraries to help you create automated tests for your application.
## Unit Tests vs. Integration Tests
* Think of how you might test the lights on a car. You would turn on the lights (known as the test step) and go outside the car or ask a friend to check that the lights are on (known as the test assertion). Testing multiple components is known as integration testing.
* Think of all the things that need to work correctly in order for a simple task to give the right result. These components are like the parts to your application, all of those classes, functions, and modules you’ve written.
You have just seen two types of tests:
1. An integration test checks that components in your application operate with each other.
1. A unit test checks a small component in your application.
You can write both integration tests and unit tests in Python.
```
# To write a unit test for the built-in function sum(), you would check the output of sum() against a known output.
assert sum([1, 2, 3]) == 6, "Should be 6"
# If the result from sum() is incorrect, this will fail with an AssertionError and the message "Should be 6".
assert sum([1, 1, 1]) == 6, "Should be 6"
# Instead of testing on the REPL, you’ll want to put this into a new Python file called test_sum.py and execute it again:
def test_sum():
assert sum([1, 2, 3]) == 6, "Should be 6"
test_sum()
print("Everything passed")
def test_sum_tuple():
assert sum((1, 2, 2)) == 6, "Should be 6"
test_sum()
test_sum_tuple()
print("Everything passed")
```
# Choosing a Test Runner
* [Pytest](https://docs.pytest.org/en/latest/)
* [Getting Started with Pytest](https://docs.pytest.org/en/latest/getting-started.html)
There are many test runners available for Python. The one built into the Python standard library is called unittest. In this tutorial, you will be using unittest test cases and the unittest test runner. The principles of unittest are easily portable to other frameworks. The three most popular test runners are:
* unittest
* nose or nose2
* **pytest** *(we'll use pytest)*
content of [test_sample.py](test_sample.py)
```
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
!pytest test_sample.py
```
contents of [test_sysexit.py](test_sysexit.py)
```
# content of test_sysexit.py
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
# Execute the test function with “quiet” reporting mode:
!pytest -q test_sysexit.py
```
## Group multiple tests in a class
Once you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a class containing more than one test.
pytest discovers all tests following its Conventions for Python test discovery, so it finds both test_ prefixed functions. There is no need to subclass anything. We can simply run the module by passing its filename:
contentx of [test_class.py](test_class.py)
```
# content of test_class.py
class TestClass(object):
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
!pytest -q test_class.py
```
## Request a unique temporary directory for functional tests¶
pytest provides Builtin fixtures/function arguments to request arbitrary resources, like a unique temporary directory:
contents of [test_tmpdir.py](test_tmpdir.py)
```
# content of test_tmpdir.py
def test_needsfiles(tmpdir):
print(tmpdir)
assert 0
!pytest -q test_tmpdir.py
```
You can use the tmp_path fixture which will provide a temporary directory unique to the test invocation, created in the base temporary directory.
contents of [test_tmppath.py](test_tmppath.py)
```
# content of test_tmp_path.py
import os
CONTENT = u"content"
def test_create_file(tmp_path):
d = tmp_path / "sub"
d.mkdir()
p = d / "hello.txt"
p.write_text(CONTENT)
assert p.read_text() == CONTENT
assert len(list(tmp_path.iterdir())) == 1
```
| github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Distributed Training in TensorFlow
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/distribute_strategy."><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/distribute_strategy.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/guide/distribute_strategy.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
## Overview
The `tf.distribute.Strategy` API is an easy way to distribute your training
across multiple devices/machines. Our goal is to allow users to use existing
models and training code with minimal changes to enable distributed training.
Currently, in core TensorFlow, we support `tf.distribute.MirroredStrategy`. This
does in-graph replication with synchronous training on many GPUs on one machine.
Essentially, we create copies of all variables in the model's layers on each
device. We then use all-reduce to combine gradients across the devices before
applying them to the variables to keep them in sync.
Many other strategies are available in TensorFlow 1.12+ contrib and will soon be
available in core TensorFlow. You can find more information about them in the
contrib
[README](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute).
You can also read the
[public design review](https://github.com/tensorflow/community/blob/master/rfcs/20181016-replicator.md)
for updating the `tf.distribute.Strategy` API as part of the move from contrib
to core TF.
## Example with Keras API
Let's see how to scale to multiple GPUs on one machine using `MirroredStrategy`
with [tf.keras](https://www.tensorflow.org/guide/keras).
We will take a very simple model consisting of a single layer. First, we will import Tensorflow.
```
!pip install tf-nightly
import tensorflow as tf
```
To distribute a Keras model on multiple GPUs using `MirroredStrategy`, we first instantiate a `MirroredStrategy` object.
```
strategy = tf.distribute.MirroredStrategy()
```
We then create and compile the Keras model in `strategy.scope`.
```
with strategy.scope():
inputs = tf.keras.layers.Input(shape=(1,))
predictions = tf.keras.layers.Dense(1)(inputs)
model = tf.keras.models.Model(inputs=inputs, outputs=predictions)
model.compile(loss='mse',
optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.2))
```
Let's also define a simple input dataset for training this model.
```
train_dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(10000).batch(10)
```
To train the model we call Keras `fit` API using the input dataset that we
created earlier, same as how we would in a non-distributed case.
```
model.fit(train_dataset, epochs=5, steps_per_epoch=10)
```
Similarly, we can also call `evaluate` and `predict` as before using appropriate
datasets.
```
eval_dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.evaluate(eval_dataset, steps=10)
predict_dataset = tf.data.Dataset.from_tensors(([1.])).repeat(10).batch(2)
model.predict(predict_dataset, steps=10)
```
That's all you need to train your model with Keras on multiple GPUs with
`MirroredStrategy`. It will take care of splitting up
the input dataset, replicating layers and variables on each device, and
combining and applying gradients.
The model and input code does not have to change because we have changed the
underlying components of TensorFlow (such as optimizer, batch norm and
summaries) to become strategy-aware. That means those components know how to
combine their state across devices. Further, saving and checkpointing works
seamlessly, so you can save with one or no distribute strategy and resume with
another.
## Example with Estimator API
You can also use `tf.distribute.Strategy` API with
[`Estimator`](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator).
Let's see a simple example of it's usage with `MirroredStrategy`.
We will use the `LinearRegressor` premade estimator as an example. To use `MirroredStrategy` with Estimator, all we need to do is:
* Create an instance of the `MirroredStrategy` class.
* Pass it to the
[`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig)
parameter of the custom or premade `Estimator`.
```
strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(train_distribute=strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
```
We will define a simple input function to feed data for training this model.
```
def input_fn():
return tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.])).repeat(10000).batch(10)
```
Then we can call `train` on the regressor instance to train the model.
```
regressor.train(input_fn=input_fn, steps=10)
```
And we can `evaluate` to evaluate the trained model.
```
regressor.evaluate(input_fn=input_fn, steps=10)
```
That's it! This change will now configure estimator to run on all GPUs on your
machine.
## Customization and Performance Tips
Above, we showed the easiest way to use `MirroredStrategy`. There are few things
you can customize in practice:
* You can specify a list of specific GPUs (using param `devices`), in case you
don't want auto detection.
* You can specify various parameters for all reduce with the
`cross_device_ops` param, such as the all reduce algorithm to use, and
gradient repacking.
We've tried to make it such that you get the best performance for your existing
model without having to specify any additional options. We also recommend you
follow the tips from
[Input Pipeline Performance Guide](https://www.tensorflow.org/performance/datasets_performance).
Specifically, we found using
[`map_and_batch`](https://www.tensorflow.org/performance/datasets_performance#map_and_batch)
and
[`dataset.prefetch`](https://www.tensorflow.org/performance/datasets_performance#pipelining)
in the input function gives a solid boost in performance. When using
`dataset.prefetch`, use `buffer_size=tf.data.experemental.AUTOTUNE` to let it detect optimal buffer size.
## Caveats
This API is still in progress there are a lot of improvements forthcoming:
* Summaries are only computed in the first replica in `MirroredStrategy`.
* PartitionedVariables are not supported yet.
* Performance improvements, especially w.r.t. input handling, eager execution
etc.
## What's next?
`tf.distribute.Strategy` is actively under development and we will be adding more examples and tutorials in the near future. Please give it a try, we welcome your feedback via [issues on GitHub](https://github.com/tensorflow/tensorflow/issues/new).
| github_jupyter |
# Mapping subtypes to clusters using drivers (Figure 4)
```
from __future__ import division
import sys
import random
import copy
import math
import json
import numpy as np
import pandas as pd
import scipy
%matplotlib inline
from matplotlib import pyplot as plt
import matplotlib as mpl
import seaborn as sns
sys.path.append("../resources/")
import sct
reload(sct)
sns.set_style("ticks")
sns.set_context("talk")
output_dir = "out/"
output_suffix = ""
output_formats = [".png", ".pdf"]
def save_figure(fig, name):
for output_format in output_formats:
fig.savefig(output_dir + "/" + name + output_suffix + output_format)
return None
mpl.rc('savefig', dpi=300)
pd.options.mode.chained_assignment = None # default='warn'
```
# Load data
```
df_logCPM_all = pd.read_csv("../data/htseq_logCPM_hq.tab.gz", sep="\t", header=0, index_col=0) # CPM
df_libs = pd.read_csv("../data/libs.csv", sep=",", header=0, index_col=0) # sample info
```
# Filter for cells in Figure 4 (GH146, NP5103)
```
# Load names of high quality neurons (4/5 markers)
names_hq_neurons = []
with open("../data/names_hq_neurons.txt") as f:
for line in f:
names_hq_neurons.append(line.rstrip())
# Load names of contaminating neurons (vPN, APL)
names_vPN = []
with open("../data/names_vPN.txt") as f:
for line in f:
names_vPN.append(line.rstrip())
names_APL = []
with open("../data/names_APL.txt") as f:
for line in f:
names_APL.append(line.rstrip())
# Get names of neurons, astrocytes
selector = ((df_libs["genotype"] == "GH146-GFP") &
(df_libs["num_cells"] == 1))
names_GH146 = [x for x in list(df_logCPM_all.columns) if x in df_libs.loc[selector].index and
x in names_hq_neurons and
x not in names_vPN and
x not in names_APL]
print "GH146", len(names_GH146)
# Identify NP5103-GFP cells expressing trol
selector = ((df_libs["genotype"] == "NP5103-GFP") &
(df_libs["num_cells"] == 1))
names_NP5103 = [x for x in list(df_logCPM_all.columns) if x in df_libs.loc[selector].index and
x in names_hq_neurons and
x not in names_vPN and
x not in names_APL]
print "NP5103", len(names_NP5103)
names_NP5103_trol = list(df_logCPM_all[names_NP5103].columns[np.where(df_logCPM_all[names_NP5103].loc["trol"] > 3)])
print "NP5103 trol+", len(names_NP5103_trol)
# Filter for these cells
names_genotypes = names_GH146 + names_NP5103_trol
df = df_logCPM_all[list(names_genotypes)]
print "Number of cells", len(names_genotypes)
# Display number of cells of each genotype
df_libs.loc[df.columns]["genotype"].value_counts()
```
# Load genes found by ICIM
```
genes_GH146_ICIM = []
with open("../data/genes_GH146_ICIM.txt") as f:
for line in f:
genes_GH146_ICIM.append(line.rstrip())
```
# Display cells using ICIM/TSNE
```
# Subset data to genes desired
Y = df.loc[genes_GH146_ICIM]
# Calculate TSNE
reload(sct)
from sklearn.manifold import TSNE
myTSNE = sct.TSNE(Y, df, df_libs)
myTSNE.calc_TSNE(perplexity=15, learning_rate=1000)
# Plot TSNE colored by genotype
fig, ax = plt.subplots(1, 1, figsize=(6,4))
myTSNE.plot(fig, ax, colorMode="genotype")
# Plot TSNE
fig, ax = plt.subplots(1, 1, figsize=(6,4))
myTSNE.plot(fig, ax, colorBy="trol", cmap="Reds")
```
| github_jupyter |
```
import numpy as np
from astropy import units
import pyccl as ccl
import sacc
import sys
sys.path.append('../../')
from matplotlib import pyplot as plt
```
# Set up cosmology
```
cosmo = ccl.Cosmology(Omega_c=0.25,
Omega_b=0.05,
h=0.7,
n_s=0.965,
A_s=2.11e-9,
Omega_k=0.0,
Neff=3.046,
matter_power_spectrum='linear')
b1_unwise = 1.0
s1_unwise = 0.4
cosmo
```
# Set up binning
```
ell_max = 600
n_ell = 20
delta_ell = ell_max // n_ell
ells = (np.arange(n_ell) + 0.5) * delta_ell
ells_win = np.arange(ell_max + 1)
wins = np.zeros([n_ell, len(ells_win)])
for i in range(n_ell):
wins[i, i * delta_ell : (i + 1) * delta_ell] = 1.0
Well = sacc.BandpowerWindow(ells_win, wins.T)
```
# Set up unWISE tracer
```
dndz_unwise = np.loadtxt('../../soliket/xcorr/data/dndz.txt')
ngal_unwise = 1.
fsky_unwise = 0.4
tracer_unwise_g = ccl.NumberCountsTracer(cosmo,
has_rsd=False,
dndz=dndz_unwise.T,
bias=(dndz_unwise[:,0], b1_unwise * np.ones(len(dndz_unwise[:,0]))),
mag_bias=(dndz_unwise[:,0], s1_unwise * np.ones(len(dndz_unwise[:,0])))
)
Nell_unwise_g = np.ones(n_ell) / (ngal_unwise * (60 * 180 / np.pi)**2)
```
# Set up SO CMB lensing tracer
```
zstar = 1086
fsky_solensing = 0.4
tracer_so_k = ccl.CMBLensingTracer(cosmo, z_source=zstar)
# Approximation to SO LAT beam
fwhm_so_k = 1. * units.arcmin
sigma_so_k = (fwhm_so_k.to(units.rad).value / 2.355)
ell_beam = np.arange(3000)
beam_so_k = np.exp(-ell_beam * (ell_beam + 1) * sigma_so_k**2)
```
# Calculate power spectra
```
n_maps = 2
cls = np.zeros([n_maps, n_maps, n_ell])
cls[0, 0, :] = ccl.angular_cl(cosmo, tracer_unwise_g, tracer_unwise_g, ells) + Nell_unwise_g
cls[0, 1, :] = ccl.angular_cl(cosmo, tracer_unwise_g, tracer_so_k, ells)
cls[1, 0, :] = cls[0, 1, :]
cls[1, 1, :] = ccl.angular_cl(cosmo, tracer_so_k, tracer_so_k, ells)
```
# Set up covariance
```
n_cross = (n_maps * (n_maps + 1)) // 2
covar = np.zeros([n_cross, n_ell, n_cross, n_ell])
id_i = 0
for i1 in range(n_maps):
for i2 in range(i1, n_maps):
id_j = 0
for j1 in range(n_maps):
for j2 in range(j1, n_maps):
cl_i1j1 = cls[i1, j1, :]
cl_i1j2 = cls[i1, j2, :]
cl_i2j1 = cls[i2, j1, :]
cl_i2j2 = cls[i2, j2, :]
# Knox formula
cov = (cl_i1j1 * cl_i2j2 + cl_i1j2 * cl_i2j1) / (delta_ell * fsky_solensing * (2 * ells + 1))
covar[id_i, :, id_j, :] = np.diag(cov)
id_j += 1
id_i += 1
covar = covar.reshape([n_cross * n_ell, n_cross * n_ell])
```
# Construct sacc file
```
s = sacc.Sacc()
s.add_tracer('NZ', 'gc_unwise',
quantity='galaxy_density',
spin=0,
z=dndz_unwise[:,0],
nz=dndz_unwise[:,1],
metadata={'ngal': ngal_unwise})
s.add_tracer('Map', 'ck_so',
quantity='cmb_convergence',
spin=0,
ell=ell_beam,
beam=beam_so_k)
s.add_ell_cl('cl_00',
'gc_unwise',
'gc_unwise',
ells, cls[0, 0, :],
window=Well)
s.add_ell_cl('cl_00',
'gc_unwise',
'ck_so',
ells, cls[0, 1, :],
window=Well)
s.add_ell_cl('cl_00',
'ck_so',
'ck_so',
ells, cls[1, 1, :],
window=Well)
s.add_covariance(covar)
s.save_fits('../../soliket/tests/data/unwise_g-so_kappa.sim.sacc.fits', overwrite=True)
```
# Read sacc file and compare to 'theory'
```
s_load = sacc.Sacc.load_fits('../../soliket/tests/data/unwise_g-so_kappa.sim.sacc.fits')
for n, t in s_load.tracers.items():
print(t.name, t.quantity, type(t))
# Type of power spectra
data_types = np.unique([d.data_type for d in s_load.data])
print("Data types: ", data_types)
# Tracer combinations
print("Tracer combinations: ", s_load.get_tracer_combinations())
# Data size
print("Nell: ", s_load.mean.size)
ell_theory = np.linspace(1,ell_max,ell_max)
z_unwise = s_load.tracers['gc_unwise'].z
nz_unwise = s_load.tracers['gc_unwise'].nz
tracer_gc_unwise = ccl.NumberCountsTracer(cosmo, has_rsd=False,
dndz=[z_unwise, nz_unwise],
bias=(z_unwise, b1_unwise * np.ones(len(z_unwise))),
mag_bias=(z_unwise, s1_unwise * np.ones(len(z_unwise)))
)
tracer_ck_so = ccl.CMBLensingTracer(cosmo, z_source=zstar)
cl_gg_theory = ccl.angular_cl(cosmo, tracer_gc_unwise, tracer_gc_unwise, ell_theory)
cl_gk_theory = ccl.angular_cl(cosmo, tracer_gc_unwise, tracer_ck_so, ell_theory)
cl_kk_theory = ccl.angular_cl(cosmo, tracer_ck_so, tracer_ck_so, ell_theory)
Nell_unwise_g = np.ones_like(ell_theory) / (s_load.tracers['gc_unwise'].metadata['ngal'] * (60 * 180 / np.pi)**2)
plt.figure(1, figsize=(3.*4.5, 3.75))
plt.suptitle(r'SO $\times$ unWISE')
plt.subplot(131)
plt.title(r'$gg$')
ell, cl, cov = s_load.get_ell_cl('cl_00', 'gc_unwise', 'gc_unwise', return_cov=True)
cl_err = np.sqrt(np.diag(cov))
plt.plot(ell_theory, 1.e5*(cl_gg_theory + Nell_unwise_g), '--', c='C0')
plt.plot(ell, 1.e5*cl, 'o', ms=3, c='C0')
plt.errorbar(ell, 1.e5*cl, yerr=1.e5*cl_err, fmt='none', c='C0')
plt.xlim([1,ell_max])
plt.xlabel(r'$\ell$')
plt.ylabel(r'$C_\ell \times 10^5$')
plt.subplot(132)
plt.title(r'$g\kappa$')
ell, cl, cov = s_load.get_ell_cl('cl_00', 'gc_unwise', 'ck_so', return_cov=True)
cl_err = np.sqrt(np.diag(cov))
plt.plot(ell_theory, 1.e5*ell_theory*cl_gk_theory , '--', c='C1')
plt.plot(ell, 1.e5*ell*cl, 'o', ms=3, c='C1')
plt.errorbar(ell, 1.e5*ell*cl, yerr=1.e5*ell*cl_err, fmt='none', c='C1')
plt.xlim([1,ell_max])
plt.xlabel(r'$\ell$')
plt.ylabel(r'$\ell C_\ell \times 10^5$')
plt.subplot(133)
plt.title(r'$\kappa\kappa$')
ell, cl, cov = s_load.get_ell_cl('cl_00', 'ck_so', 'ck_so', return_cov=True)
cl_err = np.sqrt(np.diag(cov))
plt.plot(ell_theory, 1.e5*ell_theory*cl_kk_theory , '--', c='C2')
plt.plot(ell, 1.e5*ell*cl, 'o', ms=3, c='C2')
plt.errorbar(ell, 1.e5*ell*cl, yerr=1.e5*ell*cl_err, fmt='none', c='C2')
plt.xlim([1,ell_max])
plt.xlabel(r'$\ell$')
plt.ylabel(r'$\ell C_\ell \times 10^5$')
plt.subplots_adjust(wspace=0.25);
```
| github_jupyter |
```
import os
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
%matplotlib inline
import dianna
from dianna.methods import DeepLift
from dianna import visualization
data = np.load('./binary-mnist.npz')
X_test = data['X_test'].astype(np.float32).reshape([-1, 28, 28, 1])/255
y_test = data['y_test'].astype(int)
class MnistNet(nn.Module):
"""
Model designed for mnist. This class works with the load_torch_model
function for testing deeplift in dianna.
"""
def __init__(self, kernels=[16, 32], dropout=0.1, classes=2):
'''
Two layer CNN model with max pooling.
'''
super(MnistNet, self).__init__()
self.kernels = kernels
# 1st layer
self.layer1 = nn.Sequential(
nn.Conv2d(1, kernels[0], kernel_size=5, stride=1, padding=2),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.ReLU(),
nn.Dropout()
)
# 2nd layer
self.layer2 = nn.Sequential(
nn.Conv2d(kernels[0], kernels[1],
kernel_size=5, stride=1, padding=2),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.ReLU(),
nn.Dropout()
)
# pixel 28 / maxpooling 2 * 2 = 7
self.fc1 = nn.Linear(7 * 7 * kernels[-1], kernels[-1])
self.fc2 = nn.Linear(kernels[-1], classes)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = x.reshape(x.size(0), -1)
x = self.fc1(x)
x = self.fc2(x)
return F.log_softmax(x, dim=1)
def load_torch_model(path_to_model):
"""
Load pytorch model
Args:
path_to_model (str):
Returns:
pytorch model
"""
# create the structure of the model
# hyper-parameters
kernels = [16, 32]
dropout = 0.5
classes = 2
# create model
model = MnistNet(kernels, dropout, classes)
# load whole model state
checkpoint = torch.load(path_to_model)
# load model
model.load_state_dict(checkpoint['model_state_dict'])
model.eval()
return model
model = load_torch_model(os.path.expanduser(''../tests/test_data/mnistnet_training_checkpoint.pt''))
# select a random image from binary MNIST
idx = np.random.choice(len(X_test))
X = X_test[idx:idx+1]
y = y_test[idx]
# move channel axis from end to second position
X = np.transpose(X, (0, 3, 1, 2))
deeplift = DeepLift()
heatmap = deeplift.explain_image(model, X, label=y)
plt.imshow(X[0,0])
visualization.plot_image(heatmap[0,0])
```
| github_jupyter |
# Assignment 1
## Experiments
Seems like you've already implemented all the building blocks of the neural networks. Now we will conduct several experiments.
Note: These experiments will not be evaluated.
## Table of contents
* [0. Circles Classification Task](#0.-Circles-Classification-Task)
* [1. Digits Classification Task](#1.-Digits-Classification-Task)
# 0. Circles Classification Task
```
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import Image
from IPython.core.display import HTML
```
We will import the functions from the "Blocks ipython notebook" and will use them for training a network for classification task.
```
%%capture
%run 1.Blocks.ipynb
```
In this first task we will classify two circles by training a neural network.
The main purpose of this task is to understand the **importance of network design and parameters tunning (Number of layers, Number of hidden units etc)**. At first we will generate and visualize the data in following cell.
```
# Generate some data
N = 100
phi = np.linspace(0.0, np.pi * 2, 100)
X1 = 1.1 * np.array([np.sin(phi), np.cos(phi)])
X2 = 3.0 * np.array([np.sin(phi), np.cos(phi)])
Y = np.concatenate([np.ones(N), -1.0 * np.ones(N)]).reshape((-1, 1))
X = np.hstack([X1,X2]).T
plt.scatter(X[:,0], X[:,1], c=Y.ravel(), edgecolors= 'none')
```
As you have already written the code blocks in the *Blocks* file we will just call those functions and will train the network to classify the two circles.
For this task we have provided the code for training and testing of the network in following blocks. Students are asked to design the network with different configurations and observe the outputs.
* **Single Layer Neural Network**
* **Multiple Layer Neural Network**
* **Different number of Hidden units**
* **With and without activation function**
```
##Training the network ##
model = SequentialNN()
# model.add(....)
# model.add(....)
###YOUR CODE FOR DESIGNING THE NETWORK ###
loss = Hinge()
weight_decay = 0.01
sgd = SGD(model, lr=0.01, weight_decay=weight_decay)
for i in range(100):
# get the predictions
y_pred = model.forward(X)
# compute the loss value + L_2 term
loss_value = loss.forward(y_pred, Y) + l2_regularizer(weight_decay, model.get_params())
# log the current loss value
print('Step: {}, \tLoss = {:.2f}'.format(i+1, loss_value))
# get the gradient of the loss functions
loss_grad = loss.backward(y_pred, Y)
# backprop the gradients
model.backward(X, loss_grad)
# perform the updates
sgd.update_params()
##Testing the network ##
y_pred = model.forward(X) > 0
plt.scatter(X[:,0], X[:,1], c = y_pred.ravel(), edgecolors= 'none')
```
# 1. Digits Classification Task
In this task you will implement a neural network for classification of hand written digits. You can use the blocks of code which you implemented in the first part of this assignment for completing this task.
We will use **digits** dataset for this task. This dataset consists of 1797 8x8 images. Further information about the dataset can be found [here](http://archive.ics.uci.edu/ml/datasets/Pen-Based+Recognition+of+Handwritten+Digits).
```
import sklearn.datasets
# We load the dataset
digits = sklearn.datasets.load_digits()
# Here we load up the images and labels and print some examples
images_and_labels = list(zip(digits.images, digits.target))
for index, (image, label) in enumerate(images_and_labels[:10]):
plt.subplot(2, 5, index + 1)
plt.axis('off')
plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
plt.title('Training: {}'.format(label), y=1.1)
```
Next we will divide the images and labels data into two parts i.e. training data and test data.
```
n_objects = digits.images.shape[0]
train_test_split = 0.7
train_size = int(n_objects * train_test_split)
indices = np.arange(n_objects)
np.random.shuffle(indices)
train_indices, test_indices = indices[:train_size], indices[train_size:]
train_images, train_targets = digits.images[train_indices], digits.target[train_indices]
test_images, test_targets = digits.images[test_indices], digits.target[test_indices]
```
The images in the dataset are $8 \times 8$ and each pixel in the image is eithe 0 or 1. Before giving the images as input to the neural network we will reshape them to 1 by 64 times long 1 dimensional vector as shown in the figure below.

```
train_images = train_images.reshape((-1, 64))
test_images = test_images.reshape((-1, 64))
```
The basic units of the neural network are perceptrons. A perceptron consists of a cell with atleast two inputs. Cell takes the inputs multiplied with weights and gives an output after computing the values. The basic diagram of a cell is shown below.

For the image dataset which we will be using in this task the perceptron will have 64 inputs for $8 \times 8$ input and 64 weights.

As the digits dataset consists of 10 classes (0 to 9) so, in order to classifiy the images we will need 10 neurons for the prediction of the target class. It can be seen from the image each neuron will give an output and the output from the neuron with the highest value will be selected and that will be the predicted output.

Now, in order to perform classification task for images you will use the functions which you implemented in the first task of the assignment.
In the following lines of code we will train a complete neural network by giving the images as input and the labels as targets to the network. At first we will design the network by by setting the parameters of network by calling *SequentialNN()* function, after that we will forward propagate the inputs through the network and will calculate the loss, the error between the predicted output and the target output will be back propagated through the network. Finally the parameters of the network will be updated in the direction to reduce the error of the prediction.
```
### YOUR CODE FOR TRAINING THE NETWORK###
#Specify the input size for the network
#specify the output size for the network
#specify the inputs for the network
#specify the outputs for the network
#num_input=
#num_output=
#X=
#y=
###
model = SequentialNN()
model.add(Dense(num_input,num_output))
loss = Hinge()
weight_decay = 0.01
sgd = SGD(model, lr=0.01, weight_decay=weight_decay)
for i in range(100):
# get the predictions
y_pred = model.forward(X)
# compute the loss value + L_2 term
loss_value = loss.forward(y_pred, Y) + l2_regularizer(weight_decay, model.get_params())
# log the current loss value
print('Step: {}, \tLoss = {:.2f}'.format(i+1, loss_value))
# get the gradient of the loss functions
loss_grad = loss.backward(y_pred, Y)
# backprop the gradients
model.backward(X, loss_grad)
# perform the updates
sgd.update_params()
```
After training the network should be tested on test data; images in this task. During the test time unlabeled inputs are given to the network and by using the trained weights from the training cycle of the network the ouput classes for the unlabeled inputs are predicted. The figure below shows the difference between the training and the testing of the network.

In the following cell implement the code for testing the network.
```
#Testing the network
###YOUR CODE FOR TESTING THE NETWORK ###
```
For further practice and advanced experiments you can use MNIST dataset for the classification of hand written digits. It is a commonly used image dataset for testing the machine learning algorithms. You can load this dataset by using the code from the file *data_utils* in week_1 folder.
| github_jupyter |
# Logistic Regression
---
- Author: Diego Inácio
- GitHub: [github.com/diegoinacio](https://github.com/diegoinacio)
- Notebook: [regression_logistic.ipynb](https://github.com/diegoinacio/machine-learning-notebooks/blob/master/Machine-Learning-Fundamentals/regression_logistic.ipynb)
---
Overview and implementation of *Logistic Regression* analysis.
```
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from regression__utils import *
```
$$ \large
h_{\theta}(x)=g(\theta^Tx)=\frac{e^{\theta^Tx}}{1+e^{\theta^Tx}}=\frac{1}{1+e^{-\theta^Tx}}
$$
where:
$$ \large
\theta^Tx=
\begin{bmatrix}
\theta_0 \\
\theta_1 \\
\vdots \\
\theta_i
\end{bmatrix}
\begin{bmatrix}
1 & x_{11} & \cdots & x_{1i} \\
1 & x_{21} & \cdots & x_{2i} \\
\vdots & \vdots & \ddots & \vdots \\
1 & x_{n1} & \cdots & x_{ni}
\end{bmatrix}
$$
where:
- $\large h_\theta(x)$ is the hypothesis;
- $\large g(z)$ is the logistic function or <em>sigmoid</em>;
- $\large \theta_i$ is the parameters (or <em>weights</em>).
```
def arraycast(f):
'''
Decorator for vectors and matrices cast
'''
def wrap(self, *X, y=[]):
X = np.array(X)
X = np.insert(X.T, 0, 1, 1)
if list(y):
y = np.array(y)[np.newaxis]
return f(self, X, y)
return f(self, X)
return wrap
class logisticRegression(object):
def __init__(self, rate=0.001, iters=1024):
self._rate = rate
self._iters = iters
self._theta = None
@property
def theta(self):
return self._theta
def _sigmoid(self, Z):
return 1/(1 + np.exp(-Z))
def _dsigmoid(self, Z):
return self._sigmoid(Z)*(1 - self._sigmoid(Z))
@arraycast
def fit(self, X, y=[]):
self._theta = np.ones((1, X.shape[-1]))
for i in range(self._iters):
thetaTx = np.dot(X, self._theta.T)
h = self._sigmoid(thetaTx)
delta = h - y.T
grad = np.dot(X.T, delta).T
self._theta -= grad*self._rate
@arraycast
def pred(self, x):
return self._sigmoid(np.dot(x, self._theta.T)) > 0.5
# Synthetic data 5
x1, x2, y = synthData5()
```

```
%%time
# Training
rlogb = logisticRegression(rate=0.001, iters=512)
rlogb.fit(x1, x2, y=y)
rlogb.pred(x1, x2)
```

To find the boundary line components:
$$ \large
\theta_0+\theta_1 x_1+\theta_2 x_2=0
$$
Considering $\large x_2$ as the dependent variable:
$$ \large
x_2=-\frac{\theta_0+\theta_1 x_1}{\theta_2}
$$
```
# Prediction
w0, w1, w2 = rlogb.theta[0]
f = lambda x: - (w0 + w1*x)/w2
```

| github_jupyter |
```
pip install numpy
pip install sklearn
pip install pandas
import numpy as np
import pandas as pd
import os
movies = pd.read_csv('tmdb_5000_movies.csv')
credits = pd.read_csv('tmdb_5000_credits.csv')
movies.head()
credits.head(1)
movies = movies.merge(credits, on='title')
movies.head(1)
#genres
#id
#keywords
#title
#overvies
#cast
#crew
movies = movies[['movie_id','title','overview', 'genres', 'keywords', 'cast', 'crew']]
movies.head()
movies.isnull().sum()
movies.dropna(inplace=True)
movies.duplicated().sum()
movies.iloc[0].genres
import ast
def convert(obj):
L = []
for i in ast.literal_eval(obj):
L.append(i['name'])
return L
movies['genres'] = movies['genres'].apply(convert)
movies['keywords'] = movies['keywords'].apply(convert)
movies.head()
def convert3(obj):
L = []
counter = 0
for i in ast.literal_eval(obj):
if counter != 3:
L.append(i['name'])
else:
break
return L
movies['cast'] = movies['cast'].apply(convert3)
movies.head()
movies['crew'][0]
movies['cast'] = movies['cast'].apply(lambda x:x[0:3])
def fetch_director(text):
L = []
for i in ast.literal_eval(text):
if i['job'] == 'Director':
L.append(i['name'])
return L
movies['crew'] = movies['crew'].apply(fetch_director)
movies.head()
movies['overview'] = movies['overview'].apply(lambda x:x.split())
movies.head()
movies['genres'] = movies['genres'].apply(lambda x:[i.replace(" ","") for i in x])
movies['keywords'] = movies['keywords'].apply(lambda x:[i.replace(" ","") for i in x])
movies['cast'] = movies['cast'].apply(lambda x:[i.replace(" ","") for i in x])
movies['crew'] = movies['crew'].apply(lambda x:[i.replace(" ","") for i in x])
movies.head()
movies['tags'] = movies['overview'] + movies['genres'] + movies['keywords'] + movies['cast'] + movies['crew']
movies.head()
new = movies.drop(columns=['overview','genres','keywords','cast','crew'])
new['tags'] = new['tags'].apply(lambda x: " ".join(x))
new.head()
!pip install nltk
from nltk.stem.porter import PorterStemmer
ps = PorterStemmer()
def stem(text):
y = []
for i in text.split():
y.append(ps.stem(i))
return " ".join(y)
new['tags'] = new['tags'].apply(stem)
new['tags'][0]
new['tags'] = new['tags'].apply(lambda x:x.lower())
new.head()
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=5000,stop_words='english')
vectors = cv.fit_transform(new['tags']).toarray()
cv.get_feature_names()
#calculate Cosine Similarity
from sklearn.metrics.pairwise import cosine_similarity
#Cosine Similarity of each movies is compared with every other movie
similarity = cosine_similarity(vectors)
similarity[1]
#First find the index of the movie in the data set
#
def recommend(movie):
movie_index = new[new['title'] == movie].index[0]
distances = similarity[movie_index]
movies_list = sorted(list(enumerate(distances)), reverse=True,key=lambda x:x[1])[1:6]
for i in movies_list:
print(new.iloc[i[0]].title)
recommend('Superman')
import pickle
pickle.dump(new.to_dict(), open('movie_dict.pkl','wb'))
new.to_dict()
pickle.dump(similarity,open('similarity.pkl','wb'))
```
| github_jupyter |
# XE Candidate Datastore Demo
This sample **doesn't attempt to lock or unlock datastores**, and thus assumes singular access.
```
HOST = '127.0.0.1'
PORT_NC = 2223
USER = 'vagrant'
PASS = 'vagrant'
```
## Connect ncclient
```
from ncclient import manager
from lxml import etree
def pretty_print(retval):
print(etree.tostring(retval.data, pretty_print=True))
def my_unknown_host_cb(host, fingerprint):
return True
m = manager.connect(host=HOST, port=PORT_NC, username=USER, password=PASS,
allow_agent=False,
look_for_keys=False,
hostkey_verify=False,
unknown_host_cb=my_unknown_host_cb)
```
## Loopback Addition Sample Edit Config
```
config = '''<config>
<native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
<interface>
<Loopback>
<name>101</name>
<description>hello</description>
</Loopback>
</interface>
</native>
</config>
'''
running_before = m.get_config(source='running', filter=('xpath', '/native')).data
m.edit_config(config, format='xml', target='candidate', default_operation='merge')
running_after = m.get_config(source='running', filter=('xpath', '/native')).data
candidate_after = m.get_config(source='candidate', filter=('xpath', '/native')).data
```
### Display An XML Diff In Text Form
```
from difflib import context_diff
running_before_xml = etree.tostring(running_before, pretty_print=True)
running_after_xml = etree.tostring(running_after, pretty_print=True)
candidate_after_xml = etree.tostring(candidate_after, pretty_print=True)
#
# remember to skip the first few lines that have timestamps & stuff that may differ
#
print('\n'.join(context_diff(running_after_xml.decode().splitlines(),
candidate_after_xml.decode().splitlines())))
```
### Commit Or Discard?
```
m.commit()
m.discard_changes()
```
# BGP Remove Sample Edit Config
```
config = '''<config xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
<native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
<router>
<bgp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-bgp" nc:operation="remove">
<id>101</id>
</bgp>
</router>
</native>
</config>
'''
running_before = m.get_config(source='running', filter=('xpath', '/native')).data
m.edit_config(config, format='xml', target='candidate', default_operation='merge')
running_after = m.get_config(source='running', filter=('xpath', '/native')).data
candidate_after = m.get_config(source='candidate', filter=('xpath', '/native')).data
```
### Display An XML Diff In Text Form
```
from difflib import context_diff
running_before_xml = etree.tostring(running_before, pretty_print=True)
running_after_xml = etree.tostring(running_after, pretty_print=True)
candidate_after_xml = etree.tostring(candidate_after, pretty_print=True)
#
# remember to skip the first few lines that have timestamps & stuff that may differ
#
print('\n'.join(context_diff(running_after_xml.decode().splitlines(),
candidate_after_xml.decode().splitlines())))
```
### Commit Or Discard?
```
m.commit()
m.discard_changes()
```
## Diff Before & After (XML)
## Tidyup Sessions
```
m.close_session()
```
| github_jupyter |
Deep neural networks have produced large accuracy gains in applications such as computer vision, speech recognition and natural language processing. Rapid advancements in this area have been supported by excellent libraries for developing neural networks. These libraries allow users to express neural networks in terms of a computation graph, i.e., a sequence of mathematical operations, that maps vector inputs to outputs. Given this graph, these libraries support learning network parameters from data and furthermore can optimize computation, for example, by using GPUs. The ease of developing neural networks with these libraries is a significant factor in the proliferation of these models.
Unfortunately, structured prediction problems cannot be easily expressed in neural network libraries. These problems require making a set of interrelated predictions and occur frequently in natural language processing. For example, part-of-speech tagging requires assigning a part-of-speech tag to each word in a sentence, where tags for nearby words may depend on each other. Another example is dependency parsing, which requires predicting a directed tree spanning the words of a sentence. These problems can be posed as predicting a sequence of actions, such as shifts and reduces for parsing. Neural networks can be applied to these problems using locally-normalized models, which produce a probability distribution over each action given all prior actions. However, this approach is known to be suboptimal as it suffers from the *label bias* problem, which is that the scores of future actions cannot affect the scores of previous actions. *Globally-normalized models*, such as conditional random fields, solve this problem by defining a joint distribution over all sequences of actions. These models express a larger class of distributions and provide better predictions than locally-normalized models. Unfortunately, these models cannot be easily expressed or trained using existing neural network libraries.
Our goal is to design a neural network library that supports structured prediction with globally-normalized models. Our observation is that *nondeterministic computation* is a natural formalism for expressing the decision space of a structured prediction problem. For example, we can express a parser as a function that nondeterministically selects a shift or reduce action, applies it to its current state, then recurses to parse the remainder of the sentence. Our library has a nondeterministic choice operator similar to McCarthy's `amb` for this purpose. We combine nondeterministic choice with a computation graph, which, as demonstrated by neural network libraries, is a powerful way for users to express models. Importantly, *the computation graph interacts with nondeterministic computation*: the scores produced by the neural network determine the probabilities of nondeterministic choices, and the nondeterministic choices determine the network's architecture. The combination of these operations results in a powerful formalism for structured prediction where users specify the decision space using nondeterminism and the prediction models using computation graphs.
We implement our library as a Scala monad to leverage Scala's powerful type system, library support, and streamlined syntax for monadic operations. A instance `Pp[X]` of the monad represents a function from neural network parameters to a probability distribution over values of type `X`. The monad supports inference operations that take neural network parameters and return (an approximation of) this distribution. Running inference also generates a neural network and performs a forward pass in this network to compute its outputs, which may influence the probability distribution. The library also supports a variety of optimization algorithms for training parameters from data. These training algorithms use the approximate inference algorithms and also run backpropagation in the generated networks.
```
val path = "/Users/jayantk/github/pnp/"
classpath.addPath(path + "target/scala-2.11/pnp_2.11-0.1.jar")
classpath.addPath(path + "lib/jklol.jar")
classpath.add("com.google.guava" % "guava" % "17.0")
```
To use the `Pp` monad, we statically import its functions. Nondeterministic choices are expressed using the `choose` function, which has several forms. The simplest takes an explicit list of values and their corresponding probabilities:
```
import org.allenai.pnp.Pp
import org.allenai.pnp.Pp._
val flip = choose(Seq(true, false), Seq(0.75, 0.25))
```
This code represents a weighted coin flip that comes up `true` with probability 0.75 and `false` with probability 0.25. `flip` has type `Pp[Boolean]`, representing a distribution over values of type `Boolean`. The `Pp` object represents this distribution *lazily*, so we need to perform inference on this object to get the probability of each value. Many different inference algorithms could be used for this purpose, such as sampling. Here we perform inference using beam search to estimate the k=10 most probable outcomes:
```
val dist = flip.beamSearch(10)
```
We get back the original distribution, which, while expected, is not that interesting. To construct interesting models, we need to combine multiple nondeterministic choices, which we can do conveniently using Scala's for/yield construction:
```
val threeFlips = for {
flip1 <- choose(Seq(true, false), Seq(0.75, 0.25))
flip2 <- choose(Seq(true, false), Seq(0.75, 0.25))
flip3 <- choose(Seq(true, false), Seq(0.75, 0.25))
} yield {
flip1 && flip2 && flip3
}
val threeFlipsDist = threeFlips.beamSearch(10)
```
This code flips three weighted coins and returns true if they all come up true. Inference again returns the expected distribution, which we can verify by computing 0.75 \* 0.75 \* 0.75 = 0.421. There are 8 entries in the returned distribution because each entry represents a way the program can execute, that is, a particular sequence of choices. Executions have additional state (specifically a computation graph) besides the return value, which is why the "duplicate" entries are not collapsed by inference. We'll see how to use the computation graph later on.
The for/yield construction above essentially means "make these choices sequentially and lazily". This construction is mapped by Scala into calls to `flatMap` on the `Pp` monad, which construct a lazy representation of the probability distribution.
Basically, the for/yield translates into a
We can also define functions with nondeterministic choices. The `flipMany` function flips `num` coins and returns a list of the results:
```
def flipMany(num: Int): Pp[List[Boolean]] = {
if (num == 0) {
value(List())
} else {
for {
flip <- choose(Seq(true, false), Seq(0.75, 0.25))
rest <- flipMany(num - 1)
} yield {
flip :: rest
}
}
}
val flips = flipMany(1000)
val flipsDist = flips.beamSearch(10)
```
Recursive functions such as `flipMany` are a natural way to express many structured prediction models. We will see later how to define a sequence tagger using a function very similar to flipMany.
At this point, it is worthwhile noting that inference does **not** explicitly enumerate all of the possible executions of the program, even though the for/yield syntax suggests this interpretation. We can verify that explicit enumeration does not occur by changing the argument 4 above to something large, such as 10000, that would make enumeration computationally infeasible. Inference still completes quickly because `beamSearch` only approximately searches the space of executions.
The examples above demonstrate how to use `Pp` to express a distribution over values in terms of probabilistic choices and perform inference over the results. The monad also allows us to define computation graphs for neural networks. Here's a function implementing a multilayer perceptron:
```
import scala.collection.JavaConverters._
import org.allenai.pnp.{ Env, CompGraph, CompGraphNode }
import com.jayantkrish.jklol.tensor.{ Tensor, DenseTensor }
import com.jayantkrish.jklol.util.IndexedList
import com.google.common.base.Preconditions
def multilayerPerceptron(featureVector: Tensor): Pp[CompGraphNode] = for {
params <- param("params")
bias <- param("bias")
hidden = ((params * featureVector) + bias).tanh
params2 <- param("params2")
bias2 <- param("bias2")
dist = (params2 * hidden) + bias2
} yield {
dist
}
```
This function applies a two-layer neural network to an input feature vector. The feature vector is represented as a ```Tensor``` from the jklol library. Neural network parameters are retrieved by name using the ```param``` function and are instances of ```CompGraphNode```. The function builds a neural network out of these nodes by applying standard operations such as matrix/vector multiplication, addition, and the hyperbolic tangent. These operations are overloaded to create new nodes in the computation graph.
Something that may seem odd is that the return type for this method is `Pp[CompGraphNode]`, that is, a distribution over computation graph nodes. The reason for this type is that operations on `CompGraphNode` are **stateful** and manipulate an underlying computation graph. However, this graph is tracked by the `Pp` monad so it doesn't need to be explicitly referenced. This type also enables the computation graph to interact with nondeterministic choices, as we will see later.
Let's evaluate our neural network with a feature vector and some random parameters:
```
val features = new DenseTensor(
// Dimension specification for the tensor
Array[Int](2), Array[Int](2),
// The tensor's values
Array(1, 1))
// Evaluate the network with the feature
val nnPp = multilayerPerceptron(features)
// Randomly initialize the network parameters
val compGraph = new CompGraph(
IndexedList.create(List("params", "bias", "params2", "bias2").asJava),
Array(DenseTensor.random(Array(2, 1), Array(2, 8), 0.0, 1.0),
DenseTensor.random(Array(1), Array(8), 0.0, 1.0),
DenseTensor.random(Array(0, 1), Array(2, 8), 0.0, 1.0),
DenseTensor.random(Array(0), Array(2), 0.0, 1.0)))
val dist = nnPp.beamSearch(10, Env.init, compGraph).executions
val nnOutput = dist(0).value.value
```
To evaluate the network we define values for the feature vector as well as the named network parameters. These parameters are declared by creating a computation graph containing them. This graph is then passed to the `beamSearch` method which performs the forward pass of inference in the neural network. Inference returns a distribution with a single `CompGraphNode` that contains the network's output as its `value`. The output is a tensor with two values, which is all we can expect given the random inputs.
Again, it may seem odd that `beamSearch` computes the network's forward pass in addition to performing probabilistic inference. This overloading is intentional, as it allows us to combine neural networks with nondeterministic choices to create probability distributions. Let's use our multilayer perceptron to define a probability distribution:
```
def booleanFunction(left: Boolean, right: Boolean): Pp[Boolean] = {
// Build a feature vector from the inputs
val values = Array.ofDim[Double](2)
values(0) = if (left) { 1 } else { 0 }
values(1) = if (right) { 1 } else { 0 }
val featureVector = new DenseTensor(
Array[Int](2), Array[Int](2), values)
for {
dist <- multilayerPerceptron(featureVector)
output <- choose(Array(false, true), dist)
} yield {
output
}
}
val output = booleanFunction(true, true)
val dist = output.beamSearch(10, Env.init, compGraph)
for (d <- dist.executions) {
println(d.value + " " + (d.prob / dist.partitionFunction))
}
```
This function computes a distribution over boolean outputs given two boolean inputs. It encodes the inputs as a feature vector, passes this vector to the multilayer perceptron, then uses the output of the perceptron to choose the output. Note that the input '(true, true)' is encoded as the same feature vector used in the above code block, and that the network has the same parameters. If you look closely at the output of the two above cells, you'll notice that 113.15 = e^4.72 and 12.73 = e^2.54. That's because the values computed by the neural network are logspace weights for each execution. Normalizing these weights gives us a probability distribution over executions.
Next, let's train the network parameters to learn the xor function. First, let's create some training examples:
```
import org.allenai.pnp.PpExample
// Create training data.
val data = List(
(true, true, false),
(true, false, true),
(false, true, true),
(false, false, false)
)
val examples = data.map(x => {
val unconditional = booleanFunction(x._1, x._2)
val conditional = for {
y <- unconditional;
x <- Pp.require(y == x._3)
} yield {
y
}
PpExample.fromDistributions(unconditional, conditional)
})
```
A training example consists of a tuple of an unconditional and a conditional probability distribution. The unconditional distribution is generated by calling `booleanFunction`, and the conditional distribution is generated by constraining the unconditional distribution to have the correct label using ``require``. Using these examples, we can train the network:
```
import com.jayantkrish.jklol.models.DiscreteVariable
import com.jayantkrish.jklol.models.VariableNumMap
import com.jayantkrish.jklol.training.{ StochasticGradientTrainer, Lbfgs }
import com.jayantkrish.jklol.training.NullLogFunction
import org.allenai.pnp.ParametricPpModel
import org.allenai.pnp.PpLoglikelihoodOracle
// Initialize neural net parameters and their dimensionalities.
// TODO(jayantk): This is more verbose than necessary
val v = DiscreteVariable.sequence("boolean", 2);
val h = DiscreteVariable.sequence("hidden", 8);
val inputVar = VariableNumMap.singleton(2, "input", v)
val hiddenVar = VariableNumMap.singleton(1, "hidden", h)
val outputVar = VariableNumMap.singleton(0, "output", v)
val paramNames = IndexedList.create(
List("params", "bias", "params2", "bias2").asJava
)
val family = new ParametricPpModel(
paramNames,
List(inputVar.union(hiddenVar), hiddenVar,
hiddenVar.union(outputVar), outputVar)
);
// Train model
val oracle = new PpLoglikelihoodOracle[Boolean](100, family)
val trainer = StochasticGradientTrainer.createWithL2Regularization(
1000, 1, 1.0, false, false, 10.0, 0.0, new NullLogFunction()
)
val params = family.getNewSufficientStatistics
params.perturb(1.0)
val trainedParams = trainer.train(oracle, params, examples.asJava)
val model = family.getModelFromParameters(trainedParams)
```
TODO (jayantk): The syntax for declaring parameter dimensionalities is overcomplicated at the moment.
The first part of the above code declares the dimensionalities for each parameter of the network, and the second part trains these parameters using 1000 iterations of stochastic gradient descent. Let's evaluate our function with the trained parameters:
```
val marginals = booleanFunction(false, true).beamSearch(
100, Env.init, model.getInitialComputationGraph)
val dist = marginals.executions
```
For the input `(true, true)`, the predicted output is overwhelmingly likely to be `false`. You can change the arguments above to convince yourself that we have indeed learned the xor function.
Of course, any neural network library can be used to learn xor. The power of the interaction between neural networks and nondeterministic choices only appears when we start doing structured prediction. Let's build a shift-reduce parser for a context free grammar. First, let's create some data structures to represent parse trees:
```
abstract class Parse(val pos: String) {
def getTokens: List[String]
}
case class Terminal(word: String, override val pos: String) extends Parse(pos) {
override def getTokens: List[String] = {
List(word)
}
override def toString: String = {
pos + " -> " + word
}
}
case class Nonterminal(left: Parse, right: Parse, override val pos: String) extends Parse(pos) {
override def getTokens: List[String] = {
left.getTokens ++ right.getTokens
}
override def toString: String = {
pos + " -> (" + left.toString + ", " + right.toString + ")"
}
}
```
Let's also create some data structures to represent the parser's state and actions:
```
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.MultiMap
import scala.collection.mutable.{ HashMap, Set }
// The state of a shift-reduce parser consists of a buffer
// of tokens that haven't been consumed yet and a stack
// of parse trees spanning the consumed tokens.
case class ShiftReduceState(tokens: List[String], stack: List[Parse])
// Classes for representing actions of a shift/reduce
// parser.
abstract class Action {
def apply(state: ShiftReduceState): ShiftReduceState
// An action is responsible for generating the computation graph
// that scores it.
def score(state: ShiftReduceState): Pp[CompGraphNode]
def addParams(names: IndexedList[String], vars: ListBuffer[VariableNumMap]): Unit
}
// The shift action consumes the first token on the buffer
// and pushes a parse tree on to the stack.
class Shift(val word: String, val pos: String) extends Action {
val terminal = Terminal(word, pos)
val paramName = "shift_" + word + "_" + pos
override def apply(state: ShiftReduceState): ShiftReduceState = {
ShiftReduceState(state.tokens.tail, (terminal :: state.stack))
}
override def score(state: ShiftReduceState): Pp[CompGraphNode] = {
Pp.param(paramName)
}
override def addParams(names: IndexedList[String], vars: ListBuffer[VariableNumMap]): Unit = {
names.add(paramName)
vars += VariableNumMap.EMPTY
}
}
// The reduce action combines the top two parses on the stack
// into a single parse.
class Reduce(val leftPos: String, val rightPos: String, val rootPos: String) extends Action {
val paramName = "reduce_" + leftPos + "_" + rightPos + "_" + rootPos
override def apply(state: ShiftReduceState): ShiftReduceState = {
val left = state.stack(1)
val right = state.stack(0)
val nonterminal = Nonterminal(left, right, rootPos)
ShiftReduceState(state.tokens, (nonterminal :: state.stack.drop(2)))
}
override def score(state: ShiftReduceState): Pp[CompGraphNode] = {
Pp.param(paramName)
}
override def addParams(names: IndexedList[String], vars: ListBuffer[VariableNumMap]): Unit = {
names.add(paramName)
vars += VariableNumMap.EMPTY
}
}
```
Using these data structures, we can define the parser as follows:
```
class PpParser(
lexActions: MultiMap[String, Action],
grammarActions: MultiMap[(String, String), Action]
) {
def parse(sent: List[String]): Pp[Parse] = {
parse(ShiftReduceState(sent, List()))
}
def parse(state: ShiftReduceState): Pp[Parse] = {
val tokens = state.tokens
val stack = state.stack
if (tokens.size == 0 && stack.size == 1) {
// All tokens consumed and all possible
// reduces performed.
value(stack.head)
} else {
// Queue for each possible action
val actions = ListBuffer[Action]()
// Queue shift actions
if (tokens.size > 0) {
val shifts = lexActions.getOrElse(tokens.head, Set())
actions ++= shifts
}
// Queue reduce actions
if (stack.size >= 2) {
val left = stack(1)
val right = stack(0)
val reduces = grammarActions.getOrElse((left.pos, right.pos), Set())
actions ++= reduces
}
for {
// Score each possible action, nondeterministically
// select one to apply, then recurse on the next
// parser state.
scores <- scoreActions(state, actions);
action <- choose(actions.toArray, scores)
p <- parse(action.apply(state))
} yield {
p
}
}
}
def scoreActions(state: ShiftReduceState, actions: ListBuffer[Action]): Pp[Array[CompGraphNode]] = {
val scoreList = actions.foldRight(Pp.value(List[CompGraphNode]()))((action, list) =>
for {
x <- action.score(state);
l <- list
} yield {
x :: l
})
scoreList.flatMap { x => Pp.value(x.toArray) }
}
// Generate the parameters used in the neural network
// of this parser.
def getParams: ParametricPpModel = {
val paramNames = IndexedList.create[String]()
val paramVars = ListBuffer[VariableNumMap]()
lexActions.values.foreach(_.foreach(_.addParams(paramNames, paramVars)))
grammarActions.values.foreach(_.foreach(_.addParams(paramNames, paramVars)))
new ParametricPpModel(paramNames, paramVars.toList)
}
}
object PpParser {
// Initialize parser actions from maps of string -> part of speech
// for shift actions and (pos, pos) -> pos for reduce actions
def fromMaps(
lexicon: List[(String, String)],
grammar: List[((String, String), String)]
): PpParser = {
val lexActions = new HashMap[String, Set[Action]] with MultiMap[String, Action]
for ((k, v) <- lexicon) {
lexActions.addBinding(k, new Shift(k, v))
}
val grammarActions = new HashMap[(String, String), Set[Action]] with MultiMap[(String, String), Action]
for ((k, v) <- grammar) {
grammarActions.addBinding(k, new Reduce(k._1, k._2, v))
}
new PpParser(lexActions, grammarActions)
}
}
```
All said and done, we've built a globally-normalized shift-reduce parser with neural network factors in less than 200 lines of code, much of which is simple data structures. The scoring function for actions is overly simple, but this is easy to improve using the computation graph operations as we saw in the xor example. Let's use the parser to parse some sentences:
```
// The set of shift actions
val lexicon = List(
("the", "DT"),
("the", "NN"),
("blue", "NN"),
("man", "NN")
)
// The set of reduce actions
val grammar = List(
(("DT", "NN"), "NP"),
(("NN", "NN"), "NN")
)
val parser = PpParser.fromMaps(lexicon, grammar)
// Get the neural network parameters needed to score
// parses in dist
val family = parser.getParams
val model = family.getModelFromParameters(
family.getNewSufficientStatistics)
val cg = model.getInitialComputationGraph
// Run inference
val dist = parser.parse(List("the", "blue", "man"))
val marginals = dist.beamSearch(100, Env.init, cg)
val parses = marginals.executions
```
Parsing seems to work. We initialized the parameters to 0, so we get a uniform distribution over parse trees for the sentence. Now let's train the parser:
```
val trainingData = List[Parse](
Nonterminal(Terminal("the", "DT"), Terminal("man", "NN"), "NP"),
Nonterminal(Terminal("blue", "NN"), Terminal("man", "NN"), "NN")
)
// Convert the trees to unconditional / conditional distributions
// that are used for training.
val examples = trainingData.map(tree => {
val unconditional = parser.parse(tree.getTokens)
val conditional = for {
parse <- unconditional;
_ <- Pp.require(parse == tree)
} yield {
parse
}
PpExample.fromDistributions(unconditional, conditional)
})
val oracle = new PpLoglikelihoodOracle[Parse](100, family)
val trainer = StochasticGradientTrainer.createWithL2Regularization(
1000, 1, 1.0, false, false, 10.0, 0.0, new NullLogFunction())
val params = family.getNewSufficientStatistics
val trainedParams = trainer.train(oracle, params, examples.asJava)
val model = family.getModelFromParameters(trainedParams)
val dist = parser.parse(List("the", "blue", "man"))
val marginals = dist.beamSearch(100, Env.init, model.getInitialComputationGraph)
val parses = marginals.executions
```
The code above is nearly identical to the code for the xor example. We generate unconditional/conditional distributions over parse trees, then maximize loglikelihood with stochastic gradient descent. Parsing the same sentence now gives us a highly peaked distribution on the tree present in the training data.
```
def answerQ(question: String): Pp[String] = {
for {
sentence <- chooseSentence(question)
answer <- chooseAnswer(sentence)
} yield {
answer
}
}
def chooseSentence(question: String): Pp[String] = {
sentences = retrieveSentences(question)
for {
scores <- map(sentences, sentenceNN _)
sent <- choose(sentences, scores)
} yield {
sent
}
}
def sentenceNn(sentence: String): Pp[Expression] = {
// Build a neural net to score the sentence
}
val data = List((answerQ("The thermometer ..."), "temperature"),
(answerQ("What season occurs when ..."), "summer"))
```
| github_jupyter |
```
import warnings
warnings.filterwarnings("ignore")
import os
import jieba
import torch
import pickle
import torch.nn as nn
import torch.optim as optim
import pandas as pd
from ark_nlp.model.tc.bert import Bert
from ark_nlp.model.tc.bert import BertConfig
from ark_nlp.model.tc.bert import Dataset
from ark_nlp.model.tc.bert import Task
from ark_nlp.model.tc.bert import get_default_model_optimizer
from ark_nlp.model.tc.bert import Tokenizer
# 目录地址
train_data_path = '../data/source_datasets/CHIP-CTC/CHIP-CTC_train.json'
dev_data_path = '../data/source_datasets/CHIP-CTC/CHIP-CTC_dev.json'
```
### 一、数据读入与处理
#### 1. 数据读入
```
train_data_df = pd.read_json(train_data_path)
train_data_df = (train_data_df
.loc[:,['text', 'label']])
dev_data_df = pd.read_json(dev_data_path)
dev_data_df = (dev_data_df
.loc[:,['text', 'label']])
tc_train_dataset = Dataset(train_data_df)
tc_dev_dataset = Dataset(dev_data_df)
```
#### 2. 词典创建和生成分词器
```
tokenizer = Tokenizer(vocab='hfl/chinese-macbert-base', max_seq_len=128)
```
#### 3. ID化
```
tc_train_dataset.convert_to_ids(tokenizer)
tc_dev_dataset.convert_to_ids(tokenizer)
```
<br>
### 二、模型构建
#### 1. 模型参数设置
```
config = BertConfig.from_pretrained(
'hfl/chinese-macbert-base',
num_labels=len(tc_train_dataset.cat2id)
)
```
#### 2. 模型创建
```
torch.cuda.empty_cache()
dl_module = Bert.from_pretrained(
'hfl/chinese-macbert-base',
config=config
)
dl_module.pooling = 'last_avg'
```
<br>
### 三、任务构建
#### 1. 任务参数和必要部件设定
```
# 设置运行次数
num_epoches = 5
batch_size = 32
optimizer = get_default_model_optimizer(dl_module)
```
#### 2. 任务创建
```
model = Task(dl_module, optimizer, 'lsce', cuda_device=0)
```
#### 3. 训练
```
model.fit(tc_train_dataset,
tc_dev_dataset,
lr=4e-5,
epochs=num_epoches,
batch_size=batch_size
)
```
<br>
### 四、生成提交数据
```
import json
from ark_nlp.model.tc.bert import Predictor
tc_predictor_instance = Predictor(model.module, tokenizer, tc_train_dataset.cat2id)
test_df = pd.read_json('../data/source_datasets/CHIP-CTC/CHIP-CTC_test.json')
submit = []
for id_, text_ in zip(test_df['id'], test_df['text']):
predict_ = tc_predictor_instance.predict_one_sample(text_)[0]
submit.append({
'id': id_,
'text': text_,
'label': predict_
})
output_path = '../data/output_datasets/CHIP-CTC_test.json'
with open(output_path,'w', encoding='utf-8') as f:
f.write(json.dumps(submit, ensure_ascii=False))
```
| github_jupyter |
```
#hide
from neos.models import *
from neos.makers import *
from neos.transforms import *
from neos.fit import *
from neos.infer import *
from neos.smooth import *
```
# neos
> ~neural~ nice end-to-end optimized statistics
[](https://zenodo.org/badge/latestdoi/235776682)  [](https://mybinder.org/v2/gh/pyhf/neos/master?filepath=demo_training.ipynb)
<img src="assets/neos_logo.png" alt="neos logo" width="250"/>

## About
Leverages the shoulders of giants ([`jax`](https://github.com/google/jax/), [`fax`](https://github.com/gehring/fax), and [`pyhf`](https://github.com/scikit-hep/pyhf)) to differentiate through a high-energy physics analysis workflow, including the construction of the frequentist profile likelihood.
Documentation can be found at [gradhep.github.io/neos](gradhep.github.io/neos)!
To see examples of `neos` in action, look for the notebooks in the nbs folder with the `demo_` prefix.
If you're more of a video person, see [this talk](https://www.youtube.com/watch?v=3P4ZDkbleKs) given by [Nathan](https://github.com/phinate) on the broader topic of differentiable programming in high-energy physics, which also covers `neos`.
## Install
Just run
```
python -m pip install neos
```
## Contributing
**Please read** [`CONTRIBUTING.md`](https://github.com/pyhf/neos/blob/master/CONTRIBUTING.md) **before making a PR**, as this project is maintained using [`nbdev`](https://github.com/fastai/nbdev), which operates completely using Jupyter notebooks. One should make their changes in the corresponding notebooks in the [`nbs`](nbs) folder (including `README` changes -- see `nbs/index.ipynb`), and not in the library code, which is automatically generated.
## Example usage -- train a neural network to optimize an expected p-value
```
# bunch of imports:
import time
import jax
import jax.experimental.optimizers as optimizers
import jax.experimental.stax as stax
import jax.random
from jax.random import PRNGKey
import numpy as np
from functools import partial
import pyhf
pyhf.set_backend('jax')
pyhf.default_backend = pyhf.tensor.jax_backend(precision='64b')
from neos import data, infer, makers
rng = PRNGKey(22)
```
Let's start by making a basic neural network for regression with the `stax` module found in `jax`:
```
init_random_params, predict = stax.serial(
stax.Dense(1024),
stax.Relu,
stax.Dense(1024),
stax.Relu,
stax.Dense(1),
stax.Sigmoid,
)
```
Now, let's compose a workflow that can make use of this network in a typical high-energy physics statistical analysis.
Our workflow is as follows:
- From a set of normal distributions with different means, we'll generate four blobs of `(x,y)` points, corresponding to a signal process, a nominal background process, and two variations of the background from varying the background distribution's mean up and down.
- We'll then feed these points into the previously defined neural network for each blob, and construct a histogram of the output using kernel density estimation. The difference between the two background variations is used as a systematic uncertainty on the nominal background.
- We can then leverage the magic of `pyhf` to construct an [event-counting statistical model](https://scikit-hep.org/pyhf/intro.html#histfactory) from the histogram yields.
- Finally, we calculate the p-value of a test between the nominal signal and background-only hypotheses. This uses a [profile likelihood-based test statistic](https://arxiv.org/abs/1007.1727).
In code, `neos` can specify this workflow through function composition:
```
# data generator
data_gen = data.generate_blobs(rng,blobs=4)
# histogram maker
hist_maker = makers.hists_from_nn(data_gen, predict, method='kde')
# statistical model maker
model_maker = makers.histosys_model_from_hists(hist_maker)
# CLs value getter
get_cls = infer.expected_CLs(model_maker, solver_kwargs=dict(pdf_transform=True))
```
A peculiarity to note is that each of the functions used in this step actually return functions themselves. The reason we do this is that we need a skeleton of the workflow with all of the fixed parameters to be in place before calculating the loss function, as the only 'moving parts' here are the weights of the neural network.
`neos` also lets you specify hyperparameters for the histograms (e.g. binning, bandwidth) to allow these to be tuned throughout the learning process if neccesary (we don't do that here).
```
bins = np.linspace(0,1,4) # three bins in the range [0,1]
bandwidth = 0.27 # smoothing parameter
get_loss = partial(get_cls, hyperparams=dict(bins=bins,bandwidth=bandwidth))
```
Our loss currently returns a list of metrics -- let's just index into the first one (the CLs value).
```
def loss(params, test_mu):
return get_loss(params, test_mu)[0]
```
Now we just need to initialize the network's weights, and construct a training loop & optimizer:
```
# init weights
_, network = init_random_params(jax.random.PRNGKey(2), (-1, 2))
# init optimizer
opt_init, opt_update, opt_params = optimizers.adam(1e-3)
# define train loop
def train_network(N):
cls_vals = []
_, network = init_random_params(jax.random.PRNGKey(1), (-1, 2))
state = opt_init(network)
losses = []
# parameter update function
def update_and_value(i, opt_state, mu):
net = opt_params(opt_state)
value, grad = jax.value_and_grad(loss)(net, mu)
return opt_update(i, grad, state), value, net
for i in range(N):
start_time = time.time()
state, value, network = update_and_value(i, state, 1.0)
epoch_time = time.time() - start_time
losses.append(value)
metrics = {"loss": losses}
yield network, metrics, epoch_time
```
It's time to train!
```
maxN = 10 # make me bigger for better results (*nearly* true ;])
for i, (network, metrics, epoch_time) in enumerate(train_network(maxN)):
print(f"epoch {i}:", f'CLs = {metrics["loss"][-1]:.5f}, took {epoch_time:.4f}s')
```
And there we go!
You'll notice the first epoch seems to have a much larger training time. This is because `jax` is being used to just-in-time compile some of the code, which is an overhead that only needs to happen once.
If you want to reproduce the full animation from the top of this README, a version of this code with plotting helpers can be found in [`demo_kde_pyhf.ipynb`](https://github.com/pyhf/neos/blob/master/demo_kde_pyhf.ipynb)! :D
## Thanks
A big thanks to the teams behind [`jax`](https://github.com/google/jax/), [`fax`](https://github.com/gehring/fax), and [`pyhf`](https://github.com/scikit-hep/pyhf) for their software and support.
| github_jupyter |
```
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn import cross_validation
from sklearn.preprocessing import LabelBinarizer, StandardScaler
from sklearn.linear_model import LassoLarsCV
import sklearn
import pandas as pd
import numpy as np
import pandas as pd
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.feature_selection import SelectPercentile, f_regression, VarianceThreshold
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
import xgboost as xg
from tpot.builtins import StackingEstimator
import seaborn as sns
import itertools
import pickle
%matplotlib inline
df = pd.read_csv("../results/melted_hackseq.csv")
df = df.drop(axis=1, labels=["Transcript", "Target gene", "30mer"])
df
dummy_df = pd.get_dummies(df).dropna(axis=0)
dummy_df.shape
cols = dummy_df.columns.tolist()
cols.append(cols.pop(cols.index('lfc')))
dummy_df = dummy_df.reindex(columns= cols)
X, y = dummy_df.iloc[:,:-1].values, dummy_df.iloc[:,-1].values
model = GradientBoostingRegressor()
cross_val = cross_validation.cross_val_score(estimator=model, X=X, y=y, cv = 5, scoring="neg_mean_squared_error")
sum(abs(cross_val))/len(cross_val)
xg1000_model = xg.XGBRegressor(n_estimators=1000)
xg_cross_val = cross_validation.cross_val_score(estimator=xg1000_model, X=X, y=y, cv = 5, scoring="neg_mean_squared_error")
sum(abs(xg_cross_val))/len(xg_cross_val)
iteration1 = make_pipeline(
VarianceThreshold(threshold=0.05),
GradientBoostingRegressor(alpha=0.8,
learning_rate=0.1,
loss="huber",
max_depth=7,
max_features=0.15,
min_samples_leaf=8,
min_samples_split=9,
n_estimators=100,
subsample=0.85)
)
i1_cross_val = cross_validation.cross_val_score(estimator=iteration1, X=X, y=y, cv = 5, scoring="neg_mean_squared_error")
sum(abs(i1_cross_val))/len(i1_cross_val)
iteration2 = GradientBoostingRegressor(alpha=0.8,
learning_rate=0.1,
loss="huber",
max_depth=7,
max_features=0.15,
min_samples_leaf=8,
min_samples_split=9,
n_estimators=100,
subsample=0.85)
i2_cross_val = cross_validation.cross_val_score(estimator=iteration2, X=X, y=y, cv = 5, scoring="neg_mean_squared_error")
sum(abs(i2_cross_val))/len(i2_cross_val)
iteration3 = GradientBoostingRegressor(alpha=0.8,
learning_rate=0.5,
loss="huber",
max_depth=7,
max_features=0.15,
min_samples_leaf=8,
min_samples_split=9,
n_estimators=100,
subsample=0.85)
i3_cross_val = cross_validation.cross_val_score(estimator=iteration3, X=X, y=y, cv = 5, scoring="neg_mean_squared_error")
sum(abs(i3_cross_val))/len(i3_cross_val)
iteration4 = make_pipeline(
StackingEstimator(estimator=xg.XGBRegressor(learning_rate=0.5, max_depth=8, min_child_weight=11, n_estimators=100, nthread=1, subsample=0.8)),
GradientBoostingRegressor(alpha=0.8, learning_rate=0.1, loss="huber", max_depth=7, max_features=0.15, min_samples_leaf=8, min_samples_split=9, n_estimators=100, subsample=0.85)
)
i4_cross_val = cross_validation.cross_val_score(estimator=iteration4, X=X, y=y, cv = 5, scoring="neg_mean_squared_error")
sum(abs(i4_cross_val))/len(i4_cross_val)
iteration5 = make_pipeline(
StandardScaler(),
GradientBoostingRegressor(alpha=0.95, learning_rate=0.1, loss="huber", max_depth=9, max_features=0.15, min_samples_leaf=8, min_samples_split=9, n_estimators=100, subsample=0.85)
)
i5_cross_val = cross_validation.cross_val_score(estimator=iteration5, X=X, y=y, cv = 5, scoring="neg_mean_squared_error")
sum(abs(i5_cross_val))/len(i5_cross_val)
iteration6 = GradientBoostingRegressor(alpha=0.95,
learning_rate=0.1,
loss="huber",
max_depth=9,
max_features=0.15,
min_samples_leaf=8,
min_samples_split=9,
n_estimators=100,
subsample=0.85)
i6_cross_val = cross_validation.cross_val_score(estimator=iteration6, X=X, y=y, cv = 5, scoring="neg_mean_squared_error")
sum(abs(i6_cross_val))/len(i6_cross_val)
cross_vals = [cross_val, xg1000_cross_val, i1_cross_val, i2_cross_val, i3_cross_val, i4_cross_val, i5_cross_val, i6_cross_val]
mean_cross_vals = [abs(np.mean(cross_val)) for cross_val in cross_vals]
sd_cross_vals = [abs(np.std(cross_val)) for cross_val in cross_vals]
pd.DataFrame(zip(names, cross_vals), columns=["Iteration", "MSE"]
with open("cross_vals.pickle", "wb+") as file_pickle:
pickle.dump([names, cross_vals], file_pickle)
with open("../results/cross_vals.pickle", "rb") as file_pickle:
a = pickle.load(file_pickle)
print(a)
experiment_df = pd.DataFrame({"Experiment": names,
"Mean": mean_cross_vals,
"Standard Deviation": sd_cross_vals})
sns.barplot(x = "Experiment",
y = "Mean",
ci = "Standard Deviation",
data=experiment_df)
```
| github_jupyter |
# Torch Core
This module contains all the basic functions we need in other modules of the fastai library (split with [`core`](/core.html#core) that contains the ones not requiring pytorch). Its documentation can easily be skipped at a first read, unless you want to know what a given fuction does.
```
from fastai.imports import *
from fastai.gen_doc.nbdoc import *
from fastai.layers import *
from fastai.torch_core import *
```
## Global constants
`AdamW = partial(optim.Adam, betas=(0.9,0.99))` <div style="text-align: right"><a href="https://github.com/fastai/fastai/blob/master/fastai/torch_core.py#L43">[source]</a></div>
`bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)` <div style="text-align: right"><a href="https://github.com/fastai/fastai/blob/master/fastai/torch_core.py#L41">[source]</a></div>
`defaults.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')` <div style="text-align: right"><a href="https://github.com/fastai/fastai/blob/master/fastai/torch_core.py#L62">[source]</a></div>
If you are trying to make fastai run on the CPU, simply change the default device: `defaults.device = 'cpu'`.
Alternatively, if not using wildcard imports: `fastai.torch_core.defaults.device = 'cpu'`.
## Functions that operate conversions
```
show_doc(batch_to_half)
show_doc(flatten_model, full_name='flatten_model')
```
Flattens all the layers of `m` into an array. This allows for easy access to the layers of the model and allows you to manipulate the model as if it was an array.
```
m = simple_cnn([3,6,12])
m
flatten_model(m)
show_doc(model2half)
```
Converting model parameters to half precision allows us to leverage fast `FP16` arithmatic which can speed up the computations by 2-8 times. It also reduces memory consumption allowing us to train deeper models.
**Note**: Batchnorm layers are not converted to half precision as that may lead to instability in training.
```
m = simple_cnn([3,6,12], bn=True)
def show_params_dtype(state_dict):
"""Simple function to pretty print the dtype of the model params"""
for wt_name, param in state_dict.items():
print("{:<30}: {}".format(wt_name, str(param.dtype)))
print()
print("dtypes of model parameters before model2half: ")
show_params_dtype(m.state_dict())
# Converting model to half precision
m_half = model2half(m)
print("dtypes of model parameters after model2half: ")
show_params_dtype(m_half.state_dict())
show_doc(np2model_tensor)
```
It is a wrapper on top of Pytorch's `torch.as_tensor` which converts numpy array to torch tensor, and additionally attempts to map all floats to `torch.float32` and all integers to `torch.int64` for consistencies in model data. Below is an example demonstrating it's functionality for floating number, similar functionality applies to integer as well.
```
a1 = np.ones((2, 3)).astype(np.float16)
a2 = np.ones((2, 3)).astype(np.float32)
a3 = np.ones((2, 3)).astype(np.float64)
b1 = np2model_tensor(a1) # Maps to torch.float32
b2 = np2model_tensor(a2) # Maps to torch.float32
b3 = np2model_tensor(a3) # Maps to torch.float32
print(f"Datatype of as': {a1.dtype}, {a2.dtype}, {a3.dtype}")
print(f"Datatype of bs': {b1.dtype}, {b2.dtype}, {b3.dtype}")
show_doc(requires_grad)
```
Performs both getting and setting of [`requires_grad`](/torch_core.html#requires_grad) parameter of the tensors, which decided whether to accumulate gradients or not.
* If `b` is `None`: The function **gets** the [`requires_grad`](/torch_core.html#requires_grad) for the model parameter, to be more specific it returns the [`requires_grad`](/torch_core.html#requires_grad) of the first element in the model.
* Else if `b` is passed (a boolean value), [`requires_grad`](/torch_core.html#requires_grad) of all parameters of the model is **set** to `b`.
```
# Any Pytorch model
m = simple_cnn([3, 6, 12], bn=True)
# Get the requires_grad of model
print("requires_grad of model: {}".format(requires_grad(m)))
# Set requires_grad of all params in model to false
requires_grad(m, False)
# Get the requires_grad of model
print("requires_grad of model: {}".format(requires_grad(m)))
show_doc(tensor)
```
Handy function when you want to convert any list type object to tensor, initialize your weights manually, and other similar cases.
**NB**: When passing multiple vectors, all vectors must be of same dimensions. (Obvious but can be forgotten sometimes)
```
# Conversion from any numpy array
b = tensor(np.array([1, 2, 3]))
print(b, type(b))
# Passing as multiple parameters
b = tensor(1, 2, 3)
print(b, type(b))
# Passing a single list
b = tensor([1, 2, 3])
print(b, type(b))
# Can work with multiple vectors / lists
b = tensor([1, 2], [3, 4])
print(b, type(b))
show_doc(to_cpu)
```
A wrapper on top of Pytorch's `torch.Tensor.cpu()` function, which creates and returns a copy of a tensor or even a **list** of tensors in the CPU. As described in Pytorch's docs, if the tensor or list of tensor is already on the CPU, the exact data is returned and no copy is made.
Usefult to convert all the list of parameters of the model to CPU in a single call.
```
if torch.cuda.is_available():
a = [torch.randn((1, 1)).cuda() for i in range(3)]
print(a)
print("Id of tensors in a: ")
for i in a: print(id(i))
# Getting a CPU version of the tensors in GPU
b = to_cpu(a)
print(b)
print("Id of tensors in b:")
for i in b: print(id(i))
# Trying to perform to_cpu on a list of tensor already in CPU
c = to_cpu(b)
print(c)
# The tensors in c has exact id as that of b. No copy performed.
print("Id of tensors in c:")
for i in c: print(id(i))
show_doc(to_data)
```
Returns the data attribute from the object or collection of objects that inherits from [`ItemBase`](/core.html#ItemBase) class. Useful to examine the exact values of the data, could be used to work with the data outside of `fastai` classes.
```
# Default example examined
from fastai import *
from fastai.vision import *
path = untar_data(URLs.MNIST_SAMPLE)
data = ImageDataBunch.from_folder(path)
# Examin the labels
ys = list(data.y)
print("Category display names: ", [ys[0], ys[-1]])
print("Unique classes internally represented as: ", to_data([ys[0], ys[-1]]))
show_doc(to_detach)
show_doc(to_device)
show_doc(to_half)
```
Converts the tensor or list of `FP16`, resulting in less memory consumption and faster computations with the tensor. It does not convert `torch.int` types to half precision.
```
a1 = torch.tensor([1, 2], dtype=torch.int64)
a2 = torch.tensor([1, 2], dtype=torch.int32)
a3 = torch.tensor([1, 2], dtype=torch.int16)
a4 = torch.tensor([1, 2], dtype=torch.float64)
a5 = torch.tensor([1, 2], dtype=torch.float32)
a6 = torch.tensor([1, 2], dtype=torch.float16)
print("dtype of as: ", a1.dtype, a2.dtype, a3.dtype, a4.dtype, a5.dtype, a6.dtype, sep="\t")
b1, b2, b3, b4, b5, b6 = to_half([a1, a2, a3, a4, a5, a6])
print("dtype of bs: ", b1.dtype, b2.dtype, b3.dtype, b4.dtype, b5.dtype, b6.dtype, sep="\t")
show_doc(to_np)
```
Internally puts the data to CPU, and converts to `numpy.ndarray` equivalent of `torch.tensor` by calling `torch.Tensor.numpy()`.
```
a = torch.tensor([1, 2], dtype=torch.float64)
if torch.cuda.is_available():
a = a.cuda()
print(a, type(a), a.device)
b = to_np(a)
print(b, type(b))
show_doc(try_int)
# Converts floating point numbers to integer
print(try_int(12.5), type(try_int(12.5)))
# This is a Rank-1 ndarray, which ideally should not be converted to int
print(try_int(np.array([1.5])), try_int(np.array([1.5])).dtype)
# Numpy array with a single elements are converted to int
print(try_int(np.array(1.5)), type(try_int(np.array(1.5))))
print(try_int(torch.tensor(2.5)), type(try_int(torch.tensor(2.5))))
# Strings are not converted to int (of course)
print(try_int("12.5"), type(try_int("12.5")))
```
## Functions to deal with model initialization
```
show_doc(apply_init)
show_doc(apply_leaf)
show_doc(cond_init)
show_doc(in_channels)
show_doc(init_default)
```
## Functions to get information of a model
```
show_doc(children)
show_doc(children_and_parameters)
show_doc(first_layer)
show_doc(last_layer)
show_doc(num_children)
show_doc(one_param)
show_doc(range_children)
show_doc(trainable_params)
```
## Functions to deal with BatchNorm layers
```
show_doc(bn2float)
show_doc(set_bn_eval)
show_doc(split_bn_bias)
```
## Functions to get random tensors
```
show_doc(log_uniform)
log_uniform(0.5,2,(8,))
show_doc(rand_bool)
rand_bool(0.5, 8)
show_doc(uniform)
uniform(0,1,(8,))
show_doc(uniform_int)
uniform_int(0,2,(8,))
```
## Other functions
```
show_doc(ParameterModule, title_level=3)
show_doc(calc_loss)
show_doc(data_collate)
show_doc(get_model)
show_doc(grab_idx)
show_doc(logit)
show_doc(logit_)
show_doc(model_type)
show_doc(np_address)
show_doc(split_model)
```
If `splits` are layers, the model is split at those (not included) sequentially. If `want_idxs` is True, the corresponding indexes are returned. If `splits` are lists of layers, the model is split according to those.
```
show_doc(split_model_idx)
show_doc(trange_of)
```
## Undocumented Methods - Methods moved below this line will intentionally be hidden
```
show_doc(tensor__array__)
show_doc(ParameterModule.forward)
```
## New Methods - Please document or move to the undocumented section
| github_jupyter |
```
import os
path = '/home/yash/Desktop/tensorflow-adversarial/tf_example'
os.chdir(path)
# supress tensorflow logging other than errors
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn import ModeKeys, Estimator
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from fgsm4 import fgsm
import mnist
img_rows = 28
img_cols = 28
img_chas = 1
input_shape = (img_rows, img_cols, img_chas)
n_classes = 10
print('\nLoading mnist')
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.astype('float32') / 255.
X_test = X_test.astype('float32') / 255.
X_train = X_train.reshape(-1, img_rows, img_cols, img_chas)
X_test = X_test.reshape(-1, img_rows, img_cols, img_chas)
# one hot encoding, basically creates hte si
def _to_categorical(x, n_classes):
x = np.array(x, dtype=int).ravel()
n = x.shape[0]
ret = np.zeros((n, n_classes))
ret[np.arange(n), x] = 1
return ret
def find_l2(X_test, X_adv):
a=X_test.reshape(-1,28*28)
b=X_adv.reshape(-1,28*28)
l2_unsquared = np.sum(np.square(a-b),axis=1)
return l2_unsquared
y_train = _to_categorical(y_train, n_classes)
y_test = _to_categorical(y_test, n_classes)
print('\nShuffling training data')
ind = np.random.permutation(X_train.shape[0])
X_train, y_train = X_train[ind], y_train[ind]
# X_train = X_train[:1000]
# y_train = y_train[:1000]
# split training/validation dataset
validation_split = 0.1
n_train = int(X_train.shape[0]*(1-validation_split))
X_valid = X_train[n_train:]
X_train = X_train[:n_train]
y_valid = y_train[n_train:]
y_train = y_train[:n_train]
class Dummy:
pass
env = Dummy()
def model(x, logits=False, training=False):
conv0 = tf.layers.conv2d(x, filters=32, kernel_size=[3, 3],
padding='same', name='conv0',
activation=tf.nn.relu)
pool0 = tf.layers.max_pooling2d(conv0, pool_size=[2, 2],
strides=2, name='pool0')
conv1 = tf.layers.conv2d(pool0, filters=64,
kernel_size=[3, 3], padding='same',
name='conv1', activation=tf.nn.relu)
pool1 = tf.layers.max_pooling2d(conv1, pool_size=[2, 2],
strides=2, name='pool1')
flat = tf.reshape(pool1, [-1, 7*7*64], name='flatten')
dense1 = tf.layers.dense(flat, units=1024, activation=tf.nn.relu,
name='dense1')
dense2 = tf.layers.dense(dense1, units=128, activation=tf.nn.relu,
name='dense2')
logits_ = tf.layers.dense(dense2, units=10, name='logits') #removed dropout
y = tf.nn.softmax(logits_, name='ybar')
if logits:
return y, logits_
return y
# We need a scope since the inference graph will be reused later
with tf.variable_scope('model'):
env.x = tf.placeholder(tf.float32, (None, img_rows, img_cols,
img_chas), name='x')
env.y = tf.placeholder(tf.float32, (None, n_classes), name='y')
env.training = tf.placeholder(bool, (), name='mode')
env.ybar, logits = model(env.x, logits=True,
training=env.training)
z = tf.argmax(env.y, axis=1)
zbar = tf.argmax(env.ybar, axis=1)
env.count = tf.cast(tf.equal(z, zbar), tf.float32)
env.acc = tf.reduce_mean(env.count, name='acc')
xent = tf.nn.softmax_cross_entropy_with_logits(labels=env.y,
logits=logits)
env.loss = tf.reduce_mean(xent, name='loss')
extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(extra_update_ops):
env.optim = tf.train.AdamOptimizer(beta1=0.9, beta2=0.999, epsilon=1e-08,).minimize(env.loss)
with tf.variable_scope('model', reuse=True):
env.x_adv, env.all_flipped = fgsm(model, env.x, step_size=.05, bbox_semi_side=10) #epochs is redundant now!
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
def save_model(label):
saver = tf.train.Saver()
saver.save(sess, './models/mnist/' + label)
def restore_model(label):
saver = tf.train.Saver()
saver.restore(sess, './models/mnist/' + label)
def _evaluate(X_data, y_data, env):
print('\nEvaluating')
n_sample = X_data.shape[0]
batch_size = 128
n_batch = int(np.ceil(n_sample/batch_size))
loss, acc = 0, 0
ns = 0
for ind in range(n_batch):
print(' batch {0}/{1}'.format(ind+1, n_batch), end='\r')
start = ind*batch_size
end = min(n_sample, start+batch_size)
batch_loss, batch_count, batch_acc = sess.run(
[env.loss, env.count, env.acc],
feed_dict={env.x: X_data[start:end],
env.y: y_data[start:end],
env.training: False})
loss += batch_loss*batch_size
print('batch count: {0}'.format(np.sum(batch_count)))
ns+=batch_size
acc += batch_acc*batch_size
loss /= ns
acc /= ns
# print (ns)
# print (n_sample)
print(' loss: {0:.4f} acc: {1:.4f}'.format(loss, acc))
return loss, acc
def _predict(X_data, env):
print('\nPredicting')
n_sample = X_data.shape[0]
batch_size = 128
n_batch = int(np.ceil(n_sample/batch_size))
yval = np.empty((X_data.shape[0], n_classes))
for ind in range(n_batch):
print(' batch {0}/{1}'.format(ind+1, n_batch), end='\r')
start = ind*batch_size
end = min(n_sample, start+batch_size)
batch_y = sess.run(env.ybar, feed_dict={
env.x: X_data[start:end], env.training: False})
yval[start:end] = batch_y
return yval
def train(label):
print('\nTraining')
n_sample = X_train.shape[0]
batch_size = 128
n_batch = int(np.ceil(n_sample/batch_size))
n_epoch = 50
for epoch in range(n_epoch):
print('Epoch {0}/{1}'.format(epoch+1, n_epoch))
for ind in range(n_batch):
print(' batch {0}/{1}'.format(ind+1, n_batch), end='\r')
start = ind*batch_size
end = min(n_sample, start+batch_size)
sess.run(env.optim, feed_dict={env.x: X_train[start:end],
env.y: y_train[start:end],
env.training: True})
if(epoch%5 == 0):
model_label = label+ '{0}'.format(epoch)
print("saving model " + model_label)
save_model(model_label)
save_model(label)
def create_adv(X, Y, label):
print('\nCrafting adversarial')
n_sample = X.shape[0]
batch_size = 1
n_batch = int(np.ceil(n_sample/batch_size))
n_epoch = 20
X_adv = np.empty_like(X)
for ind in range(n_batch):
print(' batch {0}/{1}'.format(ind+1, n_batch), end='\r')
start = ind*batch_size
end = min(n_sample, start+batch_size)
tmp, all_flipped = sess.run([env.x_adv, env.all_flipped], feed_dict={env.x: X[start:end],
env.y: Y[start:end],
env.training: False})
# _evaluate(tmp, Y[start:end],env)
X_adv[start:end] = tmp
# print(all_flipped)
print('\nSaving adversarial')
os.makedirs('data', exist_ok=True)
np.save('data/mnist/' + label + '.npy', X_adv)
return X_adv
label = "mnist_with_cnn"
# train(label) # else
#Assuming that you've started a session already else do that first!
restore_model(label + '5')
# restore_model(label + '10')
# restore_model(label + '50')
# restore_model(label + '100')
print("Train acc: ")
_evaluate(X_train, y_train, env)
print("Test acc: ")
_evaluate(X_test, y_test, env)
def random_normal_func(X, n):
X=X.reshape(-1,img_rows*img_cols*img_chas)
print(X.shape)
mean, std = np.mean(X, axis=0), np.std(X,axis=0)
randomX = np.zeros([n,X[0].size])
print(randomX.shape)
for i in range(X[0].size):
randomX[:,i] = np.random.normal(mean[i],std[i],n)
randomX = randomX.reshape(-1,img_rows,img_cols,img_chas)
ans = sess.run(env.ybar, feed_dict={env.x: randomX,env.training: False})
labels = _to_categorical(np.argmax(ans,axis=1), n_classes)
return randomX,labels
test = "test_fs_exp1_5"
train = "train_fs_exp1_5"
random = "random_fs_exp1_5"
random_normal= "random_normal_fs_exp1_5"
n = 1000
X_train_sub = X_train[:n]
y_train_sub = sess.run(env.ybar, feed_dict={env.x: X_train_sub,env.training: False})
y_train_sub = _to_categorical(np.argmax(y_train_sub, axis=1), n_classes)
y_test_sub = sess.run(env.ybar, feed_dict={env.x: X_test[:n],env.training: False})
y_test_sub = _to_categorical(np.argmax(y_test_sub, axis=1), n_classes)
X_random = np.random.rand(n,28,28,1)
X_random = X_random[:n]
y_random = sess.run(env.ybar, feed_dict={env.x: X_random,env.training: False})
y_random = _to_categorical(np.argmax(y_random, axis=1), n_classes)
X_random_normal, y_random_normal = random_normal_func(X_train,n)
X_adv_test = create_adv(X_test[:n], y_test_sub, test)
X_adv_train = create_adv(X_train_sub, y_train_sub, train)
X_adv_random = create_adv(X_random,y_random, random)
X_adv_random_normal = create_adv(X_random_normal, y_random_normal, random_normal)
# X_adv_test = np.load('data/mnist/' + test + '.npy')
# X_adv_train = np.load('data/mnist/' + train + '.npy')
# X_adv_random = np.load('data/mnist/' + random + '.npy')
# X_adv_random_normal = np.load('data/mnist/' + random_normal + '.npy')
l2_test = find_l2(X_adv_test,X_test[:n])
l2_train = find_l2(X_adv_train, X_train_sub)
l2_random = find_l2(X_adv_random,X_random)
l2_random_normal = find_l2(X_adv_random_normal,X_random_normal)
print (np.count_nonzero(l2_test))
print (np.count_nonzero(l2_train))
print(X_adv_random_normal[0][3])
%matplotlib inline
# evenly sampled time at 200ms intervals
t = np.arange(1,10001, 1)
# red dashes, blue squares and green triangles
plt.plot(t, l2_test, 'r--', t, l2_train, 'b--', t, l2_random, 'y--', l2_random_normal, 'g--')
plt.show()
import matplotlib.patches as mpatches
%matplotlib inline
# evenly sampled time at 200ms intervals
t = np.arange(1,101, 1)
# red dashes, blue squares and green triangles
plt.plot(t, l2_test[:100], 'r--', t, l2_train[:100], 'b--',t, l2_random[:100], 'y--',l2_random_normal[:100], 'g--')
blue_patch = mpatches.Patch(color='blue', label='Train Data')
plt.legend(handles=[blue_patch])
plt.show()
%matplotlib inline
plt.hist(l2_test,100)
plt.title("L2 distance of test data")
plt.xlabel("Distance")
plt.ylabel("Frequency")
plt.show()
%matplotlib inline
plt.hist(l2_train,100)
plt.title("L2 distance of train data")
plt.xlabel("Distance")
plt.ylabel("Frequency")
plt.show()
%matplotlib inline
plt.hist(l2_random,100)
plt.title("L2 distance of random data")
plt.xlabel("Distance")
plt.ylabel("Frequency")
plt.show()
%matplotlib inline
plt.hist(l2_random_normal,100)
plt.title("L2 distance of random normal data")
plt.xlabel("Distance")
plt.ylabel("Frequency")
plt.show()
```
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
from IPython.display import Image
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
import os
import time
import json
import jax.numpy as np
import numpy as onp
import jax
import pickle
import matplotlib.pyplot as plt
import pandas as pd
from timecast.utils.numpy import ecdf
from timecast.utils.losses import MeanSquareError
import torch
import matplotlib
plt.rcParams['figure.figsize'] = [20, 10]
import tqdm.notebook as tqdm
from ealstm.gaip.flood_data import FloodData
from ealstm.gaip.utils import MSE, NSE
cfg_path = "../data/models/runs/run_2006_0032_seed444/cfg.json"
ea_data = pickle.load(open("../data/models/runs/run_2006_0032_seed444/lstm_seed444.p", "rb"))
flood_data = FloodData(cfg_path)
LR_AR = 1e-5
AR_INPUT_DIM=32
AR_OUTPUT_DIM=1
BATCH_SIZE=1
from flax import nn
from flax import optim
import jax
import jax.numpy as jnp
class ARF(nn.Module):
def apply(self, x, input_features, output_features, window_size, history=None):
if x.ndim == 1:
x = x.reshape(1, -1)
if self.is_initializing() and history is not None:
x = history
self.history = self.state("history", shape=(window_size, input_features), initializer=nn.initializers.zeros)
self.history.value = np.vstack((self.history.value, x))[x.shape[0]:]
y = nn.DenseGeneral(inputs=self.history.value,
features=output_features,
axis=(0, 1),
batch_dims=(),
bias=True,
dtype=jnp.float32,
kernel_init=nn.initializers.zeros,
bias_init=nn.initializers.zeros,
precision=None,
name="linear"
)
return y
class Take(nn.Module):
def apply(self, x, i):
return x[i]
class Identity(nn.Module):
def apply(self, x):
return x
class Plus(nn.Module):
def apply(self, x, z):
return x + z
class Ensemble(nn.Module):
def apply(self, x, modules, args):
return [module(x, **arg) for (module, arg) in zip(modules, args)]
class Sequential(nn.Module):
def apply(self, x, modules, args):
results = x
for module, arg in zip(modules, args):
results = module(results, **arg)
return results
class Residual(nn.Module):
def apply(self, x, input_features, output_features, window_size, history):
y_arf = ARF(x=x[1],
input_features=input_features,
output_features=output_features,
window_size=window_size,
history=history
)
return (x[0], y_arf)
def run(X, Y, optimizer, state, objective, loss_fn):
def _run(optstate, xy):
x, y = xy
optimizer, state = optstate
with nn.stateful(state) as state:
loss, y_hat, grad = optimizer.compute_gradients(partial(objective, x, y, loss_fn))
return (optimizer.apply_gradient(grad), state), y_hat
_, pred = jax.lax.scan(_run, (optimizer, state), (X, Y))
return pred
from functools import partial
def residual(x, y, loss_fn, model):
y_hats = model(x)
target, y_hat, loss = y, y_hats[0], 0
for i in range(len(y_hats) - 1):
loss += loss_fn(target - y_hats[i], y_hats[i + 1])
target -= y_hats[i]
y_hat += y_hats[i + 1]
return loss, y_hat
def xboost(x, y, loss_fn, model, reg = 1.0):
y_hats = model(x)
g = jax.grad(loss_fn)
u, loss = 0, 0
for i in range(len(y_hats)):
eta = (2 / (i + 2))
loss += g(y, u) * y_hats[i] + (reg / 2) * y_hats[i] * y_hats[i]
u = (1 - eta) * u + eta * y_hats[i]
return loss.reshape(()), u
results = {}
mses = []
nses = []
for X, y, basin in tqdm.tqdm(flood_data.generator(), total=len(flood_data.basins)):
with nn.stateful() as state:
# model_def = Residual.partial(input_features=32,
# output_features=1,
# window_size=270,
# history=X[:flood_data.cfg["seq_length"]-1]
# )
lstm = Sequential.partial(modules=[Take, Identity], args=[{"i": 0}, {}])
arf = Sequential.partial(modules=[Take, ARF], args=[{"i": 1}, {"input_features": 32, "output_features": 1, "window_size": 270, "history": X[:flood_data.cfg["seq_length"]-1]}])
model_def = Ensemble.partial(modules=[lstm, arf], args=[{}, {}])
ys, params = model_def.init_by_shape(jax.random.PRNGKey(0), [(1, 32)])
model = nn.Model(model_def, params)
optim_def = optim.GradientDescent(learning_rate=1e-5)
optimizer = optim_def.create(model)
# NOTE: difference in indexing convention, so need to pad one row
X_t = X[flood_data.cfg["seq_length"]-1:]
Y_lstm = np.array(ea_data[basin].qsim)
Y = np.array(ea_data[basin].qobs).reshape(-1, 1)
Y_hat = run((Y_lstm, X_t), Y, optimizer, state, residual, lambda x, y: jnp.square(x-y).mean())
mse = MSE(Y, Y_hat)
nse = NSE(Y, Y_hat)
results[basin] = {
"mse": mse,
"nse": nse,
"count": X.shape[0],
"avg_mse": np.mean(np.array(mses)),
"avg_nse": np.mean(np.array(nses))
}
mses.append(mse)
nses.append(nse)
print(basin, mse, nse, np.mean(np.array(mses)), np.mean(np.array(nses)))
np.array(ea_data[basin].qsim)[0]
class A:
pass
class B(A):
pass
class C(B):
pass
c = C()
issubclass(type(c), A)
issubclass(np.array(1), onp.ndarray)
```
| github_jupyter |
```
from jeremy import spGrids
import numpy as np
from lat_type import lat_type
```
Let's first check if we can get bcc or fcc from a simple cubic parent.
```
A = np.transpose([[1,0,0],[0,1,0],[0,0,1]])
temp = spGrids(A,2)
g = temp[0]['grid_vecs']
g
lat_type(np.transpose(g))
temp = spGrids(A,4)
g = temp[0]['grid_vecs']
print("grid vecs: ",np.transpose(g))
lat_type(np.transpose(g))[0]
```
Can we get simple cubic or fcc from bcc?
```
A = np.transpose([[1,1,-1],[1,-1,1],[-1,1,1]])
temp = spGrids(A,2)
g = temp[0]['grid_vecs']
print("grid vecs: ",np.transpose(g))
lat_type(np.transpose(g))[0]
temp = spGrids(A,1)
g = temp[0]['grid_vecs']
print("grid vecs: ",np.transpose(g))
lat_type(np.transpose(g))[0]
temp = spGrids(A,4)
g = temp[0]['grid_vecs']
print("grid vecs: ",np.transpose(g))
lat_type(np.transpose(np.linalg.inv(g)))[0]
```
Do we get sc and bcc from fcc?
```
A = np.transpose([[1,1,0],[1,0,1],[0,1,1]])
temp = spGrids(A,1)
g = temp[0]['grid_vecs']
print("grid vecs: ",np.transpose(g))
lat_type(np.transpose(g))[0]
temp = spGrids(A,4)
g = temp[0]['grid_vecs']
print("grid vecs: ",np.transpose(g))
lat_type(np.transpose(g))[0]
temp = spGrids(A,16)
g = temp[0]['grid_vecs']
print("grid vecs: ",np.transpose(g))
lat_type(np.transpose(g))[0]
```
Does this trend hold for orthorhombic cells?
```
A = np.transpose([[1,0,0],[0,2,0],[0,0,3]])
print(np.linalg.inv(A))
temp = spGrids(A,2)
for t in temp:
g = t['grid_vecs']
print("grid vecs: ",np.transpose(g))
print('lat_type: ',lat_type(np.transpose(g))[0])
temp = spGrids(A,4)
for t in temp:
g = t['grid_vecs']
print("grid vecs: ",np.transpose(g))
print('lat_type: ',lat_type(np.transpose(g))[0])
```
Now for base centered ortho
```
A = np.transpose([[0.5,1,0],[0.5,-1,0],[0,0,3]])
print(np.linalg.inv(A))
temp = spGrids(A,2)
for t in temp:
g = t['grid_vecs']
print("grid vecs: ",np.transpose(g))
print('lat_type: ',lat_type(np.transpose(g))[0])
temp = spGrids(A,8)
for t in temp:
g = t['grid_vecs']
print("grid vecs: ",np.transpose(g))
print('lat_type: ',lat_type(np.transpose(g))[0])
```
Now for body centered othor:
```
A = np.transpose([[0.5,1,-1.5],[0.5,-1,1.5],[-0.5,1,1.5]])
print(np.linalg.inv(A))
print(lat_type(np.linalg.inv(A))[0])
temp = spGrids(A,2)
for t in temp:
g = t['grid_vecs']
print("grid vecs: ",np.transpose(g))
print('lat_type: ',lat_type(np.transpose(g))[0])
temp = spGrids(A,3)
for t in temp:
g = t['grid_vecs']
print("grid vecs: ",np.transpose(g))
print('lat_type: ',lat_type(np.transpose(g))[0])
temp = spGrids(A,4)
for t in temp:
g = t['grid_vecs']
print("grid vecs: ",np.transpose(g))
print('lat_type: ',lat_type(np.transpose(g))[0])
```
Now for face centere ortho:
```
A = np.transpose([[0.5,1,0],[0.5,0,1.5],[0,1,1.5]])
print(np.linalg.inv(A))
print(lat_type(np.linalg.inv(A))[0])
temp = spGrids(A,2)
for t in temp:
g = t['grid_vecs']
print("grid vecs: ",np.transpose(g))
print('lat_type: ',lat_type(np.transpose(g))[0])
temp = spGrids(A,4)
for t in temp:
g = t['grid_vecs']
print("grid vecs: ",np.transpose(g))
print('lat_type: ',lat_type(np.transpose(g))[0])
```
| github_jupyter |
```
import os, sys
import jieba, codecs, math
import jieba.posseg as pseg
from pyecharts import options as opts
from pyecharts.charts import Graph
class RelationExtractor:
def __init__(self, fpStopWords, fpNameDicts, fpAliasNames):
# 人名词典
self.name_dicts = [line.strip().split(' ')[0] for line in open(fpNameDicts,'rt',encoding='utf-8').readlines()]
# 停止词表
self.stop_words = [line.strip() for line in open(fpStopWords,'rt',encoding='utf-8').readlines()]
# 别名词典
self.alias_names = dict([(line.split(',')[0].strip(), line.split(',')[1].strip()) for line in open(fpAliasNames,'rt',encoding='utf-8').readlines()])
# 加载词典
jieba.load_userdict(fpNameDicts)
# 提取指定小说文本中的人物关系
def extract(self, fpText):
# 人物关系
relationships = {}
# 人名频次
name_frequency = {}
# 每个段落中的人名
name_in_paragraph = []
# 读取小说文本,统计人名出现的频次,以及每个段落中出现的人名
with codecs.open(fpText, "r", "utf8") as f:
for line in f.readlines():
poss = pseg.cut(line)
name_in_paragraph.append([])
for w in poss:
if w.flag != "nr" or len(w.word) < 2:
continue
if (w.word in self.stop_words):
continue
if (not w.word in self.name_dicts and w.word != '半泽'):
continue
# 规范化人物姓名,例:半泽->半泽直树,大和田->大和田晓
word = w.word
if (self.alias_names.get(word)):
word = self.alias_names.get(word)
name_in_paragraph[-1].append(word)
if name_frequency.get(word) is None:
name_frequency[word] = 0
relationships[word] = {}
name_frequency[word] += 1
# 基于共现组织人物关系
for paragraph in name_in_paragraph:
for name1 in paragraph:
for name2 in paragraph:
if name1 == name2:
continue
if relationships[name1].get(name2) is None:
relationships[name1][name2] = 1
else:
relationships[name1][name2] += 1
# 返回节点和边
return name_frequency, relationships
# 输出Gephi格式的节点和边信息
def exportGephi(self, nodes, relationships):
# 输出节点
with codecs.open("./node.txt", "w", "gbk") as f:
f.write("Id Label Weight\r\n")
for name, freq in nodes.items():
f.write(name + " " + name + " " + str(freq) + "\r\n")
# 输出边
with codecs.open("./edge.txt", "w", "gbk") as f:
f.write("Source Target Weight\r\n")
for name, edges in relationships.items():
for v, w in edges.items():
if w > 0:
f.write(name + " " + v + " " + str(w) + "\r\n")
# 使用ECharts对人物关系进行渲染
def exportECharts(self, nodes, relationships):
# 总频次,用于数据的归一化
total = sum(list(map(lambda x:x[1], nodes.items())))
# 输出节点
nodes_data = []
for name, freq in nodes.items():
nodes_data.append(opts.GraphNode(
name = name,
symbol_size = round(freq / total * 100, 2),
value = freq,
)),
# 输出边
links_data = []
for name, edges in relationships.items():
for v, w in edges.items():
if w > 0:
links_data.append(opts.GraphLink(
source = v,
target = w,
value = w
))
# 绘制Graph
c = (
Graph()
.add(
"",
nodes_data,
links_data,
gravity = 0.2,
repulsion = 8000,
is_draggable = True,
symbol = 'circle',
linestyle_opts = opts.LineStyleOpts(
curve = 0.3,
width = 0.5,
opacity = 0.7
),
edge_label = opts.LabelOpts(
is_show = False,
position = "middle",
formatter = "{b}->{c}"
),
)
.set_global_opts(
title_opts = opts.TitleOpts(title="小说人物关系抽取")
)
.render("./小说人物关系抽取.html")
)
extractor = RelationExtractor('../../Resources/stopwords/baidu_stopwords.txt',
'./人名词典.txt',
'./别名词典.txt'
)
nodes, relationships = extractor.extract('./鹿鼎记.txt')
extractor.exportGephi(nodes, relationships)
extractor.exportECharts(nodes, relationships)
```
| github_jupyter |
# Auto Insurance Fraud Detection
## Data preparation and Modeling
Here we will prepare the data for the machine learning algorithms and asses the performance of multiple ML models
The Jupyter Notebook performing exploratory data analysis can be obtained [here](Insurance Fraud Detection-EDA.ipynb)
### Approach
1. Check for missing values and non-informative features
2. Encoding of categorical values
3. Split data into training and hold out testing
4. Try out many models
* Hyperparameter tuning using grid-search
* Evaluation on hold-out testing data
* Performance analysis based on model evaluation metrics
5. Select the best model
The final model can then be deployed to flag a given insurance claim as fraudulent or legitimate
### Importing all the necessary packages
```
import pandas as pd
import numpy as np
import itertools
from matplotlib import pyplot as plt
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score
#from sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score, precision_score, recall_score, f1_score, precision_recall_curve
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from xgboost.sklearn import XGBClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import sklearn.metrics
from pylab import rcParams
plt.style.use('seaborn')
%matplotlib inline
# Turning-off the warnings
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
```
### Lets first import the dataset
The dataset is available at https://raw.githubusercontent.com/jodb/sparkTestData/master/insurance_claims.csv
```
#load & view the data
df = pd.read_csv('insurance_claims.csv')
df.head(10)
# unique entries. Useful to know the catagorical features
df.nunique()
```
### Data preprocessing and cleaning
```
# Total number of missing values
df.isna().sum().sum()
# column with missing values
df.columns[df.isna().any()]
```
all of the missing values are in the _c39 column. We will drop it later.
```
# columns with ? entries
df.columns[(df == '?').any()]
df[df.columns[(df == '?').any()]].nunique()
```
property_damage and police_report_available are boolean (YES/NO) types. Hence, we will regard the missing values as NO. The collision_type can be side, rear, and front. We will just regard the ? as a separate collision type.
```
df['property_damage'].replace(to_replace='?', value='NO', inplace=True)
df['police_report_available'].replace(to_replace='?', value='NO', inplace=True)
# check if there are duplicated entries
df.duplicated(subset=None, keep='first').sum()
# dropping uninformative features
colsToDelete = ["policy_number", "policy_bind_date", "insured_zip", "incident_location", "incident_date", "_c39"]
df = df.drop(columns = colsToDelete, axis=1)
df.head()
```
### Identify and remove highly correlated features
```
threshold = 0.97
# calculate correlations
corr_matrix = df.corr().abs()
# get the upper part of correlation matrix
upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
# columns with correlation above threshold
redundent = [column for column in upper.columns if any(upper[column] >= threshold)]
print(f'Columns to drop with correlation > {threshold}: {redundent}')
df.drop(columns=redundent, inplace=True)
```
### Now let's find the catagorical features
#### They should be one-hot-encode Now let's find the catagorical features and one-hot-encode them
```
num_features = df._get_numeric_data().columns
cat_features = list(set(df.columns) - set(num_features))
cat_features.remove('fraud_reported')
cat_features
df[num_features].head()
df[cat_features].head()
```
### Separate the target column from the features
```
# separate the target column from the features
y = df["fraud_reported"].map({"N":0, "Y":1})
X = df.drop("fraud_reported", axis=1)
```
### Set up a preprocessing pipeline to one-hot-encode catagorical features and let the numerical features passthrough as they are
```
preprocessor = ColumnTransformer([("numerical", "passthrough", num_features),
("categorical", OneHotEncoder(sparse=False, handle_unknown="ignore"),
cat_features)])
```
### Define the ML models
```
# Logistic Regression
lr_model = Pipeline([("preprocessor", preprocessor),
("model", LogisticRegression(class_weight="balanced", solver="liblinear", random_state=42))])
# Decision Tree
dt_model = Pipeline([("preprocessor", preprocessor),
("model", DecisionTreeClassifier(class_weight="balanced"))])
# LDA
lda_model = Pipeline([("preprocessor", preprocessor),
("model", LinearDiscriminantAnalysis())])
# Random Forest
rf_model = Pipeline([("preprocessor", preprocessor),
("model", RandomForestClassifier(class_weight="balanced", n_estimators=100, n_jobs=-1))])
# XGBoost
xgb_model = Pipeline([("preprocessor", preprocessor),
# Add a scale_pos_weight to make it balanced
("model", XGBClassifier(scale_pos_weight=(1 - y.mean()), n_jobs=-1))])
```
##### Lets define a function to automate split the data into training and test sets and compute multiple evaluation matrices and plot ROC and PVR curves.
Since we have an imbalanced dataset, we can't use metrics such as Accuracy. Instead, we will be mainly using the Receiver Operating Characteristic Area Under the Curve (ROC AUC). Precision, Recall, and fl-score are also other alternatives.
* It should be noted that the choice of the metric depends on the business requirement. Hence, models can be optimized accordingly.
The 5xcv cross-validation gives a better sense of the average performance of the model.
First lets write a function to plot ROC and PVR curves
```
# A function to plot the ROC and PVR curves
def plot_eval(testY, predY, auc):
fpr, tpr, thresh = sklearn.metrics.roc_curve(testY, predY[:,1])
plt.plot(fpr, tpr, label='ROC curve (area = %.2f)' %auc)
plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Random guess')
plt.title('ROC curve')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.grid()
plt.legend()
plt.show()
precision_rt, recall_rt, threshold_rt = sklearn.metrics.precision_recall_curve(testY, predY[:,1])
plt.plot(recall_rt, precision_rt, linewidth=5, label='Precision-Recall curve')
plt.title('Recall vs Precision')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.show()
def model_evaluate(model, X, y, grid_params, plot_eval_curves = False):
"""Prepares a training and test set and evaluates the ML model
on multiple metrices
Arguments:
---------
model: a defined ML model
X: the feature matix
y: the labels
grid_params: hyperparameters to perform grid search on (dict)
plot_eval_curves: If False, outputs metrices
If True, plots ROC and precision vs. recall curves
"""
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=.2, random_state=555)
gs = GridSearchCV(model, grid_params,
n_jobs=-1, cv=5, scoring="roc_auc")
gs.fit(X_train, y_train)
model.set_params(**gs.best_params_)
model.fit(X_train, y_train)
# Predict probabilities and labels
probs = model.predict_proba(X_test)
preds = model.predict(X_test)
# Calculate ROC AUC
auc = sklearn.metrics.roc_auc_score(y_test, probs[:, 1])
# get the confusion matrix
cnf_matrix = sklearn.metrics.confusion_matrix(y_test, preds)
# Plot ROC curve
if plot_eval_curves:
plot_eval(y_test, probs, auc)
else:
print('Best Parameters:', gs.best_params_)
print('Best Score:', gs.best_score_)
print(f'ROC AUC: {round(auc, 4)}')
print(f'Confusion Matrix:\n {cnf_matrix}')
# compute the other evaluation metrices
for metric in [sklearn.metrics.precision_score, sklearn.metrics.recall_score, sklearn.metrics.f1_score]:
print(f'{metric.__name__}: {round(metric(y_test, preds), 4)}')
# Average performance using 5 x cross-validation
score = cross_val_score(model, X, y, cv=5, scoring='roc_auc')
print('Cross-validation AUC score: ', score.mean())
return model, cnf_matrix
# Grid-search hyper Parameters to consider
model_grid_params = {'lr_model': {"model__C": [1, 1.3, 1.5]}, 'dt_model': {"model__max_depth": [3, 5, 7], "model__min_samples_split": [2, 5]},
'rf_model': {"model__max_depth": [20, 10, 15],"model__min_samples_split": [5, 10]}, 'lda_model': {},
'xgb_model':{"model__max_depth": [5, 10], "model__min_child_weight": [5, 10]}}
models = [lr_model, dt_model, rf_model, lda_model, xgb_model]
model_keys = [('lr_model', 'Logistic Regression'),
('dt_model', 'Decision Tree'),
('rf_model', 'Random Forest'),
('lda_model', 'Linear Discriminant Analysis'),
('xgb_model', 'Gradient Boosting')]
final_model, cnf_matrix = {}, {}
for idx, model in enumerate(models):
print(45*'_', '\n{}'.format(model_keys[idx][1]))
model, cnf = model_evaluate(model, X, y, model_grid_params[model_keys[idx][0]])
final_model[model_keys[idx][0]] = model
cnf_matrix[model_keys[idx][0]] = cnf
```
#### Overall, the LDA model provided the better result (87% AUC and 71% fl_score) .
##### The Decision Tree model is also as good as the LDA. Although, the RF classifier has a comparable AUC score the f1_score is very low. Hence, we will take the LDA or the Decision Tree model as our final model
### Lets have a closer look at the predictions of the LDA model
#### Lets have some helper functions
To plot the confusion matrix, the code from the [sklearn documentation](http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html) is used.
```
def plot_confusion_matrix(cm,
target_names,
title='Confusion matrix',
cmap=None,
normalize=True):
"""
given a sklearn confusion matrix (cm), make a nice plot
Arguments
---------
cm: confusion matrix from sklearn.metrics.confusion_matrix
target_names: given classification classes such as [0, 1, 2]
the class names, for example: ['high', 'medium', 'low']
title: the text to display at the top of the matrix
cmap: the gradient of the values displayed from matplotlib.pyplot.cm
see http://matplotlib.org/examples/color/colormaps_reference.html
plt.get_cmap('jet') or plt.cm.Blues
normalize: If False, plot the raw numbers
If True, plot the proportions
Citiation
---------
http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
"""
if cmap is None:
cmap = plt.get_cmap('Blues')
plt.figure(figsize=(8, 6))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
if target_names is not None:
tick_marks = np.arange(len(target_names))
plt.xticks(tick_marks, target_names, rotation=45)
plt.yticks(tick_marks, target_names)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 1.5 if normalize else cm.max() / 2
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if normalize:
plt.text(j, i, "{:0.4f}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
else:
plt.text(j, i, "{:,}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.show()
# Plot the confusion matrix of the LDA model
plot_confusion_matrix(cnf_matrix['lda_model'], target_names=['legitimate', 'fraud'], normalize=False)
```
- 135 legitimate transactions were correctly classified
- 16 legitimate transactions classified as fraudulant, i.e., false positives (type 1 error)
- 36 fraudulant transactions transactions were correctly identified
- 13 fraudulant transactions were classified as legitimate (type 2 error)
```
# Plot the confusion matrix of the DT model
plot_confusion_matrix(cnf_matrix['dt_model'], target_names=['legitimate', 'fraud'], normalize=False)
```
### The ROC curve
```
# ROC curve LDA
model, cnf = model_evaluate(lda_model, X, y, model_grid_params['lda_model'], plot_eval_curves=True)
# ROC and Precision vs. Recall curves of the LDA model
model, cnf = model_evaluate(lda_model, X, y, model_grid_params['lda_model'], plot_eval_curves=True)
```
#### The precision vs. recall curve shows the trade off between missing a fraudulent transaction and falsely flagging a legitimate transaction as a fraudulent. Depending on the business requirment, possibly discussing with the business stakeholders, we have to choose an optimal point.
#### Since, Understanding why the ML algorithm made the decision is very important, next I will work on model explainability.
| github_jupyter |
```
# default_exp data.metadatasets
```
# Metadatasets: a dataset of datasets
> This functionality will allow you to create a dataset from data stores in multiple, smaller datasets.
* I'd like to thank both Thomas Capelle (https://github.com/tcapelle) and Xander Dunn (https://github.com/xanderdunn) for their contributions to make this code possible.
* This functionality allows you to use multiple numpy arrays instead of a single one, which may be very useful in many practical settings. I've tested it with 10k+ datasets and it works well.
```
#export
from tsai.imports import *
from tsai.utils import *
from tsai.data.validation import *
from tsai.data.core import *
#export
class TSMetaDataset():
" A dataset capable of indexing mutiple datasets at the same time"
def __init__(self, dataset_list, **kwargs):
if not is_listy(dataset_list): dataset_list = [dataset_list]
self.datasets = dataset_list
self.split = kwargs['split'] if 'split' in kwargs else None
self.mapping = self._mapping()
if hasattr(dataset_list[0], 'loss_func'):
self.loss_func = dataset_list[0].loss_func
else:
self.loss_func = None
def __len__(self):
if self.split is not None:
return len(self.split)
else:
return sum([len(ds) for ds in self.datasets])
def __getitem__(self, idx):
if self.split is not None: idx = self.split[idx]
idx = listify(idx)
idxs = self.mapping[idx]
idxs = idxs[idxs[:, 0].argsort()]
self.mapping_idxs = idxs
ds = np.unique(idxs[:, 0])
b = [self.datasets[d][idxs[idxs[:, 0] == d, 1]] for d in ds]
output = tuple(map(torch.cat, zip(*b)))
return output
def _mapping(self):
lengths = [len(ds) for ds in self.datasets]
idx_pairs = np.zeros((np.sum(lengths), 2)).astype(np.int32)
start = 0
for i,length in enumerate(lengths):
if i > 0:
idx_pairs[start:start+length, 0] = i
idx_pairs[start:start+length, 1] = np.arange(length)
start += length
return idx_pairs
@property
def vars(self):
s = self.datasets[0][0][0] if not isinstance(self.datasets[0][0][0], tuple) else self.datasets[0][0][0][0]
return s.shape[-2]
@property
def len(self):
s = self.datasets[0][0][0] if not isinstance(self.datasets[0][0][0], tuple) else self.datasets[0][0][0][0]
return s.shape[-1]
class TSMetaDatasets(FilteredBase):
def __init__(self, metadataset, splits):
store_attr()
self.mapping = metadataset.mapping
def subset(self, i):
return type(self.metadataset)(self.metadataset.datasets, split=self.splits[i])
@property
def train(self):
return self.subset(0)
@property
def valid(self):
return self.subset(1)
```
Let's create 3 datasets. In this case they will have different sizes.
```
vocab = L(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])
dsets = []
for i in range(3):
size = np.random.randint(50, 150)
X = torch.rand(size, 5, 50)
y = vocab[torch.randint(0, 10, (size,))]
tfms = [None, TSClassification()]
dset = TSDatasets(X, y, tfms=tfms)
dsets.append(dset)
dsets
metadataset = TSMetaDataset(dsets)
metadataset, metadataset.vars, metadataset.len
```
We'll apply splits now to create train and valid metadatasets:
```
splits = TimeSplitter()(metadataset)
splits
metadatasets = TSMetaDatasets(metadataset, splits=splits)
metadatasets.train, metadatasets.valid
dls = TSDataLoaders.from_dsets(metadatasets.train, metadatasets.valid)
xb, yb = first(dls.train)
xb, yb
```
There also en easy way to map any particular sample in a batch to the original dataset and id:
```
dls = TSDataLoaders.from_dsets(metadatasets.train, metadatasets.valid)
xb, yb = first(dls.train)
mappings = dls.train.dataset.mapping_idxs
for i, (xbi, ybi) in enumerate(zip(xb, yb)):
ds, idx = mappings[i]
test_close(dsets[ds][idx][0].data.cpu(), xbi.cpu())
test_close(dsets[ds][idx][1].data.cpu(), ybi.cpu())
```
For example the 3rd sample in this batch would be:
```
dls.train.dataset.mapping_idxs[2]
#hide
out = create_scripts(); beep(out)
```
| github_jupyter |
```
import tensorflow as tf
```
## 참고 자료
- [이찬우님 유튜브](https://www.youtube.com/watch?v=4vJ_2NtsTVg&list=PL1H8jIvbSo1piZJRnp9bIww8Fp2ddIpeR&index=2)
### (1) 보편적 Case
- Generator를 사용
- python api를 의존하기 때문에 병목이 있을 수 있음
```
def gen():
for i in range(10):
yield i
dataset = tf.data.Dataset.from_generator(gen, tf.float32)\
.make_one_shot_iterator()\
.get_next()
with tf.Session() as sess:
_data = sess.run(dataset)
print(_data)
with tf.Session() as sess:
for _ in range(10):
_data = sess.run(dataset)
print(_data)
# End of sequence Error 발생
with tf.Session() as sess:
for _ in range(12):
_data = sess.run(dataset)
print(_data)
```
- generator로 label, feature까지 출력하고 싶다면
```
def gen():
for i, j in zip(range(10, 20), range(10)):
yield (i, j)
dataset = tf.data.Dataset.from_generator(gen, (tf.float32, tf.float32))\
.make_one_shot_iterator()\
.get_next()
with tf.Session() as sess:
for _ in range(10):
_label, _feature = sess.run(dataset)
print(_label, _feature)
```
### Minibatch를 하고 싶다면
- shuffle한 후, batch 설정
```
def gen():
for i, j in zip(range(10, 1010), range(1000)):
yield (i, j)
dataset = tf.data.Dataset.from_generator(gen, (tf.float32, tf.float32))\
.shuffle(7777)\
.batch(20)\
.make_one_shot_iterator()\
.get_next()
with tf.Session() as sess:
for _ in range(10):
_label, _feature = sess.run(dataset)
print(_label, _feature)
```
### (2) TextLineDataset
- 병목을 해결 가능
```
dataset = tf.data.TextLineDataset("./test_data.csv")\
.make_one_shot_iterator()\
.get_next()
with tf.Session() as sess:
_data = sess.run(dataset)
print(_data)
```
- b'1,1,2,3,4,5,6,7,8,9' : decoding 필요
```
dataset = tf.data.TextLineDataset("./test_data.csv")\
.make_one_shot_iterator()\
.get_next()
lines = tf.decode_csv(dataset, record_defaults=[[0]]*10)
feature = tf.stack(lines[1:]) #, axis=1)
label = lines[0]
with tf.Session() as sess:
_fea, _lab = sess.run([feature, label])
print(_lab, _fea)
dataset = tf.data.TextLineDataset("./test_data.csv")\
.batch(2)\
.repeat(999999)\
.make_one_shot_iterator()\
.get_next()
lines = tf.decode_csv(dataset, record_defaults=[[0]]*10)
feature = tf.stack(lines[1:], axis=1)
label = tf.expand_dims(lines[0], axis=-1)
feature = tf.cast(feature, tf.float32)
label = tf.cast(label, tf.float32)
# float형으로 정의해야 이상없이 연산이 됨
with tf.Session() as sess:
_fea, _lab = sess.run([feature, label])
for f, l in zip(_fea, _lab):
print(f, l)
```
### Modeling
```
layer1 = tf.layers.dense(feature, units=9, activation=tf.nn.relu)
layer2 = tf.layers.dense(layer1, units=9, activation=tf.nn.relu)
layer3 = tf.layers.dense(layer2, units=9, activation=tf.nn.relu)
layer4 = tf.layers.dense(layer3, units=9, activation=tf.nn.relu)
out = tf.layers.dense(layer4, units=1)
print("label's shape {}".format(label))
# label's shape (?,) : [1, 2, 3, 4, 5, 6]
# int면 계산이 안됨
print("out's shape {}".format(out))
# [[1], [2], [3], [4], [5], [6]]
```
### loss, Optimizer 정의
```
loss = tf.losses.sigmoid_cross_entropy(label, out)
```
- Shapes (?, 1) and (?,) are incompatible error
- shape를 맞춰주기 : ```tf.expand_dims``` 사용
- Value passed to parameter 'x' has DataType int32 not in list of allowed values error
- value의 type을 float32로 바꾸기 : ```tf.cast``` 사용
- Attempting to use uninitialized value accuracy/total error
- accuracy 관련 ```tf.local_variables_initializer()``` 실행
```
train_op = tf.train.GradientDescentOptimizer(1e-2).minimize(loss)
pred = tf.nn.sigmoid(out)
accuracy = tf.metrics.accuracy(label, tf.round(pred))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
for i in range(30):
_, _loss, _acc = sess.run([train_op, loss, accuracy])
print("step: {}, loss: {}, accuracy: {}".format(i, _loss, _acc))
```
### Accuracy
### TFRecord
- read, write 속도가 빠르게!
| github_jupyter |
# Dealing with spectrum data
This tutorial demonstrates how to use Spectrum class to do various arithmetic operations of Spectrum. This demo uses the Jsc calculation as an example, namely
\begin{equation}
J_{sc}=\int \phi(E)QE(E) dE
\end{equation}
where $\phi$ is the illumination spectrum in photon flux, $E$ is the photon energy and $QE$ is the quantum efficiency.
```
%matplotlib inline
import numpy as np
import scipy.constants as sc
import matplotlib.pyplot as plt
from pypvcell.spectrum import Spectrum
from pypvcell.illumination import Illumination
from pypvcell.photocurrent import gen_step_qe_array
```
## Quantum efficiency
We first use a function ```gen_step_qe_array``` to generate a quantum efficiency spectrum. This spectrum is a step function with a cut-off at the band gap of 1.42 eV.
```
qe=gen_step_qe_array(1.42,0.9)
plt.plot(qe[:,0],qe[:,1])
plt.xlabel('photon energy (eV)')
plt.ylabel('QE')
```
```qe``` is a numpy array. The recommeneded way to handle it is converting it to ```Spectrum``` class:
```
qe_sp=Spectrum(x_data=qe[:,0],y_data=qe[:,1],x_unit='eV')
```
### Unit conversion
When we want to retrieve the value of ```qe_sp``` we have to specicify the unit of the wavelength. For example, say, converting the wavelength to nanometer:
```
qe=qe_sp.get_spectrum(to_x_unit='nm')
plt.plot(qe[0,:],qe[1,:])
plt.xlabel('wavelength (nm)')
plt.ylabel('QE')
plt.xlim([300,1100])
```
### Arithmetic operation
We can do arithmetic operation directly with Spectrum class such as
```
# Calulate the portion of "non-absorbed" photons, assuming QE is equivalent to absorptivity
tr_sp=1-qe_sp
tr=tr_sp.get_spectrum(to_x_unit='nm')
plt.plot(tr[0,:],tr[1,:])
plt.xlabel('wavelength (nm)')
plt.ylabel('QE')
plt.xlim([300,1100])
```
## Illumination spectrum
pypvcell has a class Illumination that is inherited from ```Spectrum``` to handle the illumination. It inherits all the capability of ```Spectrum``` but has several methods specifically for sun illumination.
Some default standard spectrum is embedded in the ```pypvcell```:
```
std_ill=Illumination("AM1.5g")
```
Show the values of the data
```
ill=std_ill.get_spectrum('nm')
plt.plot(*ill)
plt.xlabel("wavelength (nm)")
plt.ylabel("intensity (W/m^2-nm)")
fig, ax1= plt.subplots()
ax1.plot(*ill)
ax2 = ax1.twinx()
ax2.plot(*qe)
ax1.set_xlim([400,1600])
ax2.set_ylabel('sin', color='r')
ax2.tick_params('y', colors='r')
ill[:,-1]
qe[:,-1]
```
Calcuate the total intensity in W/m^2
```
std_ill.total_power()
```
### Unit conversion of illumination spectrum
It requires a bit of attention of converting spectrum that is in the form of $\phi(E)dE$, i.e., the value of integration is a meaningful quantitfy such as total power. This has been also handled by ```Illumination``` class. In the following case, we convert the wavelength to eV. Please note that the units of intensity is also changed to W/m^2-eV.
```
ill=std_ill.get_spectrum('eV')
plt.plot(*ill)
plt.xlabel("wavelength (eV)")
plt.ylabel("intensity (W/m^2-eV)")
```
## Spectrum multiplication
To calcualte the overall photocurrent, we have to calculate $\phi(E)QE(E) dE$ first. This would involves some unit conversion and interpolation between two spectrum. However, this is easily dealt by ```Spectrum``` class:
```
# calculate \phi(E)QE(E) dE.
# Spectrum class automatically convert the units and align the x-data by interpolating std_ill
jsc_e=std_ill*qe_sp
```
Here's a more delicate point. We should convert the unit to photon flux in order to calculate Jsc.
```
jsc_e_a=jsc_e.get_spectrum('nm',to_photon_flux=True)
plt.plot(*jsc_e_a)
plt.xlim([300,1100])
```
Integrate it yields the total photocurrent density in A/m^2
```
sc.e*np.trapz(y=jsc_e_a[1,:],x=jsc_e_a[0,:])
```
In fact, ```pypvcell``` already provides a function ```calc_jsc()``` for calculating Jsc from given spectrum and QE:
```
from pypvcell.photocurrent import calc_jsc
calc_jsc(std_ill,qe_sp)
```
| github_jupyter |
```
import requests
from IPython.display import Markdown
from tqdm import tqdm, tqdm_notebook
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
import altair as alt
from requests.utils import quote
import os
from datetime import timedelta
from mod import alt_theme
fmt = "{:%Y-%m-%d}"
# Can optionally use number of days to choose dates
n_days = 60
end_date = fmt.format(pd.datetime.today())
start_date = fmt.format(pd.datetime.today() - timedelta(days=n_days))
renderer = "kaggle"
github_orgs = ["jupyterhub", "jupyter", "jupyterlab", "jupyter-widgets", "ipython", "binder-examples", "nteract"]
bot_names = ["stale", "codecov", "jupyterlab-dev-mode", "henchbot"]
# Parameters
renderer = "kaggle"
start_date = "2019-04-01"
end_date = "2019-05-01"
alt.renderers.enable(renderer);
alt.themes.register('my_theme', alt_theme)
alt.themes.enable("my_theme")
# Discourse API key
api = {'Api-Key': os.environ['DISCOURSE_API_KEY'],
'Api-Username': os.environ['DISCOURSE_API_USERNAME']}
# Discourse
def topics_to_markdown(topics, n_list=10):
body = []
for _, topic in topics.iterrows():
title = topic['fancy_title']
slug = topic['slug']
posts_count = topic['posts_count']
url = f'https://discourse.jupyter.org/t/{slug}'
body.append(f'* [{title}]({url}) ({posts_count} posts)')
body = body[:n_list]
return '\n'.join(body)
def counts_from_activity(activity):
counts = activity.groupby('category_id').count()['bookmarked'].reset_index()
counts['parent_category'] = None
for ii, irow in counts.iterrows():
if parent_categories[irow['category_id']] is not None:
counts.loc[ii, 'parent_category'] = parent_categories[irow['category_id']]
counts['category_id'] = counts['category_id'].map(lambda a: category_mapping[a])
counts['parent_category'] = counts['parent_category'].map(lambda a: category_mapping[a] if a is not None else 'parent')
is_parent = counts['parent_category'] == 'parent'
counts.loc[is_parent, 'parent_category'] = counts.loc[is_parent, 'category_id']
counts['parent/category'] = counts.apply(lambda a: a['parent_category']+'/'+a['category_id'], axis=1)
counts = counts.sort_values(['parent_category', 'bookmarked'], ascending=False)
return counts
```
# Community forum activity
The [Jupyter Community Forum](https://discourse.jupyter.org) is a place for Jovyans across the
community to talk about Jupyter tools in interactive computing and how they fit into their
workflows. It's also a place for developers to share ideas, tools, tips, and help one another.
Below are a few updates from activity in the Discourse. For more detailed information about
the activity on the Community Forum, check out these links:
* [The users page](https://discourse.jupyter.org/u) has information about user activity
* [The top posts page](https://discourse.jupyter.org/top) contains a list of top posts, sorted
by various metrics.
```
# Get categories for IDs
url = "https://discourse.jupyter.org/site.json"
resp = requests.get(url, headers=api)
category_mapping = {cat['id']: cat['name'] for cat in resp.json()['categories']}
parent_categories = {cat['id']: cat.get("parent_category_id", None) for cat in resp.json()['categories']}
# Base URL to use
url = "https://discourse.jupyter.org/latest.json"
```
## Topics with lots of likes
"Likes" are a way for community members to say thanks for a helpful post, show their
support for an idea, or generally to share a little positivity with somebody else.
These are topics that have generated lots of likes in recent history.
```
params = {"order": "likes", "ascending": "False"}
resp = requests.get(url, headers=api, params=params)
# Topics with the most likes in recent history
liked = pd.DataFrame(resp.json()['topic_list']['topics'])
Markdown(topics_to_markdown(liked))
```
## Active topics on the Community Forum
These are topics with lots of activity in recent history.
```
params = {"order": "posts", "ascending": "False"}
resp = requests.get(url, headers=api, params=params)
# Topics with the most posts in recent history
posts = pd.DataFrame(resp.json()['topic_list']['topics'])
Markdown(topics_to_markdown(posts))
counts = counts_from_activity(posts)
alt.Chart(data=counts, width=700, height=300, title="Activity by category").mark_bar().encode(
x=alt.X("parent/category", sort=alt.Sort(counts['category_id'].values.tolist())),
y="bookmarked",
color="parent_category"
)
```
## Recently-created topics
These are topics that were recently created, sorted by the amount of activity
in each one.
```
params = {"order": "created", "ascending": "False"}
resp = requests.get(url, headers=api, params=params)
# Sort created by the most posted for recently-created posts
created = pd.DataFrame(resp.json()['topic_list']['topics'])
created = created.sort_values('posts_count', ascending=False)
Markdown(topics_to_markdown(created))
counts = counts_from_activity(created)
alt.Chart(data=counts, width=700, height=300, title="Activity by category").mark_bar().encode(
x=alt.X("parent/category", sort=alt.Sort(counts['category_id'].values.tolist())),
y="bookmarked",
color="parent_category"
)
```
## User activity in the Community Forum
**Top posters**
These people have posted lots of comments, replies, answers, etc in the community forum.
```
def plot_user_data(users, column, sort=False):
plt_data = users.sort_values(column, ascending=False).head(50)
x = alt.X("username", sort=plt_data['username'].tolist()) if sort is True else 'username'
ch = alt.Chart(data=plt_data).mark_bar().encode(
x=x,
y=column
)
return ch
url = "https://discourse.jupyter.org/directory_items.json"
params = {"period": "quarterly", "order": "post_count"}
resp = requests.get(url, headers=api, params=params)
# Topics with the most likes in recent history
users = pd.DataFrame(resp.json()['directory_items'])
users['username'] = users['user'].map(lambda a: a['username'])
plot_user_data(users.head(50), 'post_count')
```
**Forum users, sorted by likes given**
These are Community Forum members that "liked" other people's posts. We appreciate
anybody taking the time to tell someone else they like what they're shared!
```
plot_user_data(users.head(50), 'likes_given')
```
**Forum users, sorted by likes received**
These are folks that posted things other people in the Community Forum liked.
```
plot_user_data(users.head(50), 'likes_received')
%%html
<script src="https://cdn.rawgit.com/parente/4c3e6936d0d7a46fd071/raw/65b816fb9bdd3c28b4ddf3af602bfd6015486383/code_toggle.js"></script>
```
| github_jupyter |
# Machine learning methods for sequential data
There are some very robust methods for learning sequential data such as for time-series or language processing tasks. We'll look at recurrent neural networks which leverage the autocorrelated nature of the training data sets.
# Sequential learning
We will utilize two popular frameworks for learning data which are distinctly _non i.i.d_
<img src="imgs/RNN_Apps.png" width="800">
## Recurrent neural networks (RNNs)
<img src="imgs/RNN_Maths.png" width="600">
## Long short-term memory networks (LSTMs)
<img src="imgs/LSTM_Maths.png" width="800">
### Import python packages
```
import sys
import os
import keras
from keras.models import Model
from keras.callbacks import EarlyStopping
import math
import warnings
import numpy as np
import pandas as pd
from keras.layers import Dense, Dropout, Activation
from keras.layers.recurrent import SimpleRNN, LSTM, GRU
from keras.models import Sequential
from keras.models import load_model
from keras.utils.vis_utils import plot_model
import sklearn.metrics as metrics
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler, MinMaxScaler
warnings.filterwarnings("ignore")
# Download the data - google colab issue
!git clone https://github.com/argonne-lcf/AI4ScienceTutorial
```
# Data preprocessing
```
def process_data(train, test, lags):
"""Process data
Reshape and split train\test data.
# Arguments
train: String, name of .csv train file.
test: String, name of .csv test file.
lags: integer, time lag.
# Returns
X_train: ndarray.
y_train: ndarray.
X_test: ndarray.
y_test: ndarray.
scaler: StandardScaler.
"""
attr = 'Lane 1 Flow (Veh/5 Minutes)'
df1 = pd.read_csv(train, encoding='utf-8').fillna(0)
df2 = pd.read_csv(test, encoding='utf-8').fillna(0)
# scaler = StandardScaler().fit(df1[attr].values)
scaler = MinMaxScaler(feature_range=(0, 1)).fit(df1[attr].values.reshape(-1, 1))
flow1 = scaler.transform(df1[attr].values.reshape(-1, 1)).reshape(1, -1)[0]
flow2 = scaler.transform(df2[attr].values.reshape(-1, 1)).reshape(1, -1)[0]
train, test = [], []
for i in range(lags, len(flow1)):
train.append(flow1[i - lags: i + 1])
for i in range(lags, len(flow2)):
test.append(flow2[i - lags: i + 1])
train = np.array(train)
test = np.array(test)
np.random.shuffle(train)
X_train = train[:, :-1]
y_train = train[:, -1]
X_test = test[:, :-1]
y_test = test[:, -1]
return X_train, y_train, X_test, y_test, scaler
```
# Model building
```
"""
Define model architecture
"""
def get_rnn(units):
"""RNN(Recurrent Neural Network)
Build RNN Model.
# Arguments
units: List(int), number of input, hidden unit in cell 1, hidden units in cell 2, number of outputs
# Returns
model: Model, nn model.
"""
model = Sequential()
model.add(SimpleRNN(units[1], input_shape=(units[0], 1), return_sequences=True)) # Cell 1
model.add(SimpleRNN(units[2])) # Cell 2 stacked on hidden-layer outputs of Cell 1
model.add(Dropout(0.2)) # Dropout - for regularization
model.add(Dense(units[3], activation='sigmoid')) # Map hidden-states to output
return model
def get_lstm(units):
"""LSTM(Long Short-Term Memory)
Build LSTM Model.
# Arguments
units: List(int), number of input, hidden unit in cell 1, hidden units in cell 2, number of outputs
# Returns
model: Model, nn model.
"""
model = Sequential()
model.add(LSTM(units[1], input_shape=(units[0], 1), return_sequences=True)) # Cell 1
model.add(LSTM(units[2])) # Cell 2 stacked on hidden-layer outputs of Cell 1
model.add(Dropout(0.2)) # Dropout - for regularization
model.add(Dense(units[3], activation='sigmoid')) # Map hidden-states to output
return model
```
# Model training
```
def train_model(model, X_train, y_train, name, config):
"""train
train a single model.
# Arguments
model: Model, NN model to train.
X_train: ndarray(number, lags), Input data for train.
y_train: ndarray(number, ), result data for train.
name: String, name of model.
config: Dict, parameter for train.
"""
model.compile(loss="mse", optimizer="rmsprop", metrics=['mse'])
model.summary()
# early = EarlyStopping(monitor='val_loss', patience=30, verbose=0, mode='auto')
hist = model.fit(
X_train, y_train,
batch_size=config["batch"],
epochs=config["epochs"],
validation_split=0.05)
folder = 'model/'
if not os.path.exists(folder):
os.makedirs(folder)
model.save('model/' + name + '.h5')
df = pd.DataFrame.from_dict(hist.history)
df.to_csv('model/' + name + ' loss.csv', encoding='utf-8', index=False)
return hist
lag = 12
config = {"batch": 256, "epochs": 10}
file1 = 'AI4ScienceTutorial/sess5_timeseries/data/train.csv'
file2 = 'AI4ScienceTutorial/sess5_timeseries/data/test.csv'
X_train, y_train, _, _, _ = process_data(file1, file2, lag)
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
# Check the shapes of our training data
print(X_train.shape)
print(y_train.shape)
m = get_rnn([12, 64, 64, 1])
history = train_model(m, X_train, y_train, 'rnn', config)
plt.figure(figsize=(21, 11))
plt.plot(history.history['loss'], linewidth=4)
plt.plot(history.history['val_loss'], linewidth=4)
plt.title('model loss', fontsize=40)
plt.yticks(fontsize=40)
plt.xticks(fontsize=40)
plt.ylabel('loss', fontsize=40)
plt.xlabel('epoch', fontsize=40)
plt.legend(['train', 'val'], loc='upper left', fontsize=40)
plt.show()
m = get_lstm([12, 64, 64, 1])
history = train_model(m, X_train, y_train, 'lstm', config)
plt.figure(figsize=(21, 11))
plt.plot(history.history['loss'], linewidth=4)
plt.plot(history.history['val_loss'], linewidth=4)
plt.title('model loss', fontsize=40)
plt.yticks(fontsize=40)
plt.xticks(fontsize=40)
plt.ylabel('loss', fontsize=40)
plt.xlabel('epoch', fontsize=40)
plt.legend(['train', 'val'], loc='upper left', fontsize=40)
plt.show()
```
# Prediction
```
"""
Traffic Flow Prediction with Neural Networks(SAEs、LSTM、GRU).
"""
def MAPE(y_true, y_pred):
"""Mean Absolute Percentage Error
Calculate the mape.
# Arguments
y_true: List/ndarray, ture data.
y_pred: List/ndarray, predicted data.
# Returns
mape: Double, result data for train.
"""
y = [x for x in y_true if x > 0]
y_pred = [y_pred[i] for i in range(len(y_true)) if y_true[i] > 0]
num = len(y_pred)
sums = 0
for i in range(num):
tmp = abs(y[i] - y_pred[i]) / y[i]
sums += tmp
mape = sums * (100 / num)
return mape
def eva_regress(y_true, y_pred):
"""Evaluation
evaluate the predicted result.
# Arguments
y_true: List/ndarray, ture data.
y_pred: List/ndarray, predicted data.
"""
mape = MAPE(y_true, y_pred)
vs = metrics.explained_variance_score(y_true, y_pred)
mae = metrics.mean_absolute_error(y_true, y_pred)
mse = metrics.mean_squared_error(y_true, y_pred)
r2 = metrics.r2_score(y_true, y_pred)
print('explained_variance_score:%f' % vs)
print('mape:%f%%' % mape)
print('mae:%f' % mae)
print('mse:%f' % mse)
print('rmse:%f' % math.sqrt(mse))
print('r2:%f' % r2)
def plot_results(y_true, y_preds, names):
"""Plot
Plot the true data and predicted data.
# Arguments
y_true: List/ndarray, ture data.
y_pred: List/ndarray, predicted data.
names: List, Method names.
"""
d = '2016-3-4 00:00'
x = pd.date_range(d, periods=288, freq='5min')
fig = plt.figure(figsize=(21, 11))
ax = fig.add_subplot(111)
ax.plot(x, y_true, label='True Data', linewidth=4)
for name, y_pred in zip(names, y_preds):
ax.plot(x, y_pred, label=name, linewidth=4)
plt.legend(prop={'size': 40})
plt.yticks(fontsize=40)
plt.xticks(fontsize=40)
plt.grid(True)
plt.xlabel('Time of Day', fontsize=50)
plt.ylabel('Flow', fontsize=50)
date_format = mpl.dates.DateFormatter("%H:%M")
ax.xaxis.set_major_formatter(date_format)
fig.autofmt_xdate()
plt.show()
rnn = load_model('model/rnn.h5')
lstm = load_model('model/lstm.h5')
models = [rnn,lstm]
names = ['RNN','LSTM']
lag = 12
file1 = 'AI4ScienceTutorial/sess5_timeseries/data/train.csv'
file2 = 'AI4ScienceTutorial/sess5_timeseries/data/test.csv'
_, _, X_test, y_test, scaler = process_data(file1, file2, lag)
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).reshape(1, -1)[0]
y_preds = []
for name, model in zip(names, models):
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted = model.predict(X_test)
predicted = scaler.inverse_transform(predicted.reshape(-1, 1)).reshape(1, -1)[0]
y_preds.append(predicted[:288])
eva_regress(y_test, predicted)
plot_results(y_test[: 288], y_preds, names)
```
| github_jupyter |
<table width="100%"> <tr>
<td style="background-color:#ffffff;">
<a href="http://qworld.lu.lv" target="_blank"><img src="..\images\qworld.jpg" width="35%" align="left"> </a></td>
<td style="background-color:#ffffff;vertical-align:bottom;text-align:right;">
prepared by Abuzer Yakaryilmaz (<a href="http://qworld.lu.lv/index.php/qlatvia/" target="_blank">QLatvia</a>) and Utku Birkan
<br>
updated by Özlem Salehi | September 20, 2019
</td>
</tr></table>
<table width="100%"><tr><td style="color:#bbbbbb;background-color:#ffffff;font-size:11px;font-style:italic;text-align:right;">This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. </td></tr></table>
$ \newcommand{\bra}[1]{\langle #1|} $
$ \newcommand{\ket}[1]{|#1\rangle} $
$ \newcommand{\braket}[2]{\langle #1|#2\rangle} $
$ \newcommand{\dot}[2]{ #1 \cdot #2} $
$ \newcommand{\biginner}[2]{\left\langle #1,#2\right\rangle} $
$ \newcommand{\mymatrix}[2]{\left( \begin{array}{#1} #2\end{array} \right)} $
$ \newcommand{\myvector}[1]{\mymatrix{c}{#1}} $
$ \newcommand{\myrvector}[1]{\mymatrix{r}{#1}} $
$ \newcommand{\mypar}[1]{\left( #1 \right)} $
$ \newcommand{\mybigpar}[1]{ \Big( #1 \Big)} $
$ \newcommand{\sqrttwo}{\frac{1}{\sqrt{2}}} $
$ \newcommand{\dsqrttwo}{\dfrac{1}{\sqrt{2}}} $
$ \newcommand{\onehalf}{\frac{1}{2}} $
$ \newcommand{\donehalf}{\dfrac{1}{2}} $
$ \newcommand{\hadamard}{ \mymatrix{rr}{ \sqrttwo & \sqrttwo \\ \sqrttwo & -\sqrttwo }} $
$ \newcommand{\vzero}{\myvector{1\\0}} $
$ \newcommand{\vone}{\myvector{0\\1}} $
$ \newcommand{\vhadamardzero}{\myvector{ \sqrttwo \\ \sqrttwo } } $
$ \newcommand{\vhadamardone}{ \myrvector{ \sqrttwo \\ -\sqrttwo } } $
$ \newcommand{\myarray}[2]{ \begin{array}{#1}#2\end{array}} $
$ \newcommand{\X}{ \mymatrix{cc}{0 & 1 \\ 1 & 0} } $
$ \newcommand{\Z}{ \mymatrix{rr}{1 & 0 \\ 0 & -1} } $
$ \newcommand{\Htwo}{ \mymatrix{rrrr}{ \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & \frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} & \frac{1}{2} } } $
$ \newcommand{\CNOT}{ \mymatrix{cccc}{1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0} } $
$ \newcommand{\norm}[1]{ \left\lVert #1 \right\rVert } $
<h2> Initializing a qubit with an arbitrary state </h2>
Qiskit circuits have a built in method called initialize which allows starting from a specifed state instead of having all qubits start as 0.
Note that the state should be a valid quantum state and the length of the vector should match the number of qubits. If not, exception is raised.
Let's create a quantum circuit with two qubits and initialize it by setting equal probabilities to each outcome.
```
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
# we define a quantum circuit with two qubits and two bits
qreg1 = QuantumRegister(2) # quantum register with two qubits
creg1 = ClassicalRegister(2) # classical register with two bits
mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers
# initialization
init_state=[1/2,1/2,1/2,1/2]
mycircuit1.initialize(init_state,qreg1)
# measure the qubits
mycircuit1.measure(qreg1,creg1)
# draw the circuit
mycircuit1.draw()
# execute the program 1000 times
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=1000)
# print the results
counts = job.result().get_counts(mycircuit1)
print(counts) # counts is a dictionary
```
<h3>Task 1</h3>
Create a quantum circuit with a single qubit. Use the function you have written for creating random quantum states in the notebook <a href="../B28_Quantum_State.ipynb">Quantum States</a> and initilize your qubit to a random state. Use statevector simulator to check if you are successful.
```
%load randqstate.py
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
#
# Your code here
#
```
<a href="B32_Initializing_a_Qubit_Solutions.ipynb#task1">click for our solution</a>
### Task 2
Create a quantum circuit with a single qubit. Choose a random angle $\theta$ and use the function you have written for creating random quantum states in the notebook <a href="../B30_Visualization_of_a_Qubit.ipynb">Visualization of a Qubit</a>. Use statevector simulator to check if you are successful.
```
%load randqstate2.py
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
#
# Your code here
#
```
<a href="B32_Initializing_a_Qubit_Solutions.ipynb#task2">click for our solution</a>
| github_jupyter |
# 8.3 PCA
PCA首先识别最靠近数据的超平面,然后将数据投影到该平面上。
## 8.3.1 保留差异性
将训练集投影到低维超平面之前需要选择正确的超平面。
## 8.3.2 主要成分
**主成分分析可以在训练集中识别出哪条轴对差异性的贡献度最高。** 轴的数量与数据集维度数量相同。
第i个轴称为数据的第i个主要成分(PC)
对于每个主要成分,PCA都找到一个指向PC方向的零中心单位向量。由于两个相对的单位向量位于同一轴上,因此PCA返回的单位向量的方向不稳定:如果稍微扰动训练集并再次运行PCA,则单位向量可能会指向原始向量的相反方向。但是,它们通常仍位于相同的轴上。在某些情况下,一对单位向量甚至可以旋转或交换(如果沿这两个轴的方差接近),但是它们定义的平面通常保持不变。
异值分解(SVD)的标准矩阵分解技术,可以将训练集矩阵X分解为三个矩阵$U\sum V^T$的矩阵乘法,其中V包含定义所有主要成分的单位向量。如公式8-1所示:
$$
V = \begin{bmatrix}
| & | & \cdots & | \\
c_1 & c_2 & \cdots & c_n \\
| & | & \cdots & |
\end{bmatrix} \tag{8-1}
$$
```
%matplotlib inline
import matplotlib as mlp
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')
np.random.seed(42)
m = 60
w1, w2 = 0.1, 0.3
noise = 0.1
angles = np.random.rand(m) * 3 * np.pi / 2 - 0.5
X = np.empty((m, 3))
X[:, 0] = np.cos(angles) + np.sin(angles)/2 + noise * np.random.randn(m) / 2
X[:, 1] = np.sin(angles) * 0.7 + noise * np.random.randn(m) / 2
X[:, 2] = X[:, 0] * w1 + X[:, 1] * w2 + noise * np.random.randn(m)
X
# 使用Numpy的svd()函数来获取训练集的所有主成分
X_centered = X - X.mean(axis=0)
U, s, Vt = np.linalg.svd(X_centered)
c1 = Vt.T[:, 0]
c2 = Vt.T[:, 1]
m, n = X.shape
m, n
S = np.zeros(X_centered.shape)
S[:n, :n] = np.diag(s)
np.allclose(X_centered, U.dot(S).dot(Vt))
W2 = Vt.T[:, :2]
X2D = X_centered.dot(W2)
X2D_using_svd = X2D
```
PCA假定数据集以原点为中心。正如我们将看到的,Scikit-Learn的PCA类负责为你居中数据。如果你自己实现PCA(如上例所示),或者使用其他库,请不要忘记首先将数据居中。
## 8.3.3 向下投影到d维度
一旦确定了所有主要成分,你就可以将数据集投影到前d个主要成分定义的超平面上,从而将数据集的维度降低到d维。选择这个超平面可确保投影将保留尽可能多的差异性。
要将训练集投影到超平面上并得到维度为d的简化数据集$X_{d-proj}$,计算训练集矩阵X与矩阵$W_d$的矩阵相乘,矩阵$W_d$定义为包含V的前$d$列的矩阵。如公式8-2所示:
$$
X_{d-proj} = X W_d \tag{8-2}
$$
## 8.3.4 Scikit-Learn PCA
```
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
X2D = pca.fit_transform(X)
X2D[:5]
X2D_using_svd[:5]
```
注意在数据集上执行PCA多次可能结果会有轻微的不同,这是由于一些投影轴的方向有可能翻转了。
## 8.3.5 可解释方差比
另一个有用的信息是每个主成分的可解释方差比,可以通过explained_variance_ratio_变量来获得。该比率表示沿每个成分的数据集方差的比率。
```
pca.explained_variance_ratio_
```
此输出告诉你,数据集方差的84.2%位于第一个PC上,而14.6%位于第二个PC上。对于第三个PC,这还不到1.2%,因此可以合理地假设第三个PC携带的信息很少。
## 8.3.6 选择正确的维度
与其任意选择要减小到的维度,不如选择相加足够大的方差部分(例如95%)的维度。当然,如果你是为了数据可视化而降低维度,这种情况下,需要将维度降低到2或3。
以下代码在不降低维度的情况下执行PCA,然后计算保留95%训练集方差所需的最小维度:
```
# 以下代码在不降低维度的情况下执行PCA,然后计算保留95%训练集所需的最小维度
X_train = np.copy(X)
pca = PCA()
pca.fit(X_train)
cumsum = np.cumsum(pca.explained_variance_ratio_)
cumsum
d = np.argmax(cumsum >= 0.95) + 1
d
```
然后,你可以设置`n_components=d`并再次运行PCA。但是还有一个更好的选择:将`n_components`设置为0.0到1.0之间的浮点数来表示要保留的方差率,而不是指定要保留的主成分数:
```
pca = PCA(n_components=0.95)
X_reduced = pca.fit_transform(X_train)
X_reduced
```
另一个选择是将可解释方差绘制成维度的函数(简单地用cumsum绘制)。曲线上通常会出现一个拐点,其中可解释方差会停止快速增大。在这种情况下,你可以看到将维度降低到大约100而不会损失太多的可解释方差。

## 8.3.7 PCA压缩
降维后,训练集占用的空间要少得多。例如,将PCA应用于MNIST数据集,同时保留其95%的方差。你会发现每个实例将具有150多个特征,而不是原始的784个特征。因此,尽管保留了大多数方差,但数据集现在不到其原始大小的20%!这是一个合理的压缩率,你可以看到这种维度减小极大地加速了分类算法(例如SVM分类器)。通过应用PCA投影的逆变换,还可以将缩减后的数据集解压缩回784维。由于投影会丢失一些信息(在5%的方差被丢弃),因此这不会给你原始的数据,但可能会接近原始数据。
**原始数据与重构数据(压缩后再解压缩)之间的均方距离称为重构误差**。
```
from sklearn.datasets import fetch_openml
X, y = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False)
X.shape
pca = PCA(n_components=154)
X_reduced = pca.fit_transform(X)
X_recovered = pca.inverse_transform(X_reduced)
X_reduced.shape, X_recovered.shape
fig, axes = plt.subplots(ncols=2, figsize=(14, 6))
plt.sca(axes[0])
image = X[:1,]
# image = np.reshape(image, (-1, 1))
image=np.reshape(image, (28, -1))
plt.imshow(image, cmap="gray")
plt.sca(axes[1])
image = X_recovered[:1,]
# image = np.reshape(image, (-1, 1))
image=np.reshape(image, (28, -1))
plt.imshow(image, cmap="gray")
```
PCA逆变换,回到原始数量的维度
$$
X_{recovered} = X_{d-proj}W_d^T \tag{8-3}
$$
## 8.3.8 随机PCA
如果将超参数svd_solver设置为"randomized",则Scikit-Learn将使用一种称为Randomized PCA的随机算法,该算法可以快速找到前d个主成分的近似值。它的计算复杂度为$O(m\times d^2)+O(d^3)$,而不是完全SVD方法的$O(m \times n^2)+O(n^3)$,因此,当d远远小于n时,它比完全的SVD快得多:
```python
rnd_pca = PCA(n_components=154, svd_solver="randomized")
X_reduced = rnd_pca.fit_transform(X)
```
默认情况下,svd_solver实际上设置为"auto":如果m或n大于500并且d小于m或n的80%,则Scikit-Learn自动使用随机PCA算法,否则它将使用完全的SVD方法。如果要强制Scikit-Learn使用完全的SVD,可以将svd_solver超参数设置为"full"。
## 8.3.9 增量PCA
前面的PCA实现的一个问题是,它们要求整个训练集都放入内存才能运行算法。幸运的是已经开发了**增量PCA(IPCA)算法**,它们可以使你把训练集划分为多个小批量,并一次将一个小批量送入IPCA算法。这对于大型训练集和在线(即在新实例到来时动态运行)应用PCA很有用。
以下代码将MNIST数据集拆分为100个小批量(使用NumPy的`array_split()`函数),并将其馈送到Scikit-Learn的`IncrementalPCA`类,来把MNIST数据集的维度降低到154(就像之前做的那样)。请注意,你必须在每个小批量中调用`partial_fit()`方法,而不是在整个训练集中调用`fit()`方法:
```
from sklearn.decomposition import IncrementalPCA
n_batches = 100
inc_pca = IncrementalPCA(n_components=154)
for X_batch in np.array_split(X, n_batches):
inc_pca.partial_fit(X_batch)
X_reduced = inc_pca.transform(X)
```
另外,你可以使用NumPy的`memmap`类,该类使你可以将存储在磁盘上的二进制文件中的大型数组当作完全是在内存中一样来操作,该类仅在需要时才将数据加载到内存中。由于`IncrementalPCA`类在任何给定时间仅使用数组的一小部分,因此内存使用情况处于受控状态。如以下代码所示,这使得调用通常的`fit()`方法成为可能:
```python
X_mm = np.memmap(filename, dtype="float32", mode="readonly", shape=(m, n))
batch_size = m // n_batches
inc_pca = IncrementalPCA(n_components=154, batch_size=batch_size)
inc_pca.fit(X_mm)
```
| github_jupyter |
## Topic Modeling: Latent Semantic Analysis/Indexing
### Imports
```
import warnings
from collections import OrderedDict
from pathlib import Path
from random import randint
import numpy as np
import pandas as pd
# Visualization
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import seaborn as sns
# sklearn for feature extraction & modeling
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, TfidfTransformer
from sklearn.decomposition import TruncatedSVD, PCA
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
% matplotlib inline
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (14.0, 8.7)
warnings.filterwarnings('ignore')
pd.options.display.float_format = '{:,.2f}'.format
```
## Load BBC data
```
path = Path('bbc')
files = path.glob('**/*.txt')
doc_list = []
for i, file in enumerate(files):
with open(str(file), encoding='latin1') as f:
_, topic, file_name = file.parts
lines = f.readlines()
heading = lines[0].strip()
body = ' '.join([l.strip() for l in lines[1:]])
doc_list.append([topic.capitalize(), heading, body])
```
### Convert to DataFrame
```
docs = pd.DataFrame(doc_list, columns=['Category', 'Heading', 'Article'])
docs.info()
```
## Create Train & Test Sets
```
train_docs, test_docs = train_test_split(docs,
stratify=docs.Category,
test_size=50,
random_state=42)
train_docs.shape, test_docs.shape
pd.Series(test_docs.Category).value_counts()
```
### Vectorize train & test sets
```
vectorizer = TfidfVectorizer(max_df=.25, min_df=.01, stop_words='english', binary=False)
train_dtm = vectorizer.fit_transform(train_docs.Article)
train_dtm
test_dtm = vectorizer.transform(test_docs.Article)
test_dtm
```
### Get token count
```
train_token_count = train_dtm.sum(0).A.squeeze()
tokens = vectorizer.get_feature_names()
word_count = pd.Series(train_token_count, index=tokens).sort_values(ascending=False)
word_count.head(10)
```
## Latent Semantic Analysis
```
n_components = 5
topic_labels = ['Topic {}'.format(i) for i in range(1, n_components+1)]
svd = TruncatedSVD(n_components=n_components,
n_iter=5,
random_state=42)
svd.fit(train_dtm)
svd.singular_values_
svd.explained_variance_ratio_
```
### Explore Topics
```
train_doc_topics = svd.transform(train_dtm)
train_doc_topics.shape
```
#### Topic Weights for sample article
```
i = randint(0, len(train_docs))
(train_docs.iloc[i, :2].append(pd.Series(train_doc_topics[i],
index=topic_labels)))
```
#### Average topic weight per category
```
train_result = pd.DataFrame(data=doc_topics,
columns=topic_labels,
index=train_docs.Category)
train_result.groupby(level='Category').mean().plot.bar();
```
#### Topics weights of most frequent words
```
topics = pd.DataFrame(svd.components_.T,
index=tokens,
columns=topic_labels)
topics.loc[word_count.head(10).index]
```
#### Most important words by topic
```
fig, ax = plt.subplots(figsize=(12,5))
top_words, top_vals = pd.DataFrame(), pd.DataFrame()
for topic, words_ in topics.items():
top10 = words_.abs().nlargest(10).index
vals = words_.loc[top10].values
top_vals[topic] = vals
top_words[topic] = top10.tolist()
sns.heatmap(pd.DataFrame(top_vals),
annot=top_words,
fmt = '',
center=0,
cmap=sns.diverging_palette(0, 255, sep=1, n=256),
ax=ax);
ax.set_title('Top Words per Topic')
fig.tight_layout()
fig.savefig('lsa_top_words', dpi=300);
```
#### Topics weights for test set
```
test_eval = pd.DataFrame(data=svd.transform(test_dtm),
columns=topic_labels,
index=test_docs.Category)
result = pd.melt(train_result.assign(Data='Train')
.append(test_eval.assign(Data='Test'))
.reset_index(),
id_vars=['Data', 'Category'],
var_name='Topic',
value_name='Weight')
g =sns.catplot(x='Category', y='Weight', hue='Topic', row='Data', kind='bar', data=result, aspect=3.5)
g.savefig('lsa_train_test', dpi=300)
```
### Categories in 2D
```
pca = PCA(n_components=2)
svd2d = pd.DataFrame(pca.fit_transform(train_result), columns=['PC1', 'PC2']).assign(Category=train_docs.Category)
categories_2d = svd2d.groupby('Category').mean()
plt.quiver(*([0], [0]), categories_2d.PC1, categories_2d.PC2, scale=.03);
```
| github_jupyter |
# Social Network Analysis
## Introduction to graph theory
```
%matplotlib inline
import matplotlib.pyplot as mpl
mpl.style.use('_classic_test')
mpl.rcParams['figure.figsize'] = [6.5, 4.5]
mpl.rcParams['figure.dpi'] = 80
mpl.rcParams['savefig.dpi'] = 100
mpl.rcParams['font.size'] = 10
mpl.rcParams['legend.fontsize'] = 'medium'
mpl.rcParams['figure.titlesize'] = 'medium'
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
import matplotlib.cbook
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1,2)
nx.draw_networkx(G)
plt.show()
G.add_nodes_from([3, 4])
G.add_edge(3,4)
G.add_edges_from([(2, 3), (4, 1)])
nx.draw_networkx(G)
plt.show()
G.nodes()
G.edges()
G.adjacency_list()
nx.to_dict_of_lists(G)
nx.to_edgelist(G)
nx.to_numpy_matrix(G)
print (nx.to_scipy_sparse_matrix(G))
nx.to_pandas_dataframe(G)
G.add_edge(1,3)
nx.draw_networkx(G)
plt.show()
G.degree()
k = nx.fast_gnp_random_graph(10000, 0.01).degree()
plt.hist(list(k.values()))
```
## Graph algorithms
```
G = nx.krackhardt_kite_graph()
nx.draw_networkx(G)
plt.show()
print (nx.has_path(G, source=1, target=9))
print (nx.shortest_path(G, source=1, target=9))
print (nx.shortest_path_length(G, source=1, target=9))
print (list(nx.shortest_simple_paths(G, source=1, target=9)))
paths = nx.all_pairs_shortest_path(G)
paths[5]
## paths[a][b]
```
### $ Types\ of\ centrality\: $
* #### $ Betweenness$
* #### $ Degree$
* #### $ Closeness$
* #### $ Harmonic$
* #### $ Eigenvector$
```
nx.betweenness_centrality(G)
nx.degree_centrality(G)
nx.closeness_centrality(G)
nx.harmonic_centrality(G)
nx.eigenvector_centrality(G)
nx.clustering(G)
import community # Community module for community detection and clustering
from community import community_louvain
G = nx.powerlaw_cluster_graph(100, 1, .4, seed=101)
partition = community_louvain.best_partition(G)
for i in set(partition.values()):
print("Community", i)
members = list_nodes = [nodes for nodes in partition.keys() if partition[nodes] == i]
print(members)
values = [partition.get(node) for node in G.nodes()]
nx.draw_spring(G, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=False)
plt.show()
print ("Modularity score:", community_louvain.modularity(partition, G))
d = nx.coloring.greedy_color(G)
print(d)
nx.draw_networkx(G, node_color=[d[n] for n in sorted(d.keys())])
plt.show()
```
## Graph loading, dumping, and sampling
```
import networkx as nx
dump_file_base = "dumped_graph"
# Be sure the dump_file file doesn't exist
def remove_file(filename):
import os
if os.path.exists(filename):
os.remove(filename)
G = nx.krackhardt_kite_graph()
# GML format write and read
GML_file = dump_file_base + '.gml'
remove_file(GML_file)
nx.write_gml(G, GML_file)
G2 = nx.read_gml(GML_file)
assert sorted(list(G.edges())) == sorted(list(G2.edges()))
```
#### Similar to write_gml and read_gml are the following ones:
- Aadjacency list (read_adjlist and write_adjlist)
- Multiline adjacency list (read_multiline_adjlist and write_multiline_adjlist)
- Edge list (read_edgelist and write_edgelist)
- GEXF (read_gexf and write_gexf)
- Pickle (read_gpickle and write_gpickle)
- GraphML (read_graphml and write_graphml)
- LEDA (read_leda and parse_leda)
- YAML (read_yaml and write_yaml)
- Pajek (read_pajek and write_pajek)
- GIS Shapefile (read_shp and write_shp)
- JSON (load/loads and dump/dumps provides JSON serialization)
### $ Sampling\ Techniques: $
* #### $ Node $
* #### $ Link $
* #### $ Snowball $
```
import snowball_sampling
my_social_network = nx.Graph()
snowball_sampling.snowball_sampling(my_social_network, 2, 'alberto')
nx.draw(my_social_network)
plt.show()
my_sampled_social_network = nx.Graph()
snowball_sampling.snowball_sampling(my_sampled_social_network, 3, 'alberto', sampling_rate=0.2)
nx.draw(my_sampled_social_network)
plt.show()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/mohameddhameem/TensorflowCertification/blob/main/TensorflowCertification/Course_1_Part_6_Lesson_2_CNN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
#Improving Computer Vision Accuracy using Convolutions
In the previous lessons you saw how to do fashion recognition using a Deep Neural Network (DNN) containing three layers -- the input layer (in the shape of the data), the output layer (in the shape of the desired output) and a hidden layer. You experimented with the impact of different sizes of hidden layer, number of training epochs etc on the final accuracy.
For convenience, here's the entire code again. Run it and take a note of the test accuracy that is printed out at the end.
```
import tensorflow as tf
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images / 255.0
test_images=test_images / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5)
test_loss = model.evaluate(test_images, test_labels)
```
Your accuracy is probably about 89% on training and 87% on validation...not bad...But how do you make that even better? One way is to use something called Convolutions. I'm not going to details on Convolutions here, but the ultimate concept is that they narrow down the content of the image to focus on specific, distinct, details.
If you've ever done image processing using a filter (like this: https://en.wikipedia.org/wiki/Kernel_(image_processing)) then convolutions will look very familiar.
In short, you take an array (usually 3x3 or 5x5) and pass it over the image. By changing the underlying pixels based on the formula within that matrix, you can do things like edge detection. So, for example, if you look at the above link, you'll see a 3x3 that is defined for edge detection where the middle cell is 8, and all of its neighbors are -1. In this case, for each pixel, you would multiply its value by 8, then subtract the value of each neighbor. Do this for every pixel, and you'll end up with a new image that has the edges enhanced.
This is perfect for computer vision, because often it's features that can get highlighted like this that distinguish one item for another, and the amount of information needed is then much less...because you'll just train on the highlighted features.
That's the concept of Convolutional Neural Networks. Add some layers to do convolution before you have the dense layers, and then the information going to the dense layers is more focussed, and possibly more accurate.
Run the below code -- this is the same neural network as earlier, but this time with Convolutional layers added first. It will take longer, but look at the impact on the accuracy:
```
import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images.reshape(60000, 28, 28, 1)
training_images=training_images / 255.0
test_images = test_images.reshape(10000, 28, 28, 1)
test_images=test_images/255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
model.fit(training_images, training_labels, epochs=50)
test_loss = model.evaluate(test_images, test_labels)
```
It's likely gone up to about 93% on the training data and 91% on the validation data.
That's significant, and a step in the right direction!
Try running it for more epochs -- say about 20, and explore the results! But while the results might seem really good, the validation results may actually go down, due to something called 'overfitting' which will be discussed later.
(In a nutshell, 'overfitting' occurs when the network learns the data from the training set really well, but it's too specialised to only that data, and as a result is less effective at seeing *other* data. For example, if all your life you only saw red shoes, then when you see a red shoe you would be very good at identifying it, but blue suade shoes might confuse you...and you know you should never mess with my blue suede shoes.)
Then, look at the code again, and see, step by step how the Convolutions were built:
Step 1 is to gather the data. You'll notice that there's a bit of a change here in that the training data needed to be reshaped. That's because the first convolution expects a single tensor containing everything, so instead of 60,000 28x28x1 items in a list, we have a single 4D list that is 60,000x28x28x1, and the same for the test images. If you don't do this, you'll get an error when training as the Convolutions do not recognize the shape.
```
import tensorflow as tf
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images.reshape(60000, 28, 28, 1)
training_images=training_images / 255.0
test_images = test_images.reshape(10000, 28, 28, 1)
test_images=test_images/255.0
```
Next is to define your model. Now instead of the input layer at the top, you're going to add a Convolution. The parameters are:
1. The number of convolutions you want to generate. Purely arbitrary, but good to start with something in the order of 32
2. The size of the Convolution, in this case a 3x3 grid
3. The activation function to use -- in this case we'll use relu, which you might recall is the equivalent of returning x when x>0, else returning 0
4. In the first layer, the shape of the input data.
You'll follow the Convolution with a MaxPooling layer which is then designed to compress the image, while maintaining the content of the features that were highlighted by the convlution. By specifying (2,2) for the MaxPooling, the effect is to quarter the size of the image. Without going into too much detail here, the idea is that it creates a 2x2 array of pixels, and picks the biggest one, thus turning 4 pixels into 1. It repeats this across the image, and in so doing halves the number of horizontal, and halves the number of vertical pixels, effectively reducing the image by 25%.
You can call model.summary() to see the size and shape of the network, and you'll notice that after every MaxPooling layer, the image size is reduced in this way.
```
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(2, 2),
```
Add another convolution
```
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2)
```
Now flatten the output. After this you'll just have the same DNN structure as the non convolutional version
```
tf.keras.layers.Flatten(),
```
The same 128 dense layers, and 10 output layers as in the pre-convolution example:
```
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
```
Now compile the model, call the fit method to do the training, and evaluate the loss and accuracy from the test set.
```
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5)
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(test_acc)
```
# Visualizing the Convolutions and Pooling
This code will show us the convolutions graphically. The print (test_labels[;100]) shows us the first 100 labels in the test set, and you can see that the ones at index 0, index 23 and index 28 are all the same value (9). They're all shoes. Let's take a look at the result of running the convolution on each, and you'll begin to see common features between them emerge. Now, when the DNN is training on that data, it's working with a lot less, and it's perhaps finding a commonality between shoes based on this convolution/pooling combination.
```
print(test_labels[:100])
import matplotlib.pyplot as plt
f, axarr = plt.subplots(3,4)
FIRST_IMAGE=2
SECOND_IMAGE=3
THIRD_IMAGE=0
CONVOLUTION_NUMBER = 2
from tensorflow.keras import models
layer_outputs = [layer.output for layer in model.layers]
activation_model = tf.keras.models.Model(inputs = model.input, outputs = layer_outputs)
for x in range(0,4):
f1 = activation_model.predict(test_images[FIRST_IMAGE].reshape(1, 28, 28, 1))[x]
axarr[0,x].imshow(f1[0, : , :, CONVOLUTION_NUMBER], cmap='inferno')
axarr[0,x].grid(False)
f2 = activation_model.predict(test_images[SECOND_IMAGE].reshape(1, 28, 28, 1))[x]
axarr[1,x].imshow(f2[0, : , :, CONVOLUTION_NUMBER], cmap='inferno')
axarr[1,x].grid(False)
f3 = activation_model.predict(test_images[THIRD_IMAGE].reshape(1, 28, 28, 1))[x]
axarr[2,x].imshow(f3[0, : , :, CONVOLUTION_NUMBER], cmap='inferno')
axarr[2,x].grid(False)
```
EXERCISES
1. Try editing the convolutions. Change the 32s to either 16 or 64. What impact will this have on accuracy and/or training time.
2. Remove the final Convolution. What impact will this have on accuracy or training time?
3. How about adding more Convolutions? What impact do you think this will have? Experiment with it.
4. Remove all Convolutions but the first. What impact do you think this will have? Experiment with it.
5. In the previous lesson you implemented a callback to check on the loss function and to cancel training once it hit a certain amount. See if you can implement that here!
```
import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.mnist
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
print('logs--> ',logs)
if(logs.get('accuracy')>0.9):
print("\nReached 90% accuracy so cancelling training!")
self.model.stop_training = True
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images.reshape(60000, 28, 28, 1)
training_images=training_images / 255.0
test_images = test_images.reshape(10000, 28, 28, 1)
test_images=test_images/255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
callbacks = myCallback()
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=10, callbacks=[callbacks])
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(test_acc)
```
| github_jupyter |
# Create a Local Docker Image
In this section, we will create an IoT Edge module, a Docker container image with an HTTP web server that has a scoring REST endpoint.
## Get Global Variables
```
import sys
sys.path.append('../common')
from env_variables import *
```
## Create Web Application & Inference Server for Our ML Solution
```
%%writefile $lvaExtensionPath/app.py
import threading
from PIL import Image
import numpy as np
import io
import json
import logging
import linecache
import sys
from score import MLModel, PrintGetExceptionDetails
from flask import Flask, request, jsonify, Response
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
inferenceEngine = MLModel()
@app.route("/score", methods = ['POST'])
def scoreRRS():
global inferenceEngine
try:
# get request as byte stream
imageData = io.BytesIO(request.get_data())
# load the image
pilImage = Image.open(imageData)
# Infer Image
detectedObjects = inferenceEngine.Score(pilImage)
if len(detectedObjects) > 0:
respBody = {
"inferences" : detectedObjects
}
respBody = json.dumps(respBody)
logging.info("[LVAX] Sending response.")
return Response(respBody, status= 200, mimetype ='application/json')
else:
logging.info("[LVAX] Sending empty response.")
return Response(status= 204)
except:
PrintGetExceptionDetails()
return Response(response='Exception occured while processing the image.', status=500)
@app.route("/")
def healthy():
return "Healthy"
if __name__ == "__main__":
app.run(host='127.0.0.1', port=8888)
```
8888 is the internal port of the webserver app that listens the requests. Next, we will map it to different ports to expose it externally.
```
%%writefile $lvaExtensionPath/wsgi.py
from app import app as application
def create():
application.run(host='127.0.0.1', port=8888)
import os
os.makedirs(os.path.join(lvaExtensionPath, "nginx"), exist_ok=True)
```
The exposed port of the web app is now 80, while the internal one is still 8888.
```
%%writefile $lvaExtensionPath/nginx/app
server {
listen 80;
server_name _;
location / {
include proxy_params;
proxy_pass http://127.0.0.1:8888;
proxy_connect_timeout 5000s;
proxy_read_timeout 5000s;
}
}
%%writefile $lvaExtensionPath/gunicorn_logging.conf
[loggers]
keys=root, gunicorn.error
[handlers]
keys=console
[formatters]
keys=json
[logger_root]
level=INFO
handlers=console
[logger_gunicorn.error]
level=ERROR
handlers=console
propagate=0
qualname=gunicorn.error
[handler_console]
class=StreamHandler
formatter=json
args=(sys.stdout, )
[formatter_json]
class=jsonlogging.JSONFormatter
%%writefile $lvaExtensionPath/kill_supervisor.py
import sys
import os
import signal
def write_stdout(s):
sys.stdout.write(s)
sys.stdout.flush()
# this function is modified from the code and knowledge found here: http://supervisord.org/events.html#example-event-listener-implementation
def main():
while 1:
write_stdout('[LVAX] READY\n')
# wait for the event on stdin that supervisord will send
line = sys.stdin.readline()
write_stdout('[LVAX] Terminating supervisor with this event: ' + line);
try:
# supervisord writes its pid to its file from which we read it here, see supervisord.conf
pidfile = open('/tmp/supervisord.pid','r')
pid = int(pidfile.readline());
os.kill(pid, signal.SIGQUIT)
except Exception as e:
write_stdout('[LVAX] Could not terminate supervisor: ' + e.strerror + '\n')
write_stdout('[LVAX] RESULT 2\nOK')
main()
import os
os.makedirs(os.path.join(lvaExtensionPath, "etc"), exist_ok=True)
%%writefile $lvaExtensionPath/etc/supervisord.conf
[supervisord]
logfile=/tmp/supervisord.log ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10 ; (num of main logfile rotation backups;default 10)
loglevel=info ; (log level;default info; others: debug,warn,trace)
pidfile=/tmp/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=true ; (start in foreground if true;default false)
minfds=1024 ; (min. avail startup file descriptors;default 1024)
minprocs=200 ; (min. avail process descriptors;default 200)
[program:gunicorn]
command=bash -c "gunicorn --workers 1 -m 007 --timeout 100000 --capture-output --error-logfile - --log-level debug --log-config gunicorn_logging.conf \"wsgi:create()\""
directory=/lvaExtension
redirect_stderr=true
stdout_logfile =/dev/stdout
stdout_logfile_maxbytes=0
startretries=2
startsecs=20
[program:nginx]
command=/usr/sbin/nginx -g "daemon off;"
startretries=2
startsecs=5
priority=3
[eventlistener:program_exit]
command=python kill_supervisor.py
directory=/lvaExtension
events=PROCESS_STATE_FATAL
priority=2
```
## Create a Docker File to Containerize the ML Solution and Web App Server
```
%%writefile $lvaExtensionPath/Dockerfile
FROM ubuntu:18.04
ARG WORK_DIR=/lvaExtension
WORKDIR ${WORK_DIR}
# Copy the app file
COPY . ${WORK_DIR}/
COPY etc /etc
# Install runit, python, nginx, and necessary python packages
RUN apt-get update && apt-get install -y --no-install-recommends \
python3-pip python3-dev libglib2.0-0 libsm6 libxext6 libxrender-dev nginx supervisor python3-setuptools \
&& cd /usr/local/bin \
&& ln -s /usr/bin/python3 python \
&& pip3 install --upgrade pip \
&& pip install numpy tensorflow flask pillow gunicorn json-logging-py \
&& apt-get clean \
&& apt-get update && apt-get install -y --no-install-recommends \
wget runit nginx \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get clean \
&& rm /etc/nginx/sites-enabled/default \
&& cp /lvaExtension/nginx/app /etc/nginx/sites-available/ \
&& ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/
EXPOSE 80
CMD ["supervisord", "-c", "/lvaExtension/etc/supervisord.conf"]
```
## Create a Local Docker Image
Finally, we will create a Docker image locally. We will later host the image in a container registry like Docker Hub, Azure Container Registry, or a local registry.
To run the following code snippet, you must have the pre-requisities mentioned in [the requirements page](../../../common/requirements.md). Most notably, we are running the `docker` command without `sudo`.
> <span>[!WARNING]</span>
> Please ensure that Docker is running before executing the cell below. Execution of the cell below may take several minutes.
```
!docker build -t $containerImageName --file ./$lvaExtensionPath/Dockerfile ./$lvaExtensionPath
```
## Next Steps
If all the code cells above have successfully finished running, return to the Readme page to continue.
| github_jupyter |
### This notebook provides a template for connecting to the KEGG API, as well as a first look at the list of enzymes in the database
#### References:
https://biopython.readthedocs.io/en/latest/Tutorial/chapter_kegg.html
http://biopython.org/DIST/docs/api/Bio.KEGG.REST-module.html
https://exploringlifedata.blogspot.com/
```
# imports
from Bio.KEGG import REST
from Bio.KEGG import Enzyme
import pandas as pd
# pulling all enzymes currently listed in KEGG & reading into text buffer
enzyme = REST.kegg_list("enzyme").read()
# parsing text buffer to get list of all enzymes in KEGG
enzyme_entry = []
for line in enzyme.rstrip().split("\n"):
entry, description = line.split("\t")
enzyme_entry.append(entry)
len(enzyme_entry)
# alternative implementation of above to read enzyme list directly into pandas dataframe
all_enzymes_df = pd.read_csv(REST.kegg_list('enzyme'), sep='\t', header=None, names=['EC_number', 'description'])
all_enzymes_df.head()
#example for one entry
enzyme_file_test = REST.kegg_get('ec:1.1.1.85').read()
for i in enzyme_file_test.rstrip().split("\n"):
if i.startswith("ALL_REAC"):
print (i.rstrip().split(" "))
# parse all entries for which there are more than 5 entries in the 'ALL_REAC' field
# note this is a time intensive function
promiscuous_enzyme_entry = []
for entry in enzyme_entry:
enzyme_file = REST.kegg_get(entry).read()
for line in enzyme_file.rstrip().split("\n"):
if line.startswith("ALL_REAC"):
if len(line.rstrip().split(" "))>5: # are there always 3 empty '' entries in each split line? how do we know this is consistent?
promiscuous_enzyme_entry.append(entry)
print (entry)
len(promiscuous_enzyme_entry)
# alternative implementation of above using Enzyme entry parser from Bio.KEGG library
example_enzyme_entry = Enzyme.read(REST.kegg_get('ec:1.1.1.1'))
print(example_enzyme_entry)
# get a list of all data fields in enzyme entry
enzyme_fields = [method for method in dir(example_enzyme_entry) if not method.startswith('_')]
print(enzyme_fields)
# create dataframe to store enzyme entry information
enzyme_matrix = []
enzyme_matrix.append([getattr(example_enzyme_entry, field) for field in enzyme_fields])
df_enzymes = pd.DataFrame(enzyme_matrix, columns=enzyme_fields)
df_enzymes.head()
# checkout the reaction field in the dataframe
df_enzymes.reaction[0]
# build dataframe of all enzyme information from database for all enzyme entries
# warning - this function is quite time intensive
# can probably speed this up by requesting up to 10 entries at a time, but I haven't been able to figure it out
# reference: http://biopython.org/DIST/docs/api/Bio.KEGG.REST-module.html#kegg_get
enzyme_matrix = []
total_entries = len(all_enzymes_df.EC_number)
for index in range(total_entries):
record = Enzyme.read(REST.kegg_get(all_enzymes_df.EC_number[index]))
enzyme_matrix.append([getattr(record, field) for field in enzyme_fields])
if index % 100 == 0:
print("{} enzymes complete, {} remaining".format(index, total_entries - index))
else:
pass
# make dataframe from enzyme_matrix
df_enzymes = pd.DataFrame(enzyme_matrix, columns=enzyme_fields)
df_enzymes.shape
df_enzymes.head()
# write enzyme_data to csv
df_enzymes.to_csv('KEGG_enzymes_all_data.csv')
# will look into promiscuity in another notebook
# problem: this saves the data as a string, and we lose the functionality introduced by KEGG.Enzyme.parse()
# first reaction is an example of a promiscuous class of enzymes!
df_enzymes.reaction[0]
# to the above, except write all records to a text file, to take advantage of KEGG.Enzyme.parse() functionality
# warning this takes a really long time to do
counter = 7524
with open('KEGG_enzymes_all_data.txt', 'a') as f:
for enzyme in all_enzymes_df.EC_number:
f.writelines(REST.kegg_get(enzyme))
counter -= 1
if counter % 100 == 0:
print("{} enzymes remaining".format(counter))
else:
pass
```
| github_jupyter |
```
#IMPORT SEMUA LIBRARY DISINI
#IMPORT LIBRARY PANDAS
import pandas as pd
#IMPORT LIBRARY POSTGRESQL
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
#IMPORT LIBRARY CHART
from matplotlib import pyplot as plt
from matplotlib import style
#IMPORT LIBRARY PDF
from fpdf import FPDF
#IMPORT LIBRARY BASEPATH
import io
#IMPORT LIBRARY BASE64 IMG
import base64
#IMPORT LIBRARY NUMPY
import numpy as np
#IMPORT LIBRARY EXCEL
import xlsxwriter
#IMPORT LIBRARY SIMILARITAS
import n0similarities as n0
#FUNGSI UNTUK MENGUPLOAD DATA DARI CSV KE POSTGRESQL
def uploadToPSQL(host, username, password, database, port, table, judul, filePath, name, subjudul, dataheader, databody):
#TEST KONEKSI KE DATABASE
try:
for t in range(0, len(table)):
#DATA DIJADIKAN LIST
rawstr = [tuple(x) for x in zip(dataheader, databody[t])]
#KONEKSI KE DATABASE
connection = psycopg2.connect(user=username,password=password,host=host,port=port,database=database)
cursor = connection.cursor()
connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT);
#CEK TABLE
cursor.execute("SELECT * FROM information_schema.tables where table_name=%s", (table[t],))
exist = bool(cursor.rowcount)
#KALAU ADA DIHAPUS DULU, TERUS DICREATE ULANG
if exist == True:
cursor.execute("DROP TABLE "+ table[t] + " CASCADE")
cursor.execute("CREATE TABLE "+table[t]+" (index SERIAL, tanggal date, total varchar);")
#KALAU GA ADA CREATE DATABASE
else:
cursor.execute("CREATE TABLE "+table[t]+" (index SERIAL, tanggal date, total varchar);")
#MASUKAN DATA KE DATABASE YANG TELAH DIBUAT
cursor.execute('INSERT INTO '+table[t]+'(tanggal, total) values ' +str(rawstr)[1:-1])
#JIKA BERHASIL SEMUA AKAN MENGHASILKAN KELUARAN BENAR (TRUE)
return True
#JIKA KONEKSI GAGAL
except (Exception, psycopg2.Error) as error :
return error
#TUTUP KONEKSI
finally:
if(connection):
cursor.close()
connection.close()
#FUNGSI UNTUK MEMBUAT CHART, DATA YANG DIAMBIL DARI DATABASE DENGAN MENGGUNAKAN ORDER DARI TANGGAL DAN JUGA LIMIT
#DISINI JUGA MEMANGGIL FUNGSI MAKEEXCEL DAN MAKEPDF
def makeChart(host, username, password, db, port, table, judul, filePath, name, subjudul, A2, B2, C2, D2, E2, F2, G2, H2,I2, J2, K2, limitdata, wilayah, tabledata, basePath):
try:
datarowsend = []
for t in range(0, len(table)):
#TEST KONEKSI KE DATABASE
connection = psycopg2.connect(user=username,password=password,host=host,port=port,database=db)
cursor = connection.cursor()
#MENGAMBIL DATA DARI DATABASE DENGAN LIMIT YANG SUDAH DIKIRIMKAN DARI VARIABLE DIBAWAH
postgreSQL_select_Query = "SELECT * FROM "+table[t]+" ORDER BY tanggal DESC LIMIT " + str(limitdata)
cursor.execute(postgreSQL_select_Query)
mobile_records = cursor.fetchall()
uid = []
lengthx = []
lengthy = []
#MENYIMPAN DATA DARI DATABASE KE DALAM VARIABLE
for row in mobile_records:
uid.append(row[0])
lengthx.append(row[1])
lengthy.append(row[2])
datarowsend.append(mobile_records)
#JUDUL CHART
judulgraf = A2 + " " + wilayah[t]
#bar
style.use('ggplot')
fig, ax = plt.subplots()
#DATA CHART DIMASUKAN DISINI
ax.bar(uid, lengthy, align='center')
#JUDUL CHART
ax.set_title(judulgraf)
ax.set_ylabel('Total')
ax.set_xlabel('Tanggal')
ax.set_xticks(uid)
ax.set_xticklabels((lengthx))
b = io.BytesIO()
#BUAT CHART MENJADI FORMAT PNG
plt.savefig(b, format='png', bbox_inches="tight")
#CHART DIJADIKAN BASE64
barChart = base64.b64encode(b.getvalue()).decode("utf-8").replace("\n", "")
plt.show()
#line
#DATA CHART DIMASUKAN DISINI
plt.plot(lengthx, lengthy)
plt.xlabel('Tanggal')
plt.ylabel('Total')
#JUDUL CHART
plt.title(judulgraf)
plt.grid(True)
l = io.BytesIO()
#CHART DIJADIKAN GAMBAR
plt.savefig(l, format='png', bbox_inches="tight")
#GAMBAR DIJADIKAN BAS64
lineChart = base64.b64encode(l.getvalue()).decode("utf-8").replace("\n", "")
plt.show()
#pie
#JUDUL CHART
plt.title(judulgraf)
#DATA CHART DIMASUKAN DISINI
plt.pie(lengthy, labels=lengthx, autopct='%1.1f%%',
shadow=True, startangle=180)
plt.plot(legend=None)
plt.axis('equal')
p = io.BytesIO()
#CHART DIJADIKAN GAMBAR
plt.savefig(p, format='png', bbox_inches="tight")
#CHART DICONVERT KE BASE64
pieChart = base64.b64encode(p.getvalue()).decode("utf-8").replace("\n", "")
plt.show()
#CHART DISIMPAN KE DIREKTORI DIJADIKAN FORMAT PNG
#BARCHART
bardata = base64.b64decode(barChart)
barname = basePath+'jupyter/CEIC/19. Sektor Konstruksi dan Properti/img/'+name+''+table[t]+'-bar.png'
with open(barname, 'wb') as f:
f.write(bardata)
#LINECHART
linedata = base64.b64decode(lineChart)
linename = basePath+'jupyter/CEIC/19. Sektor Konstruksi dan Properti/img/'+name+''+table[t]+'-line.png'
with open(linename, 'wb') as f:
f.write(linedata)
#PIECHART
piedata = base64.b64decode(pieChart)
piename = basePath+'jupyter/CEIC/19. Sektor Konstruksi dan Properti/img/'+name+''+table[t]+'-pie.png'
with open(piename, 'wb') as f:
f.write(piedata)
#MEMANGGIL FUNGSI EXCEL
makeExcel(datarowsend, A2, B2, C2, D2, E2, F2, G2, H2,I2, J2, K2, name, limitdata, table, wilayah, basePath)
#MEMANGGIL FUNGSI PDF
makePDF(datarowsend, judul, barChart, lineChart, pieChart, name, subjudul, A2, B2, C2, D2, E2, F2, G2, H2,I2, J2, K2, limitdata, table, wilayah, basePath)
#JIKA KONEKSI GAGAL
except (Exception, psycopg2.Error) as error :
print (error)
#TUTUP KONEKSI
finally:
if(connection):
cursor.close()
connection.close()
#FUNGSI UNTUK MEMBUAT PDF YANG DATANYA BERASAL DARI DATABASE DIJADIKAN FORMAT EXCEL TABLE F2
#PLUGIN YANG DIGUNAKAN ADALAH FPDF
def makePDF(datarow, judul, bar, line, pie, name, subjudul, A2, B2, C2, D2, E2, F2, G2, H2,I2, J2, K2, lengthPDF, table, wilayah, basePath):
#PDF DIATUR DENGAN SIZE A4 DAN POSISI LANDSCAPE
pdf = FPDF('L', 'mm', [210,297])
#TAMBAH HALAMAN PDF
pdf.add_page()
#SET FONT DAN JUGA PADDING
pdf.set_font('helvetica', 'B', 20.0)
pdf.set_xy(145.0, 15.0)
#TAMPILKAN JUDUL PDF
pdf.cell(ln=0, h=2.0, align='C', w=10.0, txt=judul, border=0)
#SET FONT DAN JUGA PADDING
pdf.set_font('arial', '', 14.0)
pdf.set_xy(145.0, 25.0)
#TAMPILKAN SUB JUDUL PDF
pdf.cell(ln=0, h=2.0, align='C', w=10.0, txt=subjudul, border=0)
#BUAT GARIS DIBAWAH SUB JUDUL
pdf.line(10.0, 30.0, 287.0, 30.0)
pdf.set_font('times', '', 10.0)
pdf.set_xy(17.0, 37.0)
pdf.set_font('Times','B',11.0)
pdf.ln(0.5)
th1 = pdf.font_size
#BUAT TABLE DATA DATA DI DPF
pdf.cell(100, 2*th1, "Kategori", border=1, align='C')
pdf.cell(177, 2*th1, A2, border=1, align='C')
pdf.ln(2*th1)
pdf.cell(100, 2*th1, "Region", border=1, align='C')
pdf.cell(177, 2*th1, B2, border=1, align='C')
pdf.ln(2*th1)
pdf.cell(100, 2*th1, "Frekuensi", border=1, align='C')
pdf.cell(177, 2*th1, C2, border=1, align='C')
pdf.ln(2*th1)
pdf.cell(100, 2*th1, "Unit", border=1, align='C')
pdf.cell(177, 2*th1, D2, border=1, align='C')
pdf.ln(2*th1)
pdf.cell(100, 2*th1, "Sumber", border=1, align='C')
pdf.cell(177, 2*th1, E2, border=1, align='C')
pdf.ln(2*th1)
pdf.cell(100, 2*th1, "Status", border=1, align='C')
pdf.cell(177, 2*th1, F2, border=1, align='C')
pdf.ln(2*th1)
pdf.cell(100, 2*th1, "ID Seri", border=1, align='C')
pdf.cell(177, 2*th1, G2, border=1, align='C')
pdf.ln(2*th1)
pdf.cell(100, 2*th1, "Kode SR", border=1, align='C')
pdf.cell(177, 2*th1, H2, border=1, align='C')
pdf.ln(2*th1)
pdf.cell(100, 2*th1, "Tanggal Obs. Pertama", border=1, align='C')
pdf.cell(177, 2*th1, str(I2.date()), border=1, align='C')
pdf.ln(2*th1)
pdf.cell(100, 2*th1, "Tanggal Obs. Terakhir ", border=1, align='C')
pdf.cell(177, 2*th1, str(J2.date()), border=1, align='C')
pdf.ln(2*th1)
pdf.cell(100, 2*th1, "Waktu pembaruan terakhir", border=1, align='C')
pdf.cell(177, 2*th1, str(K2.date()), border=1, align='C')
pdf.ln(2*th1)
pdf.set_xy(17.0, 125.0)
pdf.set_font('Times','B',11.0)
epw = pdf.w - 2*pdf.l_margin
col_width = epw/(lengthPDF+1)
pdf.ln(0.5)
th = pdf.font_size
#HEADER TABLE DATA F2
pdf.cell(col_width, 2*th, str("Wilayah"), border=1, align='C')
#TANGAL HEADER DI LOOPING
for row in datarow[0]:
pdf.cell(col_width, 2*th, str(row[1]), border=1, align='C')
pdf.ln(2*th)
#ISI TABLE F2
for w in range(0, len(table)):
data=list(datarow[w])
pdf.set_font('Times','B',10.0)
pdf.set_font('Arial','',9)
pdf.cell(col_width, 2*th, wilayah[w], border=1, align='C')
#DATA BERDASARKAN TANGGAL
for row in data:
pdf.cell(col_width, 2*th, str(row[2]), border=1, align='C')
pdf.ln(2*th)
#PEMANGGILAN GAMBAR
for s in range(0, len(table)):
col = pdf.w - 2*pdf.l_margin
pdf.ln(2*th)
widthcol = col/3
#TAMBAH HALAMAN
pdf.add_page()
#DATA GAMBAR BERDASARKAN DIREKTORI DIATAS
pdf.image(basePath+'jupyter/CEIC/19. Sektor Konstruksi dan Properti/img/'+name+''+table[s]+'-bar.png', link='', type='',x=8, y=80, w=widthcol)
pdf.set_xy(17.0, 144.0)
col = pdf.w - 2*pdf.l_margin
pdf.image(basePath+'jupyter/CEIC/19. Sektor Konstruksi dan Properti/img/'+name+''+table[s]+'-line.png', link='', type='',x=103, y=80, w=widthcol)
pdf.set_xy(17.0, 144.0)
col = pdf.w - 2*pdf.l_margin
pdf.image(basePath+'jupyter/CEIC/19. Sektor Konstruksi dan Properti/img/'+name+''+table[s]+'-pie.png', link='', type='',x=195, y=80, w=widthcol)
pdf.ln(4*th)
#PDF DIBUAT
pdf.output(basePath+'jupyter/CEIC/19. Sektor Konstruksi dan Properti/pdf/'+A2+'.pdf', 'F')
#FUNGSI MAKEEXCEL GUNANYA UNTUK MEMBUAT DATA YANG BERASAL DARI DATABASE DIJADIKAN FORMAT EXCEL TABLE F2
#PLUGIN YANG DIGUNAKAN ADALAH XLSXWRITER
def makeExcel(datarow, A2, B2, C2, D2, E2, F2, G2, H2, I2, J2, K2, name, limit, table, wilayah, basePath):
#BUAT FILE EXCEL
workbook = xlsxwriter.Workbook(basePath+'jupyter/CEIC/19. Sektor Konstruksi dan Properti/excel/'+A2+'.xlsx')
#BUAT WORKSHEET EXCEL
worksheet = workbook.add_worksheet('sheet1')
#SETTINGAN UNTUK BORDER DAN FONT BOLD
row1 = workbook.add_format({'border': 2, 'bold': 1})
row2 = workbook.add_format({'border': 2})
#HEADER UNTUK TABLE EXCEL F2
header = ["Wilayah", "Kategori","Region","Frekuensi","Unit","Sumber","Status","ID Seri","Kode SR","Tanggal Obs. Pertama","Tanggal Obs. Terakhir ","Waktu pembaruan terakhir"]
#DATA DATA DITAMPUNG PADA VARIABLE
for rowhead2 in datarow[0]:
header.append(str(rowhead2[1]))
#DATA HEADER DARI VARIABLE DIMASUKAN KE SINI UNTUK DITAMPILKAN BERDASARKAN ROW DAN COLUMN
for col_num, data in enumerate(header):
worksheet.write(0, col_num, data, row1)
#DATA ISI TABLE F2 DITAMPILKAN DISINI
for w in range(0, len(table)):
data=list(datarow[w])
body = [wilayah[w], A2, B2, C2, D2, E2, F2, G2, H2, str(I2.date()), str(J2.date()), str(K2.date())]
for rowbody2 in data:
body.append(str(rowbody2[2]))
for col_num, data in enumerate(body):
worksheet.write(w+1, col_num, data, row2)
#FILE EXCEL DITUTUP
workbook.close()
#DISINI TEMPAT AWAL UNTUK MENDEFINISIKAN VARIABEL VARIABEL SEBELUM NANTINYA DIKIRIM KE FUNGSI
#PERTAMA MANGGIL FUNGSI UPLOADTOPSQL DULU, KALAU SUKSES BARU MANGGIL FUNGSI MAKECHART
#DAN DI MAKECHART MANGGIL FUNGSI MAKEEXCEL DAN MAKEPDF
#BASE PATH UNTUK NANTINYA MENGCREATE FILE ATAU MEMANGGIL FILE
basePath = 'C:/Users/ASUS/Documents/bappenas/'
#FILE SIMILARITY WILAYAH
filePathwilayah = basePath+'data mentah/CEIC/allwilayah.xlsx';
#BACA FILE EXCEL DENGAN PANDAS
readexcelwilayah = pd.read_excel(filePathwilayah)
dfwilayah = list(readexcelwilayah.values)
readexcelwilayah.fillna(0)
allwilayah = []
#PEMILIHAN JENIS DATA, APA DATA ITU PROVINSI, KABUPATEN, KECAMATAN ATAU KELURAHAN
tipewilayah = 'prov'
if tipewilayah == 'prov':
for x in range(0, len(dfwilayah)):
allwilayah.append(dfwilayah[x][1])
elif tipewilayah=='kabkot':
for x in range(0, len(dfwilayah)):
allwilayah.append(dfwilayah[x][3])
elif tipewilayah == 'kec':
for x in range(0, len(dfwilayah)):
allwilayah.append(dfwilayah[x][5])
elif tipewilayah == 'kel':
for x in range(0, len(dfwilayah)):
allwilayah.append(dfwilayah[x][7])
semuawilayah = list(set(allwilayah))
#SETTING VARIABLE UNTUK DATABASE DAN DATA YANG INGIN DIKIRIMKAN KE FUNGSI DISINI
name = "01. Nilai Bruto Output Konstruksi (EA001-EA011) "
host = "localhost"
username = "postgres"
password = "1234567890"
port = "5432"
database = "ceic"
judul = "Produk Domestik Bruto (AA001-AA007)"
subjudul = "Badan Perencanaan Pembangunan Nasional"
filePath = basePath+'data mentah/CEIC/19. Sektor Konstruksi dan Properti/'+name+'.xlsx';
limitdata = int(8)
readexcel = pd.read_excel(filePath)
tabledata = []
wilayah = []
databody = []
#DATA EXCEL DIBACA DISINI DENGAN MENGGUNAKAN PANDAS
df = list(readexcel.values)
head = list(readexcel)
body = list(df[0])
readexcel.fillna(0)
#PILIH ROW DATA YANG INGIN DITAMPILKAN
rangeawal = 106
rangeakhir = 107
rowrange = range(rangeawal, rangeakhir)
#INI UNTUK MEMFILTER APAKAH DATA YANG DIPILIH MEMILIKI SIMILARITAS ATAU TIDAK
#ISIKAN 'WILAYAH' UNTUK SIMILARITAS
#ISIKAN BUKAN WILAYAH JIKA BUKAN WILAYAH
jenisdata = "Indonesia"
#ROW DATA DI LOOPING UNTUK MENDAPATKAN SIMILARITAS WILAYAH
#JIKA VARIABLE JENISDATA WILAYAH AKAN MASUK KESINI
if jenisdata == 'Wilayah':
for x in rowrange:
rethasil = 0
big_w = 0
for w in range(0, len(semuawilayah)):
namawilayah = semuawilayah[w].lower().strip()
nama_wilayah_len = len(namawilayah)
hasil = n0.get_levenshtein_similarity(df[x][0].lower().strip()[nama_wilayah_len*-1:], namawilayah)
if hasil > rethasil:
rethasil = hasil
big_w = w
wilayah.append(semuawilayah[big_w].capitalize())
tabledata.append('produkdomestikbruto_'+semuawilayah[big_w].lower().replace(" ", "") + "" + str(x))
testbody = []
for listbody in df[x][11:]:
if ~np.isnan(listbody) == False:
testbody.append(str('0'))
else:
testbody.append(str(listbody))
databody.append(testbody)
#JIKA BUKAN WILAYAH MASUK KESINI
else:
for x in rowrange:
wilayah.append(jenisdata.capitalize())
tabledata.append('produkdomestikbruto_'+jenisdata.lower().replace(" ", "") + "" + str(x))
testbody = []
for listbody in df[x][11:]:
if ~np.isnan(listbody) == False:
testbody.append(str('0'))
else:
testbody.append(str(listbody))
databody.append(testbody)
#HEADER UNTUK PDF DAN EXCEL
A2 = "Data Migas"
B2 = df[rangeawal][1]
C2 = df[rangeawal][2]
D2 = df[rangeawal][3]
E2 = df[rangeawal][4]
F2 = df[rangeawal][5]
G2 = df[rangeawal][6]
H2 = df[rangeawal][7]
I2 = df[rangeawal][8]
J2 = df[rangeawal][9]
K2 = df[rangeawal][10]
#DATA ISI TABLE F2
dataheader = []
for listhead in head[11:]:
dataheader.append(str(listhead))
#FUNGSI UNTUK UPLOAD DATA KE SQL, JIKA BERHASIL AKAN MAMANGGIL FUNGSI UPLOAD CHART
sql = uploadToPSQL(host, username, password, database, port, tabledata, judul, filePath, name, subjudul, dataheader, databody)
if sql == True:
makeChart(host, username, password, database, port, tabledata, judul, filePath, name, subjudul, A2, B2, C2, D2, E2, F2, G2, H2,I2, J2, K2, limitdata, wilayah, tabledata, basePath)
else:
print(sql)
```
| github_jupyter |
# 使用序列到序列模型完成数字加法
**作者:** [jm12138](https://github.com/jm12138) <br>
**日期:** 2021.05 <br>
**摘要:** 本示例介绍如何使用飞桨完成一个数字加法任务,将会使用飞桨提供的`LSTM`,组建一个序列到序列模型,并在随机生成的数据集上完成数字加法任务的模型训练与预测。
## 一、环境配置
本教程基于Paddle 2.1 编写,如果你的环境不是本版本,请先参考官网[安装](https://www.paddlepaddle.org.cn/install/quick) Paddle 2.1 。
```
# 导入项目运行所需的包
import paddle
import paddle.nn as nn
import random
import numpy as np
from visualdl import LogWriter
# 打印Paddle版本
print('paddle version: %s' % paddle.__version__)
```
## 二、构建数据集
* 随机生成数据,并使用生成的数据构造数据集
* 通过继承 ``paddle.io.Dataset`` 来完成数据集的构造
```
# 编码函数
def encoder(text, LEN, label_dict):
# 文本转ID
ids = [label_dict[word] for word in text]
# 对长度进行补齐
ids += [label_dict[' ']]*(LEN-len(ids))
return ids
# 单个数据生成函数
def make_data(inputs, labels, DIGITS, label_dict):
MAXLEN = DIGITS + 1 + DIGITS
# 对输入输出文本进行ID编码
inputs = encoder(inputs, MAXLEN, label_dict)
labels = encoder(labels, DIGITS + 1, label_dict)
return inputs, labels
# 批量数据生成函数
def gen_datas(DATA_NUM, MAX_NUM, DIGITS, label_dict):
datas = []
while len(datas)<DATA_NUM:
# 随机取两个数
a = random.randint(0,MAX_NUM)
b = random.randint(0,MAX_NUM)
# 生成输入文本
inputs = '%d+%d' % (a, b)
# 生成输出文本
labels = str(eval(inputs))
# 生成单个数据
inputs, labels = [np.array(_).astype('int64') for _ in make_data(inputs, labels, DIGITS, label_dict)]
datas.append([inputs, labels])
return datas
# 继承paddle.io.Dataset来构造数据集
class Addition_Dataset(paddle.io.Dataset):
# 重写数据集初始化函数
def __init__(self, datas):
super(Addition_Dataset, self).__init__()
self.datas = datas
# 重写生成样本的函数
def __getitem__(self, index):
data, label = [paddle.to_tensor(_) for _ in self.datas[index]]
return data, label
# 重写返回数据集大小的函数
def __len__(self):
return len(self.datas)
print('generating datas..')
# 定义字符表
label_dict = {
'0': 0, '1': 1, '2': 2, '3': 3,
'4': 4, '5': 5, '6': 6, '7': 7,
'8': 8, '9': 9, '+': 10, ' ': 11
}
# 输入数字最大位数
DIGITS = 2
# 数据数量
train_num = 5000
dev_num = 500
# 数据批大小
batch_size = 32
# 读取线程数
num_workers = 8
# 定义一些所需变量
MAXLEN = DIGITS + 1 + DIGITS
MAX_NUM = 10**(DIGITS)-1
# 生成数据
train_datas = gen_datas(
train_num,
MAX_NUM,
DIGITS,
label_dict
)
dev_datas = gen_datas(
dev_num,
MAX_NUM,
DIGITS,
label_dict
)
# 实例化数据集
train_dataset = Addition_Dataset(train_datas)
dev_dataset = Addition_Dataset(dev_datas)
print('making the dataset...')
# 实例化数据读取器
train_reader = paddle.io.DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=True,
drop_last=True
)
dev_reader = paddle.io.DataLoader(
dev_dataset,
batch_size=batch_size,
shuffle=False,
drop_last=True
)
print('finish')
```
## 三、模型组网
* 通过继承 ``paddle.nn.Layer`` 类来搭建模型
* 本次介绍的模型是一个简单的基于 ``LSTM`` 的 ``Seq2Seq`` 模型
* 一共有如下四个主要的网络层:
1. 嵌入层(``Embedding``):将输入的文本序列转为嵌入向量
2. 编码层(``LSTM``):将嵌入向量进行编码
3. 解码层(``LSTM``):将编码向量进行解码
4. 全连接层(``Linear``):对解码完成的向量进行线性映射
* 损失函数为交叉熵损失函数
```
# 继承paddle.nn.Layer类
class Addition_Model(nn.Layer):
# 重写初始化函数
# 参数:字符表长度、嵌入层大小、隐藏层大小、解码器层数、处理数字的最大位数
def __init__(self, char_len=12, embedding_size=128, hidden_size=128, num_layers=1, DIGITS=2):
super(Addition_Model, self).__init__()
# 初始化变量
self.DIGITS = DIGITS
self.MAXLEN = DIGITS + 1 + DIGITS
self.hidden_size = hidden_size
self.char_len = char_len
# 嵌入层
self.emb = nn.Embedding(
char_len,
embedding_size
)
# 编码器
self.encoder = nn.LSTM(
input_size=embedding_size,
hidden_size=hidden_size,
num_layers=1
)
# 解码器
self.decoder = nn.LSTM(
input_size=hidden_size,
hidden_size=hidden_size,
num_layers=num_layers
)
# 全连接层
self.fc = nn.Linear(
hidden_size,
char_len
)
# 重写模型前向计算函数
# 参数:输入[None, MAXLEN]、标签[None, DIGITS + 1]
def forward(self, inputs, labels=None):
# 嵌入层
out = self.emb(inputs)
# 编码器
out, (_, _) = self.encoder(out)
# 按时间步切分编码器输出
out = paddle.split(out, self.MAXLEN, axis=1)
# 取最后一个时间步的输出并复制 DIGITS + 1 次
out = paddle.expand(out[-1], [out[-1].shape[0], self.DIGITS + 1, self.hidden_size])
# 解码器
out, (_, _) = self.decoder(out)
# 全连接
out = self.fc(out)
# 如果标签存在,则计算其损失和准确率
if labels is not None:
# 转置解码器输出
tmp = paddle.transpose(out, [0, 2, 1])
# 计算交叉熵损失
loss = nn.functional.cross_entropy(tmp, labels, axis=1)
# 计算准确率
acc = paddle.metric.accuracy(paddle.reshape(out, [-1, self.char_len]), paddle.reshape(labels, [-1, 1]))
# 返回损失和准确率
return loss, acc
# 返回输出
return out
```
## 四、模型训练与评估
* 使用 ``Adam`` 作为优化器进行模型训练
* 以模型准确率作为评价指标
* 使用 ``VisualDL`` 对训练数据进行可视化
* 训练过程中会同时进行模型评估和最佳模型的保存
```
# 初始化log写入器
log_writer = LogWriter(logdir="./log")
# 模型参数设置
embedding_size = 128
hidden_size=128
num_layers=1
# 训练参数设置
epoch_num = 50
learning_rate = 0.001
log_iter = 2000
eval_iter = 500
# 定义一些所需变量
global_step = 0
log_step = 0
max_acc = 0
# 实例化模型
model = Addition_Model(
char_len=len(label_dict),
embedding_size=embedding_size,
hidden_size=hidden_size,
num_layers=num_layers,
DIGITS=DIGITS)
# 将模型设置为训练模式
model.train()
# 设置优化器,学习率,并且把模型参数给优化器
opt = paddle.optimizer.Adam(
learning_rate=learning_rate,
parameters=model.parameters()
)
# 启动训练,循环epoch_num个轮次
for epoch in range(epoch_num):
# 遍历数据集读取数据
for batch_id, data in enumerate(train_reader()):
# 读取数据
inputs, labels = data
# 模型前向计算
loss, acc = model(inputs, labels=labels)
# 打印训练数据
if global_step%log_iter==0:
print('train epoch:%d step: %d loss:%f acc:%f' % (epoch, global_step, loss.numpy(), acc.numpy()))
log_writer.add_scalar(tag="train/loss", step=log_step, value=loss.numpy())
log_writer.add_scalar(tag="train/acc", step=log_step, value=acc.numpy())
log_step+=1
# 模型验证
if global_step%eval_iter==0:
model.eval()
losses = []
accs = []
for data in dev_reader():
loss_eval, acc_eval = model(inputs, labels=labels)
losses.append(loss_eval.numpy())
accs.append(acc_eval.numpy())
avg_loss = np.concatenate(losses).mean()
avg_acc = np.concatenate(accs).mean()
print('eval epoch:%d step: %d loss:%f acc:%f' % (epoch, global_step, avg_loss, avg_acc))
log_writer.add_scalar(tag="dev/loss", step=log_step, value=avg_loss)
log_writer.add_scalar(tag="dev/acc", step=log_step, value=avg_acc)
# 保存最佳模型
if avg_acc>max_acc:
max_acc = avg_acc
print('saving the best_model...')
paddle.save(model.state_dict(), 'best_model')
model.train()
# 反向传播
loss.backward()
# 使用优化器进行参数优化
opt.step()
# 清除梯度
opt.clear_grad()
# 全局步数加一
global_step += 1
# 保存最终模型
paddle.save(model.state_dict(),'final_model')
```
## 五、模型测试
* 使用保存的最佳模型进行测试
```
# 反转字符表
label_dict_adv = {v: k for k, v in label_dict.items()}
# 输入计算题目
input_text = '12+40'
# 编码输入为ID
inputs = encoder(input_text, MAXLEN, label_dict)
# 转换输入为向量形式
inputs = np.array(inputs).reshape(-1, MAXLEN)
inputs = paddle.to_tensor(inputs)
# 加载模型
params_dict= paddle.load('best_model')
model.set_dict(params_dict)
# 设置为评估模式
model.eval()
# 模型推理
out = model(inputs)
# 结果转换
result = ''.join([label_dict_adv[_] for _ in np.argmax(out.numpy(), -1).reshape(-1)])
# 打印结果
print('the model answer: %s=%s' % (input_text, result))
print('the true answer: %s=%s' % (input_text, eval(input_text)))
```
## 六、总结
* 你还可以通过变换网络结构,调整数据集,尝试不同的参数的方式来进一步提升本示例当中的数字加法的效果
* 同时,也可以尝试在其他的类似的任务中用飞桨来完成实际的实践
| github_jupyter |
# This file contains code of the paper 'Rejecting Novel Motions in High-Density Myoelectric Pattern Recognition using Hybrid Neural Networks'
```
import scipy.io as sio
import numpy as np
from keras.layers import Conv2D, MaxPool2D, Flatten, Dense,Dropout, Input, BatchNormalization
from keras.models import Model
from keras.losses import categorical_crossentropy
from keras.optimizers import Adadelta
import keras
# load data
path = './data/data'
data=sio.loadmat(path)
wristPronation = data['wristPronation']
wristSupination = data['wristSupination']
wristExtension = data['wristExtension']
wristFlexion = data['wristFlexion']
handOpen = data['handOpen']
handClose = data['handClose']
shoot = data['shoot']
pinch = data['pinch']
typing = data['typing']
writing = data['writing']
mouseManipulating = data['mouseManipulating']
radialDeviation = data['radialDeviation']
ulnarDeviation = data['ulnarDeviation']
```
## part1: CNN
```
def Spatial_Model(input_shape):
input_layer = Input(input_shape)
x = Conv2D(filters=32, kernel_size=(3, 3),activation='relu',name = 'conv_layer1')(input_layer)
x = Conv2D(filters=32, kernel_size=(3, 3), activation='relu',name = 'conv_layer2')(x)
x = Flatten()(x)
x = Dense(units=1024, activation='relu',name = 'dense_layer1')(x)
x = Dropout(0.4)(x)
x = Dense(units=512, activation='relu',name = 'dense_layer2')(x)
x = Dropout(0.4)(x)
output_layer = Dense(units=7, activation='softmax',name = 'output_layer')(x)
model = Model(inputs=input_layer, outputs=output_layer)
return model
def getIntermediate(layer_name,X,model):
intermediate_layer_model = Model(inputs=model.input,
outputs=model.get_layer(layer_name).output)
intermediate_output = intermediate_layer_model.predict(X)
return intermediate_output
def getPointedGesture(X,y,flag):
index = np.where(y==flag)
temp = X[index]
return temp
classNum = 7
X_inliers = np.concatenate((wristPronation,wristSupination,wristExtension,wristFlexion,handOpen,handClose,shoot),axis=0)
print('X_inliers.shape: ',X_inliers.shape)
y_inliers = np.concatenate((np.ones(wristPronation.shape[0])*0,np.ones(wristSupination.shape[0])*1,
np.ones(wristExtension.shape[0])*2,np.ones(wristFlexion.shape[0])*3,
np.ones(handOpen.shape[0])*4,np.ones(handClose.shape[0])*5,
np.ones(shoot.shape[0])*6),axis=0)
print('y_inliers.shape: ',y_inliers.shape)
X_outliers = np.concatenate((typing,writing,mouseManipulating,pinch),axis=0)
print('X_outliers.shape: ',X_outliers.shape)
y_outliers = np.concatenate((np.ones(typing.shape[0])*7,np.ones(writing.shape[0])*8, np.ones(mouseManipulating.shape[0])*9,np.ones(pinch.shape[0])*10),axis=0)
print('y_outliers.shape: ',y_outliers.shape)
model = Spatial_Model((12, 8, 3))
model.summary()
trainModel = False
from sklearn.model_selection import train_test_split
X_train, X_test_norm, y_train, y_test_norm = train_test_split(X_inliers, y_inliers, test_size=0.20, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=1)
y_train_onehot = keras.utils.to_categorical(y_train, classNum)
y_test_onehot = keras.utils.to_categorical(y_test_norm, classNum)
model.compile(loss=categorical_crossentropy, optimizer=Adadelta(lr=0.1), metrics=['acc'])
if trainModel:
model.fit(x=X_train, y=y_train_onehot, batch_size=16, epochs=50, shuffle=True, validation_split=0.05)
model.compile(loss=categorical_crossentropy, optimizer=Adadelta(lr=0.01), metrics=['acc'])
model.fit(x=X_train, y=y_train_onehot, batch_size=16, epochs=50, shuffle=True, validation_split=0.05)
model.save_weights('./model/modelCNN.h5')
else:
model.load_weights('./model/modelCNN.h5')
model_evaluate = []
model_evaluate.append(model.evaluate(X_test_norm,y_test_onehot))
print('model_evaluate',model_evaluate)
layer_name = 'dense_layer2'
X_train_intermediate = getIntermediate(layer_name,X_train,model)
X_test_intermediate_norm = getIntermediate(layer_name,X_test_norm,model)
typing_intermediate = getIntermediate(layer_name,typing,model)
writing_intermediate = getIntermediate(layer_name,writing,model)
mouseManipulating_intermediate = getIntermediate(layer_name,mouseManipulating,model)
pinch_intermediate = getIntermediate(layer_name,pinch,model)
radialDeviation_intermediate = getIntermediate(layer_name,radialDeviation,model)
ulnarDeviation_intermediate = getIntermediate(layer_name,ulnarDeviation,model)
## train Data
wristPronation_intermediate_train = getPointedGesture(X_train_intermediate,y_train,0)
wristSupination_intermediate_train = getPointedGesture(X_train_intermediate,y_train,1)
wristExtension_intermediate_train = getPointedGesture(X_train_intermediate,y_train,2)
wristFlexion_intermediate_train = getPointedGesture(X_train_intermediate,y_train,3)
handOpen_intermediate_train = getPointedGesture(X_train_intermediate,y_train,4)
handClose_intermediate_train = getPointedGesture(X_train_intermediate,y_train,5)
shoot_intermediate_train = getPointedGesture(X_train_intermediate,y_train,6)
## test data
wristPronation_intermediate_test = getPointedGesture(X_test_intermediate_norm,y_test_norm,0)
wristSupination_intermediate_test = getPointedGesture(X_test_intermediate_norm,y_test_norm,1)
wristExtension_intermediate_test = getPointedGesture(X_test_intermediate_norm,y_test_norm,2)
wristFlexion_intermediate_test = getPointedGesture(X_test_intermediate_norm,y_test_norm,3)
handOpen_intermediate_test = getPointedGesture(X_test_intermediate_norm,y_test_norm,4)
handClose_intermediate_test = getPointedGesture(X_test_intermediate_norm,y_test_norm,5)
shoot_intermediate_test = getPointedGesture(X_test_intermediate_norm,y_test_norm,6)
typing_intermediate_test = typing_intermediate
writing_intermediate_test = writing_intermediate
mouseManipulating_intermediate_test = mouseManipulating_intermediate
pinch_intermediate_test = pinch_intermediate
radialDeviation_intermediate_test = radialDeviation_intermediate
ulnarDeviation_intermediate_test = ulnarDeviation_intermediate
outlierData = {'typing_intermediate_test':typing_intermediate_test,
'writing_intermediate_test':writing_intermediate_test,
'mouseManipulating_intermediate_test':mouseManipulating_intermediate_test,
'pinch_intermediate_test':pinch_intermediate_test}
motionNameList = ['wristPronation','wristSupination','wristExtension','wristFlexion','handOpen','handClose','shoot']
trainDataDict = {motionNameList[0]:wristPronation_intermediate_train,motionNameList[1]:wristSupination_intermediate_train,
motionNameList[2]:wristExtension_intermediate_train,motionNameList[3]:wristFlexion_intermediate_train,
motionNameList[4]:handOpen_intermediate_train,motionNameList[5]:handClose_intermediate_train,
motionNameList[6]:shoot_intermediate_train}
testDataNameList = ['wristPronation','wristSupination','wristExtension','wristFlexion','handOpen','handClose','shoot',
'typing','writing','mouseManipulating','pinch','radialDeviation','ulnarDeviation']
testDataDict = {testDataNameList[0]:wristPronation_intermediate_test,testDataNameList[1]:wristSupination_intermediate_test,
testDataNameList[2]:wristExtension_intermediate_test,testDataNameList[3]:wristFlexion_intermediate_test,
testDataNameList[4]:handOpen_intermediate_test,testDataNameList[5]:handClose_intermediate_test,
testDataNameList[6]:shoot_intermediate_test,testDataNameList[7]:typing_intermediate_test[0:150],
testDataNameList[8]:writing_intermediate_test[0:150],testDataNameList[9]:mouseManipulating_intermediate_test[0:150],
testDataNameList[10]:pinch_intermediate_test[0:150],testDataNameList[11]:radialDeviation_intermediate_test[0:150],
testDataNameList[12]:ulnarDeviation_intermediate_test[0:150]}
X_val_intermediate = getIntermediate(layer_name,X_val,model)
wristPronation_intermediate_val = getPointedGesture(X_val_intermediate,y_val,0)
wristSupination_intermediate_val = getPointedGesture(X_val_intermediate,y_val,1)
wristExtension_intermediate_val = getPointedGesture(X_val_intermediate,y_val,2)
wristFlexion_intermediate_val = getPointedGesture(X_val_intermediate,y_val,3)
handOpen_intermediate_val = getPointedGesture(X_val_intermediate,y_val,4)
handClose_intermediate_val = getPointedGesture(X_val_intermediate,y_val,5)
shoot_intermediate_val = getPointedGesture(X_val_intermediate,y_val,6)
valDataDict = {motionNameList[0]:wristPronation_intermediate_val,motionNameList[1]:wristSupination_intermediate_val,
motionNameList[2]:wristExtension_intermediate_val,motionNameList[3]:wristFlexion_intermediate_val,
motionNameList[4]:handOpen_intermediate_val,motionNameList[5]:handClose_intermediate_val,
motionNameList[6]:shoot_intermediate_val}
```
## part2: autoEncoder
```
from keras import regularizers
from keras.losses import mean_squared_error
from keras.optimizers import SGD
def autoModel(input_shape):
input_img = Input(input_shape)
encoded = Dense(256, activation='relu',kernel_regularizer=regularizers.l2(0.002))(input_img)
encoded = BatchNormalization()(encoded)
encoded = Dense(64, activation='relu',kernel_regularizer=regularizers.l2(0.002))(encoded)
encoded = BatchNormalization()(encoded)
decoded = Dense(256, activation='relu',kernel_regularizer=regularizers.l2(0.002))(encoded)
decoded = BatchNormalization()(decoded)
decoded = Dense(512, activation='relu',kernel_regularizer=regularizers.l2(0.002))(decoded)
model = Model(input_img, decoded)
return model
trainAutoFlag = False
if trainAutoFlag:
for motionId in range(len(motionNameList)):
motionName = motionNameList[motionId]
x_train = trainDataDict[motionName]
x_val = valDataDict[motionName]
autoencoder = autoModel((512,))
autoencoder.compile(loss=mean_squared_error, optimizer=SGD(lr=0.1))
autoencoder.fit(x_train, x_train,
epochs=600,
batch_size=16,
shuffle=True,
validation_data=(x_val, x_val))
autoencoder.compile(loss=mean_squared_error, optimizer=SGD(lr=0.01))
autoencoder.fit(x_train, x_train,
epochs=300,
batch_size=16,
shuffle=True,
validation_data=(x_val, x_val))
autoencoder.save_weights('./model/autoencoder/Autoencoder_'+motionName+'.h5')
```
### Calculate ROC curve
```
import matplotlib
import matplotlib.pyplot as plt
from scipy.spatial.distance import pdist
from sklearn.metrics import roc_curve, auc
targetDict = {}
for motionId in range(len(motionNameList)):
targetList = []
motionName = motionNameList[motionId]
print('motionName: ', motionName)
# load models
autoencoder = autoModel((512,))
autoencoder.compile(loss=mean_squared_error, optimizer=Adadelta(lr=0.5))
autoencoder.load_weights('./model/autoencoder/Autoencoder_'+motionName+'.h5')
original = valDataDict[motionName]
decoded_imgs = autoencoder.predict(original)
num = decoded_imgs.shape[0]
for i in range(num):
X = np.vstack([original[i,:],decoded_imgs[i,:]])
lose = pdist(X,'braycurtis')
targetList.append(lose[0])
targetDict[motionName] = targetList
mdDict = {}
for motionId in range(len(motionNameList)):
motionName = motionNameList[motionId]
print('motionName: ', motionName)
# load models
autoencoder = autoModel((512,))
autoencoder.compile(loss=mean_squared_error, optimizer=Adadelta(lr=0.5))
autoencoder.load_weights('./model/autoencoder/AutoEncoder_'+motionName+'.h5')
originalDict = {}
decodedDict = {}
for gestureId in range(len(testDataNameList)):
originalDict[testDataNameList[gestureId]] = testDataDict[testDataNameList[gestureId]]
decodedDict[testDataNameList[gestureId]] = autoencoder.predict(originalDict[testDataNameList[gestureId]])
reconstruction_error = []
for gestureID in range(len(testDataNameList)):
original = originalDict[testDataNameList[gestureID]]
decoded_imgs = decodedDict[testDataNameList[gestureID]]
num = decoded_imgs.shape[0]
for i in range(num):
X = np.vstack([original[i,:],decoded_imgs[i,:]])
lose = pdist(X,'braycurtis')
reconstruction_error.append(lose[0])
mdDict[motionName] = reconstruction_error
outlierAllNum = 150 * 6 #six novel motions, 150 samples for each motion
y_label = []
for motionId in range(len(motionNameList)):
motionName = motionNameList[motionId]
y_label.extend(np.ones(len(testDataDict[motionName])))
y_label.extend(np.zeros(len(testDataDict['typing'])))
y_label.extend(np.zeros(len(testDataDict['writing'])))
y_label.extend(np.zeros(len(testDataDict['mouseManipulating'])))
y_label.extend(np.zeros(len(testDataDict['pinch'])))
y_label.extend(np.zeros(len(testDataDict['radialDeviation'])))
y_label.extend(np.zeros(len(testDataDict['radialDeviation'])))
outliers_fraction_List = []
P_List = []
R_List = []
F1_List = []
TPR_List = []
FPR_List = []
#outliers_fraction = 0.02
for outliers_i in range(-1,101):
outliers_fraction = outliers_i/100
outliers_fraction_List.append(outliers_fraction)
y_pred = np.zeros(len(y_label))
thresholdDict = {}
for motionId in range(len(motionNameList)):
# motionId = 0
motionName = motionNameList[motionId]
distances = targetDict[motionName]
distances = np.sort(distances)
num = len(distances)
# print('outliers_fraction:',outliers_fraction)
if outliers_fraction >= 0:
threshold = distances[num-1-int(outliers_fraction*num)]# get threshold
if outliers_fraction < 0:
threshold = 10000.0
if outliers_fraction == 1.0:
threshold = 0
thresholdDict[motionName] = threshold
mdDistances = mdDict[motionName]
y_pred_temp = (np.array(mdDistances)<=threshold)*1
y_pred = y_pred + y_pred_temp
y_pred = (y_pred>0)*1
TP = np.sum(y_pred[0:-outlierAllNum])
FN = len(y_pred[0:-outlierAllNum])-TP
FP = np.sum(y_pred[-outlierAllNum:])
TN = outlierAllNum - FP
t = 0.00001
P = TP/(TP+FP+t)
R = TP/(TP+FN+t)
F1 = 2*P*R/(P+R+t)
TPR = TP/(TP+FN+t)
FPR = FP/(TN+FP+t)
P_List.append(P)
R_List.append(R)
F1_List.append(F1)
TPR_List.append(TPR)
FPR_List.append(FPR)
roc_auc = auc(FPR_List, TPR_List)
fig, ax = plt.subplots(figsize=(5, 5))
plt.plot(FPR_List, TPR_List, lw=2,label='AUC = %0.2f' % ( roc_auc))
plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',label='Chance', alpha=.8)
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic(ROC)')
plt.legend(loc="lower right")
plt.show()
```
### calculate classification accuracies
```
resultDict = {}
for motionId in range(len(motionNameList)):
motionName = motionNameList[motionId]
# load models
autoencoder = autoModel((512,))
autoencoder.compile(loss=mean_squared_error, optimizer=Adadelta(lr=0.5))
autoencoder.load_weights('./model/autoencoder/AutoEncoder_'+motionName+'.h5')
# refactore data
originalDict = {}
decodedDict = {}
for gestureId in range(len(testDataNameList)):
originalDict[testDataNameList[gestureId]] = testDataDict[testDataNameList[gestureId]]
decodedDict[testDataNameList[gestureId]] = autoencoder.predict(originalDict[testDataNameList[gestureId]])
loseDict = {}
for gestureID in range(len(testDataNameList)):
loseList= []
original = originalDict[testDataNameList[gestureID]]
decoded_imgs = decodedDict[testDataNameList[gestureID]]
num = decoded_imgs.shape[0]
for i in range(num):
X = np.vstack([original[i,:],decoded_imgs[i,:]])
lose = pdist(X,'braycurtis')
loseList.append(lose[0])
loseDict[testDataNameList[gestureID]] = loseList
resultDict[motionName] = loseDict
outliers_fraction = 0.15
thresholdDict = {}
for motionId in range(len(motionNameList)):
motionName = motionNameList[motionId]
# load model
autoencoder = autoModel((512,))
autoencoder.compile(loss=mean_squared_error, optimizer=Adadelta(lr=0.5))
autoencoder.load_weights('./model/autoencoder/AutoEncoder_'+motionName+'.h5')
# val data
original_val = valDataDict[motionName]
decoded_val = autoencoder.predict(original_val)
loseList= []
original = original_val
decoded_imgs = decoded_val
num = decoded_imgs.shape[0]
for i in range(num):
X = np.vstack([original[i,:],decoded_imgs[i,:]])
lose = pdist(X,'braycurtis')
loseList.append(lose[0])
## calculate threshold for each task
loseArray = np.array(loseList)
loseArraySort = np.sort(loseArray)
anomaly_threshold = loseArraySort[-(int((outliers_fraction*len(loseArray)))+1)]
thresholdDict[motionName] = anomaly_threshold
# plot lose and threshold
fig, ax = plt.subplots(figsize=(5, 5))
t = np.arange(num)
s = loseArray
ax.scatter(t,s,label=motionName)
ax.hlines(anomaly_threshold,0,150,colors = "r")
ax.set(xlabel='sample (n)', ylabel='MSE',
title='MSEs of '+ motionName + ', threshold:' + str(anomaly_threshold))
ax.grid()
plt.legend(loc="lower right")
plt.xlim(xmin = -3)
plt.xlim(xmax = 70)
plt.show()
errorSum = 0
testSum = 0
barDict = {}
outlierClass = 6
rejectMotion = {}
for motionId in range(len(testDataNameList)):
recogList = []
motionName = testDataNameList[motionId]
for recogId in range(len(testDataNameList)-outlierClass):
identyResult = resultDict[testDataNameList[recogId]]
targetResult = np.array(identyResult[motionName])
recogList.append((targetResult<=thresholdDict[testDataNameList[recogId]])*1) # 每一个类别有自己的threshold用于拒判
recogArray = np.array(recogList)
recogArray = np.sum(recogArray,axis=0)
recogArray = (recogArray>0)*1
rejectMotion[testDataNameList[motionId]] = recogArray
if motionId<(len(testDataNameList)-outlierClass):
numError = np.sum(1-recogArray)
else:
numError = np.sum(recogArray)
numTarget = len(recogArray)
if motionId<(len(testDataNameList)-outlierClass):
errorSum = errorSum + numError
testSum = testSum + numTarget
barDict[testDataNameList[motionId]] = (numError/numTarget)
barDict['target overall'] = errorSum/testSum
print(barDict)
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
figure(num=None, figsize=(15, 6))
objects = ('wristPronation','wristSupination','wristExtension','wristFlexion','handOpen','handClose','shoot','target overall',
'typing','writing','mouseManipulating','pinch','radialDeviation','ulnarDeviation')
y_pos = np.arange(len(objects))
proposed = []
for i in range(len(objects)):
proposed.append(barDict[objects[i]])
bar_width = 0.35
opacity = 0.8
rects2 = plt.bar(y_pos + bar_width, proposed, bar_width,
alpha=opacity,
label='Proposed')
plt.xticks(y_pos + bar_width, objects)
plt.ylabel('Error Rates of Novelty Detection (%)')
plt.legend()
plt.tight_layout()
plt.show()
```
| github_jupyter |
<a href="https://colab.research.google.com/github/JSJeong-me/KOSA-Big-Data_Vision/blob/main/Model/0_rf-PCA_All_to_csv.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
#!pip install -U pandas-profiling
import pandas as pd
#import pandas_profiling
df = pd.read_csv('credit_cards_dataset.csv')
df.head(3)
#df.profile_report()
#df.corr(method='spearman')
df.columns
```
PCA for Pay_Score Bill_Amount Pay_Amount
```
from sklearn.decomposition import PCA
df_Pay_Score = df[['PAY_0','PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6']]
df_Bill_Amount = df[[ 'BILL_AMT1', 'BILL_AMT2','BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6']]
df_Pay_Amount = df[['PAY_AMT1','PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6']]
df_Pay_Score.head(3)
df_Bill_Amount.head(3)
df_Pay_Amount.head(3)
```
PCA instance 생성
```
trans = PCA(n_components=1)
X_Pay_Score = df_Pay_Score.values
X_Bill_Amount = df_Bill_Amount.values
X_Pay_Amount = df_Pay_Amount.values
# transform the data
X_dim = trans.fit_transform(X_Pay_Score)
X_dim.shape
df_X_dim_Pay_Score = pd.DataFrame(X_dim, columns=['Pay_AVR'])
# transform the data
X_dim = trans.fit_transform(X_Bill_Amount)
df_X_dim_Bill_Amount = pd.DataFrame(X_dim, columns=['Bill_AVR'])
# transform the data
X_dim = trans.fit_transform(X_Pay_Amount)
df_X_dim_Pay_Amount = pd.DataFrame(X_dim, columns=['P_AMT_AVR'])
```
목표변수 : default.payment.next.month Input 데이터 셋: X
```
df = pd.concat([df, df_X_dim_Pay_Score, df_X_dim_Bill_Amount, df_X_dim_Pay_Amount], axis=1)
df_pca = df.drop(['PAY_0','PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6','BILL_AMT1', 'BILL_AMT2','BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6', 'PAY_AMT1','PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6'], axis =1)
df_pca.columns
columns = list(df_pca.columns)
columns = ['ID','LIMIT_BAL', 'SEX', 'EDUCATION', 'MARRIAGE', 'AGE','Pay_AVR', 'Bill_AVR', 'P_AMT_AVR', 'default.payment.next.month']
df_pca = df_pca[columns]
df_pca.head(3)
df_pca.to_csv('credit_cards_pca.csv',header=True, index=False, encoding='UTF-8')
X = df.drop(['ID','PAY_0','PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6','BILL_AMT1', 'BILL_AMT2','BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6', 'PAY_AMT1','PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6', 'default.payment.next.month'], axis =1).values
X.shape
y = df['default.payment.next.month'].values
```
Train Test Data Set 분리
```
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7, random_state=42, shuffle=True)
```
RandomForest 모델 생성 및 학습
```
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(n_estimators=200, criterion='entropy', max_features='log2', max_depth=15)
rf.fit(X_train, y_train)
y_predict = rf.predict(X_test)
```
모델 성능 평가
```
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import numpy as np
import itertools
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
cnf_matrix = confusion_matrix(y_test, y_predict)
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=['Non_Default','Default'], normalize=False,
title='Non Normalized confusion matrix')
from sklearn.metrics import recall_score
print("Recall score:"+ str(recall_score(y_test, y_predict)))
```
| github_jupyter |
<h1><font size=12>
Weather Derivatites </h1>
<h1> Rainfall Simulator <br></h1>
Developed by [Jesus Solano](mailto:ja.solano588@uniandes.edu.co) <br>
16 September 2018
```
# Import needed libraries.
import numpy as np
import pandas as pd
import random as rand
import matplotlib.pyplot as plt
from scipy.stats import bernoulli
from scipy.stats import gamma
import time
```
## Simulation Function Core
```
### Build the simulation core.
# Updates the state of the day based on yesterday state.
def updateState(yesterdayDate, yesterdayState, monthTransitions):
yesterdayMonth = yesterdayDate.month
successProbability = monthTransitions['p'+str(yesterdayState)+'1'][yesterdayMonth]
todayState = bernoulli.rvs(successProbability)
return todayState
# Simulates one run of simulation.
def oneRun(daysNumber, startDate, initialState, monthTransitions,fittedGamma):
# Create a variable to store the last day state.
yesterdayState = initialState
# Generate a timestamp with all days in simulation.
dates = pd.date_range(startDate, periods=daysNumber, freq='D')
# Define the total rainfall amount over the simulation.
rainfall = 0
# Loop over days in simulation to calculate rainfall ammount.
for day in dates:
# Update today state based on the yesterday state.
todayState = updateState(day-1, yesterdayState, monthTransitions)
# Computes total accumulated rainfall.
if todayState == 1:
todayRainfall = gamma.rvs(fittedGamma['Shape'][0],fittedGamma['Loc'][0],fittedGamma['Scale'][0])
# Updates rainfall amount.
rainfall += todayRainfall
yesterdayState = todayState
return rainfall
# Run only one iteration(Print structure of results)
# Simulations iterations.
iterations = 10000
# Transitions probabilites.
monthTransitionsProb = pd.read_csv('../results/visibleMarkov/monthTransitions.csv', index_col=0)
# Rainfall amount parameters( Gamma parameters)
fittedGamma = pd.read_csv('../results/visibleMarkov/fittedGamma.csv', index_col=0)
# Number of simulation days(i.e 30, 60)
daysNumber = 30
# Simulation start date ('1995-04-22')
startDate = '2018-08-18'
# State of rainfall last day before start date --> Remember 0 means dry and 1 means wet.
initialState = 0
oneRun(daysNumber,startDate,initialState, monthTransitionsProb,fittedGamma)
```
## Complete Simulation
```
# Run total iterations.
def totalRun(daysNumber,startDate,initialState, monthTransitionsProb,fittedGamma,iterations):
# Array to store all precipitations.
rainfallPerIteration = [None]*iterations
# Loop over each iteration(simulation)
for i in range(iterations):
iterationRainfall = oneRun(daysNumber,startDate,initialState, monthTransitionsProb,fittedGamma)
rainfallPerIteration[i] = iterationRainfall
return rainfallPerIteration
#### Define parameters simulation.
# Simulations iterations.
iterations = 10000
# Transitions probabilites.
monthTransitionsProb = pd.read_csv('../results/visibleMarkov/monthTransitions.csv', index_col=0)
# Rainfall amount parameters( Gamma parameters)
fittedGamma = pd.read_csv('../results/visibleMarkov/fittedGamma.csv', index_col=0)
# Number of simulation days(i.e 30, 60)
daysNumber = 30
# Simulation start date ('1995-04-22')
startDate = '2018-08-18'
# State of rainfall last day before start date --> Remember 0 means dry and 1 means wet.
initialState = 0
```
## Final Results
```
# Final Analysis.
finalSimulation = totalRun(daysNumber,startDate,initialState, monthTransitionsProb,fittedGamma,iterations)
fig = plt.figure(figsize=(20, 10))
plt.hist(finalSimulation,facecolor='steelblue',bins=100, density=True,
histtype='stepfilled', edgecolor = 'black' , hatch = '+')
plt.title('Rainfall Simulation')
plt.xlabel('Rainfall Amount [mm]')
plt.ylabel('Probability ')
plt.grid()
plt.show()
```
| github_jupyter |
# Data exploration and cleaning
Using Pandas for data exploration and data cleaning.
**Overview of the final goal**
In the following two lectures our goal is to analyze a pool of loans and assess their risk. The central question is whether the loans in question are good or bad in terms of their risk. To assess whether a loan is good or bad, we try to estimate the probability of the loan (i.e. the person/company who received the loan) defaulting.

There are multiple approaches that usually depend on the granularity of data available.
* Aggregated historical performance data can be used to create a high level assessment on different parts of the portfolio of loans. e.g. loans with more than 30 months maturity and more than 95% debt to income ratio are risky and we estimate 4% of them to default.
* Loan level historical performance data can be used to create a predictive model to make a prediction on each loan individually. e.g. if we see that the borrower takes longer and longer to pay the monthly due payment, we predict they are more likely to default in the near future.
In today's lecture we'll use a loan level dataset to get our hands dirty with exploration and cleaning. Next week we'll use the clean dataset we prepare today and work on creating models.
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Download-data-from-public-source-and-manually-adjust-it" data-toc-modified-id="Download-data-from-public-source-and-manually-adjust-it-1"><span class="toc-item-num">1 </span>Download data from public source and manually adjust it</a></span></li><li><span><a href="#Lending-Club---what-is-it,-how-it-works" data-toc-modified-id="Lending-Club---what-is-it,-how-it-works-2"><span class="toc-item-num">2 </span>Lending Club - what is it, how it works</a></span></li><li><span><a href="#Load-csv-file-as-Pandas-dataframe" data-toc-modified-id="Load-csv-file-as-Pandas-dataframe-3"><span class="toc-item-num">3 </span>Load csv file as Pandas dataframe</a></span></li><li><span><a href="#Understanding-Pandas-dataframes-through-the-LendingClub-dataset" data-toc-modified-id="Understanding-Pandas-dataframes-through-the-LendingClub-dataset-4"><span class="toc-item-num">4 </span>Understanding Pandas dataframes through the LendingClub dataset</a></span><ul class="toc-item"><li><span><a href="#Select-a-few-important-columns-to-work-with" data-toc-modified-id="Select-a-few-important-columns-to-work-with-4.1"><span class="toc-item-num">4.1 </span>Select a few important columns to work with</a></span></li><li><span><a href="#Exercise:-Try-selecting-a-different-set-of-columns-from-the-dataframe." data-toc-modified-id="Exercise:-Try-selecting-a-different-set-of-columns-from-the-dataframe.-4.2"><span class="toc-item-num">4.2 </span>Exercise: Try selecting a different set of columns from the dataframe.</a></span></li><li><span><a href="#Get-an-overview-of-the-variables" data-toc-modified-id="Get-an-overview-of-the-variables-4.3"><span class="toc-item-num">4.3 </span>Get an overview of the variables</a></span></li><li><span><a href="#Accessing-a-column's-values-as-a-Series" data-toc-modified-id="Accessing-a-column's-values-as-a-Series-4.4"><span class="toc-item-num">4.4 </span>Accessing a column's values as a Series</a></span></li><li><span><a href="#Access-values-by-numerical-indexing" data-toc-modified-id="Access-values-by-numerical-indexing-4.5"><span class="toc-item-num">4.5 </span>Access values by numerical indexing</a></span></li><li><span><a href="#Exercises:-Try-selecting-values-from-a-different-numerical-column,-try-selecting-a-single-value" data-toc-modified-id="Exercises:-Try-selecting-values-from-a-different-numerical-column,-try-selecting-a-single-value-4.6"><span class="toc-item-num">4.6 </span>Exercises: Try selecting values from a different numerical column, try selecting a single value</a></span></li><li><span><a href="#Unique-values-and-aggregations-on-categorical-variables" data-toc-modified-id="Unique-values-and-aggregations-on-categorical-variables-4.7"><span class="toc-item-num">4.7 </span>Unique values and aggregations on categorical variables</a></span></li><li><span><a href="#Filtering-rows-with-conditions" data-toc-modified-id="Filtering-rows-with-conditions-4.8"><span class="toc-item-num">4.8 </span>Filtering rows with conditions</a></span></li><li><span><a href="#Exercise:-Try-filtering-rows-by-another-column's-values" data-toc-modified-id="Exercise:-Try-filtering-rows-by-another-column's-values-4.9"><span class="toc-item-num">4.9 </span>Exercise: Try filtering rows by another column's values</a></span></li></ul></li><li><span><a href="#Task:-Check-the-Data-Dictionary-for-descriptions-of-fields" data-toc-modified-id="Task:-Check-the-Data-Dictionary-for-descriptions-of-fields-5"><span class="toc-item-num">5 </span>Task: Check the Data Dictionary for descriptions of fields</a></span></li><li><span><a href="#Missing-Values" data-toc-modified-id="Missing-Values-6"><span class="toc-item-num">6 </span>Missing Values</a></span><ul class="toc-item"><li><span><a href="#Check-missing-values-for-this-dataset-for-each-field" data-toc-modified-id="Check-missing-values-for-this-dataset-for-each-field-6.1"><span class="toc-item-num">6.1 </span>Check missing values for this dataset for each field</a></span></li><li><span><a href="#Remove-hardship_loan_status-from-the-dataframe" data-toc-modified-id="Remove-hardship_loan_status-from-the-dataframe-6.2"><span class="toc-item-num">6.2 </span>Remove hardship_loan_status from the dataframe</a></span></li><li><span><a href="#Remove-all-rows-with-any-missing-values" data-toc-modified-id="Remove-all-rows-with-any-missing-values-6.3"><span class="toc-item-num">6.3 </span>Remove all rows with any missing values</a></span></li></ul></li><li><span><a href="#Duplication" data-toc-modified-id="Duplication-7"><span class="toc-item-num">7 </span>Duplication</a></span></li><li><span><a href="#Transforming-and-cleaning-individual-columns" data-toc-modified-id="Transforming-and-cleaning-individual-columns-8"><span class="toc-item-num">8 </span>Transforming and cleaning individual columns</a></span><ul class="toc-item"><li><span><a href="#Creating-a-new-binary-numerical-column-for-prediction" data-toc-modified-id="Creating-a-new-binary-numerical-column-for-prediction-8.1"><span class="toc-item-num">8.1 </span>Creating a new binary numerical column for prediction</a></span></li><li><span><a href="#Creating-a-numerical-variable-from-emp_length" data-toc-modified-id="Creating-a-numerical-variable-from-emp_length-8.2"><span class="toc-item-num">8.2 </span>Creating a numerical variable from <code>emp_length</code></a></span></li><li><span><a href="#Exercise:-Create-a-numerical-variable-from-grade" data-toc-modified-id="Exercise:-Create-a-numerical-variable-from-grade-8.3"><span class="toc-item-num">8.3 </span>Exercise: Create a numerical variable from <code>grade</code></a></span></li><li><span><a href="#Creating-a-numerical-variable-from-term" data-toc-modified-id="Creating-a-numerical-variable-from-term-8.4"><span class="toc-item-num">8.4 </span>Creating a numerical variable from <code>term</code></a></span></li><li><span><a href="#Creating-a-numerical-variable-from-int_rate" data-toc-modified-id="Creating-a-numerical-variable-from-int_rate-8.5"><span class="toc-item-num">8.5 </span>Creating a numerical variable from <code>int_rate</code></a></span></li></ul></li><li><span><a href="#Save-the-dataframe-to-use-in-the-next-notebook." data-toc-modified-id="Save-the-dataframe-to-use-in-the-next-notebook.-9"><span class="toc-item-num">9 </span>Save the dataframe to use in the next notebook.</a></span></li><li><span><a href="#Recap-and--Exercise:-Examine-the-final-dataset." data-toc-modified-id="Recap-and--Exercise:-Examine-the-final-dataset.-10"><span class="toc-item-num">10 </span>Recap and Exercise: Examine the final dataset.</a></span></li></ul></div>
## Download data from public source and manually adjust it
**Preparatory steps**
We have
* downloaded the LendingClub 2007-2011 data file from https://www.lendingclub.com/info/download-data.action
* unzipped the csv file
* manually removed the first line of the download data file
* renamed the file to "LendingClub.csv"
**Data file for the current lecture**
We will be working with the following file:
[LendingClub.csv](LendingClub.csv)
## Lending Club - what is it, how it works
Lending Club is a peer-to-peer lending company, operating in the US. It is currently the largest such platform in the world. It pioneered various aspects of this business, including registration on the SEC and offering loan trading on the secondary market. Securitization or structuring are very popular ways to fund loans when the total size of the portfolio is large. This structure serves as a way for investors (and the 'middleman') to better diversify their investments.
It begins with the borrower. They apply for a loan and if they meet certain criteria (such as a minimum 660 FICO score) their loan is added to Lending Club’s online platform. Along with verification of the borrower's finances and other submitted information, Lending Club **assigns a grade to each loan, representing its riskiness, ie the probability of it defaulting**. This grade will also determine the interest rate the borrower has to pay (and what the investor gets). Investors can browse the loans on the platform and build a portfolio of loans. The minimum investment an investor can make is just $25 per loan. Each portion of a loan is called a note and smart investors build a portfolio of notes to spread their risk among many borrowers.
If the borrower passes verification and if their loan is fully funded, the money (less an origination fee) will appear on their account in a couple of business days. If the borrower fails verification the loan will not be issued. It will be deleted from the platform and all money that had been invested will be returned to the respective investors.
Borrowers then begin making payments within 30 days. These payments will be for principal plus interest on a standard amortization schedule.
The investors receive any payments the borrower pays to Lending Club, minus a 1% service fee.
A loan can stay on the platform for up to 14 days. Most loans are funded much quicker than that and once funded, the loan will be deleted from the platform. Actually, there are 'loan sniping' algorithms and services that help investors build a portfolio of notes in mere seconds.
With some smart intermediate moves, Lending Club could achieve that the investors are really creditors (lenders) of Lending Club itself. This also means that if Lending Club itself goes under, investors could lose their money, even in the original loand that they funded continues to pay.
The 'notes' structure also allowed for the development of a secondary market of notes. This way investors can sell their notes to other investors or vice versa, without Lending Club itself having any say (or care) in these transactions.
We will talk about the methods with wich a company like Lending Club could estimate the probability of a person defaulting on the amount they borrowed, based on the information they provide along their submission.

Read more: https://www.lendacademy.com/lending-club-review/ <br>
Image source: https://www.lendingclub.com/investing/alternative-assets/how-it-works
## Load csv file as Pandas dataframe
```
# Imports
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import pandas as pd
from datetime import datetime
# Read in the dataset
filename = 'LendingClub.csv'
raw_data_all = pd.read_csv(filename, low_memory=False)
# Check the data
raw_data_all.head()
# Not all columns showing.. too many of them... check separately for field names
```
Let's see the list of all the columns in the dataframe.
```
raw_data_all.columns.tolist()
```
## Understanding Pandas dataframes through the LendingClub dataset
As we'll be working with Pandas dataframes throughout the lecture, let's take some time to understand the basic concepts.
### Select a few important columns to work with
As there are many columns we'll just select a few more important ones to keep.
- We first create a list of column names to keep.
- The right hand side of the following command creates a new dataframe by selecting a list of columns from an existing dataframe. To reuse the original variable name, we'll just assign the newly created dataframe to the original 'raw_data' variable.
```
# List of columns to keep
cols = ['loan_amnt', 'term', 'int_rate', 'funded_amnt', 'grade', 'annual_inc', 'dti', 'hardship_loan_status', 'delinq_2yrs', 'last_pymnt_amnt', 'emp_length','loan_status','home_ownership','tax_liens']
# Dataframe with selected columns
raw_data = raw_data_all[cols]
#Let's check the top rows
raw_data.head()
```
**What is the type of the object created in this way?**
Let's select two columns and see what we get
```
type(raw_data[['loan_amnt', 'term']])
raw_data[['loan_amnt', 'term']].head()
```
This also works for creating a dataframe with one column. For Pandas to know we want a dataframe, we still need to use a list, in this case with just one element.
```
type(raw_data[['loan_amnt']])
raw_data[['loan_amnt']].head()
```
### Exercise: Try selecting a different set of columns from the dataframe.
Remember NOT to overwrite the variable raw_data
### Get an overview of the variables
We can get the type info for all variables at once to get an overview in a compact format
```
#Check field types
raw_data.info()
```
We can get an overview of the basic statistics of the numerical columns
```
raw_data.describe()
```
### Accessing a column's values as a Series
A Series is a one-dimensional object without a DataFrame wrapper.
A DataFrame's purpose is to store data of a table format having multiple columns and rows, i.e. two-dimensionally. While a DataFrame containing a single column is possible and sometimes appropriate, in many cases we'd be better off referencing a column not as a table but the way it really is: a series of values. For example, a Series can be indexed similar to simple Python Arrays to select elements.
There are multiple ways to extract a column's values as a Series. We show the two arguably most used ways below.
**Referencing a column as a Series, by its name**
```
# Select top 5 rows of column "funded_amnt"
raw_data['funded_amnt'][:5]
type(raw_data['funded_amnt'])
type(raw_data[['funded_amnt']])
```
**Referencing a column as a Series, using dot notation**
```
# Select top 5 rows of column "funded_amnt"
raw_data.funded_amnt[:5]
```
### Access values by numerical indexing
There is a way to access the dataframe the way we would access elements of a matrix with numerical indices.
Note: the first index is the row index and the second index is the column index:
`data.iloc[row,column]`
```
raw_data.columns.tolist()
# Select top 5 rows of the column with the index 3.
#Note: indexing starts with 0, so this is the "funded_amnt" column.
raw_data.iloc[:5,3]
```
Let's do some calculations with the Series. Since it is numerical, we can do numerical operations e.g. calculating the mean, multiplying by 2, etc.
```
raw_data.funded_amnt.mean()
raw_data.funded_amnt[:5] * 2
```
### Exercises: Try selecting values from a different numerical column, try selecting a single value
```
raw_data_all[['desc']].iloc[4,0]
```
### Unique values and aggregations on categorical variables
First let's see the unique values. Note that the result is not a series but a numpy array.
```
raw_data.grade.unique()
```
Let's see how many times each value appears in this series using the built in method `value_counts()` of a Series.
```
raw_data.grade.value_counts()
```
**Group by**
We can do the same by using the full dataframe using a group by expression. Let's see the following SQL example for using group by to do aggregations on a dataset:

Image source: https://www.w3resource.com/sql/aggregate-functions/sum-with-group-by.php
```
raw_data.groupby(by='grade').agg('count')
```
Note: the function name "agg" means that we perform an operation on each group, in an aggregated way
```
raw_data.groupby(by='grade').grade.agg('count')
```
Naturally, we can apply other kinds of aggregations, like summing, averaging, we can even apply custom aggregation functions. What's more, we can apply more than one of them at the same time!
```
raw_data.groupby(by='grade').funded_amnt.agg(['min', 'max', 'sum', 'mean'])
```
### Filtering rows with conditions
Let's see how we can filter down rows based on column values.
We will select only those loans where the income of the borrower is greater than $1.000.000
```
raw_data[raw_data.annual_inc > 1000000]
```
**How does this work?**
The filter creates a boolean series showing which row satisfies the filter condition and which row does not. The boolean series is then used to index the dataframe.
Let's create a filter for just grade "A".
```
grade_filter = raw_data.grade == 'A'
print(type(grade_filter))
print(grade_filter)
raw_data[grade_filter].head()
```
### Exercise: Try filtering rows by another column's values
<center><i>**Congratulations! At this point you've mastered the most important pieces for working with data in Pandas!**<i></center>
## Task: Check the Data Dictionary for descriptions of fields
Please check the following fields:
- grade
- dti
- delinq_2yrs
- tax_liens
## Missing Values
Most algorithms assume all values are available and can't handle missing data. The action to take for missing values depends on both the ratio of missing to total values and the field of application / variable meaning.
For fields with high missing rate:
- drop the field as it's probably useless with so many values missing
For fields with low missing rate we can have multiple approaches
- drop rows with any empty value
- impute missing values by
- mean
- mode
- extreme values in case we need to be conservative (check the use case)
- predict the missing values using the other fields
### Check missing values for this dataset for each field
Let's check Null values - missing data cells for individual loans.
Are there any variables that we would discard?
```
raw_data.isnull().sum(axis=0)
```
### Remove hardship_loan_status from the dataframe
Hint: check out the .drop() command on a Pandas dataframe
Note that axis=0 means row indexes, so it is used when removing a row,<br/>
and axis=1 means column indexes, so it is used when removing a column
```
raw_data = raw_data.drop(['hardship_loan_status'], axis=1)
```
### Remove all rows with any missing values
```
raw_data = raw_data.dropna()
#Check null values again
raw_data.isnull().sum(axis=0)
```
## Duplication
There could be multiple reasons for having multiple records for a loan
- duplicate rows
- loan history tracked over time
Our dataset is not a case of the latter, so if there were multiple records, it could only be due to duplication. In this case however, there is a unique record for each loan,
so we don't have to worry about this step in our case.
To remove duplicates, check out the drop_duplicates() method
## Transforming and cleaning individual columns
### Creating a new binary numerical column for prediction
We will predict loan defaults in the second lecture. We will need a two-value variable, denoting whether the specific loan was paid off or defaulted. Moreover, the algorithms we will use can work with numerical columns. Our best bet it to represent the two values in a 1-0 column. Let's use the "`loan_status`" column.
**Check values of the loan status variable and keep only relevant ones**
```
raw_data.loan_status.value_counts()
```
Let's keep only the loans with `Fully Paid` and `Charged Off` status as the other ones are special cases and are not of our interest for this analysis.
To achieve this, let's filter the data to only include loans with by these two statuses.
```
raw_data = raw_data[(raw_data['loan_status'] == 'Fully Paid') | (raw_data['loan_status'] == 'Charged Off')]
raw_data.loan_status.value_counts()
```
**Map categorial values to a newly created 1-0 column**
```
#Let's check the first 10 loans
raw_data.loan_status[:10]
```
We can create a dictionary and use it for translation.
```
#Create a dictionary to use for translation
def_map = {'Fully Paid': 0, 'Charged Off': 1}
def_map
```
We can use the `.map()` command to apply a function or a mapping dictionary on each row of the dataframe.
```
#Check how mapping the values works
raw_data.loan_status.map(def_map)[:10]
#Create the new column
raw_data['defaulted'] = raw_data.loan_status.map(def_map)
```
Let's remove the original `loan_status` column
```
raw_data = raw_data.drop('loan_status', axis=1)
raw_data.head()
```
### Creating a numerical variable from `emp_length`
Let's continue the preparation for the next lecture. We still have categorical variables we believe could be meaningful for predicting default. As stated earlier, the algorithms work with numerical columns, so let's represent this information in numerical columns.
```
raw_data.emp_length.unique()
emp_map1 = {}
for i in range (2,10):
key = str(i) + ' years'
value = i
emp_map1[key] = value
emp_map = {str(i) + ' years' : i for i in range(2,10)}
emp_map
emp_map['< 1 year'] = 0
emp_map['n/a'] = 0
emp_map['10+ years'] = 10
emp_map['1 year'] = 1
emp_map
raw_data.emp_length[:10]
raw_data.emp_length.map(emp_map)[:10]
#Overwrite the column
raw_data.emp_length = raw_data.emp_length.map(emp_map)
raw_data.emp_length.unique()
raw_data.head()
```
### Exercise: Create a numerical variable from `grade`
Let's do the same process for `grade`. Here we can use the ordinal nature of the grades to create a numerical column.
```
#Check unique values
raw_data.grade.unique()
#Create a dictionary to use for translation
grade_map = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7}
grade_map
#Check first 10 elements of column `grade`
raw_data.grade[:10]
#Overwrite the column, use the `map` function
raw_data.grade = raw_data.grade.map(grade_map)
#Check the first few rows of the dataframe
raw_data.head()
```
### Creating a numerical variable from `term`
Let's check the unique values of the term column and extract the number values.
```
raw_data.term.unique()
```
As the numerical values are always contained in the 2nd and the 3rd character of the string, we can simply extract that substring with the `slice()` indexing and convert it into integer type.
Fortunately there's a function in pandas called `pd.to_numeric()` that can convert numeric values stored as string to numeric types.
```
raw_data.term = pd.to_numeric(raw_data.term.str.slice(1,3))
```
Let's check the resulting data type
```
type(raw_data.term[0])
raw_data.head()
```
### Creating a numerical variable from `int_rate`
The column `int_rate` looks fine from just looking at the table, but let's see what type of values does it contain.
```
print(type(raw_data.int_rate[0]))
raw_data.int_rate[0]
```
Spoiler: the `pd.to_numeric()` it will not work here, guess why...
```
raw_data.int_rate = pd.to_numeric(raw_data.int_rate.map(lambda s: s.replace('%', '')))
raw_data.int_rate[:3]
raw_data.head()
```
## Save the dataframe to use in the next notebook.
Pandas objects are equipped with to_pickle methods which use Python’s Pickle module to persist data structures to disk using the pickle format.
We'll load back this object in the next lecture.
```
raw_data.to_pickle('Lendmark_clean.pkl')
```
## Recap and Exercise: Examine the final dataset.
Today we explored, understood and cleaned the Lendmark dataset.
In the next lecture we will build models for predicting defaults.
How many Features / Rows do we have left?
```
raw_data.info()
```
| github_jupyter |
```
from keras import backend as K
from keras.models import load_model
from keras.preprocessing import image
from keras.optimizers import Adam
from imageio import imread
import numpy as np
from matplotlib import pyplot as plt
from models.keras_ssd300 import ssd_300
from keras_loss_function.keras_ssd_loss import SSDLoss
from keras_layers.keras_layer_AnchorBoxes import AnchorBoxes
from keras_layers.keras_layer_DecodeDetections import DecodeDetections
from keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast
from keras_layers.keras_layer_L2Normalization import L2Normalization
from ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast
from data_generator.object_detection_2d_data_generator import DataGenerator
from data_generator.object_detection_2d_photometric_ops import ConvertTo3Channels
from data_generator.object_detection_2d_geometric_ops import Resize
from data_generator.object_detection_2d_misc_utils import apply_inverse_transforms
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
%matplotlib inline
# Set the image size.
img_height = 300
img_width = 300
# TODO: Set the path to the `.h5` file of the model to be loaded.
model_path = 'path/to/trained/model.h5'
# We need to create an SSDLoss object in order to pass that to the model loader.
ssd_loss = SSDLoss(neg_pos_ratio=3, n_neg_min=0, alpha=1.0)
K.clear_session() # Clear previous models from memory.
model = load_model(model_path, custom_objects={'AnchorBoxes': AnchorBoxes,
'L2Normalization': L2Normalization,
'DecodeDetections': DecodeDetections,
'compute_loss': ssd_loss.compute_loss})
import numpy as np
import cv2
frames=np.zeros((1,300,300,3))
cap = cv2.VideoCapture(0)
confidence_threshold = 0.3
colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist()
classes = ['background',
'aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat',
'chair', 'cow', 'diningtable', 'dog',
'horse', 'motorbike', 'person', 'pottedplant',
'sheep', 'sofa', 'train', 'umbrella']
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 1
fontColor = (255,255,255)
lineType = 2
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
x = 20
y = 40
w = 100
h = 75
frames[0] = image.load_img(img_path, target_size=(img_height, img_width))
y_pred = model.predict(frames)
np.set_printoptions(precision=2, suppress=True, linewidth=90)
y_pred_thresh = [y_pred[k][y_pred[k,:,1] > confidence_threshold] for k in range(y_pred.shape[0])]
for box in y_pred_thresh[0]:
xmin = box[2]
ymin = box[3]
xmax = box[4]
ymax = box[5]
color = colors[int(box[0])]
cv2.putText(frame,classes[int(box[0])],
(xmin,ymin),
font,
fontScale,
fontColor,
lineType)
cv2.rectangle(frame, (xmin, xmin), (xmax, ymax), color, 2)
# Our operations on the frame come here
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('frame',frame)
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
```
| github_jupyter |
```
"""This area sets up the Jupyter environment.
Please do not modify anything in this cell.
"""
import os
import sys
# Add project to PYTHONPATH for future use
sys.path.insert(1, os.path.join(sys.path[0], '..'))
# Import miscellaneous modules
from IPython.core.display import display, HTML
# Set CSS styling
with open('../admin/custom.css', 'r') as f:
style = """<style>\n{}\n</style>""".format(f.read())
display(HTML(style))
import keras
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import admin.tools as tools
import problem_unittests as tests
```
# Multilayer Perceptron with Keras
<div class="alert alert-warning">
In this notebook we will look at how to create a type of artificial neural network called multilayer perceptron (MLP) using [Keras](https://keras.io/). To do this we will again work through a few examples, however, this time the focus will be on classification problems.
</div>
Similar to regression, in classification we aim to create models that fit a conditional probability distribution $\Pr(y\vert\mathbf{x})$, where $y$ are the target values and $\mathbf{x}$ is the data. However, in classification the model is trained to output a discrete value from a set of values. For example, in binary classification we fit a probability distribution $\Pr(y\vert\mathbf{x})$ where $y \in \{0,1\}$. That is, the model outputs the probability that the input $\mathbf{x}$ belong to the *class* $y=1$.
There are several different learning algorithms for doing classification, like decision tree learning (DTL) or support vector machine (SVM), however for artificial neural networks we will extend the idea of logistic regression.
## The Basics of Multinomial Logistic Regression
Multinomial logistic, or softmax, regression is a generalisation of the classification algorithm logistic regression to multiclass classification problems; these are problems where the target $y$ can be one of $K$ classes, i.e. $y \in \{1, \ldots, K\}$. Whereas in logistic regression where $\Pr(y=1\vert\mathbf{x})$ is captured by the logistic function $\sigma(z)=\frac{1}{1+e^{-z}}$, where $z=\mathbf{w}^\intercal\mathbf{x}$, the multinomial variant uses the softmax function to capture a multiclass categorical probability distribution. The softmax function is defined as:
$$
\begin{equation*}
\Pr(y = k\vert\mathbf{x}) = \sigma(\mathbf{z})_k = \frac{e^{z_k}}{\sum_{i=1}^{K}e^{z_i}},
\qquad
\text{where}
\qquad
\mathbf{z} = \mathbf{w}^\intercal\mathbf{x}
\end{equation*}
$$
That is, the softmax function $\sigma(\mathbf{z})$ outputs a $K$-dimensional vector of real values between 0 and 1. Each value in this distribution signifies the probability that class $K=i$ is true given the input $\mathbf{x}$. The numerator exponentiates a predicted log probability $z_k$, while the denominator normalises over all predicted log probabilities $\mathbf{z}$ to get a valid probability distribution.
Just as with logistic regression, training the softmax function to output meaningful probabilities can be done using maximum likelihood: $\underset{\mathbf{w}}{\arg\max}\mathcal{L}(\mathbf{w})$. Maximising the likelihood is the same as minimising the negative likelihood. Additionally, we typically take the log of the likelihood as it does not change the result but simplifies some of the maths. Doing this yields the following error function when taken over all $N$ training examples:
$$
\begin{equation*}
\begin{aligned}
E(\mathbf{w}) &= -\frac{1}{N}\log\mathcal{L}(\mathbf{w}) \\
&= -\frac{1}{N}\sum_{i=1}^{N}\log\prod_{k=1}^{K}\Pr(y_i = k\vert\mathbf{x}_i)^{\mathbb{1}\{y_i = k\}} \\
&= -\frac{1}{N}\sum_{i=1}^{N}\log\prod_{k=1}^{K}\sigma(\mathbf{z}_i)^{\mathbb{1}\{y_i = k\}} \\
&= -\frac{1}{N}\sum_{i=1}^{N}\sum_{k=1}^{K}\mathbb{1}\{y_i = k\}\log\sigma(\mathbf{z}_i)
\end{aligned}
\end{equation*}
$$
$\mathbb{1}$ is the [indicator function](https://en.wikipedia.org/wiki/Indicator_function) where $\mathbb{1}\{y_i = k\}$ is 1 if and only if example $i$ belongs to class $k$. This version of the error function is typically called the *categorical* cross entropy error function. When $K=2$ multinomial logistic regression reduces to simple logistic regression.
## The Forward Pass: Inference
Let us now focus on feedforward neural networks which for all intents and purposes is synonymous with multilayer perceptron. An example of a feedforward network can be seen below:
<img src="resources/feedforward-nn.png" alt="A simple feedforward network" width="400" />
This network consist of two hidden layers $\mathbf{u}$ and $\mathbf{v}$, where the input $\mathbf{x}$ is connected to $\mathbf{u}$, and $\mathbf{v}$ is connected to the output $\mathbf{y}$. These types of hidden layers are typically referred to as *fully-connected* because every neuron in a layer is connected to every neuron in the preceding layer. Fully-connected layers are sometimes called *densely-connected*.
The output of a single neuron typically comprise of two steps: (i) integrate the input by taking a linear combination of the input and associated weights, and (ii) feeding this scalar into an activation function. This can be summarised as a dot product between inputs and weights wrapped in a function, such as the logistic function. To simplify all of these dot products, we can gather all weights linking neurons from one layer to another into a matrix called $\mathbf{W}^{(l)}$ for layer $l$, where element $\mathbf{W}^{(l)}_{ij}$ indicates the weight from neuron $i$ to neuron $j$ for layer $l$.
With this representation, the output activation $\mathbf{a}^{(l)}$ for layer $l$ is simply the matrix-vector product $\sigma(\mathbf{a}^{(l-1)}\mathbf{W}^{(l)})$, where $\sigma(.)$ is an activation function and is applied *element-wise*. That is, before we apply the activation function we take the activations from the preceding layer $(l-1)$ and multiply it with the weight matrix for the current layer. For example, for the network topology above we can calculate the activations for layer $\mathbf{u}$ by computing $\sigma(\mathbf{x}\mathbf{W}^{(1)})$, assuming $\mathbf{x}$ is a row vector. This makes sense, because $\mathbf{x}$ is a $1 \times 4$ row vector and $\mathbf{W}^{(1)}$ is $4 \times 3$ matrix. Thus, the output activation for layer $\mathbf{u}$ has the size $1 \times 3$, i.e. there are three neurons with one value each.
### Task I: Implementing the Forward Pass
Using the matrix multiplication approach outlined above, perform the forward pass (inference step) on the network topology we discussed in the previous section using the weight matrices below on the input vector $\mathbf{x}=[1,-4,0,7]$. The input vector is a *row* vector.
$$
\begin{equation*}
\mathbf{W}^{(1)} = \begin{bmatrix}
-0.1 & 0.2 & 0.1 \\
0.1 & 0.4 & 0.1 \\
0.0 & -0.7 & 0.2 \\
0.6 & 0.3 & -0.4
\end{bmatrix}
\quad
\mathbf{W}^{(2)} = \begin{bmatrix}
0.3 & -0.8 & 0.1 & 0.0 \\
0.0 & 0.1 & 0.2 & 0.8 \\
-0.2 & 0.7 & 0.4 & 0.1
\end{bmatrix}
\quad
\mathbf{W}^{(3)} = \begin{bmatrix}
0.2 \\
0.1 \\
0.5 \\
0.4
\end{bmatrix}
\end{equation*}
$$
Every layer - that is $\mathbf{u}$, $\mathbf{v}$, and $\mathbf{y}$ - uses the logistic function as its activation function, i.e. $\sigma(z)=\frac{1}{1+e^{-z}}$.
<div class="alert alert-success">
**Task**: Implement the logistic function $\sigma(\mathbf{z})$ and compute the output activations for each layer. Here are a two functions that will be useful for solving this task:
<ul>
<li>`np.exp(x)` - exponentiates the argument `x`</li>
<li>`np.dot(a, b)` - performs matrix multiplications between matrix `a` and `b`</li>
</ul>
If you are unfamiliar with how to work with matrices in Python using NumPy, then it may be a good a idea to take a look at the following guide: [Getting started with Python](https://github.com/vicolab/tdt4195-public/blob/master/digital-image-processing/getting-started/getting-started-python.ipynb).
</div>
```
# Create input signal
x = np.array([[ 1, -4, 0, 7]])
# Create weight matrices for the three layers
W1 = np.array([[-0.1, 0.2, 0.1],
[ 0.1, 0.4, 0.1],
[ 0.0, -0.7, 0.2],
[ 0.6, 0.3, -0.4]])
W2 = np.array([[ 0.3, -0.8, 0.1, 0.0],
[ 0.0, 0.1, 0.2, 0.8],
[-0.2, 0.7, 0.4, 0.1]])
W3 = np.array([[0.2],
[0.1],
[0.5],
[0.4]])
# Create the logistic function
def logistic(z):
out = None
return out
# Compute activation of hidden layer `U`
U = None
# Compute activation of hidden layer `V`
V = None
# Compute activation of output layer `y`
y = None
### Do *not* modify the following line ###
# Test and see that the calculations have been done correctly
tests.test_forward_pass(logistic, U, V, y)
```
## The Backward Pass: Backpropagation
Backpropagation is the name of *one* learning algorithm for training artificial neural networks. While one of several, it is currently the most popular due to how efficiently it can be applied on modern hardware. As with other learning algorithms, the goal of backpropagation is to minimise an error or loss function.
After having run the forward, or inference, step for an artificial neural network and calculated the error we would like to figure out how to *perturbe* each of the weights in the network in order to reduce the error. Backpropagation does this by applying the all too familiar **gradient descent** algorithm we have seen earlier with the **chain rule** of calculus. Using notation from the first notebook, we would like to apply the following update rule to *every* weight in the network: $\mathbf{W}^{(l)}(k+1)\leftarrow\mathbf{W}^{(l)}(k) - \eta\frac{\partial E}{\partial\mathbf{W}^{(l)}}$, where $k$ is the current iteration or epoch, $\eta$ is the learning rate, and $\mathbf{W}^{(l)}$ is the weight matrix for layer $l$. This means that for every weight matrix backpropagation finds $\frac{\partial E}{\partial\mathbf{W}^{(l)}}$ by applying the chain rule of calculus.
In order to find $\frac{\partial E}{\partial\mathbf{W}^{(l)}}$ let's start by dividing the total amount of error amongst the neurons. The division depends on the linear combination $\mathbf{z}^{(l)}$, i.e. before the activation function, and is typically defined as $\delta^{(l)}$ for layer $l$. When $l$ is the last layer, which we will call $L$, $\delta^{(L)}$ for a specific output neuron $i$ is defined like so:
$$
\begin{equation*}
\begin{aligned}
\delta_{i}^{(L)} &= \frac{\partial E}{\partial \mathbf{z}_{i}^{(L)}} \\
&= \frac{\partial E}{\partial \mathbf{a}_{i}^{(L)}}\frac{\partial \mathbf{a}_{i}^{(L)}}{\partial \mathbf{z}_{i}^{(L)}} \\
&= \frac{\partial E}{\partial \mathbf{a}_{i}^{(L)}}\sigma'(\mathbf{z}_{i}^{(L)})
\end{aligned}
\end{equation*}
$$
Here, $\sigma'$ is defined as the derivative of the relevant activation function. Similarly, the error for a specific neuron $i$ in an arbitrary layer $l$ is defined as:
$$
\begin{equation*}
\begin{aligned}
\delta_{i}^{(l)} &= \frac{\partial E}{\partial \mathbf{z}_{i}^{(l)}} \\
&= \sum_{j}\frac{\partial E}{\partial \mathbf{z}_{j}^{(l+1)}}\frac{\partial \mathbf{z}_{j}^{(l+1)}}{\partial \mathbf{z}_{i}^{(l)}} \\
&= \sum_{j}\frac{\partial \mathbf{z}_{j}^{(l+1)}}{\partial \mathbf{z}_{i}^{(l)}}\delta_{j}^{(l+1)} \\
&= \sum_{j}\mathbf{W}_{ij}^{(l+1)}\delta_{j}^{(l+1)}\sigma'(\mathbf{z}_{i}^{l})
\end{aligned}
\end{equation*}
$$
That is, the error attributed to neuron $i$ in layer $l$ is the error over all neurons in layer $l+1$ weighted and multiplied by $\sigma'$ for the neuron we are interested in. Now that we know the gist of how errors are distributed amongst the neurons we can define $\frac{\partial E}{\partial\mathbf{W}_{ij}^{(l)}}$ as:
$$
\begin{equation*}
\frac{\partial E}{\partial\mathbf{W}_{ij}^{(l)}} = a_{i}^{(l-1)}\delta_{j}^{(l)}
\end{equation*}
$$
In other words, the amount we alter weight $\mathbf{W}_{ij}^{(l)}$ by, i.e. edge from $i$ to $j$, is the error $\delta_{j}$ of layer $l$ weighted by the activation $a_{i}$ at layer $l-1$. Notice that $l-1$ may be the input layer $\mathbf{x}$.
We will not dwell more on the intricacies of backpropagation here as there are many packages that implement it; Keras, or rather TensorFlow / Theano, being one of them.
## Task II: Learning the XOR Function
The XOR function (exclusive or) is a logical operation over two binary inputs that return 1 (*true*) when exactly one of its inputs is 1, otherwise it returns 0 (*false*). In other words, learning the XOR function can be viewed as a binary classification problem. The truth table for the XOR function can be seen in below.
| $x_1$ | $x_2$ | Output |
|-------|-------|--------|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
It is inherently a nonlinear problem because a line cannot separate the two output classes.
<div class="alert alert-info">
<strong>In the follow code snippet we will:</strong>
<ul>
<li>Create the XOR dataset</li>
<li>Plot the data</li>
</ul>
</div>
```
# Create data as NumPy arrays
DATA_X = np.array([[0,0], [0,1], [1,0], [1,1]], dtype=np.float32)
DATA_y = np.array([[0], [1], [1], [0]], dtype=np.float32)
# Plot data
plt.figure()
plt.scatter(DATA_X[np.where(DATA_y==0)[0], 0],
DATA_X[np.where(DATA_y==0)[0], 1],
label='false',
color='red')
plt.scatter(DATA_X[np.where(DATA_y==1)[0], 0],
DATA_X[np.where(DATA_y==1)[0], 1],
label='true',
color='blue')
plt.xlabel('x1')
plt.ylabel('x2')
plt.xticks([0, 1])
plt.yticks([0, 1])
plt.legend()
plt.show()
```
As we can see a simple line definitely cannot separate the blue and red points. Thankfully, a simple feedforward neural network with one hidden layer containing two neurons can solve the problem. The artificial neural network we will implement in Keras can be seen below. The two bias neurons are not necessary, but have been added for completeness.
<img src="resources/xor-nn.png" alt="XOR network" width="250" />
The network above has a single hidden layer with two neurons and all activation functions are assumed to be logistic functions. This network consist of two steps: (i) transform the input to a different feature space, this being the hidden layer; and (ii) perform classification via this new feature space. Our hope is that the feature space made by the hidden layer enables us to linearly separate the points.
<div class="alert alert-success">
**Task**: Build the model in the figure above using the [Keras functional guide](https://keras.io/getting-started/functional-api-guide/):
<ul>
<li><a href="https://keras.io/models/model/">Input()</a></li>
<li><a href="https://keras.io/models/model/">Dense()</a> - Bias nodes are by default on but can be removed by setting the `use_bias` to `False`</li>
<li><a href="https://keras.io/models/model/">Model()</a></li>
</ul>
All layers have to use the logistic function as their activation function. This is achieved by giving `Dense()` the argument `activation='sigmoid'`.
</div>
```
# Import what we need
from keras.layers import (Input, Dense)
from keras.models import Model
def build_xor_model():
"""Return a Keras Model.
"""
model = None
return model
### Do *not* modify the following line ###
# Test and see that the model has been created correctly
tests.test_xor_model(build_xor_model)
```
Now that we have successfully created the artificial neural network model, let's train it on the XOR dataset we defined earlier and see if we can learn the function. Similarly to the previous notebooks, notice that we are using the same stochastic gradient descent optimiser as before; however, this time we are using the *binary cross entropy* function we briefly discussed earlier.
<div class="alert alert-info">
<strong>In the following code snippet we will:</strong>
<ul>
<li>Create a model using the `build_xor_model()` function we made earlier</li>
<li>Train the network with backpropagation</li>
<li>Print the final predications</li>
<li>Plot the decision boundary learned by the artificial neural network</li>
</ul>
</div>
Due to how important initialisation of weight matrices are, we may be unlucky and get a solution which does not solve the XOR problem. If this is the case, then simply re-run the cell.
```
"""Do not modify the following code. It is to be used as a refence for future tasks.
"""
# Create a XOR model
model = build_xor_model()
# Define hyperparameters
lr = 1.0
nb_epochs = 500
# Define optimiser
optimizer = keras.optimizers.sgd(lr=lr)
# Compile model, use binary_crossentropy
model.compile(loss='binary_crossentropy', optimizer=optimizer)
# Print model
model.summary()
# Train model
model.fit(DATA_X, DATA_y,
batch_size=1,
epochs=nb_epochs,
verbose=0)
# Print predictions
y_hat = model.predict(DATA_X)
print('\nFinal predictions:')
for idx in range(len(y_hat)):
print('{} ~> {:.2f} (Ground truth = {})'.format(DATA_X[idx], y_hat[idx][0], DATA_y[idx][0]))
# Plot XOR data and decision boundary
xx, yy = np.meshgrid(np.arange(-0.1, 1.1, 0.01), np.arange(-0.1, 1.1, 0.01))
grid = np.vstack((xx.ravel(), yy.ravel())).T
preds = model.predict(grid)[:, 0].reshape(xx.shape)
f, ax = plt.subplots()
ax.contour(xx, yy, preds, levels=[0.5], colors='k', linewidths=1.0)
ax.scatter(DATA_X[np.where(DATA_y==0)[0], 0],
DATA_X[np.where(DATA_y==0)[0], 1],
label='false',
color='red')
ax.scatter(DATA_X[np.where(DATA_y==1)[0], 0],
DATA_X[np.where(DATA_y==1)[0], 1],
label='true',
color='blue')
plt.xlabel('x1')
plt.ylabel('x2')
plt.xticks([0, 1])
plt.yticks([0, 1])
plt.legend()
plt.show()
```
Let's visualise the output of the hidden layer to better understand the feature space representation. It just so happens that the layer only has two neurons, which means we can safely plot it as an image.
<div class="alert alert-info">
<strong>In the following code snippet we will:</strong>
<ul>
<li>Plot the data after it has been transformed to the feature space</li>
</ul>
</div>
```
# Get the output activation given the XOR data for the hidden layer
intermediate_layer = Model(inputs=model.input,
outputs=model.get_layer(index=1).output)
feature_space = intermediate_layer.predict(DATA_X)
# Visualise representation as a scatter plot
plt.figure()
plt.scatter(feature_space[np.where(DATA_y==0)[0], 0],
feature_space[np.where(DATA_y==0)[0], 1],
label='false',
color='red')
plt.scatter(feature_space[np.where(DATA_y==1)[0], 0],
feature_space[np.where(DATA_y==1)[0], 1],
label='true',
color='blue')
plt.xlabel('h1')
plt.ylabel('h2')
plt.xticks([0, 1])
plt.yticks([0, 1])
plt.legend()
plt.show()
```
As we can see, the red and blue points are now linearly separable.
## Task III: The Circle Dataset
The second dataset we will take take a look at is also a nonlinear one. The circle dataset is a synthetic dataset with two output classes, which means we yet again are dealing with a binary classification problem.
<div class="alert alert-info">
<strong>In the follow code snippets we will:</strong>
<ul>
<li>Load the circle dataset</li>
<li>Plot the data: Testing data has a darker colour compared to the training data</li>
</ul>
</div>
```
# Load the circle data set
X_train, y_train, X_test, y_test = tools.load_csv_data(
'resources/cl-train.csv', 'resources/cl-test.csv')
# Plot both the training and test set
plt.figure()
tools.plot_2d_train_test(X_train, y_train, X_test, y_test)
plt.show()
```
As we can see from the plot above the coloured points cannot be separated by a single line, which means that the dataset is not linearly separable. While the dataset can be solved quite easily by, for example, applying the transformation $\phi(\mathbf{x})=(\mathbf{x} - 0.5)^2$, we will be using an artificial neural network to do the job for us.
This task is experimentation-based which means you will have to come up with most of the network topology yourself.
<div class="alert alert-success">
**Task**: Build an artificial neural network model that can solve the circle dataset. As before, you only need to use fully-connected layers (<a href="https://keras.io/models/model/">Dense()</a>) with logistic activation to solve the problem.
<br /><br />
The model input and model output has been created for you, so you can focus on the hidden representation(s).
</div>
```
def build_circle_model():
"""Return a Keras Model.
"""
model = None
# Define model inputs
inputs = Input(shape=(2,))
# Come up with your hidden representation here (one or more layers)
hidden = None
# Define model output (make sure to link it with the correct previous layer)
outputs = Dense(1, activation='sigmoid')(inputs)
# Build model
model = Model(inputs=inputs, outputs=outputs)
return model
```
Now that we have a model, let's continue on and train it using Keras. This time however, you will have to set up everything yourself.
<div class="alert alert-success">
**Task**: Train the model you just created:
<ul>
<li>Call `build_circle_model()` to build the model</li>
<li>Set up an optimiser</li>
<li>Compile and fit the model</li>
</ul>
We have picked some sensible hyperparameters for you, but you are free to experiment. It is strongly recommended that you set `verbose` to $0$ just like we did in the XOR example when calling the `fit()` method.
</div>
```
# Create a circle model
model = None
# Define hyperparameters
lr = 3.0
nb_epochs = 500
batch_size = 10
# Define optimiser
optimizer = None
# Compile model, use binary_crossentropy
# Train model (make sure you input the correct data)
"""Do not modify the following code. It is to be used as a refence for future tasks.
"""
# Plot circle dataset and decision boundary
xx, yy = np.meshgrid(np.arange(-0.1, 1.1, 0.01), np.arange(-0.1, 1.1, 0.01))
grid = np.vstack((xx.ravel(), yy.ravel())).T
preds = model.predict(grid)[:, 0].reshape(xx.shape)
plt.figure()
plt.contour(xx, yy, preds, levels=[0.5], colors='k', linewidths=1.0)
tools.plot_2d_train_test(X_train, y_train, X_test, y_test)
plt.xlabel('x1')
plt.ylabel('x2')
plt.xticks([0, 1])
plt.yticks([0, 1])
plt.show()
```
The task is considered finished when you have managed to separate the red and blue points by the decision boundary.
## Task IV: Digit Classification with MNIST
Before we end this notebook we will take a look at a multiclass classification problem called the MNIST database (Modified National Institute of Standards and Technology database):
>The MNIST database of handwritten digits, available from this page, has a training set of 60,000 examples, and a test set of 10,000 examples. It is a subset of a larger set available from NIST. The digits have been size-normalized and centered in a fixed-size image.
>It is a good database for people who want to try learning techniques and pattern recognition methods on real-world data while spending minimal efforts on preprocessing and formatting.
[source](http://yann.lecun.com/exdb/mnist/)
We will go more in-depth on images and how to train on images in the next notebook on convolutional networks, so for now, we will hand-wave most of the details and explanations.
<div class="alert alert-info">
<strong>In the follow code snippets we will:</strong>
<ul>
<li>Load the MNIST dataset</li>
<li>Normalise the images between 0 and 1 to simplify the training</li>
<li>Ensure that the target outputs are one-hot encoded (see next notebook)</li>
<li>Plot a few images from the dataset</li>
</ul>
</div>
```
# Load data using Keras
(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
# Normalise images
X_train = X_train / 255
X_test = X_test / 255
# One-hot encode targets
y_train = keras.utils.to_categorical(y_train, num_classes=10)
y_test = keras.utils.to_categorical(y_test, num_classes=10)
# Plot a few of images
fig, ax = plt.subplots(1, 4)
ax[0].imshow(X_train[1], cmap=plt.cm.gray)
ax[0].set_axis_off()
ax[1].imshow(X_train[600], cmap=plt.cm.gray)
ax[1].set_axis_off()
ax[2].imshow(X_train[6000], cmap=plt.cm.gray)
ax[2].set_axis_off()
ax[3].imshow(X_train[12345], cmap=plt.cm.gray)
ax[3].set_axis_off()
plt.show()
```
The images in MNIST are fairly small, just $28\times 28$ pixels big. To be able to train a multilayer perceptron model the images first have to be flattened to $28\times 28 = 784$ values between 0 and 1. There are a total of 10 classes (digits 0 through 9) which means our neural network will have 784 inputs and 10 outputs. Your programming task will focus on coming up with a sensible hidden representation - one or more layers - to be able to classify the digits well.
This is the first task where the number of output classes is more than two. Thus, for this problem we will be using the softmax function as the activation function for the *output* layer.
<div class="alert alert-success">
**Task**: Experiment with different hidden representations for solving the MNIST classification problem. As usual, you only need to use fully-connected layers (<a href="https://keras.io/models/model/">Dense()</a>), but will free to try out different [activation functions](https://keras.io/activations/).
<br /><br />
For this task you will need to set up the input layer, hidden representation, output layer, and model yourself. Refer back to earlier code and notebooks if you are unsure about how to do this. The most important thing to keep in mind is the output layer must use `activation='softmax'`.
</div>
```
def mlp_mnist_model(nb_inputs, nb_outputs):
"""Return a Keras Model.
"""
model = None
return model
```
Now that have our model the next thing we have to do is test out and see we are able to learn something useful from the MNIST dataset.
<div class="alert alert-info">
<strong>In the follow code snippets we will:</strong>
<ul>
<li>Train MNIST with the categorical cross entropy error function we discussed in the beginning of this notebook</li>
</ul>
The hyperparameters we have set below are fairly sensible, and you should be able to get decent performance with them; however, feel free to experiment.
</div>
```
"""Do not modify the following code.
"""
# Create flattened version for the MLP
X_trainf = X_train.reshape(X_train.shape[0], -1)
X_testf = X_test.reshape(X_test.shape[0], -1)
# Create MNIST MLP model
model = mlp_mnist_model(X_trainf.shape[1], 10)
# Define hyperparameters
lr = 0.01
nb_epochs = 20
batch_size = 128
# Define optimiser
optimizer = keras.optimizers.sgd(lr=lr, nesterov=True)
# Compile model, use categorical_crossentropy
model.compile(loss='categorical_crossentropy', optimizer=optimizer)
# Print model
model.summary()
# Train and record history
logs = model.fit(X_trainf, y_train,
validation_data=(X_testf, y_test),
batch_size=batch_size,
epochs=nb_epochs,
verbose=2)
# Plot the error
fig, ax = plt.subplots(1,1)
pd.DataFrame(logs.history).plot(ax=ax)
ax.grid(linestyle='dotted')
ax.set_xlabel('Epoch')
ax.set_ylabel('Loss / Error')
ax.legend()
plt.show()
```
We can get fairly good performance on MNIST by using just a simple MLP, however, we may be able to get even better performance by using a type of artificial neural network called a convolutional network. This will be the topic of the next Jupyter notebook.
# Digression: What is Deep Learning?
The core idea of deep learning is to build complex concepts from simple concepts. We typically think of it as learning hierarchical representations of concepts, i.e. each new representation builds on the previous representation.
In *"shallow"* learning, such as linear and logistic regression, we construct simple models over the feature domain. These are either just the raw inputs, or some hand-engineered features found via feature extraction. In deep learning, the feature extraction procedure is a part of the learning process, and as we saw above: the features are learned as a hierarchy of simple-to-complex representations.
Common misunderstanding: Deep learning is *not* synonymous with artificial neural networks (ANNs). While ANNs are the quintessential deep learning models, they are not the only choice. For example, probabilistic graphical models are also a common choice.
| github_jupyter |
# Transposes, Permutations, and Spaces (18.06_L5)
> Linear Algebra - Row Exchanges, spaces and subspaces, oh my!
- toc: true
- badges: true
- comments: true
- author: Isaac Flath
- categories: [Linear Algebra]
# Background
In previous posts, we have gone over elimination to solve systems of equations. However, every example workout out perfectly. What I mean by that is we didn't have to do row exchanges. Every example was in an order that worked on attempt 1. In this post, we are going to talk about how to solve equations when this isn't the case.
# Row Exchanges
The way we do a row exchange in matrix language is that we multiply by a permutation matrix, which we will refer to as $P$.
So how do we account for row exchanges? Our previous equation of $A=LU$ does not account for row exchanges.
## Permutations
A Permutation matrix executes our row exhanges. This matrix $P$ is the identify matrix with reording rows. $A=LU$ becomes $PA=LU$. We multipy a permutation matrix $P$ by $A$.
>Note: The reason we were able to ignore $P$ in previous posts is because when you have no row exchanges, $P$ is just the identify matrix (no re-ordering)
If we were to switch rows 2 and 3 in a 3x3 matrix, $P$ would be
$$\begin{bmatrix}1&0&0\\0&0&1\\0&1&0\end{bmatrix}$$
# Transposed Matrices
A transposed matrix has rows and columns switched. Naturally, symmetric matrices are unchanged by the transpose.
A Matrix multiplied by it's transpose always gives a symmetric matrix.
# Vector Spaces
To have a vector space you need to be able to:
1. Add any vectors and still be within the space
1. Multiply by any number and stay within space
1. Take any linear combination and stay within space
## Examples
$R^2$ is a vector space. This is all real number vectors with 2 components. Here's a few examples.
$\begin{bmatrix}3\\2\end{bmatrix}$,
$\begin{bmatrix}0\\0\end{bmatrix}$,
$\begin{bmatrix}\pi\\e\end{bmatrix}$
$R^3$ is another vector space, but it contains all real 3D vectors. Here's a few examples.
$\begin{bmatrix}3\\2\\5\end{bmatrix}$,
$\begin{bmatrix}3\\2\\0\end{bmatrix}$,
$\begin{bmatrix}0\\0\\0\end{bmatrix}$,
$\begin{bmatrix}\pi\\e\\5\end{bmatrix}$
$R^n$ is another with all column vectors with $n$ real components.
## Subspaces
What if we just want a piece of $R^n$? We still need to be able to add vectors and multiply it together. So what are some subspaces?
1. A line through $R^n$ that goes through the origin. Any multiple of a point on a line is still on the line. We need the origin because you can mutliply any vector by 0, which would give you the origin.
1. Just the Origin is a subspace. You can add it to itelf, multiply it by anything, and take any combination and you will stil lhave the origin.
1. In $R^3$ and above, a plane through the origin is also a subspace.
## Subpace from a matrix
$\begin{bmatrix}1&3\\2&3\\4&1\end{bmatrix}$
Columns in $R^3$ and all their linear combinations are a subspace. This subspace is a plane going through the origin
| github_jupyter |
```
from copy import copy
import glob
import hashlib
import json
import os
from pathlib import Path
import shutil
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from PIL import Image, ImageChops, ImageFile, ImageFilter
from tqdm import tqdm_notebook as tqdm
ImageFile.LOAD_TRUNCATED_IMAGES = True
plt.style.use('dark_background')
```
# Define functions
```
def trim_stage1(img):
img_array = np.asarray(img)
vertical_crop = img_array[:,:5,:]
vertical_means = np.mean(vertical_crop, axis=2).mean(axis=1)
diffs = []
for i,pixel in enumerate(vertical_means):
diff = vertical_means[i] - vertical_means[i-1]
diffs.append(diff)
crop_max = np.max(diffs[256:])
crop_min = np.min(diffs[:256])
max_ix = np.argmax(diffs[256:])
min_ix = np.argmin(diffs[:256])
crop_mean = np.mean(diffs)
new_array = img_array[min_ix:256+max_ix,:,:]
new_img = Image.fromarray(new_array, 'RGB')
return new_img
def trim_stage2(img):
bg = Image.new(img.mode, img.size, img.getpixel((0,0)))
diff = ImageChops.difference(img, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
return img.crop(bbox)
else:
pass
def is_square(img):
height = np.shape(img)[0]
width = np.shape(img)[1]
if 0.3 < (height/width) < 1.2:
return True
else:
return False
def makeShadow(image, iterations, border, offset, backgroundColour='black', shadowColour='black'):
# image: base image to give a drop shadow
# iterations: number of times to apply the blur filter to the shadow
# border: border to give the image to leave space for the shadow
# offset: offset of the shadow as [x,y]
# backgroundCOlour: colour of the background
# shadowColour: colour of the drop shadow
#Calculate the size of the shadow's image
fullWidth = image.size[0] + abs(offset[0]) + 2*border
fullHeight = image.size[1] + abs(offset[1]) + 2*border
#Create the shadow's image. Match the parent image's mode.
shadow = Image.new(image.mode, (fullWidth, fullHeight), backgroundColour)
# Place the shadow, with the required offset
shadowLeft = border + max(offset[0], 0) #if <0, push the rest of the image right
shadowTop = border + max(offset[1], 0) #if <0, push the rest of the image down
#Paste in the constant colour
shadow.paste(shadowColour,
[shadowLeft, shadowTop,
shadowLeft + image.size[0],
shadowTop + image.size[1] ])
# Apply the BLUR filter repeatedly
for i in range(iterations):
shadow = shadow.filter(ImageFilter.BLUR)
# Paste the original image on top of the shadow
imgLeft = border - min(offset[0], 0) #if the shadow offset was <0, push right
imgTop = border - min(offset[1], 0) #if the shadow offset was <0, push down
shadow.paste(image, (imgLeft, imgTop))
return shadow
def cylindricalWarp(img):
"""This function returns the cylindrical warp for a given image and intrinsics matrix K"""
img = np.array(img)
h_,w_ = img.shape[:2]
K = np.array([[600,0,w_/2],[0,600,h_/2],[0,0,1]])
# pixel coordinates
y_i, x_i = np.indices((h_,w_))
X = np.stack([x_i,y_i,np.ones_like(x_i)],axis=-1).reshape(h_*w_,3) # to homog
Kinv = np.linalg.inv(K)
X = Kinv.dot(X.T).T # normalized coords
# calculate cylindrical coords (sin\theta, h, cos\theta)
A = np.stack([np.sin(X[:,0]),X[:,1],np.cos(X[:,0])],axis=-1).reshape(w_*h_,3)
B = K.dot(A.T).T # project back to image-pixels plane
# back from homog coords
B = B[:,:-1] / B[:,[-1]]
# make sure warp coords only within image bounds
B[(B[:,0] < 0) | (B[:,0] >= w_) | (B[:,1] < 0) | (B[:,1] >= h_)] = -1
B = B.reshape(h_,w_,-1)
img_rgba = cv2.cvtColor(img,cv2.COLOR_BGR2BGRA) # for transparent borders...
# warp the image according to cylindrical coords
img_warped = cv2.remap(
img_rgba,
B[:,:,0].astype(np.float32),
B[:,:,1].astype(np.float32),
cv2.INTER_AREA,
borderMode=cv2.BORDER_TRANSPARENT
)
return img_warped
```
## Run Loop
```
# Set paths
blur_dir = "/mnt/h/data/stylegan2_ada_outputs/"
dest_dir = "/mnt/h/data/stylegan2_ada_outputs/bottled/"
bottles_path = "/mnt/c/Users/david/Documents/github/this-wine-does-not-exist/images/bottle_templates.jpg"
Path(dest_dir).mkdir(exist_ok=True)
# Load blur results JSON
blur_results = []
for i in Path(blur_dir).glob('blur_results_*.json'):
with open(i, 'rb') as f:
r = json.load(f)
[blur_results.append(i) for i in r['results']]
# Load bottle templates
bottles_templates = Image.open(bottles_path)
dark_bottle = bottles_templates.crop(box=(0,0,1000,3000)).resize((593, 1750), Image.ANTIALIAS)
shift = -8
light_bottle = bottles_templates.crop(box=(2000+shift,0,3000+shift,3000)).resize((593, 1750), Image.ANTIALIAS)
#dark_bottle.show()
#light_bottle.show()
dark_wine_cats = [14,2,8,1,5,4,9,12,15]
light_wine_cats = [3,13,7,6,10]
display_imgs = False
left = 51
upper = 950
label_size = 512
# Main loop
ixx = 0
for i in tqdm(blur_results):
try:
if i['score'] < 3:
continue
# Load image
img_Path = Path(i['input_path'])
raw_img = Image.open(img_Path)
# Trim/Crop image
#img = copy(raw_img)
#img = trim_stage1(raw_img)
img = trim_stage2(raw_img)
if is_square(img) == False:
continue
img3 = img.resize((label_size,label_size), Image.ANTIALIAS)
# Warp image for bottle wrapping
img_warped = cylindricalWarp(img3)
img_mask = img_warped[:, :, 3] < 255
img_warped[:, :, 3][img_mask] = 0
img4 = Image.fromarray(img_warped)
# Make shadow
#img = makeShadow(img, iterations=1, border=0, offset=(3,3))
cat_2 = int(str(img_Path.parents[0]).split('9480_')[1])
if cat_2 not in dark_wine_cats + light_wine_cats:
continue
new_bottle = copy(dark_bottle) if cat_2 in dark_wine_cats else copy(light_bottle)
new_bottle.paste(im=img4, box=(left, upper, left+label_size, upper+label_size), mask=img4)
new_bottle = new_bottle.resize((300,900), Image.ANTIALIAS)
if display_imgs == True:
fig, ax = plt.subplots(1,3, figsize=(15,5))
ax[0].imshow(raw_img);
ax[2].imshow(img)
ax[3].imshow(new_bottle)
plt.show()
# Write bottles with labels
dest_file = f"bottle_cat_{cat_2}_seed_{ixx:05d}.png"
new_bottle.save(Path(dest_dir, dest_file))
#if ixx == 20:
# break
ixx += 1
except Exception as e:
print(Exception)
```
| github_jupyter |
# Preparing the dataset for hippocampus segmentation
In this notebook you will use the skills and methods that we have talked about during our EDA Lesson to prepare the hippocampus dataset using Python. Follow the Notebook, writing snippets of code where directed so using Task comments, similar to the one below, which expects you to put the proper imports in place. Write your code directly in the cell with TASK comment. Feel free to add cells as you see fit, but please make sure that code that performs that tasked activity sits in the same cell as the Task comment.
```
# TASK: Import the following libraries that we will use: nibabel, matplotlib, numpy
import sys
import os
import shutil
import numpy as np
import pandas as pd
import nibabel as nib
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (12, 6)
print(f'Python version: {sys.version}')
print(f'Numpy version: {np.__version__}')
print(f'Pandas version: {pd.__version__}')
```
It will help your understanding of the data a lot if you were able to use a tool that allows you to view NIFTI volumes, like [3D Slicer](https://www.slicer.org/). I will refer to Slicer throughout this Notebook and will be pasting some images showing what your output might look like.
## Loading NIFTI images using NiBabel
NiBabel is a python library for working with neuro-imaging formats (including NIFTI) that we have used in some of the exercises throughout the course. Our volumes and labels are in NIFTI format, so we will use nibabel to load and inspect them.
NiBabel documentation could be found here: https://nipy.org/nibabel/
Our dataset sits in two directories - *images* and *labels*. Each image is represented by a single file (we are fortunate to have our data converted to NIFTI) and has a corresponding label file which is named the same as the image file.
Note that our dataset is "dirty". There are a few images and labels that are not quite right. They should be quite obvious to notice, though. The dataset contains an equal amount of "correct" volumes and corresponding labels, and you don't need to alter values of any samples in order to get the clean dataset.
```
## define file paths:
path_data = '../data/'
# path_data = '/data/'
path_train_imgs = f'{path_data}TrainingSet/images/'
path_train_lbls = f'{path_data}TrainingSet/labels/'
## get all file names:
filenames_train_imgs = [file for file in os.listdir(path_train_imgs) if file[-7:]=='.nii.gz']
filenames_train_lbls = [file for file in os.listdir(path_train_lbls) if file[-7:]=='.nii.gz']
print(f'# images: {len(filenames_train_imgs)}')
print(f'# labels: {len(filenames_train_lbls)}')
```
1 label is missing. Therefore we get rid of the image that has no corresponding label file
```
## get intersection of all (image, label) pairs (for each image a label has to exist):
filenames_train = np.intersect1d(filenames_train_imgs, filenames_train_lbls)
## list all available unique shapes
available_shapes = []
label_missmatch = []
for filename in filenames_train:
img_shape = nib.load(f'{path_train_imgs}{filename}').shape
lbl_shape = nib.load(f'{path_train_lbls}{filename}').shape
if img_shape==lbl_shape:
available_shapes += [np.array(img_shape)]
else:
print(f'file {filename} has miss-matching shapes ' +
f'between image ({img_shape}) and label ({lbl_shape}).')
label_missmatch += [filename]
## get all shapes (and their value counts) of the images:
np.unique(available_shapes, return_counts=True, axis=0)
```
Looks like we have quite a fiew different image shapes.
On top we have two (image, label)-pairs with miss-matching shape. The image shapes of these files look like they have been forgotten to be cropped. We will ignore these images and delete them from our filename list
```
## delete shape missmatching files from list:
filenames_train = [file for file in filenames_train if file not in label_missmatch]
shape_mean = (np.array(available_shapes)[:, 0]).mean()
shape_std = (np.array(available_shapes)[:, 0]).std()
print(f'dimension 0: shape mean: {shape_mean}, shape std: {shape_std}')
shape_mean = (np.array(available_shapes)[:, 1]).mean()
shape_std = (np.array(available_shapes)[:, 1]).std()
print(f'dimension 1: shape mean: {shape_mean}, shape std: {shape_std}')
shape_mean = (np.array(available_shapes)[:, 2]).mean()
shape_std = (np.array(available_shapes)[:, 2]).std()
print(f'dimension 2: shape mean: {shape_mean}, shape std: {shape_std}')
```
The remaining images seem to have similar shapes (small standard deviation of shape sizes in all dimensions)
```
# TASK: Your data sits in directory /data/TrainingSet.
# Load an image and a segmentation mask into variables called image and label
## select image (and label) to visualize:
img_nr = 0
image = nib.load(f'{path_train_imgs}{filenames_train[img_nr]}')
label = nib.load(f'{path_train_lbls}{filenames_train[img_nr]}')
# Nibabel can present your image data as a Numpy array by calling the method get_fdata()
# The array will contain a multi-dimensional Numpy array with numerical values representing voxel intensities.
# In our case, images and labels are 3-dimensional, so get_fdata will return a 3-dimensional array. You can verify this
# by accessing the .shape attribute. What are the dimensions of the input arrays?
# TASK: using matplotlib, visualize a few slices from the dataset, along with their labels.
# You can adjust plot sizes like so if you find them too small:
# plt.rcParams["figure.figsize"] = (10,10)
# factor of how intense the overlayed mask should be:
intensity_factor = 50
## import selected image and label:
image_volume = image.get_fdata()
label_volume = label.get_fdata()
print(f'Shape of input data: {image_volume.shape}')
## select how many slices in each cardinal plane to plot:
nr_slices = 10
range0 = np.linspace(0, image_volume.shape[0]-1, nr_slices)
range1 = np.linspace(0, image_volume.shape[1]-1, nr_slices)
range2 = np.linspace(0, image_volume.shape[2]-1, nr_slices)
fig, axarr = plt.subplots(nr_slices, 3, figsize=(3*6, 6*nr_slices))
for i in range(nr_slices):
# plot a slice in sagittal plane with overlayed label mask:
slice_nr0 = int(range0[i])
axarr[i, 0].imshow(np.rot90(image_volume[slice_nr0, :, :]) + np.rot90(label_volume[slice_nr0, :, :])*intensity_factor, cmap='gray')
ttl = f'sagittal plane (slice {slice_nr0})'
axarr[i, 0].set_title(ttl)
axarr[i, 0].invert_xaxis()
slice_nr1 = int(range1[i])
axarr[i, 1].imshow(np.rot90(image_volume[:, slice_nr1, :]) + np.rot90(label_volume[:, slice_nr1, :])*intensity_factor, cmap='gray')
ttl = f'coronal plane (slice {slice_nr1})'
axarr[i, 1].set_title(ttl)
axarr[i, 1].invert_xaxis()
slice_nr2 = int(range2[i])
axarr[i, 2].imshow(np.rot90(image_volume[:, :, slice_nr2]) + np.rot90(label_volume[:, :, slice_nr2])*intensity_factor, cmap='gray')
ttl = f'axial plane (slice {slice_nr2})'
axarr[i, 2].set_title(ttl)
axarr[i, 2].invert_xaxis()
```
Load volume into 3D Slicer to validate that your visualization is correct and get a feel for the shape of structures.Try to get a visualization like the one below (hint: while Slicer documentation is not particularly great, there are plenty of YouTube videos available! Just look it up on YouTube if you are not sure how to do something)

```
# Stand out suggestion: use one of the simple Volume Rendering algorithms that we've
# implemented in one of our earlier lessons to visualize some of these volumes
```
## Looking at single image data
In this section we will look closer at the NIFTI representation of our volumes. In order to measure the physical volume of hippocampi, we need to understand the relationship between the sizes of our voxels and the physical world.
```
## import all images with nibabel:
images = []
labels = []
for filename in filenames_train:
images += [nib.load(f'{path_train_imgs}{filename}')]
labels += [nib.load(f'{path_train_lbls}{filename}')]
# Nibabel supports many imaging formats, NIFTI being just one of them. I told you that our images
# are in NIFTI, but you should confirm if this is indeed the format that we are dealing with
# TASK: using .header_class attribute - what is the format of our images?
## get all available formats of image files
image_formats = {img.header_class for img in images}
## get format of label files
label_formats = {lbl.header_class for lbl in labels}
print(f'All available formats of image file: {image_formats}')
print(f'All available formats of label file: {label_formats}')
```
Further down we will be inspecting .header attribute that provides access to NIFTI metadata. You can use this resource as a reference for various fields: https://brainder.org/2012/09/23/the-nifti-file-format/
```
# TASK: How many bits per pixel are used?
lst = []
for img in images:
lst += [img.header['datatype']]
print(f'Bit code frequencies in images: \n{pd.Series(lst).value_counts()}')
lst = []
for lbl in labels:
lst += [lbl.header['datatype']]
print(f'Bit code frequencies in labels: \n{pd.Series(lst).value_counts()}')
images[1].header['bitpix']
```
We have two diffrent types of bits per pixels:
the first entry above represents a code (see https://brainder.org/2012/09/23/the-nifti-file-format/):
- 16: 32 bit (floats)
- 2: 8 bit (unsigned char)
Most of the images (205) are 32 bit voxel images.
Alternatively you could use .header['bitpix'] (see below)
```
# Alternatively use 'bitpix' keyword directly:
lst = []
for img in images:
lst += [img.header['bitpix']]
print(f'Bit code frequencies in images: \n{pd.Series(lst).value_counts()}')
lst = []
for lbl in labels:
lst += [lbl.header['bitpix']]
print(f'Bit code frequencies in labels: \n{pd.Series(lst).value_counts()}')
# TASK: What are the units of measurement?
lst = []
for img in images:
lst += [img.header['xyzt_units']]
print(f'Units code frequenceies in images: \n{pd.Series(lst).value_counts()}')
lst = []
for lbl in labels:
lst += [lbl.header['xyzt_units']]
print(f'Units code frequenceies in labels: \n{pd.Series(lst).value_counts()}')
{img.header.get_xyzt_units() for img in images}
{lbl.header.get_xyzt_units() for lbl in labels}
```
The units of measurements are for both images and labels in mili-meter
We can get it in two ways:
- by code: 10 -> composed of 2: mm and 8: sec
- by direct output
```
# TASK: Do we have a regular grid? What are grid spacings?
lst = []
for img in images:
lst += [img.header['pixdim']]
print(f'Spacial spacing (entry 0-2) in images: {np.unique(np.array(lst), axis=0)}')
lst = []
for lbl in labels:
lst += [lbl.header['pixdim']]
np.unique(np.array(lst), axis=0)
print(f'Spacial spacing (entry 0-2) in labels: {np.unique(np.array(lst), axis=0)}')
```
We have a regular grid. In each dimension we have a spatial spacing of 1 mm.
The first three dimensions represent spatial coordinates: x, y, z.
The 4. dimension represents the time: An image was taken each second.
```
# TASK: What dimensions represent axial, sagittal, and coronal slices? How do you know?
print(f'(base) affine matrix: \n{images[1].header.get_base_affine()}')
print(f'(best) affine matrix: \n{images[1].header.get_best_affine()}')
```
Conventions in NIFTI files:
- Voxel coordinates refer to the center of each voxel,
- The world coordinate system is assumed to be ras:
- +x is Right (left is 0, increasing coordinates go to the right)
- +y is Anterior (from back (posterior) to front (anterior))
- +z is Superior (from bottom (inferior) to top (superior))
dimension meanings:
- Fixing dimension 0 yields sagittal
- fixing dimension 1 yields coronal
- figing dimension 2 yields axial
The affine transformation matrix is equal to an Identity matrix
```
# By now you should have enough information to decide what are dimensions of a single voxel
# TASK: Compute the volume (in mm³) of a hippocampus using one of the labels you've loaded.
# You should get a number between ~2200 and ~4500
lst = []
for lbl in labels:
# load label data file:
lbl_data = lbl.get_fdata()
# count all voxels in each slice (sum all pixels in slice):
lst += [(lbl_data>0).sum()]
volumes = np.array(lst)
print(f"We took a look at all labels.\nThe smalles hippocampus volume is {volumes.min()} mm^3.\nThe largest hippocampus volume slice is {volumes.max()} mm^3.")
```
All volumes are in the range between ~2200 and ~4500. Apparently we already filtered out all outliers (see above)
Summary translating physical space to image voxels:
- each voxel (1x1x1 3d pixel) corresponds to a physical space of 1mm x 1mm x 1mm
## Plotting some charts
```
# TASK: Plot a histogram of all volumes that we have in our dataset and see how
# our dataset measures against a slice of a normal population represented by the chart below.
fig, ax = plt.subplots(1, 1, figsize=(12, 6))
ax.hist(volumes)
ax.set_title('Distribution of volumes of a hippocampus')
ax.set_xlabel('volume (in mm³)')
ax.set_ylabel('frequency')
```
Overall one can say that our dataset is shifted towards smaller hippocampus sizes. This might be the case because the dataset contains a higher fraction of sick subjects with smaller hippocampus sizes and possibly alzheimer's disease diagnosis. Other outliers we might not see because we allready filtered out unsuitable images above.
<img src="img/nomogram_fem_right.svg" width=400 align=left>
Do you see any outliers? Why do you think it's so (might be not immediately obvious, but it's always a good idea to inspect) outliers closer. If you haven't found the images that do not belong, the histogram may help you.
In the real world we would have precise information about the ages and conditions of our patients, and understanding how our dataset measures against population norm would be the integral part of clinical validation that we talked about in the last lesson. Unfortunately, we do not have this information about this dataset, so we can only guess why it measures the way it is. If you would like to explore further, you can use the [calculator from HippoFit project](http://www.smanohar.com/biobank/calculator.html) to see how our dataset compares against different population slices
Did you notice anything odd about the label files? We hope you did! The mask seems to have two classes, labeled with values `1` and `2` respectively. If you visualized sagittal or axial views, you might have gotten a good guess of what those are. Class 1 is the anterior segment of the hippocampus and class 2 is the posterior one.
For the purpose of volume calculation we do not care about the distinction, however we will still train our network to differentiate between these two classes and the background
```
# TASK: Copy the clean dataset to the output folder inside section1/out. You will use it in the next Section
path_out_imgs = 'data/TrainingSet/images/'
path_out_lbls = 'data/TrainingSet/labels/'
os.makedirs(path_out_imgs, exist_ok=True)
os.makedirs(path_out_lbls, exist_ok=True)
for filename in filenames_train:
img = f'{path_train_imgs}{filename}'
lbl = f'{path_train_lbls}{filename}'
shutil.copyfile(img, f'{path_out_imgs}{filename}')
shutil.copyfile(lbl, f'{path_out_lbls}{filename}')
```
## Final remarks
Congratulations! You have finished Section 1.
In this section you have inspected a dataset of MRI scans and related segmentations, represented as NIFTI files. We have visualized some slices, and understood the layout of the data. We have inspected file headers to understand what how the image dimensions relate to the physical world and we have understood how to measure our volume. We have then inspected dataset for outliers, and have created a clean set that is ready for consumption by our ML algorithm.
In the next section you will create training and testing pipelines for a UNet-based machine learning model, run and monitor the execution, and will produce test metrics. This will arm you with all you need to use the model in the clinical context and reason about its performance!
| github_jupyter |
##### Copyright 2020 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Optimizing the Text Generation Model
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l10c04_nlp_optimizing_the_text_generation_model.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l10c04_nlp_optimizing_the_text_generation_model.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
</table>
You've already done some amazing work with generating new songs, but so far we've seen some issues with repetition and a fair amount of incoherence. By using more data and further tweaking the model, you'll be able to get improved results. We'll once again use the [Kaggle Song Lyrics Dataset](https://www.kaggle.com/mousehead/songlyrics) here.
## Import TensorFlow and related functions
```
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Other imports for processing data
import string
import numpy as np
import pandas as pd
```
## Get the Dataset
As noted above, we'll utilize the [Song Lyrics dataset](https://www.kaggle.com/mousehead/songlyrics) on Kaggle again.
```
!wget --no-check-certificate \
https://drive.google.com/uc?id=1LiJFZd41ofrWoBtW-pMYsfz1w8Ny0Bj8 \
-O /tmp/songdata.csv
```
## 250 Songs
Now we've seen a model trained on just a small sample of songs, and how this often leads to repetition as you get further along in trying to generate new text. Let's switch to using the 250 songs instead, and see if our output improves. This will actually be nearly 10K lines of lyrics, which should be sufficient.
Note that we won't use the full dataset here as it will take up quite a bit of RAM and processing time, but you're welcome to try doing so on your own later. If interested, you'll likely want to use only some of the more common words for the Tokenizer, which will help shrink processing time and memory needed (or else you'd have an output array hundreds of thousands of words long).
### Preprocessing
```
def tokenize_corpus(corpus, num_words=-1):
# Fit a Tokenizer on the corpus
if num_words > -1:
tokenizer = Tokenizer(num_words=num_words)
else:
tokenizer = Tokenizer()
tokenizer.fit_on_texts(corpus)
return tokenizer
def create_lyrics_corpus(dataset, field):
# Remove all other punctuation
dataset[field] = dataset[field].str.replace('[{}]'.format(string.punctuation), '')
# Make it lowercase
dataset[field] = dataset[field].str.lower()
# Make it one long string to split by line
lyrics = dataset[field].str.cat()
corpus = lyrics.split('\n')
# Remove any trailing whitespace
for l in range(len(corpus)):
corpus[l] = corpus[l].rstrip()
# Remove any empty lines
corpus = [l for l in corpus if l != '']
return corpus
def tokenize_corpus(corpus, num_words=-1):
# Fit a Tokenizer on the corpus
if num_words > -1:
tokenizer = Tokenizer(num_words=num_words)
else:
tokenizer = Tokenizer()
tokenizer.fit_on_texts(corpus)
return tokenizer
# Read the dataset from csv - this time with 250 songs
dataset = pd.read_csv('/tmp/songdata.csv', dtype=str)[:250]
# Create the corpus using the 'text' column containing lyrics
corpus = create_lyrics_corpus(dataset, 'text')
# Tokenize the corpus
tokenizer = tokenize_corpus(corpus, num_words=2000)
total_words = tokenizer.num_words
# There should be a lot more words now
print(total_words)
```
### Create Sequences and Labels
```
sequences = []
for line in corpus:
token_list = tokenizer.texts_to_sequences([line])[0]
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i+1]
sequences.append(n_gram_sequence)
# Pad sequences for equal input length
max_sequence_len = max([len(seq) for seq in sequences])
sequences = np.array(pad_sequences(sequences, maxlen=max_sequence_len, padding='pre'))
# Split sequences between the "input" sequence and "output" predicted word
input_sequences, labels = sequences[:,:-1], sequences[:,-1]
# One-hot encode the labels
one_hot_labels = tf.keras.utils.to_categorical(labels, num_classes=total_words)
```
### Train a (Better) Text Generation Model
With more data, we'll cut off after 100 epochs to avoid keeping you here all day. You'll also want to change your runtime type to GPU if you haven't already (you'll need to re-run the above cells if you change runtimes).
```
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional
model = Sequential()
model.add(Embedding(total_words, 64, input_length=max_sequence_len-1))
model.add(Bidirectional(LSTM(20)))
model.add(Dense(total_words, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(input_sequences, one_hot_labels, epochs=100, verbose=1)
```
### View the Training Graph
```
import matplotlib.pyplot as plt
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.xlabel("Epochs")
plt.ylabel(string)
plt.show()
plot_graphs(history, 'accuracy')
```
### Generate better lyrics!
This time around, we should be able to get a more interesting output with less repetition.
```
seed_text = "im feeling chills"
next_words = 100
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
predicted = np.argmax(model.predict(token_list), axis=-1)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
print(seed_text)
```
### Varying the Possible Outputs
In running the above, you may notice that the same seed text will generate similar outputs. This is because the code is currently always choosing the top predicted class as the next word. What if you wanted more variance in the output?
Switching from `model.predict_classes` to `model.predict_proba` will get us all of the class probabilities. We can combine this with `np.random.choice` to select a given predicted output based on a probability, thereby giving a bit more randomness to our outputs.
```
# Test the method with just the first word after the seed text
seed_text = "im feeling chills"
next_words = 100
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
predicted_probs = model.predict(token_list)[0]
predicted = np.random.choice([x for x in range(len(predicted_probs))],
p=predicted_probs)
# Running this cell multiple times should get you some variance in output
print(predicted)
# Use this process for the full output generation
seed_text = "im feeling chills"
next_words = 100
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
predicted_probs = model.predict(token_list)[0]
predicted = np.random.choice([x for x in range(len(predicted_probs))],
p=predicted_probs)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
print(seed_text)
```
| github_jupyter |
##### Copyright 2019 The TensorFlow Authors.
```
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
```
# Загрузите данные в формате CSV
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/tutorials/load_data/csv"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />Смотрите на TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ru/tutorials/load_data/csv.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Запустите в Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ru/tutorials/load_data/csv.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />Изучайте код на GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ru/tutorials/load_data/csv.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Скачайте ноутбук</a>
</td>
</table>
Note: Вся информация в этом разделе переведена с помощью русскоговорящего Tensorflow сообщества на общественных началах. Поскольку этот перевод не является официальным, мы не гарантируем что он на 100% аккуратен и соответствует [официальной документации на английском языке](https://www.tensorflow.org/?hl=en). Если у вас есть предложение как исправить этот перевод, мы будем очень рады увидеть pull request в [tensorflow/docs](https://github.com/tensorflow/docs) репозиторий GitHub. Если вы хотите помочь сделать документацию по Tensorflow лучше (сделать сам перевод или проверить перевод подготовленный кем-то другим), напишите нам на [docs-ru@tensorflow.org list](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ru).
Этот учебник приводит пример того как выгрузить данные в формате CSV из файла в `tf.data.Dataset`
Данные использованные в этом примере взяты из списка пассажиров Титаника. Модель предскажет вероятность спасения пассажира основываясь на таких характеристиках, как возраст, пол, класс билета и путешествовал ли пассажир один.
## Установка
```
try:
# %tensorflow_version существует только в Colab.
%tensorflow_version 2.x
except Exception:
pass
from __future__ import absolute_import, division, print_function, unicode_literals
import functools
import numpy as np
import tensorflow as tf
TRAIN_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/train.csv"
TEST_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/eval.csv"
train_file_path = tf.keras.utils.get_file("train.csv", TRAIN_DATA_URL)
test_file_path = tf.keras.utils.get_file("eval.csv", TEST_DATA_URL)
# Сделаем значения numpy читабельнее.
np.set_printoptions(precision=3, suppress=True)
```
## Загрузка данных
Для начала давайте посмотрим начало CSV файла, чтобы увидеть как он отформатирован.
```
!head {train_file_path}
```
Вы можете [загрузить данные используя pandas](pandas.ipynb), и передать массивы NumPy в TensorFlow. Если Вам нужно масштабироваться до большого количества файлов или нужен загрузчик который совместим с [TensorFlow и tf.data](../../guide/data,ipynb) то используйте функцию `tf.data.experimental.make_csv_dataset`:
Единственная колонка которую нужно указать явно - это та значение которой вы собиратесь предсказывать с помощью модели.
```
LABEL_COLUMN = 'survived'
LABELS = [0, 1]
```
Сейчас прочитайте данные CSV из файла и создайте датасет.
(Для полной документации см. `tf.data.experimental.make_csv_dataset`)
```
def get_dataset(file_path, **kwargs):
dataset = tf.data.experimental.make_csv_dataset(
file_path,
batch_size=5, # Значение искусственно занижено для удобства восприятия.
label_name=LABEL_COLUMN,
na_value="?",
num_epochs=1,
ignore_errors=True,
**kwargs)
return dataset
raw_train_data = get_dataset(train_file_path)
raw_test_data = get_dataset(test_file_path)
def show_batch(dataset):
for batch, label in dataset.take(1):
for key, value in batch.items():
print("{:20s}: {}".format(key,value.numpy()))
```
Каждый элемент в датасете это пакет представленный в виде кортежа (*много примеров*, *много меток*). Данные из примеров организованы в тензоры столбцы (а не тензоры строки), каждый с таким количеством элементов каков размер пакета (12 в этом случае).
Будет лучше увидеть это вам самим.
```
show_batch(raw_train_data)
```
Как вы видите столбцы в CVS с именами. Конструктор датасета использует эти имена автоматически. Если файл с которым вы работаете не содержит имен столбцов в первой строке передайте их списком строк в аргумент `column_names` функции `make_csv_dataset`.
```
CSV_COLUMNS = ['survived', 'sex', 'age', 'n_siblings_spouses', 'parch', 'fare', 'class', 'deck', 'embark_town', 'alone']
temp_dataset = get_dataset(train_file_path, column_names=CSV_COLUMNS)
show_batch(temp_dataset)
```
Этот пример будет использовать все возможные столбцы. Если не нужны некоторые столбцы в датасете, создайте список только из тех колонок, которые вы планируете использовать и передайте его в (опциональный) аргумент `select_columns` конструктора.
```
SELECT_COLUMNS = ['survived', 'age', 'n_siblings_spouses', 'class', 'deck', 'alone']
temp_dataset = get_dataset(train_file_path, select_columns=SELECT_COLUMNS)
show_batch(temp_dataset)
```
## Препроцессинг данных
CSV файл может содержать множество видов данных. Обычно, перед тем как передать данные в вашу модель, вы хотите преобразовать эти смешанные типы в вектор фиксированной длины.
У TensorFlow есть встроенная система для описания распространенных входных преобразований: `tf.feature_column`, см. [этот учебник](../keras/feature_columns) для подробностей.
Вы можете преобработать ваши данные используя любой инструмент который вам нравится (например [nltk](https://www.nltk.org/) или [sklearn](https://scikit-learn.org/stable/)), и просто передать обработанные данные в TensorFlow.
Главное преимущество предобработки данных внутри вашей модели это то, что когда вы экспортируете модель она включает препроцессинг. В этом случае вы можете передавать необработанные данные прямо в свою модель.
### Непрерывные данные
Если ваши данные уже имеют подходящий числовой формат, вы можете упаковать данные в вектор, прежде чем передать их в модель:
```
SELECT_COLUMNS = ['survived', 'age', 'n_siblings_spouses', 'parch', 'fare']
DEFAULTS = [0, 0.0, 0.0, 0.0, 0.0]
temp_dataset = get_dataset(train_file_path,
select_columns=SELECT_COLUMNS,
column_defaults = DEFAULTS)
show_batch(temp_dataset)
example_batch, labels_batch = next(iter(temp_dataset))
```
Вот простая функция которая упакует вместе все колонки:
```
def pack(features, label):
return tf.stack(list(features.values()), axis=-1), label
```
Примените это к каждому элементу датасета:
```
packed_dataset = temp_dataset.map(pack)
for features, labels in packed_dataset.take(1):
print(features.numpy())
print()
print(labels.numpy())
```
Если у вас смешанные типы данных, то вам может захотеться выделить эти простые числовые поля. API `tf.feature_column` может с этим справиться, но это повлечет за собой накладные расходы, и это стоит делать только если действительно необходимо. Вернитесь к смешанному датасету:
```
show_batch(raw_train_data)
example_batch, labels_batch = next(iter(temp_dataset))
```
Так что выберите более общий препроцессор который выбирает список числовых свойств и упаковывает их в одну колонку:
```
class PackNumericFeatures(object):
def __init__(self, names):
self.names = names
def __call__(self, features, labels):
numeric_freatures = [features.pop(name) for name in self.names]
numeric_features = [tf.cast(feat, tf.float32) for feat in numeric_freatures]
numeric_features = tf.stack(numeric_features, axis=-1)
features['numeric'] = numeric_features
return features, labels
NUMERIC_FEATURES = ['age','n_siblings_spouses','parch', 'fare']
packed_train_data = raw_train_data.map(
PackNumericFeatures(NUMERIC_FEATURES))
packed_test_data = raw_test_data.map(
PackNumericFeatures(NUMERIC_FEATURES))
show_batch(packed_train_data)
example_batch, labels_batch = next(iter(packed_train_data))
```
#### Нормализация данных
Непрерывные данные должны быть всегда нормализованы.
```
import pandas as pd
desc = pd.read_csv(train_file_path)[NUMERIC_FEATURES].describe()
desc
MEAN = np.array(desc.T['mean'])
STD = np.array(desc.T['std'])
def normalize_numeric_data(data, mean, std):
# Центрируем данные
return (data-mean)/std
```
Сейчас создайте числовой столбец. В API `tf.feature_columns.numeric_column` можно использовать аргумент `normalizer_fn` который выполнится на каждом пакете.
Добавьте `MEAN` и `STD` к normalizer fn с помощью [`functools.partial`](https://docs.python.org/3/library/functools.html#functools.partial).
```
# See what you just created.
normalizer = functools.partial(normalize_numeric_data, mean=MEAN, std=STD)
numeric_column = tf.feature_column.numeric_column('numeric', normalizer_fn=normalizer, shape=[len(NUMERIC_FEATURES)])
numeric_columns = [numeric_column]
numeric_column
```
Когда вы обучаете модель добавьте этот столбец признаков чтобы выбрать и центрировать блок числовых данных:
```
example_batch['numeric']
numeric_layer = tf.keras.layers.DenseFeatures(numeric_columns)
numeric_layer(example_batch).numpy()
```
Использованная здесь нормализация на основе среднего требует предварительного знания средних значений каждого столбца.
### Категорийные данные
Некоторые из столбцов в данных CSV являются категорийными. Это значит, что содержимое является одним из ограниченного числа вариантов.
Используйте `tf.feature_column` API чтобы создать коллекцию с `tf.feature_column.indicator_column` для каждого категорийного столбца.
```
CATEGORIES = {
'sex': ['male', 'female'],
'class' : ['First', 'Second', 'Third'],
'deck' : ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
'embark_town' : ['Cherbourg', 'Southhampton', 'Queenstown'],
'alone' : ['y', 'n']
}
categorical_columns = []
for feature, vocab in CATEGORIES.items():
cat_col = tf.feature_column.categorical_column_with_vocabulary_list(
key=feature, vocabulary_list=vocab)
categorical_columns.append(tf.feature_column.indicator_column(cat_col))
# Посмотрите что вы только что создали.
categorical_columns
categorical_layer = tf.keras.layers.DenseFeatures(categorical_columns)
print(categorical_layer(example_batch).numpy()[0])
```
Позже, когда вы создадите модель это станет частью обработки входных данных.
### Комбинированный слой предобработки
Добавьте две коллекции столбцов признаков и передайте их в `tf.keras.layers.DenseFeatures` чтобы создать входной слой который извлечет и предобработает оба входных типа:
```
preprocessing_layer = tf.keras.layers.DenseFeatures(categorical_columns+numeric_columns)
print(preprocessing_layer(example_batch).numpy()[0])
```
## Постройте модель
Постройте `tf.keras.Sequential` начиная с препроцессингового слоя `preprocessing_layer`.
```
model = tf.keras.Sequential([
preprocessing_layer,
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid'),
])
model.compile(
loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
```
## Обучите, оцените и предскажите
Теперь модель может быть реализована и обучена.
```
train_data = packed_train_data.shuffle(500)
test_data = packed_test_data
model.fit(train_data, epochs=20)
```
После того как модель обучена вы можете проверить ее точность на множестве `test_data`.
```
test_loss, test_accuracy = model.evaluate(test_data)
print('\n\nTest Loss {}, Test Accuracy {}'.format(test_loss, test_accuracy))
```
Используйте `tf.keras.Model.predict` чтобы выводить метки на пакет или датасет пакетов.
```
predictions = model.predict(test_data)
# Покажем некоторые результаты
for prediction, survived in zip(predictions[:10], list(test_data)[0][1][:10]):
print("Predicted survival: {:.2%}".format(prediction[0]),
" | Actual outcome: ",
("SURVIVED" if bool(survived) else "DIED"))
```
| github_jupyter |
# Using R to read data and plot
__email__: anne.deslattesmays@nih.gov
(Questions? Feel free to create a new issue in the workshop's github repo [here](https://github.com/NIH-NICHD/Elements-of-Style-Workflow-Creation-Maintenance/issues))
from the command line please do the following
```bash
cd classes/1-intro-to-command-line
wget https://zenodo.org/record/4302133/files/deseq2_5k.csv
```
## Loading libraries
```
devtools::install_github('kevinblighe/EnhancedVolcano')
install.packages("data.table")
library(data.table)
library(EnhancedVolcano)
```
We will utilise the data from from [Bioconductor's Rnaseq Workflow](http://master.bioconductor.org/packages/release/workflows/vignettes/rnaseqGene/inst/doc/rnaseqGene.html). We will see this dataset again a little later from another R package for plotting. For retrieving the results of the differential expression analysis, we will follow the tutorial (from Section 3.1) of the RNA-seq workflow. Specifically, we will load the [airway](https://bioconductor.org/packages/release/data/experiment/html/airway.html) data, where different airway smooth muscle cells were treated with dexamethasone. We will use this dataset to explore different visualisations for presenting differential abundance. While the data we will use are from an RNAseq experiment, we can utilise the same visualisations for other omics data such as proteomics or metabolomics after the relevant preprocessing.
For this course we have uploaded the data in **ZENODO**, to make it easier to use them in the tutorial.
The pre-processed data can be found at: https://doi.org/10.5281/zenodo.4317512
To retrieve the data in your terminal, run the following commands within a **terminal** window
```bash
cd Elements-of-Style-Workflow-Creation-Maintenance/classes/Running-a-JupyterLab-Notebook/
```
```bash
wget https://zenodo.org/record/4317512/files/deseq2_5k.csv
```
```
results <- data.table::fread(file = "deseq2_5k.csv")
```
# Let's inspect the results
We quickly notice the log2FoldChange and adjusted pValue. In a differential expression experiment, these two metrics give us a quick overview of the most interesting measured transcripts of genes.
```
head(results)
```
# Easy volcano plots with `{EnhancedVolcano}` R package 📦
The `{EnhancedVolcano}` R package 📦 has been developed by [Kevin Blighe](https://www.biostars.org/u/41557/) - the name might seem familiar as you might have come across it several times if you find yourselves in [Biostars](https://www.biostars.org/u/41557/) frequently. Kevin Blighe, is not merely a very active Biostars users but also the admin! The `{EnhancedVolcano}` R package, is one very useful R package, as it provides great flexibility and ease for creating publication ready Volcano plots. We will be following the package `vignette`, which can be found [here](https://github.com/kevinblighe/EnhancedVolcano), in the respective GitHub repository.Let's see the package in action!
```
# A minimal function call, for a complete plot
gg<- EnhancedVolcano(toptable = results,
lab = results$feature,
x = 'log2FoldChange',
y = 'pvalue',
xlim = c(-5, 8))
gg
```
# Let's customise the 🌋 plot a bit more
- Modify cut-offs for log2FC and P value
- specify title
- adjust point and label size
```
gg<- EnhancedVolcano::EnhancedVolcano( results,
col=c('grey', 'grey', 'orange', 'purple'),
lab = results$feature,
x = 'log2FoldChange',
y = 'pvalue',
xlim = c(-5, 5),
ylim = c(15,130),
title = 'Differential abundance (untreated with respect to treated cells)',
titleLabSize = 12,
subtitle = '{EnhancedVolcano} for Elements-of-Style Tutorial',
subtitleLabSize = 10,
caption = "Treated vs Untreated with dexamethasone",
captionLabSize = 10,
pCutoff = 10e-16,
FCcutoff = 1.2,
pointSize = 1.0,
labSize = 3.0)
gg
```
# Appendix
## Generating the data we used for the plot
To save some waiting time we loaded the precomputed results from the comparison described above, our set contrast for treated and untreated with dexamethasone muscle cells. You can reproduce this table by running the following code:
```r
# this code snippet is written in markdown, enclosed in ``` and will not be executed
# to run paste in a code cell
library(magrittr)
library('DESeq2')
library(airway)
data('airway')
levels(airway$dex)
airway$dex %<>% relevel('untrt')
levels(airway$dex)
dds <- DESeqDataSet(airway, design = ~ cell + dex)
dds <- DESeq(dds, betaPrior=FALSE)
res1 <- results(dds,contrast = c('dex','trt','untrt'))
subsampled_results <- res1[1:5000,]
subsampled_results$feature <- subsampled_results@rownames
# Subsample and save an object to an Rds and a csv file
saveRDS(subsample_results, file = "deseq2_5k.rds")
loaded_results_RDS <- readRDS(file = "deseq2_5k.rds")
data.table::fwrite(as.data.frame(subsampled_results),
col.names = TRUE,
row.names = FALSE,
file = "../data/2-plotting-in-R/deseq2_5k.csv",
sep =',')
```
| github_jupyter |
#Importing and Unzipping the dataset
```
!unzip "/content/gdrive/My Drive/P14-Convolutional-Neural-Networks.zip"
!ls
```
#Building the neural network
Importing the libraries
```
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Convolution2D
from tensorflow.python.keras.layers import MaxPooling2D
from tensorflow.python.keras.layers import Flatten
from tensorflow.python.keras.layers import Dense
```
Initialising the neural network
```
classifier=Sequential()
```
Building the CNN and adding the layers
Layer 1 : Convolution Layer
```
classifier.add(Convolution2D(32,3,3,input_shape=(64,64,3),activation='relu'))
```
Layer 2: Max Pooling Layer
```
classifier.add(MaxPooling2D(pool_size=(2,2)))
```
Layer 3,4: Adding additional layers to improve accuracy
```
#Here we do not need to add the input shape ,since the input is not images but feature maps ,
#so Keras will know the size of the input feature maps
classifier.add(Convolution2D(32,3,3,activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2,2)))
```
Layer 5: Flattening Layer
```
classifier.add(Flatten())
```
Layer 6: Classic ANN Layer(Full Connection)
```
classifier.add(Dense(128,activation='relu'))
classifier.add(Dense(1,activation='sigmoid'))
#the output layer has only one node , since the output is binary (there are only 2 categories)
```
Compiling the CNN
```
classifier.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
```
#Image Pre-processing
###Data Augmentation for generalisation and preventing over-fitting
Data augmentation is a strategy that enables practitioners to significantly increase the diversity of data available for training models, without actually collecting new data. Data augmentation techniques such as cropping, padding, and horizontal flipping are commonly used to train large neural networks.
```
#We create two seperate objects of the ImageDataGenerator class one for the training set and one for the test set
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
#feature scaling
test_datagen = ImageDataGenerator(rescale=1./255)
```
Augmenting and creating training set
```
training_set = train_datagen.flow_from_directory(
'dataset/training_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
```
Augmenting and creating test set
```
test_set = test_datagen.flow_from_directory(
'dataset/test_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
```
####Notes:
1. Since the data augmentation is random ,it reduces the chances for overfitting ,since no two images are the same.
2.Data augmentation happens in batches, so a certain kind of data augmentation is applied to a batch of images.
3. The setup of the dataset directory is very important . Making a folder for each category proves to be extremely useful and can be directly used for data augmentation and model fitting.
#Fitting the model on the training set and also testing performance on test set simultaneously.
```
classifier.fit_generator(
training_set,
steps_per_epoch=8000,
epochs=25,
validation_data=test_set,
validation_steps=2000)
```
###Notes:
1.To increase the accuracy of the CNN , we can add more number of convolutional layes to the network ,or tweek the parameters of these layers.
2.Also increasing the target size of the images allows the network to capture the features more effectively and efficiently.
3.Data augmentation can be modified and more complex data augmentation operations can be applied on the dataset to increase the accuracy of the network.
| github_jupyter |
# Spatial diagnostics
This notebook is used to create the checkerboard test shown in Fig3 C
## Settings
Here are the settings you can adjust when running this notebook:
- ``num_threads``: If running on a multi-core machine, change this from ``None`` to an ``int`` in order to set the max number of threads to use
- ``feattype``: If you want to run this using RGB features rather than RCF, change this from "random" to "rgb"
- ``subset_[n,feat]``: If you want to subset the training set data for quick tests/debugging, specify that here using the `slice` object. `slice(None)` implies no subsetting of the ~80k observations for each label that are in the training set. `subset_n` slices observations; `subset_feat` subsets features.
- ``overwrite``: By default, this code will raise an error if the file you are saving already exists. If you would like to disable that and overwrite existing data files, change `overwrite` to `True`.
- ``fixed_lambda``: If True, only run the lambda that was previously chosen. Will throw an error if you haven't already generated a results file.
- ``labels_to_run``: By default, this notebook will loop through all the labels. If you would like, you can reduce this list to only loop through a subset of them, by changing ``"all"`` to a list of task names, e.g. ``["housing", "treecover"]``
```
num_threads = None
feattype = "random"
# feattype = "rgb"
subset_n = slice(None)
subset_feat = slice(None)
overwrite = True
fixed_lambda = False
labels_to_run = "all"
```
### Imports
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os
# Import necessary packages
from mosaiks import transforms
from mosaiks.utils.imports import *
from threadpoolctl import threadpool_limits
if num_threads is not None:
threadpool_limits(num_threads)
os.environ["NUMBA_NUM_THREADS"] = str(num_threads)
if overwrite is None:
overwrite = os.getenv("MOSAIKS_OVERWRITE", False)
if labels_to_run == "all":
labels_to_run = c.app_order
```
## Load Random Feature Data
This loads our feature matrix `X` for both POP and UAR samples
```
X = {}
latlons = {}
X["UAR"], latlons["UAR"] = io.get_X_latlon(c, "UAR")
X["POP"], latlons["POP"] = io.get_X_latlon(c, "POP")
```
## Run regressions
The following loop will:
1. Load the appropriate labels
2. Merge them with the feature matrix
3. Remove test set observations
4. Split data into 50/50 train/validation sets, using a checkerboard pattern of various size squares. This will cause training data to be closer or further (geographically) to validation data. It will also offset each checkerboard pattern several times to calculate uncertainty in the performance estimate induced by choosing a checkerboard origin.
5. Run both RBF smoothing and ridge regression (using RCF features) on each train/validation split.
5. Save the out-of-sample predictions for both approaches for use in Figure 3.
```
jitter_pos = c.checkerboard["num_jitter_positions_sqrt"]
prefix_str = "checkerboardJitterInterpolation"
if not (subset_n == slice(None) and subset_feat == slice(None)):
prefix_str += "_SUBSAMPLE"
if overwrite:
print(
"Setting overwrite = False because you are working with a subset of the full feature matrix."
)
overwrite = False
for label in labels_to_run:
print("*** Running regressions for: {}".format(label))
## Set some label-specific variables
this_cfg = io.get_filepaths(c, label, feattype=feattype)
c_app = getattr(this_cfg, label)
sampling_type = c_app["sampling"] # UAR or POP
if c_app["logged"]:
bounds = np.array([c_app["us_bounds_log_pred"]])
else:
bounds = np.array([c_app["us_bounds_pred"]])
# Set solver arguments for image-based features
solver_kwargs_base = {"return_preds": True, "clip_bounds": bounds}
if fixed_lambda:
best_lambda_fpath = join(
this_cfg.fig_dir_sec,
f"checkerboardJitterInterpolation_{label}_{c_app['variable']}_{this_cfg.full_suffix_image}.data",
)
sigmas_rbf = io.get_lambdas(
c,
label,
best_lambda_name="best_sigma_interp",
best_lambda_fpath=best_lambda_fpath,
)
else:
best_lambda_fpath = None
sigmas_rbf = this_cfg.checkerboard["sigmas"]
solver_kwargs_image_CB = {
**solver_kwargs_base,
"lambdas": io.get_lambdas(
c,
label,
lambda_name="lambdas_checkerboard",
best_lambda_name="best_lambda_rcf",
best_lambda_fpath=best_lambda_fpath,
),
"svd_solve": False,
"allow_linalg_warning_instances": False,
"solve_function": solve.ridge_regression,
}
# and for spatial interpolation
solver_kwargs_interpolation_CB = {
**solver_kwargs_base,
"sigmas": sigmas_rbf,
"solve_function": rbf_interpolate.rbf_interpolate_solve,
}
## get X, Y, latlon values of training data
(
this_X,
_,
this_Y,
_,
this_latlons,
_,
) = parse.merge_dropna_transform_split_train_test(
this_cfg, label, X[sampling_type], latlons[sampling_type]
)
## cast latlons to float32 to reduce footprint of RBF smoothing
this_latlons = this_latlons.astype(np.float32)
## subset
this_latlons = this_latlons[subset_n]
this_X = this_X[subset_n, subset_feat]
this_Y = this_Y[subset_n]
## -----------------------------------------------------
# Checkerboard r2 analysis (jitter, sigma-sweep)
## Lat-lon features are done with density estimation (interpolation)
## -----------------------------------------------------
# Run regressions with spatial interpolation and RCF features
metrics_checkered = {}
best_hps = {}
for features, task, solver_kwargs, hp_name, best_hp_name in [
(
this_latlons,
"latlon features sigma tuned",
solver_kwargs_interpolation_CB,
"sigmas",
"best_sigma_interp",
),
(
this_X,
"image_features",
solver_kwargs_image_CB,
"lambdas",
"best_lambda_rcf",
),
]:
print(f"Running {task}...")
results_checkered = spatial_experiments.checkered_predictions_by_radius(
features,
this_Y,
this_latlons,
this_cfg.checkerboard["deltas"],
this_cfg.plotting["extent"],
crit=["r2_score"],
return_hp_idxs=True,
num_jitter_positions_sqrt=jitter_pos,
**solver_kwargs,
)
metrics_checkered[task] = spatial_experiments.results_to_metrics(
results_checkered
)
best_hps[best_hp_name] = np.array(
[solver_kwargs[hp_name][r["hp_idxs_chosen"][0]] for r in results_checkered]
)
# Plot and save
print(f"Plotting and saving output to {this_cfg.fig_dir_sec}...")
spatial_plotter.checkerboard_vs_delta_with_jitter(
metrics_checkered,
best_hps,
this_cfg.checkerboard["deltas"],
"r2_score",
val_name=c_app["variable"],
app_name=label,
prefix=prefix_str,
suffix=this_cfg.full_suffix_image,
save_dir=this_cfg.fig_dir_sec,
overwrite=overwrite,
)
```
| github_jupyter |
> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python.
# 10.1. Analyzing the frequency components of a signal with a Fast Fourier Transform
Download the *Weather* dataset on the book's website. (http://ipython-books.github.io)
The data has been obtained here: http://www.ncdc.noaa.gov/cdo-web/datasets#GHCND.
1. Let's import the packages, including `scipy.fftpack` which includes many FFT-related routines.
```
import datetime
import numpy as np
import scipy as sp
import scipy.fftpack
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
```
2. We import the data from the CSV file. The number `-9999` is used for N/A values. Pandas can easily handle this. In addition, we tell Pandas to parse dates contained in the `DATE` column.
```
df0 = pd.read_csv('data/weather.csv',
na_values=(-9999),
parse_dates=['DATE'])
df = df0[df0['DATE']>='19940101']
df.head()
```
3. Each row contains the precipitation and extremal temperatures recorded one day by one weather station in France. For every date, we want to get a single average temperature for the whole country. The `groupby` method provided by Pandas lets us do that easily. We also remove any NA value.
```
df_avg = df.dropna().groupby('DATE').mean()
df_avg.head()
```
4. Now, we get the list of dates and the list of corresponding temperature. The unit is in tenth of degree, and we get the average value between the minimal and maximal temperature, which explains why we divide by 20.
```
date = df_avg.index.to_datetime()
temp = (df_avg['TMAX'] + df_avg['TMIN']) / 20.
N = len(temp)
```
5. Let's take a look at the evolution of the temperature.
```
plt.figure(figsize=(6,3));
plt.plot_date(date, temp, '-', lw=.5);
plt.ylim(-10, 40);
plt.xlabel('Date');
plt.ylabel('Mean temperature');
```
6. We now compute the Fourier transform and the spectral density of the signal. The first step is to compute the FFT of the signal using the `fft` function.
```
temp_fft = sp.fftpack.fft(temp)
```
7. Once the FFT has been obtained, one needs to take the square of its absolute value to get the **power spectral density** (PSD).
```
temp_psd = np.abs(temp_fft) ** 2
```
8. The next step is to get the frequencies corresponding to the values of the PSD. The `fftfreq` utility function does just that. It takes as input the length of the PSD vector, as well as the frequency unit. Here, we choose an annual unit: a frequency of 1 corresponds to 1 year (365 days). We provide `1./365` because the original unit is in days.
```
fftfreq = sp.fftpack.fftfreq(len(temp_psd), 1./365)
```
9. The `fftfreq` function returns positive and negative frequencies. We are only interested in positive frequencies here since we have a real signal (this will be explained in *How it works...*).
```
i = fftfreq>0
```
10. We now plot the power spectral density of our signal, as a function of the frequency (in unit of `1/year`).
```
plt.figure(figsize=(8,4));
plt.plot(fftfreq[i], 10*np.log10(temp_psd[i]));
plt.xlim(0, 5);
plt.xlabel('Frequency (1/year)');
plt.ylabel('PSD (dB)');
```
We observe a peak for $f=1/year$: this is because the fundamental frequency of the signal is the yearly variation of the temperature.
11. Now, we cut out the frequencies higher than the fundamental frequency.
```
temp_fft_bis = temp_fft.copy()
temp_fft_bis[np.abs(fftfreq) > 1.1] = 0
```
12. The next step is to perform an **inverse FFT** to convert the modified Fourier transform back to the temporal domain. This way, we recover a signal that mainly contains the fundamental frequency, as shown in the figure below.
```
temp_slow = np.real(sp.fftpack.ifft(temp_fft_bis))
plt.figure(figsize=(6,3));
plt.plot_date(date, temp, '-', lw=.5);
plt.plot_date(date, temp_slow, '-');
plt.xlim(datetime.date(1994, 1, 1), datetime.date(2000, 1, 1));
plt.ylim(-10, 40);
plt.xlabel('Date');
plt.ylabel('Mean temperature');
```
> You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
> [IPython Cookbook](http://ipython-books.github.io/), by [Cyrille Rossant](http://cyrille.rossant.net), Packt Publishing, 2014 (500 pages).
| github_jupyter |
```
# This is the sincere effort of Subhodeep, kindly don't copy.
# Data analysis
import pandas as pd
import numpy as np
# Visualisation
import matplotlib.pyplot as plt
# ML tools
from sklearn.ensemble import RandomForestClassifier
#using pandas
#training data
train_ds = pd.read_csv('train.csv')
#testing data
test_ds = pd.read_csv('test.csv')
#combine the above two pandas object into a list to do certain operations on both of them together.
combined = [train_ds, test_ds]
train_ds.head()
test_ds.tail()
train_ds.info()
#INFERENCE
# Survived, Sex, Embarked are categorical data.
# Pclass is categorical too but has 3 classes.
# Rest are continuous data.
# Ticket and Cabin is a mix of letters and numbers.
# All passengers have name.
# All the values of the column Sex are filled.
# Age contains missing values and are of type float64.
#In train dataset
# Cabin, Age, Embarked are empty in some cases.
test_ds.info()
# In test dataset
# Cabin, Age are empty in some cases.
# we need to deal with the missing values.
train_ds.describe() #gives stats of dataset
# Need to fill-in the missing values of Age, Embarked.
# PassengerId, Name is not related to survival, so we'll be dropping them.
# We're dropping cabin feature because it contains high amount of missing data (only 204 out of 891 filled in training dataset),
# Also it's not directly related to survival.
#We need to create features.
#People with same Parch and SibSp must be of same family, so creating a new feature called Family.
#Titles of people can be a new Feature.
#Age range can be mapped into category.
#Same as Age, Fare range can be created.
#Women & Children were more likely to survive.
#Upper-class members survived more.
#Now time to confirm some of our assumptions.
#We choose only the categorical data.
#We choose on the basis of Pclass who survived and who did not.
train_ds[['Pclass', 'Survived']].groupby(['Pclass']).mean().sort_values(by='Survived', ascending=False)
#Our assumption was right, Pclass = 1 survived the most.
train_ds[['Sex','Survived']].groupby(['Sex']).mean().sort_values(by='Survived', ascending=False)
#Female survived the most.
train_ds[['SibSp','Survived']].groupby(['SibSp']).mean().sort_values(by='Survived', ascending = False)
train_ds[['Parch','Survived']].groupby(['Parch']).mean().sort_values(by='Survived', ascending=False)
# SibSp Id = 1 & Parch = 3 survived the most.
#Enough of all the assumptions, now we actually pre-process the data.
# //Testing Codes here for new survivors by adding them to testing dataset
#Sequence -
#PassengerId, Pclass, Name, Sex, Age, SibSp, Parch, Ticket, Fare, Cabin, Embarked
jack = [
1310, #PassengerId
3, # Pclass: 3rd
"Jack Dawson", #Name
"male", # Sex: male
20.0, # Age: 20
0, #Jack had no siblings or spouses aboard (no SibSp)
0, #He had no parent or children too (no Parch)
np.nan, #ticket: no ticket
0.0, # Fare: 0; he won the ticket in gambling
np.nan, # Cabin: No
"S" #Embarked: he boarded at Southampton
]
rose = [
1311, #PassengerId
1, # Pclass: 1st class
"Rose DeWitt Bukater", #Name
"female", # Sex: female
17.0, # Age: 17 yo
1, #SibSp: 1 fiance
1, #Parch: mother, father, 2 children #because she went with only mother and fiance
np.nan, #ticket info not available
512.329200, # Fare: max expensive
np.nan,#"B56", # Cabin: as it's there on the internet.
"S" #Embarked: she boarded at Southampton
]
#movie_chars = pd.DataFrame(columns=[test_ds.columns.values])
#movie_chars.loc[0] = jack
#movie_chars.loc[1] = rose
test_ds.loc[len(test_ds)] = jack
test_ds.loc[len(test_ds)] = rose
#movie_chars.info()
len(test_ds)
test_ds.tail()
#An idea of how the dataset looks before we drop some features.
print('Shape of datasets:',train_ds.shape,test_ds.shape)
#dropping columns(Ticket and Cabin) in training and testing data.
train_ds = train_ds.drop(['Ticket','Cabin'], axis='columns')
test_ds = test_ds.drop(['Ticket','Cabin'], axis = 'columns')
#here instead of axis='columns'(axis= 1) could be used.
# Axis=1 here means it will affect all the rows for the specified columns.
# Axis=0 means it will affect all the columns for the specified rows.
combined = [train_ds, test_ds]
#this combined is the new list containing the modified train_ds and test_ds.
#Lets verify this.
print('Shape of datasets:', train_ds.shape, test_ds.shape)
# At this point we may want to add a new feature namely 'Title', but we might use that if we don't get good accuracy.
#We are dropping columns(Name and PassengerId) similarly as above.
train_ds = train_ds.drop(['Name','PassengerId'],axis=1)
test_ds = test_ds.drop(['Name','PassengerId'],axis=1)
#we combine them into 'combined'
combined = [train_ds, test_ds]
print('Shape of datasets:', train_ds.shape, test_ds.shape)
#Next up we will be mapping the column 'Sex' into numerical categorical feature.
#We will do this in both datasets in one go.
for ds in combined:
ds['Sex'] = ds['Sex'].map({'male':0, 'female':1}).astype(int)
train_ds.head()
test_ds.head()
#We complete the missing Embarked features with the maximum occuring data.
mode = (train_ds.Embarked.dropna().mode())[0] #mode returns an object and we choose the first element hence 0
for ds in combined:
ds['Embarked'] = ds['Embarked'].fillna(mode)
train_ds.head()
# TASK HERE TO MAP EMBARKED TO VALUES----->
#from sklearn.preprocessing import LabelEncoder, OneHotEncoder
#using pandas it's simpler using pandas.get_dummies()
train_ds = pd.get_dummies(train_ds,columns=['Embarked'])
test_ds = pd.get_dummies(test_ds, columns=['Embarked'])
combined = [train_ds, test_ds]
combined[0].head()
combined[1].head()
#To solve the missing age values(works for to fill in the column with numerical continuous features)
# We have 3 approaches listed below.
#1 Generating mean of the existing data and filling.
#2 Try to find correlation b/w Age,Sex,Pclass. Then we guess Age value using median for various combinations of Sex & Pclass (total 6 for 3 Pclass(es) and 2 Sex(es)).
#3 Combination of #1 and #2 i.e. predict a number b/w mean & s.d., using combinations from Sex & Pclass.
# We will choose #1 because it is a simpler approach.
train_ds['Age'].fillna(train_ds['Age'].dropna().mean() ,inplace=True)
test_ds['Age'].fillna(test_ds['Age'].dropna().mean() ,inplace=True)
combined= [train_ds, test_ds]
train_ds.head()
test_ds.head()
# FILLING MISSING FARE VALUES
train_ds.count()
test_ds.count()
#Fare in train_ds is complete, we just need to fill in the test_ds.
test_ds['Fare'].fillna(test_ds['Fare'].dropna().median() ,inplace= True)
test_ds.count()
test_ds.tail()
train_ds.head()
x = train_ds.iloc[:,1:] #All categories except survived (Training Features)
y = train_ds.iloc[:,0] #The survived category (Training Labels)
x.shape
y.shape
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=42)
#This makes sure there is 80% training data and 20% testing data from the total existing training data.
x_train.shape
x_test.shape
y_train.shape
y_test.shape
#Initial testing on a small level using RandomForestClassifier.
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(n_estimators=100)
rf.fit(x_train, y_train)
rf.score(x_test, y_test)
#Fairly a good start because the accuracy lies between somewhat 80~83%.
#Let's try with Decision Tree
from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier(max_leaf_nodes = 50)
dt.fit(x_train, y_train)
dt.score(x_test, y_test)
#similar results as above(80~83%).
#Creating a Neural Network for the above problem
#x_train = np.array(x_train)
#y_train = np.array(y_train).T # For transposing
#Create a Neural Network model
from keras.models import Sequential
model = Sequential()
from keras.layers import Dense, Activation
x_train.shape[0] #This is the number of columns of our dataset.
x_train.shape
#creating input layer and add only one hidden layer
model.add(Dense(x_train.shape[1], init='uniform', input_dim= x_train.shape[1], activation='relu'))
#input_dim is the number of features in input layer
#just after dense(x,...), x is the number of features in the first hidden layer
#adding second hidden layer
model.add(Dense(x_train.shape[1], init='uniform', input_dim=x_train.shape[1], activation='relu'))
#creating output layer
model.add(Dense(1, activation='sigmoid'))
# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
#train model
model.fit(x_train, y_train, epochs=100, batch_size=8)
#Accuracy of training data.
model.evaluate(x_train, y_train)[1]
model.predict(x_test)
#Accuracy of testing data.
model.evaluate(x_test, y_test)[1]
#A fair accuracy of about 83.24% with 2 Hidden layer NN.
# Accuracy can be further increased with normalisation.
# Testing for Rose and Jack
result = model.predict(test_ds)
result
len(result)
jack_chances = result[len(result)-2][0]*100
jack_chances
rose_chances = result[len(result)-1][0]*100
rose_chances
```
| github_jupyter |
```
# Importing required libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
import datetime as dt1
from datetime import datetime as dt
import quandl
import datetime
import scipy
# Getting the google dataset
# and store it in the variable 'df'
API_KEY = str(open('./../API.txt').read()).replace('\n', '')
df = quandl.get("WIKI/GOOG", api_key=API_KEY)
print(df.tail())
# We are gonna use Adj. Close in order to predict the stock
df = df[['Adj. Close']]
df
# forecast_out variable is keeping track of how many days into the future we want to predict
forecast_out = int(30) # 30 days into the future
df['Prediction'] = df[['Adj. Close']].shift(-forecast_out)
# printing a plot to show the evolution of Google stock in time
df['Adj. Close'].plot(figsize=(15, 6), color="green")
# creating the labels
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()
X = np.array(df.drop(['Prediction'], 1))
# scaling our features to normalize data
X = preprocessing.scale(X)
X
X_forecast = X[-forecast_out:] # set X_forecast equal to last 30
X = X[:-forecast_out] # remove last 30 from X
# y is going to be our prediction array
Y = np.array(df['Prediction'])
Y = Y[:-forecast_out]
print(Y)
# we take 20% of the train data and use it for prediction
X_train, X_test, Y_train, Y_test = cross_validation.train_test_split(X, Y, test_size=0.2)
# LINEAR REGRESSION
# Training our algorithm
clf = LinearRegression()
clf.fit(X_train, Y_train)
accuracy = clf.score(X_test, Y_test)
print("Accuracy: ", accuracy)
# showing the last 30 days
forecast_prediction = clf.predict(X_forecast)
print(forecast_prediction)
# Ploting the predicted prices
df.dropna(inplace=True)
# initialiseing a new column called forecast with nan
df['forecast'] = np.nan
last_date = df.iloc[-1].name
last_unix = last_date.timestamp()
one_day = 86400
next_unix = last_unix + one_day
print('Last date: ',last_date)
# print('Last unix: ', last_unix)
# adding predictions to the data frame to create the next 30 days
for i in forecast_prediction:
next_date = datetime.datetime.fromtimestamp(next_unix)
next_unix += one_day
df.loc[next_date] = [np.nan for _ in range(len(df.columns) - 1)] + [i]
df['Adj. Close'].plot(figsize=(15,6), color="green")
df['forecast'].plot(figsize=(15,6), color="red")
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()
# SUPORT VECTOR MACHINE PREDICTION
# initialising lists used for prediction
prices = []
dates = []
# getting data frame
df = quandl.get("WIKI/GOOG")
# selecting only the features I would need
df = df[['Adj. Close']]
df = df.reset_index()
# print(df['Date'].dt.days)
#print(df['Date'])
# print('After conversion')
# for row in df['Date']:
# print(np.datetime64(row))
# dt64 = np.datetime64(row)
# ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
# print(ts)
# interate over rows in pandas
# row[0] - date
# row[1] - price
# scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))
for _, row in df.iterrows():
#dates.append(int(str(row[0]).split('-')[2].split(' ')[0]))
dt64 = np.datetime64(row[0])
# switch to hours
ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 'D')
print(ts)
#print(ts)np.timedelta64(1, 's')
dates.append(ts)
prices.append(float(row[1]))
# normalizing data
#dates = [number/scipy.linalg.norm(dates) for number in dates]
print(dates)
# print(dates)
# print(prices)
# svr_lin = SVR(kernel='linear', C=1e3)
# svr_poly = SVR(kernel='poly', C=1e3, degree=2)
# svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)
# # SV needs a 2D array so I am converting the 1D data to 2D
# dates = np.reshape(dates, (len(dates), 1))
# # start fiting
# svr_rbf.fit(dates, prices)
# svr_lin.fit(dates, prices)
# svr_poly.fit(dates, prices)
# plt.scatter(dates, prices, color= 'black', label= 'Data')
# # plotting the line made by the RBF kernel
# plt.plot(dates, svr_rbf.predict(dates), color= 'red', label= 'RBF model')
# # plotting the line made by linear kernel
# plt.plot(dates,svr_lin.predict(dates), color= 'green', label= 'Linear model')
# # plotting the line made by polynomial kernel
# plt.plot(dates,svr_poly.predict(dates), color= 'blue', label= 'Polynomial model')
# plt.xlabel('Date')
# plt.ylabel('Price')
# plt.title('Support Vector Regression')
# plt.legend()
# plt.show()
# day = 0
# print('SVR RBF: ', svr_rbf.predict(day)[0])
# print('SVR LIN: ',svr_lin.predict(day)[0])
# print('SVR POLY: ', svr_poly.predict(day)[0])
# Getting data
# extracting Features
df = quandl.get("WIKI/GOOG")
print('Before:')
print(df)
df = df[['Open','High','Low','Close','Volume']]
df['HL_PCT']= (df['High'] - df['Close']) / df['Close'] *100
df['PCT_change']= (df['High']-df['Open']) / df['Open'] *100
df=df[['Close','HL_PCT','PCT_change','Volume']]
df.head(3)
print('After:')
print(df)
# Processing data
import math
forecast_col = 'Close'
#no na in data but good practice
df.fillna(-99999, inplace=True)
# I switched to 7 days this time
n=7 #
forecast_out = int(math.ceil(n)) #make n integer
df['label'] = df[forecast_col].shift(-forecast_out)
print(df)
# extracting features
import numpy as np
from sklearn import preprocessing, cross_validation
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
X = np.array(df.drop(['label'],1))
X = preprocessing.scale(X)
X_lately= X[-forecast_out:] #shift the most recent data (e.g. 95-100)
X = X[:-forecast_out] #shift data until beginning of X_lately (e.g. 0-94)
#print(X, len(X))
df.dropna(inplace=True)
y = np.array(df['label'])
#print(len(X)==len(y))
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2)
# applying the algorithmm
clf = LinearRegression(n_jobs=-1)
clf.fit(X_train, y_train)
# measuring accuracy
accuracy = clf.score(X_test, y_test)
print('Accuracy:', accuracy)
# From prev week
accuracy = clf.score(X_test[-10:],y_test[-10:])
print('Accuracy:', accuracy)
# Switching to ensemble learning -> RandomForestRegressor
clf = RandomForestRegressor()
clf.fit(X_train, y_train)
# I observed that the accuracy was decreassing
accuracy = clf.score(X_test, y_test)
print('Accuracy:', accuracy)
import math
import pandas as pd
import numpy as np
from sklearn import preprocessing, cross_validation, cross_decomposition
from sklearn.linear_model import LinearRegression as LR
from sklearn.svm import SVR
from sklearn.neural_network import MLPRegressor as NR
from sklearn.tree import DecisionTreeRegressor as DR
from sklearn.ensemble import RandomForestRegressor as RR
# creating a list of regressors
regressors = [LR(), SVR(), NR(), DR(), RR()]
# storing accuracy to plot it
accuracy = []
# storing prediction
forecast = []
for regressor in regressors:
# fitting the regressor
regressor.fit(X_train, y_train)
# getting the score
a = regressor.score(X_test, y_test)
print('Accuracy of ',str(regressor)[:3], ' is: ', a)
accuracy.append(a)
forecast.append(regressor.predict(X_lately))
import matplotlib.pyplot as plt
from matplotlib import style
%matplotlib inline
import datetime as dt
last_date=df.index[-1]
#print last_date
next_date= last_date + dt.timedelta(days=1)
#print next_date
dates=[]
for i in range(n): #add 7 days
next_date= last_date + dt.timedelta(days=i)
dates.append(next_date)
colors=['r','b','g','m', 'y']
for j in range(len(forecast)):
plt.plot(dates, forecast[j], '-', color=colors[j], label='{0}: {1:.2f}'.format(str(regressors[j])[:3], accuracy[j]));
plt.xticks(rotation=45)
plt.legend(loc='best') #bottom right
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('$n$=7 days prediction of google stocke market using various regressors')
plt.show()
```
| github_jupyter |
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
#export
from exp.nb_02_callbacks import *
```
# Initial Setup
```
x_train, y_train, x_valid, y_valid = get_data(url=MNIST_URL)
train_ds = Dataset(x=x_train, y=y_train)
valid_ds = Dataset(x=x_valid, y=y_valid)
nh = 50
bs = 16
c = y_train.max().item() + 1
loss_func = F.cross_entropy
data = DataBunch(*get_dls(train_ds, valid_ds, bs=bs), c=c)
#export
def create_learner(model_func, loss_func, data):
return Learner(*model_func(data), loss_func, data)
learner = create_learner(get_model, loss_func, data)
run = Runner(cbs=[AvgStatsCallback(metrics=[accuracy])])
run.fit(epochs=3, learner=learner)
learner = create_learner(partial(get_model, lr=0.3), loss_func, data)
run = Runner(cbs=[AvgStatsCallback(metrics=[accuracy])])
run.fit(epochs=3, learner=learner)
#export
def get_model_func(lr=0.5):
return partial(get_model, lr=lr)
```
# Annealing
```
We define two new callbacks:
1. a Recorder: to save track of the loss and our scheduled learning rate
2. a ParamScheduler: that can schedule any hyperparameter as long as it's registered in the state_dict of the optimizer
```
```
#export
class Recorder(Callback):
def begin_fit(self):
self.lrs = []
self.losses = []
def after_batch(self):
if not self.in_train:
return
self.lrs.append(self.opt.param_groups[-1]["lr"])
self.losses.append(self.loss.detach().cpu())
def plot_lr(self):
plt.plot(self.lrs)
def plot_loss(self):
plt.plot(self.losses)
class ParamScheduler(Callback):
_order = 1
def __init__(self, pname, sched_func):
self.pname = pname
self.sched_func = sched_func
def set_param(self):
for pg in self.opt.param_groups:
### print(self.sched_func, self.n_epochs, self.epochs)
pg[self.pname] = self.sched_func(self.n_epochs/self.epochs)
def begin_batch(self):
if self.in_train:
self.set_param()
```
```
Let's start with a simple linear schedule going from start to end.
It returns a function that takes a "pos" argument (going from 0 to 1) such that this function goes from "start" (at pos=0) to "end" (at pos=1) in a linear fashion.
```
```
def sched_linear(start, end, pos):
def _inner(start, end, pos):
return start + (end-start)*pos
return partial(_inner, start, end)
```
```
We can refator the above sched_linear function using decorators so that we donot need to create a separate instance of sched_linear for every pos value
```
```
#export
def annealer(f):
def _inner(start, end):
return partial(f, start, end)
return _inner
@annealer
def sched_linear(start, end, pos):
return start + (end-start)*pos
f = sched_linear(1,2)
f
f(pos=0.3)
f(0.3)
f(0.5)
```
```
Some more important acheduler functions
```
```
#export
@annealer
def sched_cos(start, end, pos):
return start + (end-start) * (1 + math.cos(math.pi*(1-pos))) / 2.
@annealer
def sched_no(start, end, pos):
return start
@annealer
def sched_exp(start, end, pos):
return start * ((end/start) ** pos)
annealings = "NO LINEAR COS EXP".split(" ")
a = torch.arange(start=0, end=100)
p = torch.linspace(start=0.01, end=1, steps=100)
fns = [sched_no, sched_linear, sched_cos, sched_exp]
for fn, t in zip(fns, annealings):
f = fn(start=2, end=1e-2)
plt.plot(a, [f(i) for i in p], label=t)
plt.legend();
### in earlier version of Pytorch, a Tensor object did not had "ndim" attribute
### we can add any attribute to any Python object using property() function.
### here we are adding "ndim" attribute to Tensor object using the below monkey-patching
# torch.Tensor.ndim = property(lambda x: len(x.shape))
```
```
In practice we will want to use multiple schedulers and the below function helps us do that
```
```
#export
def combine_scheds(pcts, scheds):
"""
pcts : list of %ages of each scheduler
scheds: list of all schedulers
"""
assert sum(pcts) == 1
pcts = torch.tensor([0] + listify(pcts))
assert torch.all(pcts >= 0)
pcts = torch.cumsum(input=pcts, dim=0)
def _inner(pos):
"""pos is a value b/w (0,1)"""
idx = (pos >= pcts).nonzero().max()
actual_pos = (pos-pcts[idx]) / (pcts[idx+1]-pcts[idx])
return scheds[idx](pos=actual_pos)
return _inner
### Example of a learning rate scheduler annealing:
### using 30% of training budget to go from 0.3 to 0.6 using cosine scheduler
### using the rest 70% of the trainign budget to go from 0.6 to 0.2 using another cosine scheduler
sched = combine_scheds(pcts=[0.3, 0.7], scheds=[sched_cos(start=0.3, end=0.6), sched_cos(start=0.6, end=0.2)])
plt.plot(a, [sched(i) for i in p])
```
```
We can use it for trainign quite easily.
```
```
cbfs = [Recorder,
partial(AvgStatsCallback, metrics=accuracy),
partial(ParamScheduler, pname="lr", sched_func=sched)]
cbfs
bs=512
data = DataBunch(*get_dls(train_ds, valid_ds, bs), c=c)
learner = create_learner(model_func=get_model_func(lr=0.3), loss_func=loss_func, data=data)
run = Runner(cb_funcs=cbfs)
run.fit(epochs=2, learner=learner)
run.recorder.plot_lr()
run.recorder.plot_loss()
```
# Export
```
!python notebook_to_script.py imflash217__02_anneal.ipynb
pct = [0.3, 0.7]
pct = torch.tensor([0] + listify(pct))
pct = torch.cumsum(pct, 0)
pos = 2
(pos >= pct).nonzero().max()
```
| github_jupyter |
# 📝 Exercise M5.02
The aim of this exercise is to find out whether a decision tree
model is able to extrapolate.
By extrapolation, we refer to values predicted by a model outside of the
range of feature values seen during the training.
We will first load the regression data.
```
import pandas as pd
penguins = pd.read_csv("../datasets/penguins_regression.csv")
data_columns = ["Flipper Length (mm)"]
target_column = "Body Mass (g)"
data_train, target_train = penguins[data_columns], penguins[target_column]
```
<div class="admonition note alert alert-info">
<p class="first admonition-title" style="font-weight: bold;">Note</p>
<p class="last">If you want a deeper overview regarding this dataset, you can refer to the
Appendix - Datasets description section at the end of this MOOC.</p>
</div>
First, create two models, a linear regression model and a decision tree
regression model, and fit them on the training data. Limit the depth at
3 levels for the decision tree.
```
# Write your code here.
from sklearn.linear_model import LinearRegression
linear_model = LinearRegression()
linear_model.fit(data_train, target_train)
linear_target_predicted = linear_model.predict(data_train)
from sklearn.tree import DecisionTreeRegressor
tree = DecisionTreeRegressor(max_depth=3)
tree.fit(data_train, target_train)
tree_target_predicted = tree.predict(data_train)
import matplotlib.pyplot as plt
import seaborn as sns
sns.scatterplot(data=penguins, x="Flipper Length (mm)", y="Body Mass (g)",
color="black", alpha=0.5)
plt.plot(data_train, linear_target_predicted, label="Linear regression", zorder=0)
sns.scatterplot(x=data_train.to_numpy().reshape(-1), y=tree_target_predicted, label="Tree regression", color='orange')
plt.legend()
_ = plt.title("Prediction function using a LinearRegression and a Tree")
```
Create a testing dataset, ranging from the minimum to the maximum of the
flipper length of the training dataset. Get the predictions of each model
using this test dataset.
```
import numpy as np
# Write your code here.
number_of_test_samples = data_train.shape[0]
data_test=np.linspace(data_train.min()[0], data_train.max()[0], number_of_test_samples).reshape(-1,1)
linear_predictions = linear_model.predict(data_test)
tree_predictions = tree.predict(data_test)
```
Create a scatter plot containing the training samples and superimpose the
predictions of both model on the top.
```
# Write your code here.
import matplotlib.pyplot as plt
import seaborn as sns
sns.scatterplot(data=penguins, x="Flipper Length (mm)", y="Body Mass (g)",
color="black", alpha=0.5)
plt.plot(data_test, linear_predictions, label="Linear regression", zorder=0)
sns.scatterplot(x=data_test.reshape(-1), y=tree_predictions, label="Tree regression", color='orange')
plt.legend()
_ = plt.title("Prediction function using a LinearRegression and a Tree")
```
Now, we will check the extrapolation capabilities of each model. Create a
dataset containing the value of your previous dataset. Besides, add values
below and above the minimum and the maximum of the flipper length seen
during training.
```
# Write your code here.
fake_data_test=np.linspace(data_train.min()[0]/2, 2*data_train.max()[0], number_of_test_samples).reshape(-1,1)
linear_predictions = linear_model.predict(fake_data_test)
tree_predictions = tree.predict(fake_data_test)
```
Finally, make predictions with both model on this new testing set. Repeat
the plotting of the previous exercise.
```
# Write your code here.
import matplotlib.pyplot as plt
import seaborn as sns
sns.scatterplot(data=penguins, x="Flipper Length (mm)", y="Body Mass (g)",
color="black", alpha=0.5)
plt.plot(fake_data_test, linear_predictions, label="Linear regression", zorder=0)
sns.scatterplot(x=fake_data_test.reshape(-1), y=tree_predictions, label="Tree regression", color='orange')
plt.legend()
_ = plt.title("Prediction function using a LinearRegression and a Tree")
```
| github_jupyter |
# Non-Gaussian Likelihoods
## Introduction
This example is the simplest form of using an RBF kernel in an `ApproximateGP` module for classification. This basic model is usable when there is not much training data and no advanced techniques are required.
In this example, we’re modeling a unit wave with period 1/2 centered with positive values @ x=0. We are going to classify the points as either +1 or -1.
Variational inference uses the assumption that the posterior distribution factors multiplicatively over the input variables. This makes approximating the distribution via the KL divergence possible to obtain a fast approximation to the posterior. For a good explanation of variational techniques, sections 4-6 of the following may be useful: https://www.cs.princeton.edu/courses/archive/fall11/cos597C/lectures/variational-inference-i.pdf
```
import math
import torch
import gpytorch
from matplotlib import pyplot as plt
%matplotlib inline
```
### Set up training data
In the next cell, we set up the training data for this example. We'll be using 10 regularly spaced points on [0,1] which we evaluate the function on and add Gaussian noise to get the training labels. Labels are unit wave with period 1/2 centered with positive values @ x=0.
```
train_x = torch.linspace(0, 1, 10)
train_y = torch.sign(torch.cos(train_x * (4 * math.pi))).add(1).div(2)
```
## Setting up the classification model
The next cell demonstrates the simplest way to define a classification Gaussian process model in GPyTorch. If you have already done the [GP regression tutorial](../01_Exact_GPs/Simple_GP_Regression.ipynb), you have already seen how GPyTorch model construction differs from other GP packages. In particular, the GP model expects a user to write out a `forward` method in a way analogous to PyTorch models. This gives the user the most possible flexibility.
Since exact inference is intractable for GP classification, GPyTorch approximates the classification posterior using **variational inference.** We believe that variational inference is ideal for a number of reasons. Firstly, variational inference commonly relies on gradient descent techniques, which take full advantage of PyTorch's autograd. This reduces the amount of code needed to develop complex variational models. Additionally, variational inference can be performed with stochastic gradient decent, which can be extremely scalable for large datasets.
If you are unfamiliar with variational inference, we recommend the following resources:
- [Variational Inference: A Review for Statisticians](https://arxiv.org/abs/1601.00670) by David M. Blei, Alp Kucukelbir, Jon D. McAuliffe.
- [Scalable Variational Gaussian Process Classification](https://arxiv.org/abs/1411.2005) by James Hensman, Alex Matthews, Zoubin Ghahramani.
In this example, we're using an `UnwhitenedVariationalStrategy` because we are using the training data as inducing points. In general, you'll probably want to use the standard `VariationalStrategy` class for improved optimization.
```
from gpytorch.models import ApproximateGP
from gpytorch.variational import CholeskyVariationalDistribution
from gpytorch.variational import UnwhitenedVariationalStrategy
class GPClassificationModel(ApproximateGP):
def __init__(self, train_x):
variational_distribution = CholeskyVariationalDistribution(train_x.size(0))
variational_strategy = UnwhitenedVariationalStrategy(
self, train_x, variational_distribution, learn_inducing_locations=False
)
super(GPClassificationModel, self).__init__(variational_strategy)
self.mean_module = gpytorch.means.ConstantMean()
self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel())
def forward(self, x):
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
latent_pred = gpytorch.distributions.MultivariateNormal(mean_x, covar_x)
return latent_pred
# Initialize model and likelihood
model = GPClassificationModel(train_x)
likelihood = gpytorch.likelihoods.BernoulliLikelihood()
```
### Model modes
Like most PyTorch modules, the `ExactGP` has a `.train()` and `.eval()` mode.
- `.train()` mode is for optimizing variational parameters model hyperameters.
- `.eval()` mode is for computing predictions through the model posterior.
## Learn the variational parameters (and other hyperparameters)
In the next cell, we optimize the variational parameters of our Gaussian process.
In addition, this optimization loop also performs Type-II MLE to train the hyperparameters of the Gaussian process.
```
# this is for running the notebook in our testing framework
import os
smoke_test = ('CI' in os.environ)
training_iterations = 2 if smoke_test else 50
# Find optimal model hyperparameters
model.train()
likelihood.train()
# Use the adam optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=0.1)
# "Loss" for GPs - the marginal log likelihood
# num_data refers to the number of training datapoints
mll = gpytorch.mlls.VariationalELBO(likelihood, model, train_y.numel())
for i in range(training_iterations):
# Zero backpropped gradients from previous iteration
optimizer.zero_grad()
# Get predictive output
output = model(train_x)
# Calc loss and backprop gradients
loss = -mll(output, train_y)
loss.backward()
print('Iter %d/%d - Loss: %.3f' % (i + 1, training_iterations, loss.item()))
optimizer.step()
```
## Make predictions with the model
In the next cell, we make predictions with the model. To do this, we simply put the model and likelihood in eval mode, and call both modules on the test data.
In `.eval()` mode, when we call `model()` - we get GP's latent posterior predictions. These will be MultivariateNormal distributions. But since we are performing binary classification, we want to transform these outputs to classification probabilities using our likelihood.
When we call `likelihood(model())`, we get a `torch.distributions.Bernoulli` distribution, which represents our posterior probability that the data points belong to the positive class.
```python
f_preds = model(test_x)
y_preds = likelihood(model(test_x))
f_mean = f_preds.mean
f_samples = f_preds.sample(sample_shape=torch.Size((1000,))
```
```
# Go into eval mode
model.eval()
likelihood.eval()
with torch.no_grad():
# Test x are regularly spaced by 0.01 0,1 inclusive
test_x = torch.linspace(0, 1, 101)
# Get classification predictions
observed_pred = likelihood(model(test_x))
# Initialize fig and axes for plot
f, ax = plt.subplots(1, 1, figsize=(4, 3))
ax.plot(train_x.numpy(), train_y.numpy(), 'k*')
# Get the predicted labels (probabilites of belonging to the positive class)
# Transform these probabilities to be 0/1 labels
pred_labels = observed_pred.mean.ge(0.5).float()
ax.plot(test_x.numpy(), pred_labels.numpy(), 'b')
ax.set_ylim([-1, 2])
ax.legend(['Observed Data', 'Mean'])
```
| github_jupyter |
# Dimension Reduce Cancer
```
import pandas as pd
import numpy as np
import time
import matplotlib.pyplot as plt
import csv
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from sklearn.mixture import GaussianMixture
from sklearn import metrics
from sklearn import preprocessing
from sklearn.cluster import KMeans
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.decomposition import PCA
from sklearn.decomposition import FastICA
from sklearn.decomposition import FactorAnalysis
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
import scipy
from sklearn import random_projection
from cluster_func import em
from cluster_func import kmeans
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer()
X = data.data
# clean out '?' values
X = np.nan_to_num(X)
y = data.target
#Splitting data into training and testing and keeping testing data aside
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2)
#######################################################################################################################
#######################################################################################################################
# Dimensionality reduction PCA
print("Starting FA")
print("Dimensionality reduction")
decisiontree = DecisionTreeClassifier(criterion = 'gini', max_depth = 15, min_samples_split = 5)
fa = FactorAnalysis(max_iter = 100)
pipe = Pipeline(steps=[('fa', fa), ('decisionTree', decisiontree)])
# Plot the PCA spectrum
fa.fit(X)
fig, ax = plt.subplots()
print(list(range(1,X.shape[1])),fa.noise_variance_)
#ax.bar(list(range(1,X.shape[1]+1,int((X.shape[1]+1)/10))), fa.noise_variance_, linewidth=2, color = 'blue')
#ax.bar(list(range(1,X.shape[1])), fa.noise_variance_, linewidth=2, color = 'blue')
ax.bar(np.arange(X.shape[1]), fa.noise_variance_, linewidth=2, color = 'blue')
plt.axis('tight')
plt.xlabel('n_components')
ax.set_ylabel('noise variance')
#Checking the accuracy for taking all combination of components
n_components = range(1, X.shape[1])
# Parameters of pipelines can be set using ‘__’ separated parameter names:
gridSearch = GridSearchCV(pipe, dict(fa__n_components=n_components), cv = 3)
gridSearch.fit(X, y)
results = gridSearch.cv_results_
ax1 = ax.twinx()
#Plotting the accuracies and best component
ax1.plot(results['mean_test_score'], linewidth = 2, color = 'red')
ax1.set_ylabel('Mean Cross Validation Accuracy')
ax1.axvline(gridSearch.best_estimator_.named_steps['fa'].n_components, linestyle=':', label='n_components chosen', linewidth = 2)
plt.legend(prop=dict(size=12))
plt.title('Accuracy/Noise Variance for FA (best n_components= %d)'%gridSearch.best_estimator_.named_steps['fa'].n_components )
plt.show()
#Reducing the dimensions with optimal number of components
fa_new = FactorAnalysis(n_components = gridSearch.best_estimator_.named_steps['fa'].n_components, max_iter = 100)
fa_new.fit(X_train)
X_train_transformed = fa_new.transform(X_train)
X_test_transformed = fa_new.transform(X_test)
###############################################################################################################################
#Reconstruction Error
print("Calculating Reconstruction Error")
def inverse_transform_fa(fa, X_transformed, X_train):
return X_transformed.dot(fa.components_) + np.mean(X_train, axis = 0)
reconstruction_error = []
for comp in n_components:
fa = FactorAnalysis(n_components = comp, max_iter = 100)
X_transformed = fa.fit_transform(X_train)
X_projected = inverse_transform_fa(fa, X_transformed, X_train)
reconstruction_error.append(((X_train - X_projected) ** 2).mean())
if(comp == gridSearch.best_estimator_.named_steps['fa'].n_components):
chosen_error = ((X_train - X_projected) ** 2).mean()
fig2,ax2 = plt.subplots()
ax2.plot(n_components, reconstruction_error, linewidth= 2)
ax2.axvline(gridSearch.best_estimator_.named_steps['fa'].n_components, linestyle=':', label='n_components chosen', linewidth = 2)
plt.axis('tight')
plt.xlabel('Number of components')
plt.ylabel('Reconstruction Error')
plt.title('Reconstruction error for n_components chosen %f '%chosen_error)
plt.show()
################################################################################################################################
#Clustering after dimensionality reduction
print("Clustering FA")
#Reducing the dimensions with optimal number of components
fa_new = FactorAnalysis(n_components = gridSearch.best_estimator_.named_steps['fa'].n_components, max_iter = 100)
fa_new.fit(X)
X_transformed = fa_new.transform(X)
means_init = np.array([X_transformed[y == i].mean(axis=0) for i in range(2)])
#clustering experiments
print("Expected Maximization")
component_list, array_aic, array_bic, array_homo_1, array_comp_1, array_sil_1, array_avg_log = em(X_train_transformed, X_test_transformed, y_train, y_test, init_means = means_init, component_list = [3,4,5,6,7,8,9,10,11], num_class = 2, toshow = 0)
print("KMeans")
component_list, array_homo_2, array_comp_2, array_sil_2, array_var = kmeans(X_train_transformed, X_test_transformed, y_train, y_test, init_means = means_init, component_list = [3,4,5,6,7,8,9,10,11], num_class = 2, toshow = 0)
#Writing data to file
component_list = np.array(component_list).reshape(-1,1)
array_aic = np.array(array_aic).reshape(-1,1)
array_bic = np.array(array_bic).reshape(-1,1)
array_homo_1 = np.array(array_homo_1).reshape(-1,1)
array_comp_1 = np.array(array_comp_1).reshape(-1,1)
array_sil_1 = np.array(array_sil_1).reshape(-1,1)
array_avg_log = np.array(array_avg_log).reshape(-1,1)
array_homo_2 = np.array(array_homo_2).reshape(-1,1)
array_comp_2 = np.array(array_comp_2).reshape(-1,1)
array_sil_2 = np.array(array_sil_2).reshape(-1,1)
array_var = np.array(array_var).reshape(-1,1)
reconstruction_error = np.array(reconstruction_error).reshape(-1,1)
data_em_fa_cancer = np.concatenate((component_list, array_aic, array_bic, array_homo_1, array_comp_1, array_sil_1, array_avg_log), axis =1)
data_km_fa_cancer = np.concatenate((component_list, array_homo_2, array_sil_2, array_var), axis =1)
reconstruction_error_fa_cancer = np.concatenate((np.arange(1,X.shape[1]).reshape(-1,1), reconstruction_error), axis = 1)
file = './data/data_em_fa_cancer.csv'
with open(file, 'w', newline = '') as output:
writer = csv.writer(output, delimiter=',')
writer.writerows(data_em_fa_cancer)
file = './data/data_km_fa_cancer.csv'
with open(file, 'w', newline = '') as output:
writer = csv.writer(output, delimiter=',')
writer.writerows(data_km_fa_cancer)
file = './data/reconstruction_error_fa_cancer.csv'
with open(file, 'w', newline = '') as output:
writer = csv.writer(output, delimiter=',')
writer.writerows(reconstruction_error_fa_cancer)
```
| github_jupyter |
# High-level CNN Keras (TF) Example
*Modified by Jordan A Caraballo Vega (jordancaraballo)*
```
import os
import sys
import numpy as np
os.environ['KERAS_BACKEND'] = "tensorflow"
MULTI_GPU = True
import warnings # make notebook more readable and nice
warnings.filterwarnings('ignore', category=FutureWarning)
warnings.filterwarnings('ignore', category=DeprecationWarning)
from tensorflow.python.util import deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False
import keras as K
import tensorflow
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D, Dropout
from keras.utils import multi_gpu_model
from common.params import *
from common.utils import *
# Force one-gpu
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3"
# Performance Improvement
# 1. Make sure channels-first (not last)
K.backend.set_image_data_format('channels_first')
print("OS: ", sys.platform)
print("Python: ", sys.version)
print("Keras: ", K.__version__)
print("Numpy: ", np.__version__)
print("Tensorflow: ", tensorflow.__version__)
print(K.backend.backend())
print(K.backend.image_data_format())
print("GPU: ", get_gpu_name())
print(get_cuda_version())
print("CuDNN Version ", get_cudnn_version())
CPU_COUNT = multiprocessing.cpu_count()
GPU_COUNT = len(get_gpu_name())
print("CPUs: ", CPU_COUNT)
print("GPUs: ", GPU_COUNT)
def create_symbol(n_classes=N_CLASSES):
model = Sequential()
model.add(Conv2D(50, kernel_size=(3, 3), padding='same', activation='relu',
input_shape=(3, 32, 32)))
model.add(Conv2D(50, kernel_size=(3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(100, kernel_size=(3, 3), padding='same', activation='relu'))
model.add(Conv2D(100, kernel_size=(3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(n_classes, activation='softmax'))
return model
def init_model(m, lr=LR, momentum=MOMENTUM):
m.compile(
loss = "categorical_crossentropy",
optimizer = K.optimizers.SGD(lr, momentum),
metrics = ['accuracy'])
return m
%%time
# Data into format for library
x_train, x_test, y_train, y_test = cifar_for_library(channel_first=True, one_hot=True)
print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)
print(x_train.dtype, x_test.dtype, y_train.dtype, y_test.dtype)
%%time
# Load symbol
if MULTI_GPU:
with tensorflow.device('/cpu:0'):
sym = create_symbol()
model_sym = multi_gpu_model(sym, gpus=GPU_COUNT)
else:
model_sym = create_symbol()
%%time
# Initialise model
model = init_model(model_sym)
model.summary()
%%time
# Main training loop: 1m16s
EPOCHS=40
model.fit(x_train,
y_train,
batch_size=BATCHSIZE,
epochs=EPOCHS,
verbose=1)
%%time
# Main evaluation loop
y_guess = model.predict(x_test, batch_size=BATCHSIZE)
y_guess = np.argmax(y_guess, axis=-1)
y_truth = np.argmax(y_test, axis=-1)
print("Accuracy: ", 1.*sum(y_guess == y_truth)/len(y_guess))
```
| github_jupyter |
```
import re
import csv
import random
import numpy as np
import pandas as pd
import scipy
import scipy.stats as stats
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="whitegrid")
import matplotlib.font_manager as font_manager
import matplotlib.patches as mpatches
from matplotlib.lines import Line2D
import matplotlib.ticker as mtick
import matplotlib.pyplot as plt
import matplotlib as mpl
import os
# fontpath = os.path.expanduser('~/Downloads/LinLibertine_DRah.ttf')
# prop = font_manager.FontProperties(fname=fontpath)
params = {
"axes.titlesize" : 16,
'axes.labelsize': 14,
'font.size': 14,
'legend.fontsize': 14,
'xtick.labelsize': 14,
'ytick.labelsize': 12,
# 'font.family': prop.get_name(),
'text.usetex': True
}
mpl.rcParams.update(params)
siamese_error_analysis_df = pd.read_csv('Analysis/PS_error_analysis.csv')
ss_setup_error_analysis_df = pd.read_csv('Analysis/SS_error_analysis.csv')
def measure_ss_BERT_performance(df):
# results = []
results = [float(x == 'funny') for x in df['predicted_headline_original']]
results.extend([float(x == 'serious') for x in df['predicted_headline_unfunned']])
return np.sum(results) / len(results)
def measure_ss_GPT_performance(df, gpt_threshold=1e-19):
if gpt_threshold is None:
gpt_threshold = (np.mean(df['serious_prob']) + np.mean(df['funny_prob'])) / 2
# results = []
results = [float(x <= gpt_threshold) for x in df['funny_prob']]
results.extend([float(x >= gpt_threshold) for x in df['serious_prob']])
return np.sum(results) / len(results)
```
## Performance broken down by funny / serious
```
def get_probability_percentage(df, f):
df['prob'] = df['funny_prob'] + df['serious_prob']
M = list(df['prob']).copy()
val = sorted(M)[int(f*len(M))]
return df[df['prob'] <= val]
def serious_prob_vs_likelihood_score(test_df, percentages, bootstrap_resamples=10):
x, diff = [], []
for f in percentages:
df_small = get_probability_percentage(test_df, f)
for _ in range(bootstrap_resamples):
df_small = df_small.sample(frac=1, replace=True)
x.append(f)
diff.append(np.log(1e-30 + np.mean(df_small['serious_prob'] - df_small['funny_prob'])))
# funny.append(np.log(np.mean(df_small['serious_prob']))np.log(np.mean(df_small['funny_prob'])))
# serious.append()
res = pd.DataFrame.from_dict({'likelihood-score': x, 'diff': diff})
return res
prob_vs_prob = serious_prob_vs_likelihood_score(ss_setup_error_analysis_df, [x / 10. for x in range(1, 8)])
prob_vs_prob.plot(x='likelihood-score')
```
## Better performance when modification is bigger
```
def get_modification_of_size(df, n):
def is_jaccard_below_f(row):
a = set(row['headline_original'].split(' '))
b = set(row['headline_unfunned'].split(' '))
jaccard_distance = (1 - len(a.intersection(b)) / float(len(a.union(b))))
return jaccard_distance <= n
return df[df.apply(is_jaccard_below_f, axis=1)]
def performance_variation_with_mod_size_paired(test_df, sizes, bootstrap_resamples=100):
x, siamese_bert, gpt2 = [], [], []
for size in sizes:
test_analysis_small = get_modification_of_size(test_df, size)
for _ in range(bootstrap_resamples):
test_small_resamples = test_analysis_small.sample(frac=1, replace=True)
siamese_bert.append(np.sum(test_small_resamples['correct'])/ test_small_resamples.shape[0])
gpt2.append(np.sum(test_small_resamples['GPT2-correct'])/ test_small_resamples.shape[0])
x.append(size)
res = pd.DataFrame.from_dict({'Modification-size (Jaccard)': x, 'Siamese-BERT': siamese_bert, 'GPT2': gpt2})
return res
def performance_variation_with_mod_size_single(test_df, sizes, gpt_threshold=None, bootstrap_resamples=100):
x, ss_bert, ss_gpt2 = [], [], []
for size in sizes:
test_analysis_small = get_modification_of_size(test_df, size)
for _ in range(bootstrap_resamples):
test_small_resamples = test_analysis_small.sample(frac=1, replace=True)
ss_bert.append(measure_ss_BERT_performance(test_small_resamples))
ss_gpt2.append(measure_ss_GPT_performance(test_small_resamples, gpt_threshold=None))
x.append(size)
res = pd.DataFrame.from_dict({'Modification-size (Jaccard)': x, 'SS-BERT': ss_bert, 'SS-GPT2': ss_gpt2})
return res
fs = [x / 10. for x in range(1, 8)]
perf_size_ss = performance_variation_with_mod_size_single(ss_setup_error_analysis_df, fs)
perf_size_ps = performance_variation_with_mod_size_paired(siamese_error_analysis_df, fs)
# sns.set_context('paper')
fig, ax = plt.subplots(1, 1, figsize=(5,5))
# ax = sns.lineplot(data=perf_size_ps, x='Modification-size (Jaccard)', y='Siamese-BERT', ax=ax)
x = perf_size_ss.groupby('Modification-size (Jaccard)').mean().index.to_list()
y = perf_size_ss.groupby('Modification-size (Jaccard)').mean()['SS-BERT'].to_list()
yerr = 5*perf_size_ss.groupby('Modification-size (Jaccard)').sem()['SS-BERT'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-x', mew=2, ms=7, color='tab:red')
x = perf_size_ss.groupby('Modification-size (Jaccard)').mean().index.to_list()
y_gpt = perf_size_ss.groupby('Modification-size (Jaccard)').mean()['SS-GPT2'].to_list()
y_gpt = [y_ + 0.007 for y_ in y_gpt]
yerr = 5*perf_size_ss.groupby('Modification-size (Jaccard)').sem()['SS-GPT2'].to_numpy()
ax.errorbar(x,y_gpt,yerr, elinewidth=2, linewidth=2, fmt='-p', mew=2, ms=7, color='tab:green')
x = perf_size_ps.groupby('Modification-size (Jaccard)').mean().index.to_list()
y = perf_size_ps.groupby('Modification-size (Jaccard)').mean()['Siamese-BERT'].to_list()
yerr = 5*perf_size_ps.groupby('Modification-size (Jaccard)').sem()['Siamese-BERT'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-o', mew=2, ms=7, color='tab:blue')
x = perf_size_ps.groupby('Modification-size (Jaccard)').mean().index.to_list()
y = perf_size_ps.groupby('Modification-size (Jaccard)').mean()['GPT2'].to_list()
yerr = 5*perf_size_ps.groupby('Modification-size (Jaccard)').sem()['GPT2'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-d', mew=2, ms=7, color='tab:gray')
ax.set_ylim(0.5, 0.80)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid(axis='y')
ax.set_xticks(x)
ax.set_yticks([l/100. for l in range(50, 85, 5)])
ax.set_xlabel('Size of modification')
ax.set_ylabel('Accuracy')
legend_elem = [
Line2D([0], [0], marker='x', linewidth=2, ms=9, mew=2, c='tab:red', label='BERT-1S'),
Line2D([0], [0], marker='p', linewidth=2, ms=9, mew=2, c='tab:green', label='GPT2-1S'),
Line2D([0], [0], marker='o', linewidth=2, ms=9, c='tab:blue', label='BERT-PS'),
Line2D([0], [0], marker='d', linewidth=2, ms=9, c='tab:gray', label='GPT2-PS')]
fig.legend(handles=legend_elem, ncol=2, loc='upper center', frameon=False, fontsize=17, bbox_to_anchor=(0.5, 1.15))
fig.tight_layout(pad=1.1)
# fig.savefig("performance_size.pdf", bbox_inches="tight")
# fig.show()
# ax = sns.lineplot(data=perf_size_ps, x='Modification-size (Jaccard)', y='GPT2', ax=ax)
# ax = sns.lineplot(data=perf_size_ps, x='Modification-size (Jaccard)', y='Siamese-BERT', ax=ax)
# ax = sns.lineplot(data=perf_size_ps, x='Modification-size (Jaccard)', y='GPT2', ax=ax)
```
## Better performance for higher prob
```
def performance_vs_prob_paired(test_df, percentages, bootstrap_resamples=100):
x, siamese_bert, gpt2 = [], [], []
for f in percentages:
test_analysis_small = get_probability_percentage(test_df, f)
for _ in range(bootstrap_resamples):
test_small_resamples = test_analysis_small.sample(frac=1, replace=True)
siamese_bert.append(np.sum(test_small_resamples['correct'])/ test_small_resamples.shape[0])
gpt2.append(np.sum(test_small_resamples['GPT2-correct'])/ test_small_resamples.shape[0])
x.append(f)
return pd.DataFrame.from_dict({'Mean-prob': x, 'Siamese-BERT': siamese_bert, 'GPT2': gpt2})
def performance_vs_prob_single(test_df, percentages, bootstrap_resamples=100):
x, ss_bert, ss_gpt2 = [], [], []
for f in percentages:
test_analysis_small = get_probability_percentage(test_df, f)
for _ in range(bootstrap_resamples):
test_small_resamples = test_analysis_small.sample(frac=1, replace=True)
ss_bert.append(measure_ss_BERT_performance(test_small_resamples))
ss_gpt2.append(measure_ss_GPT_performance(test_small_resamples, gpt_threshold=None))
x.append(f)
return pd.DataFrame.from_dict({'Mean-prob': x, 'SS-BERT': ss_bert, 'SS-GPT2': ss_gpt2})
siamese_with_prob = pd.concat([siamese_error_analysis_df, ss_setup_error_analysis_df[['funny_prob', 'serious_prob']]], axis=1)
percentages = [x / 10. for x in range(1, 10)]
perf_prob_ss = performance_vs_prob_single(ss_setup_error_analysis_df, percentages)
perf_prob_ps = performance_vs_prob_paired(siamese_with_prob, percentages)
fig, ax = plt.subplots(1, 1, figsize=(5,5))
# ax = sns.lineplot(data=perf_size_ps, x='Modification-size (Jaccard)', y='Siamese-BERT', ax=ax)
x = perf_prob_ss.groupby('Mean-prob').mean().index.to_list()
y = perf_prob_ss.groupby('Mean-prob').mean()['SS-BERT'].to_list()
yerr = 5*perf_prob_ss.groupby('Mean-prob').sem()['SS-BERT'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-x', mew=2, ms=7, color='tab:red')
x = perf_prob_ss.groupby('Mean-prob').mean().index.to_list()
y_gpt = perf_prob_ss.groupby('Mean-prob').mean()['SS-GPT2'].to_list()
y_gpt = [y_ + 0.007 for y_ in y_gpt]
yerr = 5*perf_prob_ss.groupby('Mean-prob').sem()['SS-GPT2'].to_numpy()
ax.errorbar(x,y_gpt,yerr, elinewidth=2, linewidth=2, fmt='-p', mew=2, ms=7, color='tab:green')
x = perf_prob_ps.groupby('Mean-prob').mean().index.to_list()
y = perf_prob_ps.groupby('Mean-prob').mean()['Siamese-BERT'].to_list()
yerr = 5*perf_prob_ps.groupby('Mean-prob').sem()['Siamese-BERT'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-o', mew=2, ms=7, color='tab:blue')
x = perf_prob_ps.groupby('Mean-prob').mean().index.to_list()
y = perf_prob_ps.groupby('Mean-prob').mean()['GPT2'].to_list()
yerr = 5*perf_prob_ps.groupby('Mean-prob').sem()['GPT2'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-d', mew=2, ms=7, color='tab:gray')
ax.set_ylim(0.5, 0.80)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid(axis='y')
ax.set_xticks(x)
ax.set_yticks([l/100. for l in range(50, 85, 5)])
ax.set_xlabel('Test on sentences in the top x\% most probable')
ax.set_ylabel('Accuracy')
legend_elem = [
Line2D([0], [0], marker='x', linewidth=2, ms=9, mew=2, c='tab:red', label='BERT-1S'),
Line2D([0], [0], marker='p', linewidth=2, ms=9, mew=2, c='tab:green', label='GPT2-1S'),
Line2D([0], [0], marker='o', linewidth=2, ms=9, c='tab:blue', label='BERT-PS'),
Line2D([0], [0], marker='d', linewidth=2, ms=9, c='tab:gray', label='GPT2-PS')]
fig.legend(handles=legend_elem, ncol=2, loc='upper center', frameon=False, fontsize=17, bbox_to_anchor=(0.5, 1.15))
# fig.tight_layout(pad=1.1)
# fig.savefig("performance_prob.pdf", bbox_inches="tight")
fig, axes = plt.subplots(1, 2, figsize=(10,5), sharey=True)
csfont = {'fontname':'Times New Roman'}
m = 6
ax = axes[0]
x = perf_size_ss.groupby('Modification-size (Jaccard)').mean().index.to_list()
y = perf_size_ss.groupby('Modification-size (Jaccard)').mean()['SS-BERT'].to_list()
yerr = m*perf_size_ss.groupby('Modification-size (Jaccard)').sem()['SS-BERT'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-x', mew=2, ms=7, color='tab:red')
x = perf_size_ss.groupby('Modification-size (Jaccard)').mean().index.to_list()
y_gpt = perf_size_ss.groupby('Modification-size (Jaccard)').mean()['SS-GPT2'].to_list()
y_gpt = [y_ + 0.007 for y_ in y_gpt]
yerr = m*perf_size_ss.groupby('Modification-size (Jaccard)').sem()['SS-GPT2'].to_numpy()
ax.errorbar(x,y_gpt,yerr, elinewidth=2, linewidth=2, fmt='-p', mew=2, ms=7, color='tab:green')
x = perf_size_ps.groupby('Modification-size (Jaccard)').mean().index.to_list()
y = perf_size_ps.groupby('Modification-size (Jaccard)').mean()['Siamese-BERT'].to_list()
yerr = m*perf_size_ps.groupby('Modification-size (Jaccard)').sem()['Siamese-BERT'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-o', mew=2, ms=7, color='tab:blue')
x = perf_size_ps.groupby('Modification-size (Jaccard)').mean().index.to_list()
y = perf_size_ps.groupby('Modification-size (Jaccard)').mean()['GPT2'].to_list()
yerr = m*perf_size_ps.groupby('Modification-size (Jaccard)').sem()['GPT2'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-d', mew=2, ms=7, color='tab:gray')
ax.set_ylim(0.5, 0.80)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid(axis='y')
ax.set_xticks(x)
ax.set_yticks([l/100. for l in range(50, 85, 5)])
ax.set_title('(a) Accuracy vs. size of modification', fontsize=24, pad=20, fontname='Helvetica')
ax.set_xlabel('Size of modification', fontsize=22)
ax.set_ylabel('Accuracy', fontsize=22)
ax = axes[1]
x = perf_prob_ss.groupby('Mean-prob').mean().index.to_list()
y = perf_prob_ss.groupby('Mean-prob').mean()['SS-BERT'].to_list()
yerr = m*perf_prob_ss.groupby('Mean-prob').sem()['SS-BERT'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-x', mew=2, ms=7, color='tab:red')
x = perf_prob_ss.groupby('Mean-prob').mean().index.to_list()
y_gpt = perf_prob_ss.groupby('Mean-prob').mean()['SS-GPT2'].to_list()
y_gpt = [y_ + 0.007 for y_ in y_gpt]
yerr = m*perf_prob_ss.groupby('Mean-prob').sem()['SS-GPT2'].to_numpy()
ax.errorbar(x,y_gpt,yerr, elinewidth=2, linewidth=2, fmt='-p', mew=2, ms=7, color='tab:green')
x = perf_prob_ps.groupby('Mean-prob').mean().index.to_list()
y = perf_prob_ps.groupby('Mean-prob').mean()['Siamese-BERT'].to_list()
yerr = m*perf_prob_ps.groupby('Mean-prob').sem()['Siamese-BERT'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-o', mew=2, ms=7, color='tab:blue')
x = perf_prob_ps.groupby('Mean-prob').mean().index.to_list()
y = perf_prob_ps.groupby('Mean-prob').mean()['GPT2'].to_list()
yerr = m*perf_prob_ps.groupby('Mean-prob').sem()['GPT2'].to_numpy()
ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-d', mew=2, ms=7, color='tab:gray')
ax.set_ylim(0.5, 0.80)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid(axis='y')
ax.set_xticks(x)
ax.set_yticks([l/100. for l in range(50, 85, 5)])
ax.set_xlabel('Quantiles of likelihood score', fontsize=22)
ax.set_title('(b) Accuracy vs. likelihood', fontsize=24, pad=20)
# ax.set_ylabel('Accuracy')
legend_elem = [
Line2D([0], [0], marker='x', linewidth=3, ms=10, mew=2, c='tab:red', label='BERT-1S'),
Line2D([0], [0], marker='p', linewidth=3, ms=10, mew=2, c='tab:green', label='GPT2-1S'),
Line2D([0], [0], marker='o', linewidth=3, ms=10, c='tab:blue', label='BERT-PS'),
Line2D([0], [0], marker='d', linewidth=3, ms=10, c='tab:gray', label='GPT2-PS')]
fig.legend(handles=legend_elem, ncol=4, loc='upper center', frameon=False, fontsize=19, bbox_to_anchor=(0.52, 1.05))
fig.tight_layout(pad=1.1)
# fig.savefig("performance_prob_size.pdf", bbox_inches="tight")
```
# Attentions
```
test_df = pd.read_csv('Analysis/test_set_paired.csv')
def load_att_maps(name):
funny_attentions = []
funny_attentions_l = np.load(name + '_funny.npz')
for i in range(len(funny_attentions_l.files)):
funny_attentions.append(funny_attentions_l['arr_' + str(i)])
serious_attentions = []
serious_attentions_l = np.load(name + '_serious.npz')
for i in range(len(serious_attentions_l.files)):
serious_attentions.append(serious_attentions_l['arr_' + str(i)])
return funny_attentions, serious_attentions
funny_attention_bert_base, serious_attention_bert_base = load_att_maps('Analysis/att_map_BERT_base_full')
funny_attention_bert_ss, serious_attention_bert_ss = load_att_maps('Analysis/att_map_BERT_ss_full')
funny_attention_bert_siamese, serious_attention_bert_siamese = load_att_maps('Analysis/att_map_BERT_siamese_full')
```
## Finetuning happens in the last layers
```
from collections import defaultdict
from scipy.spatial import distance
import math
def js_distance_between_heads(head_a, head_b):
seq_len = head_a.shape[0]
js_distances = []
for s in range(seq_len):
js_d = distance.jensenshannon(head_a[s], head_b[s])
if math.isnan(js_d):
continue
js_distances.append(js_d)
return np.mean(js_distances)
def attention_distance_comparison(att_a, att_b):
nb_layers = att_a.shape[0]
nb_heads = att_a.shape[1]
distances = np.zeros((nb_layers, nb_heads))
for l in range(nb_layers):
for h in range(nb_heads):
d_lh = js_distance_between_heads(att_a[l][h], att_b[l][h])
distances[l][h] = d_lh
return distances
def attention_distance_over_examples(lst_att_a, lst_att_b):
att_distances = []
for att_a, att_b in zip(lst_att_a, lst_att_b):
if att_a.shape != att_b.shape:
continue
att_distances.append(attention_distance_comparison(att_a, att_b))
return att_distances
# def convert_to_head_distance(att_distances):
# head_modif = defaultdict(list)
# head_modif_mat = np.zeros(att_distances[0].shape)
# for x in att_distances:
# nb_layers = x.shape[0]
# for i in range(nb_layers):
# nb_heads = x[i].shape[0]
# for h in range(nb_heads):
# head_modif[str(i)+'-'+str(h)] = x[i][h]
# head_modif_mat[i][h] += x[i][h]
# head_modif_mat /= len(att_distances)
# head_diff = {k: np.mean(v) for k, v in head_modif.items()}
# return pd.DataFrame.from_dict({'head': list(head_diff.keys()), 'distance': list(head_diff.values())}), head_modif_mat
def convert_to_layered_distance(att_distances):
# layer_modif = defaultdict(list)
layers, layer_dist = [], []
for x in att_distances:
nb_layers = x.shape[0]
for i in range(nb_layers):
# layer_modif[i].append(np.mean(x[i]))
layer_dist.append(np.mean(x[i]))
layers.append(i)
# layers_diff = {k: np.mean(v) for k, v in layer_modif.items()}
# return pd.DataFrame.from_dict({'layer': list(layers_diff.keys()), 'distance': list(layers_diff.values())})
return pd.DataFrame.from_dict({'layer': layers, 'distance': layer_dist})
attention_bert_base = funny_attention_bert_base.copy()
attention_bert_base.extend(serious_attention_bert_base.copy())
attention_bert_ss = funny_attention_bert_ss.copy()
attention_bert_ss.extend(serious_attention_bert_ss.copy())
attention_bert_siamese = funny_attention_bert_siamese.copy()
attention_bert_siamese.extend(serious_attention_bert_siamese.copy())
att_distance_ss_bert = attention_distance_over_examples(attention_bert_base, attention_bert_ss)
att_distance_siamese_bert = attention_distance_over_examples(attention_bert_base, attention_bert_siamese)
attention_distance_bert_ss_df = convert_to_layered_distance(att_distance_ss_bert)
attention_distance_bert_siamese_df = convert_to_layered_distance(att_distance_siamese_bert)
yerr = 10*attention_distance_bert_siamese_df.groupby('layer').sem()['distance'].to_numpy()
yx = attention_distance_bert_siamese_df[attention_distance_bert_siamese_df['layer'] == 0]['distance']
stats.sem(yx)
fig, ax = plt.subplots(1, 1, figsize=(5,5))
# ax = sns.lineplot(data=perf_size_ps, x='Modification-size (Jaccard)', y='Siamese-BERT', ax=ax)
x = attention_distance_bert_siamese_df.groupby('layer').mean().index.to_list()
y = attention_distance_bert_siamese_df.groupby('layer').mean()['distance'].to_list()
yerr = 10*attention_distance_bert_siamese_df.groupby('layer').sem()['distance'].to_numpy()
# ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-x', mew=2, ms=7, color='tab:red')
ax.errorbar(x,y,yerr, linewidth=2, color='tab:red', alpha=0.85)
x = attention_distance_bert_ss_df.groupby('layer').mean().index.to_list()
y_gpt = attention_distance_bert_ss_df.groupby('layer').mean()['distance'].to_list()
yerr = 10*attention_distance_bert_ss_df.groupby('layer').sem()['distance'].to_numpy()
# ax.errorbar(x,y_gpt,yerr, elinewidth=2, linewidth=2, fmt='-p', mew=2, ms=7, color='tab:blue')
ax.errorbar(x,y_gpt,yerr, linewidth=2, color='tab:blue', alpha=0.85)
# x = perf_prob_ps.groupby('Mean-prob').mean().index.to_list()
# y = perf_prob_ps.groupby('Mean-prob').mean()['Siamese-BERT'].to_list()
# yerr = 5*perf_prob_ps.groupby('Mean-prob').sem()['Siamese-BERT'].to_numpy()
# ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-o', mew=2, ms=7, color='tab:green')
# x = perf_prob_ps.groupby('Mean-prob').mean().index.to_list()
# y = perf_prob_ps.groupby('Mean-prob').mean()['GPT2'].to_list()
# yerr = 5*perf_prob_ps.groupby('Mean-prob').sem()['GPT2'].to_numpy()
# ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-d', mew=2, ms=7, color='tab:gray')
ax.set_ylim(0.0, 0.30)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid(axis='y')
ax.set_xticks([int(i) for i in range(12)])
ax.set_yticks([l/100. for l in range(0, 35, 5)])
ax.set_xticklabels([str(i+1) for i in range(12)])
ax.set_xlabel('Layers', fontsize=22)
ax.set_ylabel('Average attention distance', fontsize=22)
ax.set_title('(a) Attention distance \nto BERT', y=-0.4, fontsize=24)
legend_elem = [
Line2D([0], [0], linewidth=3, c='tab:red', label='distance(BERT-PS, BERT)', alpha=0.85),
Line2D([0], [0], linewidth=3, c='tab:blue', label='distance(BERT-1S, BERT)', alpha=0.85)
]
fig.legend(handles=legend_elem, ncol=1, loc='upper center', frameon=False, fontsize=19, bbox_to_anchor=(0.5, 1.3))
# fig.tight_layout(pad=1.13)
# fig.savefig("distance_to_bert.pdf", bbox_inches="tight")
```
### Difference between funny and serious is in the last layers
```
funny_serious_att_distance_bert = attention_distance_over_examples(funny_attention_bert_base, serious_attention_bert_base)
funny_serious_att_distance_bert_siamese = attention_distance_over_examples(funny_attention_bert_siamese, serious_attention_bert_siamese)
funny_serious_att_distance_bert_ss = attention_distance_over_examples(funny_attention_bert_ss, serious_attention_bert_ss)
funny_serious_att_distance_bert_df = convert_to_layered_distance(funny_serious_att_distance_bert)
funny_serious_att_distance_bert_siamese_df = convert_to_layered_distance(funny_serious_att_distance_bert_siamese)
funny_serious_att_distance_bert_ss_df = convert_to_layered_distance(funny_serious_att_distance_bert_ss)
fig, ax = plt.subplots(1, 1, figsize=(5,5))
# ax = sns.lineplot(data=perf_size_ps, x='Modification-size (Jaccard)', y='Siamese-BERT', ax=ax)
x = funny_serious_att_distance_bert_df.groupby('layer').mean().index.to_list()
y = funny_serious_att_distance_bert_df.groupby('layer').mean()['distance'].to_list()
yerr = 1.96*funny_serious_att_distance_bert_df.groupby('layer').sem()['distance'].to_numpy()
# ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-x', mew=2, ms=7, color='tab:red')
ax.errorbar(x,y,yerr, linewidth=2, color='tab:gray', alpha=0.85)
x = funny_serious_att_distance_bert_siamese_df.groupby('layer').mean().index.to_list()
y_gpt = funny_serious_att_distance_bert_siamese_df.groupby('layer').mean()['distance'].to_list()
yerr = 1.96*funny_serious_att_distance_bert_siamese_df.groupby('layer').sem()['distance'].to_numpy()
# ax.errorbar(x,y_gpt,yerr, elinewidth=2, linewidth=2, fmt='-p', mew=2, ms=7, color='tab:blue')
ax.errorbar(x,y_gpt,yerr, linewidth=2, color='tab:red', alpha=0.85)
x = funny_serious_att_distance_bert_ss_df.groupby('layer').mean().index.to_list()
y_gpt = funny_serious_att_distance_bert_ss_df.groupby('layer').mean()['distance'].to_list()
yerr = 1.96*funny_serious_att_distance_bert_ss_df.groupby('layer').sem()['distance'].to_numpy()
# ax.errorbar(x,y_gpt,yerr, elinewidth=2, linewidth=2, fmt='-p', mew=2, ms=7, color='tab:blue')
ax.errorbar(x,y_gpt,yerr, linewidth=2, color='tab:blue', alpha=0.85)
# x = perf_prob_ps.groupby('Mean-prob').mean().index.to_list()
# y = perf_prob_ps.groupby('Mean-prob').mean()['Siamese-BERT'].to_list()
# yerr = 5*perf_prob_ps.groupby('Mean-prob').sem()['Siamese-BERT'].to_numpy()
# ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-o', mew=2, ms=7, color='tab:green')
# x = perf_prob_ps.groupby('Mean-prob').mean().index.to_list()
# y = perf_prob_ps.groupby('Mean-prob').mean()['GPT2'].to_list()
# yerr = 5*perf_prob_ps.groupby('Mean-prob').sem()['GPT2'].to_numpy()
# ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-d', mew=2, ms=7, color='tab:gray')
ax.set_ylim(0.05, 0.23)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid(axis='y')
ax.set_xticks([int(i) for i in range(12)])
ax.set_xticklabels([str(i+1) for i in range(12)])
ax.set_yticks([l/100. for l in range(5, 25, 3)])
ax.set_xlabel('Layers', fontsize=22)
ax.set_ylabel('Average attention distance', fontsize=22)
ax.set_title('(b) Attention distance between \n funny and serious', y=-0.4, fontsize=24)
legend_elem = [
Line2D([0], [0], linewidth=3, c='tab:gray', label='funny/serious distance for BERT', alpha=0.85),
Line2D([0], [0], linewidth=3, c='tab:red', label='funny/serious distance for BERT-PS', alpha=0.85),
Line2D([0], [0], linewidth=3, c='tab:blue', label='funny/serious distance for BERT-1S', alpha=0.85)
]
fig.legend(handles=legend_elem, ncol=1, loc='upper center', frameon=False, fontsize=19, bbox_to_anchor=(0.50, 1.4))
# fig.tight_layout(pad=1.)
# fig.savefig("funny_serious_distance.pdf", bbox_inches="tight")
```
### Entropy variations with depth
```
def entropy_heads(head):
seq_len = head.shape[0]
entropies = []
for s in range(seq_len):
h = stats.entropy(head[s])
if math.isnan(h):
continue
entropies.append(h)
return np.mean(entropies)
def attention_entropy(att):
nb_layers = att.shape[0]
nb_heads = att.shape[1]
entropies = np.zeros((nb_layers, nb_heads))
for l in range(nb_layers):
for h in range(nb_heads):
d_lh = entropy_heads(att[l][h])
entropies[l][h] = d_lh
return entropies
def attention_entropy_over_examples(lst_att):
att_entropies = []
for att in lst_att:
att_entropies.append(attention_entropy(att))
return att_entropies
att_entropies_base_funny = convert_to_layered_distance(attention_entropy_over_examples(funny_attention_bert_base))
att_entropies_ss_funny = convert_to_layered_distance(attention_entropy_over_examples(funny_attention_bert_ss))
att_entropies_siamese_funny = convert_to_layered_distance(attention_entropy_over_examples(funny_attention_bert_siamese))
att_entropies_base_serious = convert_to_layered_distance(attention_entropy_over_examples(serious_attention_bert_base))
att_entropies_ss_serious = convert_to_layered_distance(attention_entropy_over_examples(serious_attention_bert_ss))
att_entropies_siamese_serious = convert_to_layered_distance(attention_entropy_over_examples(serious_attention_bert_siamese))
base_entropies = att_entropies_base_funny
ss_entropies = att_entropies_ss_funny
siamese_entropies = att_entropies_siamese_funny
# base_entropies = att_entropies_base_serious
# ss_entropies = att_entropies_ss_serious
# siamese_entropies = att_entropies_siamese_serious
fig, ax = plt.subplots(1, 1, figsize=(5,5))
# ax = sns.lineplot(data=perf_size_ps, x='Modification-size (Jaccard)', y='Siamese-BERT', ax=ax)
x = base_entropies.groupby('layer').mean().index.to_list()
y = base_entropies.groupby('layer').mean()['distance'].to_list()
yerr = 4.96*base_entropies.groupby('layer').sem()['distance'].to_numpy()
# ax.errorbar(x,y,yerr, elinewidth=2, linewidth=2, fmt='-x', mew=2, ms=7, color='tab:red')
ax.errorbar(x,y,yerr, linewidth=2, color='tab:gray', alpha=0.85)
x = siamese_entropies.groupby('layer').mean().index.to_list()
y_gpt = siamese_entropies.groupby('layer').mean()['distance'].to_list()
yerr = 4.96*siamese_entropies.groupby('layer').sem()['distance'].to_numpy()
# ax.errorbar(x,y_gpt,yerr, elinewidth=2, linewidth=2, fmt='-p', mew=2, ms=7, color='tab:blue')
ax.errorbar(x,y_gpt,yerr, linewidth=2, color='tab:red', alpha=0.85)
x = ss_entropies.groupby('layer').mean().index.to_list()
y_gpt = ss_entropies.groupby('layer').mean()['distance'].to_list()
yerr = 4.96*ss_entropies.groupby('layer').sem()['distance'].to_numpy()
# ax.errorbar(x,y_gpt,yerr, elinewidth=2, linewidth=2, fmt='-p', mew=2, ms=7, color='tab:blue')
ax.errorbar(x,y_gpt,yerr, linewidth=2, color='tab:blue', alpha=0.85)
ax.set_ylim(0.7, 2.)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid(axis='y')
ax.set_xticks([int(i) for i in range(12)])
ax.set_xticklabels([str(i+1) for i in range(12)])
ax.set_yticks([l/10. for l in range(7, 20, 2)])
ax.set_xlabel('Layers', fontsize=22)
ax.set_ylabel('Average attention entropy', fontsize=22)
legend_elem = [
Line2D([0], [0], linewidth=2, c='tab:gray', label='Entropy for BERT', alpha=0.85),
Line2D([0], [0], linewidth=2, c='tab:red', label='Entropy for BERT-PS', alpha=0.85),
Line2D([0], [0], linewidth=2, c='tab:blue', label='Entropy for BERT-1S', alpha=0.85)
]
fig.legend(handles=legend_elem, ncol=1, loc='upper center', frameon=False, fontsize=18, bbox_to_anchor=(0.55, 1.15))
fig.tight_layout(pad=1.5)
fig.savefig("entropy.pdf", bbox_inches="tight")
x= ['a', 'b', 'c']
x[-2]
```
## Attention Paid to first and last words
```
def attention_pos_head(head):
seq_len = head.shape[0]
special_pos = [1, -2]
attentions_on_first = []
attentions_on_last = []
attentions_on_other = []
attentions_on_spec_tok = []
for s in range(seq_len):
try:
att_first = head[s][1]
att_last = head[s][-2]
att_other = np.sum([head[s][p] for p in range(2, seq_len-2)]) / (len(range(2, seq_len-2)))
att_spe_tok = (head[s][0] + head[s][-1]) / 2.
# if math.isnan(att_res) or math.isinf(att_res):
# continue
# print(att_rest)
except:
print('here')
continue
attentions_on_first.append(att_first)
attentions_on_last.append(att_last)
attentions_on_other.append(att_other)
attentions_on_spec_tok.append(att_spe_tok)
# attention_on_cls.append(att_cls)
return np.mean(attentions_on_first), np.mean(attentions_on_last), np.mean(attentions_on_other), np.mean(attentions_on_spec_tok)
def attention_pos(att):
nb_layers = att.shape[0]
nb_heads = att.shape[1]
attentions_on_first = np.zeros((nb_layers, nb_heads))
attentions_on_last = np.zeros((nb_layers, nb_heads))
attentions_on_other = np.zeros((nb_layers, nb_heads))
attentions_on_spe = np.zeros((nb_layers, nb_heads))
for l in range(nb_layers):
for h in range(nb_heads):
f, l_, o, sp = attention_pos_head(att[l][h])
attentions_on_first[l][h] = f
attentions_on_last[l][h] = l_
attentions_on_other[l][h] = o
attentions_on_spe[l][h] = sp
return attentions_on_first, attentions_on_last, attentions_on_other, attentions_on_spe
def attention_pos_examples(lst_att):
attentions_on_first = []
attentions_on_last = []
attentions_on_other = []
attentions_on_spe = []
for att in lst_att:
f, l, o, sp = attention_pos(att)
attentions_on_first.append(f)
attentions_on_last.append(l)
attentions_on_other.append(o)
attentions_on_spe.append(sp)
return attentions_on_first, attentions_on_last, attentions_on_other, attentions_on_spe
bert_pos_att = attention_pos_examples(funny_attention_bert_base)
ss_pos_att = attention_pos_examples(funny_attention_bert_ss)
siamese_pos_att = attention_pos_examples(funny_attention_bert_siamese)
grid_kws = {"width_ratios": (.75, .25), "hspace": .2}
fig, axes = plt.subplots(1, 2, figsize=(10, 5), gridspec_kw=grid_kws)
ax =axes[0]
x_label = ['On first', 'On last', 'On others', "On ``[SEP]'' and ``[CLS]''"]
w = 0.3
x = np.array([0, 1, 2])
ys = [np.mean(bert_pos_x) for bert_pos_x in bert_pos_att[:3]]
yerr = [3.96*stats.sem(np.array(bert_pos_x).flatten()) for bert_pos_x in bert_pos_att[:3]]
ax.bar(x-w, ys, width=w, yerr=yerr, color='tab:gray', alpha=0.85)
# x = ['On first', 'On Last', 'On other']
ys = [np.mean(bert_pos_x) for bert_pos_x in ss_pos_att[:3]]
yerr = [3.96*stats.sem(np.array(bert_pos_x).flatten()) for bert_pos_x in ss_pos_att[:3]]
ax.bar(x, ys, width=w, yerr=yerr, color='tab:blue', alpha=0.85)
ys = [np.mean(bert_pos_x) for bert_pos_x in siamese_pos_att[:3]]
yerr = [3.96*stats.sem(np.array(bert_pos_x).flatten()) for bert_pos_x in siamese_pos_att[:3]]
ax.bar(x+w, ys, width=w, yerr=yerr, color='tab:red', alpha=0.85)
ax.set_ylim(0.037, .05)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.set_xticklabels(('', '' , 'On first', '', 'On last', '', 'On others'), fontsize=22)
ax = axes[1]
x = np.array([0])
ys = [np.mean(bert_pos_att[3])]
yerr = [3.96*stats.sem(np.array(bert_pos_att[3]).flatten()) ]
ax.bar(x-w, ys, width=w, yerr=yerr, color='tab:gray', alpha=0.85)
# x = ['On first', 'On Last', 'On other']
ys = [np.mean(ss_pos_att[3])]
yerr = [3.96*stats.sem(np.array(ss_pos_att[3]).flatten())]
ax.bar(x, ys, width=w, yerr=yerr, color='tab:blue', alpha=0.85)
ys = [np.mean(siamese_pos_att[3])]
yerr = [3.96*stats.sem(np.array(siamese_pos_att[3]).flatten())]
ax.bar(x+w, ys, width=w, yerr=yerr, color='tab:red', alpha=0.85)
ax.set_ylim(0.25, .30)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.set_xticklabels(('', '' , 'On [SEP] \& [CLS]'), fontsize=22)
legend_elem = [
mpatches.Patch(color='tab:gray', label='BERT', alpha=0.85),
mpatches.Patch(color='tab:red', label='BERT-PS', alpha=0.85),
mpatches.Patch(color='tab:blue', label='BERT-1S', alpha=0.85)
]
fig.legend(handles=legend_elem, ncol=3, loc='upper center', frameon=False, fontsize=22, bbox_to_anchor=(0.45, 1.05))
fig.tight_layout(pad=1.1)
# fig.savefig("att_pos.pdf", bbox_inches="tight")
to_plot = ss_pos_att
on_first, on_last, on_others, _ = to_plot
grid_kws = {"width_ratios": (.30, .30, .35), "hspace": .2}
fig, axes = plt.subplots(1, 3, figsize=(15, 3), sharex=True, sharey=True, gridspec_kw=grid_kws)
# fig, axes = plt.subplots(1, 1)
sns.heatmap(np.mean(np.array(on_first), axis=0), cbar=False, linewidth=0.5, ax=axes[0])
axes[0].set_title('On first', fontsize=16)
sns.heatmap(np.mean(np.array(on_last), axis=0), cbar=False, linewidth=0.5, ax=axes[1])
axes[1].set_title('On last', fontsize=16)
sns.heatmap(np.mean(np.array(on_others), axis=0), linewidth=0.5, ax=axes[2])
axes[2].set_title('On other', fontsize=16)
ax.set_xticklabels([str(i+1) for i in range(12)])
ax.set_yticklabels([str(i+1) for i in range(12)])
# fig.tight_layout(pad=1.1)
# fig.savefig("bert_ss_siamese_funny_serious.pdf", bbox_inches="tight")
```
# Head 9-5
```
def attention_mod_head(head, mod_pos):
seq_len = head.shape[0]
attention_on_chunk = []
attention_on_rest = []
attention_on_sep = []
attention_on_cls = []
for s in range(seq_len):
try:
att_cls = head[s][0]
att_sep = head[s][-1]
att_chunk = np.sum([head[s][p] for p in mod_pos]) / len(mod_pos)
att_rest = (1 - att_chunk - att_cls - att_sep)/ (seq_len - 2 - len(mod_pos))
# if math.isnan(att_res) or math.isinf(att_res):
# continue
# print(att_rest)
except:
print('here')
continue
attention_on_chunk.append(att_chunk)
attention_on_rest.append(att_rest)
attention_on_sep.append(att_sep)
attention_on_cls.append(att_cls)
return np.mean(attention_on_chunk), np.mean(attention_on_rest), np.mean(attention_on_cls), np.mean(attention_on_sep)
def attention_mod(att, mod_pos):
nb_layers = att.shape[0]
nb_heads = att.shape[1]
attentions_on_chunk = np.zeros((nb_layers, nb_heads))
attentions_on_rest = np.zeros((nb_layers, nb_heads))
attentions_on_sep = np.zeros((nb_layers, nb_heads))
attentions_on_cls = np.zeros((nb_layers, nb_heads))
for l in range(nb_layers):
for h in range(nb_heads):
c, r, s, cls = attention_mod_head(att[l][h], mod_pos)
attentions_on_chunk[l][h] = c
attentions_on_rest[l][h] = r
attentions_on_sep[l][h] = s
attentions_on_cls[l][h] = cls
return attentions_on_chunk, attentions_on_rest, attentions_on_sep, attentions_on_cls
def attention_mod_over_examples(lst_att, lst_mod_pos):
attentions_on_chunk = []
attentions_on_rest = []
attentions_on_sep = []
attentions_on_cls = []
for att, mod_pos in zip(lst_att, lst_mod_pos):
c, r, s, cls = attention_mod(att, mod_pos)
attentions_on_chunk.append(c)
attentions_on_rest.append(r)
attentions_on_sep.append(s)
attentions_on_cls.append(cls)
return attentions_on_chunk, attentions_on_rest, attentions_on_sep, attentions_on_cls
def attention_to_list_with_mod_pos(lst_funny_att, lst_serious_att, test_df):
lst_mod_pos = []
lst_reduced_funny_att, lst_reduced_serious_att = [], []
for i in range(test_df.shape[0]):
row = test_df.iloc[i]
funny = row['headline_original'].split(' ')
serious = row['headline_unfunned'].split(' ')
if len(funny) != len(serious):
continue
if len(funny) < 3:
continue
if len(set(funny).symmetric_difference(set(serious))) > 2:
continue
mod_pos = []
for j in range(len(funny)):
if funny[j] != serious[j]:
mod_pos.append(j+1) # Account for the initial token
if len(mod_pos) == 0 or len(mod_pos) > 2:
continue
lst_mod_pos.append(mod_pos)
lst_reduced_funny_att.append(lst_funny_att[i])
lst_reduced_serious_att.append(lst_serious_att[i])
return attention_mod_over_examples(lst_reduced_funny_att, lst_mod_pos), attention_mod_over_examples(lst_reduced_serious_att, lst_mod_pos)
funny_attention_base_pos, serious_attention_base_pos = attention_to_list_with_mod_pos(funny_attention_bert_base, serious_attention_bert_base, test_df)
funny_attention_ss_pos, serious_attention_ss_pos = attention_to_list_with_mod_pos(funny_attention_bert_ss, serious_attention_bert_ss, test_df)
funny_attention_siamese_pos, serious_attention_siamese_pos = attention_to_list_with_mod_pos(funny_attention_bert_siamese, serious_attention_bert_siamese, test_df)
mod_funny, non_mod_funny, _, _ = funny_attention_ss_pos
mod_serious, non_mod_serious, _, _ = serious_attention_ss_pos
# mod_funny, non_mod_funny, _, _ = funny_attention_siamese_pos
# mod_serious, non_mod_serious, _, _ = serious_attention_siamese_pos
# mod_funny, non_mod_funny, _, _ = funny_attention_base_pos
# mod_serious, non_mod_serious, _, _ = serious_attention_base_pos
vmin=0.0
vmax=0.2
grid_kws = {"width_ratios": (.22, .22, .22, .26), "hspace": .2}
fig, axes = plt.subplots(1, 4, figsize=(20, 4), gridspec_kw=grid_kws, sharex=True, sharey=True)
sns.heatmap(np.mean(np.array(mod_funny), axis=0), cbar=False, linewidth=0.5, ax=axes[0], vmin=vmin, vmax=vmax)
axes[0].set_title('(a) Modified chunks\nfunny sentence', fontsize=24)
sns.heatmap(np.mean(np.array(non_mod_funny), axis=0), cbar=False, linewidth=0.5, ax=axes[1], vmin=vmin, vmax=vmax)
axes[1].set_title('(b) Non-modified chunks\nfunny sentence', fontsize=24)
sns.heatmap(np.mean(np.array(mod_serious), axis=0), cbar=False, linewidth=0.5, ax=axes[2], vmin=vmin, vmax=vmax)
axes[2].set_title('(c) ``Modified" chunks\nserious sentence', fontsize=24)
sns.heatmap(np.mean(np.array(non_mod_serious), axis=0), linewidth=0.5, ax=axes[3], vmin=vmin, vmax=vmax)
axes[3].set_title('(d) ``Non-modified" chunks\nserious sentence', fontsize=24)
axes[0].set_yticklabels([str(i+1) for i in range(12)])
axes[0].set_ylabel('Layers', fontsize=23)
[axes[i].set_xlabel('Heads', fontsize=22) for i in range(4)]
a = [axes[i].set_xticklabels([str(i+1) for i in range(12)]) for i in range(4)]
fig.tight_layout(pad=1)
# fig.savefig("ss_mod.pdf", bbox_inches="tight")
grid_kws = {"width_ratios": (.22, .22, .22, .26), "hspace": .2}
fig, axes = plt.subplots(3, 4, figsize=(20, 12), gridspec_kw=grid_kws, sharex=True, sharey=True)
# mod_funny, non_mod_funny, _, _ = funny_attention_ss_pos
# mod_serious, non_mod_serious, _, _ = serious_attention_ss_pos
# mod_funny, non_mod_funny, _, _ = funny_attention_siamese_pos
# mod_serious, non_mod_serious, _, _ = serious_attention_siamese_pos
mod_funny, non_mod_funny, _, _ = funny_attention_base_pos
mod_serious, non_mod_serious, _, _ = serious_attention_base_pos
sns.heatmap(np.mean(np.array(mod_funny), axis=0), cbar=False, linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[0][0])
# axes[0].set_title('Average attention on chunk \n for funny for BERT-1S', fontsize=14)
axes[0][0].set_title('(a) Modified chunk\nfunny sentence', fontsize=24)
sns.heatmap(np.mean(np.array(non_mod_funny), axis=0), cbar=False, linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[0][1])
axes[0][1].set_title('(b) Non-modified chunk\nfunny sentence', fontsize=24)
sns.heatmap(np.mean(np.array(mod_serious), axis=0), cbar=False, linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[0][2])
axes[0][2].set_title('(c) Modified chunk\nserious sentence', fontsize=24)
sns.heatmap(np.mean(np.array(non_mod_serious), axis=0), linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[0][3])
axes[0][3].set_title('(d) Non-modified chunk\nserious sentence', fontsize=24)
axes[0][0].set_yticklabels([str(i+1) for i in range(12)])
axes[0][0].set_ylabel('BERT \n Layers', fontsize=23)
[axes[0][i].set_xlabel('', fontsize=22) for i in range(4)]
a = [axes[0][i].set_xticklabels([str(i+1) for i in range(12)]) for i in range(4)]
mod_funny, non_mod_funny, _, _ = funny_attention_ss_pos
mod_serious, non_mod_serious, _, _ = serious_attention_ss_pos
sns.heatmap(np.mean(np.array(mod_funny), axis=0), cbar=False, linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[1][0])
# axes[0].set_title('Average attention on chunk \n for funny for BERT-1S', fontsize=14)
# axes[1][0].set_title('a) Modified chunk\nfunny sentence', fontsize=22)
sns.heatmap(np.mean(np.array(non_mod_funny), axis=0), cbar=False, linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[1][1])
# axes[1][1].set_title('b) non-modified chunk\nfunny sentence', fontsize=22)
sns.heatmap(np.mean(np.array(mod_serious), axis=0), cbar=False, linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[1][2])
# axes[1][2].set_title('c) modified chunk\nserious sentence', fontsize=22)
sns.heatmap(np.mean(np.array(non_mod_serious), axis=0), linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[1][3])
# axes[1][3].set_title('d) non-modified chunk\nserious sentence', fontsize=22)
axes[1][0].set_yticklabels([str(i+1) for i in range(12)])
axes[1][0].set_ylabel('BERT-1S \n Layers', fontsize=23)
[axes[1][i].set_xlabel('', fontsize=22) for i in range(4)]
a = [axes[1][i].set_xticklabels([str(i+1) for i in range(12)]) for i in range(4)]
mod_funny, non_mod_funny, _, _ = funny_attention_siamese_pos
mod_serious, non_mod_serious, _, _ = serious_attention_siamese_pos
sns.heatmap(np.mean(np.array(mod_funny), axis=0), cbar=False, linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[2][0])
# axes[0].set_title('Average attention on chunk \n for funny for BERT-1S', fontsize=14)
# axes[2][0].set_title('a) Modified chunk\nfunny sentence', fontsize=22)
sns.heatmap(np.mean(np.array(non_mod_funny), axis=0), cbar=False, linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[2][1])
# axes[2][1].set_title('b) non-modified chunk\nfunny sentence', fontsize=22)
sns.heatmap(np.mean(np.array(mod_serious), axis=0), cbar=False, linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[2][2])
# axes[2][2].set_title('c) modified chunk\nserious sentence', fontsize=22)
sns.heatmap(np.mean(np.array(non_mod_serious), axis=0), linewidth=0.5, vmin=0.0, vmax=0.2, ax=axes[2][3])
# axes[2][3].set_title('d) non-modified chunk\nserious sentence', fontsize=22)
axes[2][0].set_yticklabels([str(i+1) for i in range(12)])
axes[2][0].set_ylabel('BERT-PS \n Layers', fontsize=23)
[axes[2][i].set_xlabel('Heads', fontsize=22) for i in range(4)]
a = [axes[2][i].set_xticklabels([str(i+1) for i in range(12)]) for i in range(4)]
fig.tight_layout(pad=1)
# fig.savefig("mod_appendix.pdf", bbox_inches="tight")
grid_kws = {"width_ratios": (.44, .54), "hspace": .2}
fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharex=True, sharey=True, gridspec_kw=grid_kws)
# fig, axes = plt.subplots(1, 1)
sns.heatmap(np.mean(np.array(att_distance_siamese_bert), axis=0), linewidth=0.5, cbar=False,vmin=0.0, vmax=0.3, ax=axes[0])
axes[0].set_title('(a) Attention distance between\n BERT and BERT-PS', fontsize=16)
sns.heatmap(np.mean(np.array(att_distance_ss_bert), axis=0), linewidth=0.5,vmin=0.0, vmax=0.3, ax=axes[1])
axes[1].set_title('(b) Attention distance between\n BERT and BERT-1S', fontsize=16)
axes[0].set_yticklabels([str(i+1) for i in range(12)])
axes[0].set_ylabel('Layers', fontsize=22)
[axes[i].set_xlabel('Heads', fontsize=22) for i in range(2)]
a = [axes[i].set_xticklabels([str(i+1) for i in range(12)]) for i in range(2)]
fig.tight_layout(pad=1.1)
# fig.savefig("bert_ss_siamese_att_distance.pdf", bbox_inches="tight")
grid_kws = {"width_ratios": (.30, .30, .35), "hspace": .2}
# fig, axes = plt.subplots(1, 3, figsize=(8, 3), sharex=True, sharey=True, gridspec_kw=grid_kws)
fig, ax = plt.subplots(1, 1)
sns.heatmap(np.mean(np.array(funny_serious_att_distance_bert_ss), axis=0), linewidth=0.5,vmin=0.0, vmax=0.3, ax=ax)
ax.set_yticklabels([str(i+1) for i in range(12)])
ax.set_ylabel('Layers', fontsize=22)
ax.set_xlabel('Heads', fontsize=22)
ax.set_xticklabels([str(i+1) for i in range(12)])
fig.tight_layout(pad=1.1)
# fig.savefig("bert_ss_funny_serious.pdf", bbox_inches="tight")
for i in range(12):
print(np.sum(np.mean(np.array(funny_serious_att_distance_bert_ss), axis=0)[9][i] / np.sum(np.mean(np.array(funny_serious_att_distance_bert_ss), axis=0)[9])))
grid_kws = {"width_ratios": (.30, .30, .35), "hspace": .2}
fig, axes = plt.subplots(1, 3, figsize=(12, 3), sharex=True, sharey=True, gridspec_kw=grid_kws)
# fig, axes = plt.subplots(1, 1)
sns.heatmap(np.mean(np.array(funny_serious_att_distance_bert), axis=0), linewidth=0.5, cbar=False,vmin=0.0, vmax=0.3, ax=axes[0])
axes[0].set_title('(a) BERT', fontsize=16)
sns.heatmap(np.mean(np.array(funny_serious_att_distance_bert_ss), axis=0), linewidth=0.5,vmin=0.0, cbar=False, vmax=0.3, ax=axes[1])
axes[1].set_title('(b) BERT-1S', fontsize=16)
sns.heatmap(np.mean(np.array(funny_serious_att_distance_bert_siamese), axis=0), linewidth=0.5,vmin=0.0, vmax=0.3, ax=axes[2])
axes[2].set_title('(c) BERT-PS', fontsize=16)
axes[0].set_yticklabels([str(i+1) for i in range(12)])
axes[0].set_ylabel('Layers', fontsize=22)
[axes[i].set_xlabel('Heads', fontsize=22) for i in range(3)]
a = [axes[i].set_xticklabels([str(i+1) for i in range(12)]) for i in range(3)]
fig.tight_layout(pad=1.1)
# fig.savefig("bert_ss_siamese_funny_serious.pdf", bbox_inches="tight")
```
| github_jupyter |
# Transfer Learning on a network, where roads are clustered into classes
```
import time
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import ipdb
import os
import tensorflow as tf
from tensorflow.keras.models import load_model, Model
from tensorflow.keras import backend as K
import tensorflow.keras as keras
from tensorflow.keras.layers import Layer
import dan_models
import dan_utils
from sklearn.manifold import TSNE
physical_devices = tf.config.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], True)
tf.compat.v1.enable_eager_execution()
tf.executing_eagerly()
```
# Load data
```
class_set = [2, 3, 4]
randseed = 25
res = 11
v, v_class, id_402, part1, part2, seg, det_list_class, near_road_set \
= dan_utils.load_data(class_set, res, randseed)
# region = 4
# v_class[region].insert(2, 'lat', None)
# v_class[region].insert(3, 'long', None)
# for i in range(len(v_class[0])):
# id_ = v_class[region].iloc[i, 0]
# lat = id_402.loc[id_402['id']==id_, 'lat'].values[0]
# long = id_402.loc[id_402['id']==id_, 'long'].values[0]
# v_class[region].iloc[i, 2] = lat
# v_class[region].iloc[i, 3] = long
# v_class[region].to_csv('../data/region_data/v_reg_full_%i.csv'%region)
```
### Visulization
```
def plot_dets(det_list_class_i, if_save):
for i in range(len(id_402)):
det_id = id_402.loc[i, 'id']
cls_402 = id_402.loc[i, 'class_i']
try:
cls_det = part1[part1['det'] == det_id]['0'].values[0]
if cls_402 != cls_det:
part1.loc[part1['det'] == det_id, '0'] = cls_402
print(i)
except:
cls_det = part2[part2['det'] == det_id]['0'].values[0]
if cls_402 != cls_det:
part2.loc[part2['det'] == det_id, '0'] = cls_402
print(i)
fig = plt.figure(figsize=[40, 15], dpi=75)
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
for i in range(len(det_list_class_i)):
det_id = det_list_class_i[i]
x = id_402.loc[id_402['id']==det_id, 'lat']
y = id_402.loc[id_402['id']==det_id, 'long']
# ipdb.set_trace()
if det_id in part1['det'].values:
ax1.plot(x, y, marker='+', color='red', markersize=10, markerfacecolor='none')
ax1.text(x-0.005, y, det_id, rotation=45)
elif det_id in part2['det'].values:
ax2.plot(x, y, marker='o', color='red', markersize=10, markerfacecolor='none')
ax2.text(x-0.005, y, det_id, rotation=45)
plt.show()
if if_save:
fig.savefig('../network_classification/img/%i_res%i_class_%i.png'%(randseed, res, class_i_))
print(1)
plt.close()
return
# ind, class
# 0 , blue
# 1 , green
# 2 , yellow <--
# 3 , black <--
# 4 , red <--
class_color_set = ['b', 'g', 'y', 'black', 'r']
class_i_ = 2
plot_dets(det_list_class[class_i_], if_save=0)
```
## Evaluation of 2 datasets
```
def get_NSk(set1, set2):
# designated for v_class1 and 2
set1_v_mean = set1.iloc[:, 2:-1].T.mean().T
set2_v_mean = set2.iloc[:, 2:-1].T.mean().T
var1 = set1_v_mean.std()**2
var2 = set2_v_mean.std()**2
u1 = set1_v_mean.mean()
u2 = set2_v_mean.mean()
return 2*var1 / (var1 + var2 + (u1 - u2)**2)
NSk_set = np.array([])
for i in class_set:
for j in class_set:
if i!=j:
NSk = get_NSk(v_class[i], v_class[j])
NSk_set = np.append(NSk_set, NSk)
print(NSk_set.mean())
```
# 源代码如下 (训练)
# Input classes here
```
# ind, class
# 0 , blue
# 1 , green
# 2 , yellow <--
# 3 , black <--
# 4 , red <--
class_src = 2
v_class1 = v_class[class_src] # source
near_road1 = np.array(near_road_set[class_src])
class_tar = 4
v_class2 = v_class[class_tar] # target
near_road2 = np.array(near_road_set[class_tar])
num_links = v_class1.shape[0]
near_road_src = near_road1
flow_src = v_class1.iloc[:, 2:-1]
prop = 1 # proportion of training data
from_day = 1
to_day = 24
image_train_source, image_test_source, day_train_source, day_test_source, label_train_source, label_test_source\
= dan_utils.sliding_window(
flow_src, near_road_src, from_day, to_day, prop, num_links
)
near_road_tar = near_road2
flow_tar = v_class2.iloc[:, 2:-1]
prop = 3/10
from_day = 22
to_day = 31
image_train_target, image_test_target, day_train_target, day_test_target, label_train_target, label_test_target\
= dan_utils.sliding_window(
flow_tar, near_road_tar, from_day, to_day, prop, num_links
)
dup_mul = image_train_source.shape[0]//image_train_target.shape[0]
dup_r = image_train_source.shape[0]%image_train_target.shape[0]
image_train_target, day_train_target, label_train_target = \
np.concatenate((np.tile(image_train_target, [dup_mul, 1, 1, 1]), image_train_target[:dup_r, :, :, :]), axis=0),\
np.concatenate((np.tile(day_train_target, [dup_mul, 1, 1]), day_train_target[:dup_r, :, :]), axis=0),\
np.concatenate((np.tile(label_train_target, [dup_mul, 1, 1]), label_train_target[:dup_r, :, :]), axis=0),
print(image_train_target.shape)
print(image_test_target.shape)
print(day_train_target.shape)
print(day_test_target.shape)
print(label_train_target.shape)
print(label_test_target.shape)
t_input = image_train_source.shape[2]
t_pre = label_train_source.shape[2]
k = image_train_source.shape[1]
#模型构建
input_data = keras.Input(shape=(k,t_input,num_links), name='input_data')
input_HA = keras.Input(shape=(num_links, t_pre), name='input_HA')
finish_model = dan_models.build_model(input_data, input_HA)
#参数加载
finish_model.load_weights('../model/source_%s.h5'%class_color_set[class_src])
#模型预测
model_pre = finish_model.predict([image_test_target, day_test_target])
#预测结果存储(中间层数据)
dan_utils.save_np(model_pre.reshape(model_pre.shape[0], -1), '../model/middle_res/%i_res%i_modelpre_%s_%s.csv'%(randseed, res, class_color_set[class_src], class_color_set[class_tar]))
#transfer without FT 预测精度计算
m = 5
nrmse_mean = dan_utils.nrmse_loss_func(model_pre, label_test_target, m)
mape_mean = dan_utils.mape_loss_func(model_pre, label_test_target, m)
smape_mean = dan_utils.smape_loss_func(model_pre, label_test_target, m)
mae_mean = dan_utils.mae_loss_func(model_pre, label_test_target, m)
print('nrmse = ' + str(nrmse_mean) + '\n' + 'mape = ' + str(mape_mean) + '\n' + 'smape = ' + str(smape_mean) + '\n' + 'mae = ' + str(mae_mean))
import scipy.stats
def norm_data(data):
min_ = min(data)
max_ = max(data)
normalized_data = data - min_ / (max_ - min_)
return normalized_data
def js_divergence(set1, set2):
p = np.array(set1.iloc[:, 2:-1].T.mean().T)
q = np.array(set2.iloc[:, 2:-1].T.mean().T)
M=(p+q)/2
return 0.5*scipy.stats.entropy(p, M)+0.5*scipy.stats.entropy(q, M)
# return scipy.stats.entropy(p, q) # kl divergence
def get_img_num():
return len(next(iter(os.walk('../model/dan_tsne_img_middle_res/')))[2])
def save_tsne_data(source, target):
N = get_img_num()/2 + 1
ipdb.set_trace()
np.savetxt('source.csv', source, delimiter=',')
np.savetxt('target.csv', target, delimiter=',')
def get_tsne_fig(source, target):
ipdb.set_trace()
pca_tsne = TSNE(n_components=2, random_state=25)
Xs_2D_1 = pca_tsne.fit_transform(source)
Xt_2D_1 = pca_tsne.fit_transform(target)
Xs_2D_1_df = pd.DataFrame(Xs_2D_1, columns=['x1', 'x2'])
Xs_2D_1_df['$X_S/X_T$'] = '$X_S$'
Xt_2D_1_df = pd.DataFrame(Xt_2D_1, columns=['x1', 'x2'])
Xt_2D_1_df['$X_S/X_T$'] = '$X_T$'
X_1 = pd.concat([Xs_2D_1_df, Xt_2D_1_df], axis=0)
X_1.index = range(len(X_1))
fig1 = sns.jointplot(data=X_1, x="x1", y='x2', hue="$X_S/X_T$", kind="kde", levels=5)
fig2 = sns.jointplot(data=X_1, x="x1", y='x2', hue="$X_S/X_T$")
N = get_img_num()/2 + 1
fig1.savefig('../model/dan_tsne_img_middle_res/%i_res%i_countour_%s_%s_shape1=%i_%i.png'\
%(randseed, res, class_color_set[class_src], class_color_set[class_tar], source.shape[1], N))
fig2.savefig('../model/dan_tsne_img_middle_res/%i_res%i_scatter_%s_%s_shape1=%i_%i.png'\
%(randseed, res, class_color_set[class_src], class_color_set[class_tar], target.shape[1], N))
def cal_L2_dist(total):
# ipdb.set_trace()
total_cpu = total
len_ = total_cpu.shape[0]
L2_distance = np.zeros([len_, len_])
for i in range(total_cpu.shape[1]):
total0 = np.broadcast_to(np.expand_dims(total_cpu[:, i], axis=0), (int(total_cpu.shape[0]), int(total_cpu.shape[0])))
total1 = np.broadcast_to(np.expand_dims(total_cpu[:, i], axis=1), (int(total_cpu.shape[0]), int(total_cpu.shape[0])))
# total0 = total_cpu[:, i].unsqueeze(0).expand(int(total_cpu.size(0)), int(total_cpu.size(0)))
# total1 = total_cpu[:, i].unsqueeze(1).expand(int(total_cpu.size(0)), int(total_cpu.size(0)))
L2_dist = (total0 - total1)**2
L2_distance += L2_dist
# ipdb.set_trace()
return L2_distance
def guassian_kernel(source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None):
#source = source.cpu()
#target = target.cpu()
# ipdb.set_trace()
n_samples = int(source.shape[0]*source.shape[1])+int(target.shape[0]*target.shape[1]) # number of samples
total = np.concatenate([source, target], axis=0)
L2_distance = cal_L2_dist(total)
if fix_sigma:
bandwidth = fix_sigma
else:
bandwidth = np.sum(L2_distance.data) / (n_samples**2-n_samples) # 可能出问题
bandwidth /= kernel_mul ** (kernel_num // 2)
bandwidth_list = [bandwidth * (kernel_mul**i) for i in range(kernel_num)]
kernel_val = [np.exp(-L2_distance / bandwidth_temp) for bandwidth_temp in bandwidth_list]
return sum(kernel_val) #/len(kernel_val)
def mmd_rbf_accelerate(source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None):
# ipdb.set_trace()
print(source.shape)
print(target.shape)
batch_size = int(source.size)
kernels = guassian_kernel(source, target,
kernel_mul=kernel_mul, kernel_num=kernel_num, fix_sigma=fix_sigma)
loss = 0
for i in range(batch_size):
s1, s2 = i, (i+1) % batch_size
t1, t2 = s1 + batch_size, s2 + batch_size
loss += kernels[s1, s2] + kernels[t1, t2]
loss -= kernels[s1, t2] + kernels[s2, t1]
# ipdb.set_trace()
return loss / float(batch_size)
def mmd_rbf_noaccelerate(source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None):
# ipdb.set_trace()
# save_tsne_data(source, target)
batch_size = int(source.shape[0]) # ?
kernels = guassian_kernel(source, target,
kernel_mul=kernel_mul, kernel_num=kernel_num, fix_sigma=fix_sigma)
XX = kernels[:batch_size, :batch_size]
YY = kernels[batch_size:, batch_size:]
XY = kernels[:batch_size, batch_size:]
YX = kernels[batch_size:, :batch_size]
# ipdb.set_trace()
loss = np.mean(XX + YY - XY - YX)
return loss
middle1 = Model(inputs=[input_data, input_HA], outputs=finish_model.get_layer('dense_1').output)
middle2 = Model(inputs=[input_data, input_HA], outputs=finish_model.get_layer('dense_2').output)
middle_result_source1 = middle1([image_train_source, day_train_source])
middle_result_target1 = middle1([image_train_target, day_train_target])
middle_result_source2 = middle2([image_train_source, day_train_source])
middle_result_target2 = middle2([image_train_target, day_train_target])
# save intermidiate results
# dan_utils.save_np(middle_result_source1, '../model/middle_res/%i_res%i_middle_result_source1_%s_%s.csv'\
# %(randseed, res, class_color_set[class_src], class_color_set[class_tar]))
# dan_utils.save_np(middle_result_target1, '../model/middle_res/%i_res%i_middle_result_target1_%s_%s.csv'\
# %(randseed, res, class_color_set[class_src], class_color_set[class_tar]))
# dan_utils.save_np(middle_result_source2, '../model/middle_res/%i_res%i_middle_result_source2_%s_%s.csv'\
# %(randseed, res, class_color_set[class_src], class_color_set[class_tar]))
# dan_utils.save_np(middle_result_target2, '../model/middle_res/%i_res%i_middle_result_target2_%s_%s.csv'\
# %(randseed, res, class_color_set[class_src], class_color_set[class_tar]))
def new_loss(output_final, label_train_target):
lamb = js_divergence(v_class1.iloc[:, 2:-1], v_class2.iloc[:, 2:-1])
# lamb = 0
loss0 = K.mean(K.square(output_final - label_train_target), axis=-1)
# ipdb.set_trace()
loss1 = mmd_rbf_noaccelerate(middle_result_source1, middle_result_target1)
loss2 = mmd_rbf_noaccelerate(middle_result_source2, middle_result_target2)
# loss2 = lamb * ( mmd(middle_result_source1, middle_result_target1) + mmd(middle_result_source2, middle_result_target2) )
# loss2 = 0.001 * mmd(middle_result_source2, middle_result_target2)
# print('Lambda is %.4f'%lamb)
print(middle_result_source1.shape)
print(middle_result_target1.shape)
overall_loss = loss0 + lamb* (loss1 + loss2)
return overall_loss
finish_model.compile(optimizer='adam', loss=new_loss)
# middle_result_source1 = middle1([image_train_source, day_train_source])
# middle_result_target1 = middle1([image_train_target, day_train_target])
# get_tsne_fig(middle_result_source1, middle_result_target1)
finish_model.fit([image_train_target, day_train_target], label_train_target, epochs=300, batch_size=4620,
validation_data=([image_test_target,day_test_target], label_test_target))
model_pre = finish_model.predict([image_test_target, day_test_target])
#transfer with DAN 预测精度计算
nrmse_mean = dan_utils.nrmse_loss_func(model_pre, label_test_target, m)
mape_mean = dan_utils.mape_loss_func(model_pre, label_test_target, m)
smape_mean = dan_utils.smape_loss_func(model_pre, label_test_target, m)
mae_mean = dan_utils.mae_loss_func(model_pre, label_test_target, m)
print('nrmse = ' + str(nrmse_mean) + '\n' + 'mape = ' + str(mape_mean) + '\n' + 'smape = ' + str(smape_mean) + '\n' + 'mae = ' + str(mae_mean))
#模型保存
finish_model.save_weights('../model/transfer_DAN_%s_%s_mape=%.5f_nrmse=%.5f.h5'%(class_color_set[class_src], class_color_set[class_tar], mape_mean, nrmse_mean))
mape_list = []
for i in range(num_links):
a1 = dan_utils.mape_loss_func(model_pre[:,i,:], label_test_target[:,i,:], m)
mape_list.append(a1)
mape_pd = pd.Series(mape_list)
mape_pd.sort_values()
plt.plot(model_pre[:, 0, 0])
plt.plot(label_test_target[:, 0, 0])
mape_set = []
for i in range(25):
for j in range(3):
plt.figure()
plt.plot(model_pre[:, i, j])
plt.plot(label_test_target[:, i, j])
mape = dan_utils.mape_loss_func(model_pre[:, i, j], label_test_target[:, i, j], m)
mape_set.append(mape)
plt.title('%i%i,mape=%.3f'%(i, j, mape))
```
| github_jupyter |
# Figure S1: Global optimization over parameters
This notebook contains the analysis of a direct global opimization over all four parameters ($p, q, c_{\rm constitutive}, p_{\rm uptake}$) of the model as a function of the pathogen statistics. It can be thought of as a supplement to Figure 1, motivating the choice of immune strategies considered for determining the phase boundaries.
Prerequisites:
To generate the data type:
make run
make agg
This notebook also needs the phase data from Figure 2.
Import a number of packages that we will need in the following.
```
import sys
sys.path.append('../lib/')
import numpy as np
import matplotlib.text
import matplotlib.pyplot as plt
from matplotlib import cm
%matplotlib inline
import shapely.ops
import plotting
import evolimmune
from plotting import *
import analysis
%load_ext autoreload
%autoreload 2
plt.style.use(['paper'])
eps = 1e-8
```
Load phase boundary data
```
df = analysis.loadnpz('../fig2/data/phases.npz')
polygons = evolimmune.polygons_from_boundaries(df, yconv=evolimmune.to_tau)
phases = evolimmune.phases_from_polygons(polygons)
qpos = (polygons['complete']-polygons['ac'])-polygons['pm'].intersection(polygons['pi'])-(polygons['complete']-polygons['io'])
puppos = polygons['complete']-shapely.ops.cascaded_union((polygons['ac'],
polygons['pm'],
polygons['complete']-polygons['mi']))
analysis.printunique(df)
```
Load optimization data
```
dft = analysis.loadnpz('data/opt.npz')
evolimmune.derived_quantities(dft)
analysis.printunique(dft)
```
Put it all together and produce the final figure
```
variables = ['cconstitutive', 'q', 'p', 'pup']
fig, axesgrid = plt.subplots(nrows=2, ncols=2, figsize=(7, 5.0), sharey=True, sharex=True)
ymin, ymax = 0.09, 20.0
axes = axesgrid.flatten()
boundarykwargs = dict(ylimmax=ymax, ylimmin=ymin, lw=7.5, color='w')
for counter, var in enumerate(variables):
ax = axes[counter]
cmap = cm.viridis if var != 'cconstitutive' else cm.viridis_r
cmap.set_bad('darkmagenta', 1.)
im, cbar = plotting.heatmap(dft.pivot(index='tauenv', columns='pienv', values=var),
imshow=True, zlabel=evolimmune.varname_to_tex[var], cmap=cmap, ax=ax,
interpolation='bilinear')
cbar.outline.set_linewidth(0.0)
if var == 'cconstitutive':
analysis.plot_interior_boundary(ax, phases['p'], **boundarykwargs)
analysis.plot_interior_boundary(ax, phases['a'], **boundarykwargs)
elif var in ['q', 'p']:
analysis.plot_interior_boundary(ax, qpos, **boundarykwargs)
if var == 'p':
analysis.plot_interior_boundary(ax, phases['c'], **boundarykwargs)
elif var == 'pup':
analysis.plot_interior_boundary(ax, puppos, **boundarykwargs)
ax.set_ylabel('')
ax.set_xlabel('')
ax.set_xlim(0.0, 1.0)
ax.set_ylim(ymin, ymax)
ax.set_yscale('log')
plotting.despine(ax, spines='all')
for ax in axesgrid[:, 0]:
ax.set_ylabel(r'characteristic time $\tau_{env}$')
for ax in axesgrid[-1, :]:
ax.set_xlabel('frequency $\pi_{env}$')
fig.tight_layout(pad=0.25)
fig.savefig('SIopt.pdf')
fig.savefig('SIopt.svg')
```
**Optimal parameters from a global optimization of long-term growth rate.** Regions where a parameter is unconstrained at the optimum are shown in purple. Phase boundaries pertaining to the shown parameter in white. A maximum number of 10000 function evaluations is used for the first phase of the optimization. The same model parameters as in Fig. 2 are used.
| github_jupyter |
# 3 - Faster Sentiment Analysis
In the previous notebook we managed to achieve a decent test accuracy of ~85% using all of the common techniques used for sentiment analysis. In this notebook, we'll implement a model that gets comparable results whilst training significantly faster. More specifically, we'll be implementing the "FastText" model from the paper [Bag of Tricks for Efficient Text Classification](https://arxiv.org/abs/1607.01759).
## Preparing Data
One of the key concepts in the FastText paper is that they calculate the n-grams of an input sentence and append them to the end of a sentence. Here, we'll use bi-grams. Briefly, a bi-gram is a pair of words/tokens that appear consecutively within a sentence.
For example, in the sentence "how are you ?", the bi-grams are: "how are", "are you" and "you ?".
The `generate_bigrams` function takes a sentence that has already been tokenized, calculates the bi-grams and appends them to the end of the tokenized list.
```
def generate_bigrams(x):
n_grams = set(zip(*[x[i:] for i in range(2)]))
for n_gram in n_grams:
x.append(' '.join(n_gram))
return x
```
As an example:
```
generate_bigrams(['This', 'film', 'is', 'terrible'])
```
TorchText `Field`s have a `preprocessing` argument. A function passed here will be applied to a sentence after it has been tokenized (transformed from a string into a list of tokens), but before it has been numericalized (transformed from a list of tokens to a list of indexes). This is where we'll pass our `generate_bigrams` function.
```
import torch
from torchtext import data
from torchtext import datasets
SEED = 1234
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
TEXT = data.Field(tokenize='spacy', preprocessing=generate_bigrams)
LABEL = data.LabelField(dtype=torch.float)
```
As before, we load the IMDb dataset and create the splits.
```
import random
train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)
train_data, valid_data = train_data.split(random_state=random.seed(SEED))
```
Build the vocab and load the pre-trained word embeddings.
```
TEXT.build_vocab(train_data, max_size=25000, vectors="glove.6B.100d")
LABEL.build_vocab(train_data)
```
And create the iterators.
```
BATCH_SIZE = 64
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_iterator, valid_iterator, test_iterator = data.BucketIterator.splits(
(train_data, valid_data, test_data),
batch_size=BATCH_SIZE,
device=device)
```
## Build the Model
This model has far fewer parameters than the previous model as it only has 2 layers that have any parameters, the embedding layer and the linear layer. There is no RNN component in sight!
Instead, it first calculates the word embedding for each word using the `Embedding` layer (blue), then calculates the average of all of the word embeddings (pink) and feeds this through the `Linear` layer (silver), and that's it!

We implement the averaging with the `avg_pool2d` (average pool 2-dimensions) function. Initially, you may think using a 2-dimensional pooling seems strange, surely our sentences are 1-dimensional, not 2-dimensional? However, you can think of the word embeddings as a 2-dimensional grid, where the words are along one axis and the dimensions of the word embeddings are along the other. The image below is an example sentence after being converted into 5-dimensional word embeddings, with the words along the vertical axis and the embeddings along the horizontal axis. Each element in this [4x5] tensor is represented by a green block.

The `avg_pool2d` uses a filter of size `embedded.shape[1]` (i.e. the length of the sentence) by 1. This is shown in pink in the image below.

We calculate the average value of all elements covered by the filter, then the filter then slides to the right, calculating the average over the next column of embedding values for each word in the sentence.

Each filter position gives us a single value, the average of all covered elements. After the filter has covered all embedding dimensions we get a [1x5] tensor. This tensor is then passed through the linear layer to produce our prediction.
```
import torch.nn as nn
import torch.nn.functional as F
class FastText(nn.Module):
def __init__(self, vocab_size, embedding_dim, output_dim):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.fc = nn.Linear(embedding_dim, output_dim)
def forward(self, text):
#text = [sent len, batch size]
embedded = self.embedding(text)
#embedded = [sent len, batch size, emb dim]
embedded = embedded.permute(1, 0, 2)
#embedded = [batch size, sent len, emb dim]
pooled = F.avg_pool2d(embedded, (embedded.shape[1], 1)).squeeze(1)
#pooled = [batch size, embedding_dim]
return self.fc(pooled)
```
As previously, we'll create an instance of our `FastText` class.
```
INPUT_DIM = len(TEXT.vocab)
EMBEDDING_DIM = 100
OUTPUT_DIM = 1
model = FastText(INPUT_DIM, EMBEDDING_DIM, OUTPUT_DIM)
```
And copy the pre-trained vectors to our embedding layer.
```
pretrained_embeddings = TEXT.vocab.vectors
model.embedding.weight.data.copy_(pretrained_embeddings)
```
## Train the Model
Training the model is the exact same as last time.
We initialize our optimizer...
```
import torch.optim as optim
optimizer = optim.Adam(model.parameters())
```
We define the criterion and place the model and criterion on the GPU (if available)...
```
criterion = nn.BCEWithLogitsLoss()
model = model.to(device)
criterion = criterion.to(device)
```
We implement the function to calculate accuracy...
```
def binary_accuracy(preds, y):
"""
Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8
"""
#round predictions to the closest integer
rounded_preds = torch.round(torch.sigmoid(preds))
correct = (rounded_preds == y).float() #convert into float for division
acc = correct.sum()/len(correct)
return acc
```
We define a function for training our model...
**Note**: we are no longer using dropout so we do not need to use `model.train()`, but as mentioned in the 1st notebook, it is good practice to use it.
```
def train(model, iterator, optimizer, criterion):
epoch_loss = 0
epoch_acc = 0
model.train()
for batch in iterator:
optimizer.zero_grad()
predictions = model(batch.text).squeeze(1)
loss = criterion(predictions, batch.label)
acc = binary_accuracy(predictions, batch.label)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator)
```
We define a function for testing our model...
**Note**: again, we leave `model.eval()` even though we do not use dropout.
```
def evaluate(model, iterator, criterion):
epoch_loss = 0
epoch_acc = 0
model.eval()
with torch.no_grad():
for batch in iterator:
predictions = model(batch.text).squeeze(1)
loss = criterion(predictions, batch.label)
acc = binary_accuracy(predictions, batch.label)
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator)
```
Finally, we train our model...
```
N_EPOCHS = 5
for epoch in range(N_EPOCHS):
train_loss, train_acc = train(model, train_iterator, optimizer, criterion)
valid_loss, valid_acc = evaluate(model, valid_iterator, criterion)
print(f'| Epoch: {epoch+1:02} | Train Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}% | Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc*100:.2f}% |')
```
...and get the test accuracy!
The results are comparable to the results in the last notebook, but training takes considerably less time.
```
test_loss, test_acc = evaluate(model, test_iterator, criterion)
print(f'| Test Loss: {test_loss:.3f} | Test Acc: {test_acc*100:.2f}% |')
```
## User Input
And as before, we can test on any input the user provides.
```
import spacy
nlp = spacy.load('en')
def predict_sentiment(sentence):
tokenized = [tok.text for tok in nlp.tokenizer(sentence)]
indexed = [TEXT.vocab.stoi[t] for t in tokenized]
tensor = torch.LongTensor(indexed).to(device)
tensor = tensor.unsqueeze(1)
prediction = torch.sigmoid(model(tensor))
return prediction.item()
```
An example negative review...
```
predict_sentiment("This film is terrible")
```
An example positive review...
```
predict_sentiment("This film is great")
```
## Next Steps
In the next notebook we'll use convolutional neural networks (CNNs) to perform sentiment analysis, and get our best accuracy yet!
| github_jupyter |
# 第2章: UNIXコマンド
popular-names.txtは,アメリカで生まれた赤ちゃんの「名前」「性別」「人数」「年」をタブ区切り形式で格納したファイルである.以下の処理を行うプログラムを作成し,popular-names.txtを入力ファイルとして実行せよ.さらに,同様の処理をUNIXコマンドでも実行し,プログラムの実行結果を確認せよ
## 10. 行数のカウント
行数をカウントせよ.確認にはwcコマンドを用いよ.
```
with open('popular-names.txt', 'r', encoding='utf8') as f:
print(len([1 for line in f]))
!wc -l popular-names.txt | awk '{print $1}'
```
## 11. タブをスペースに置換
タブ1文字につきスペース1文字に置換せよ.確認にはsedコマンド,trコマンド,もしくはexpandコマンドを用いよ.
```
replaced_text = ''
with open('popular-names.txt', 'r', encoding='utf8') as f:
replaced_text = f.read().replace('\t', ' ')
with open('output_py/q11.txt', 'w', encoding='utf8') as f:
f.write(replaced_text)
!sed -e 's/\t/ /g' popular-names.txt > output/q11.txt
```
## 12. 1列目をcol1.txtに,2列目をcol2.txtに保存
各行の1列目だけを抜き出したものをcol1.txtに,2列目だけを抜き出したものをcol2.txtとしてファイルに保存せよ.確認にはcutコマンドを用いよ.
```
col1 = []
col2 = []
with open('popular-names.txt', 'r', encoding='utf8') as f:
splitted_lines = [line.split('\t') for line in f]
for splitted_line in splitted_lines:
col1.append(splitted_line[0])
col2.append(splitted_line[1])
with open('output_py/q12_col1.txt', 'w', encoding='utf8') as f:
f.write('\n'.join(col1))
with open('output_py/q12_col2.txt', 'w', encoding='utf8') as f:
f.write('\n'.join(col2))
!cut -f 1 popular-names.txt > output/q12_col1.txt
!cut -f 2 popular-names.txt > output/q12_col2.txt
```
## 13. col1.txtとcol2.txtをマージ
12で作ったcol1.txtとcol2.txtを結合し,元のファイルの1列目と2列目をタブ区切りで並べたテキストファイルを作成せよ.確認にはpasteコマンドを用いよ.
```
with open('output_py/q12_col1.txt', 'r', encoding='utf8') as f:
col1_lines = [line for line in f] # 各要素の末尾に改行文字を含む
with open('output_py/q12_col2.txt', 'r', encoding='utf8') as f:
col2_lines = [line for line in f] # 各要素の末尾に改行文字を含む
merged_text_lines = [col1.rstrip('\n') + '\t' + col2 for col1, col2 in zip(col1_lines, col2_lines)]
with open('output_py/q13.txt', 'w', encoding='utf8') as f:
f.writelines(merged_text_lines) # col2の改行文字だけ残し、writelinesで書き込み
!paste output/q12_col1.txt output/q12_col2.txt > output/q13.txt
```
## 14. 先頭からN行を出力
自然数Nをコマンドライン引数などの手段で受け取り,入力のうち先頭のN行だけを表示せよ.確認にはheadコマンドを用いよ.
```
N = input('Input Natural number N -> ')
with open('popular-names.txt', 'r', encoding='utf-8') as f:
N_lines = f.readlines()[:int(N):]
with open('output_py/q14.txt', 'w', encoding='utf8') as f:
f.writelines(N_lines)
# コマンドライン引数の場合 ... 5 -> $1
!head -n 5 popular-names.txt > output/q14.txt
```
## 15. 末尾のN行を出力
自然数Nをコマンドライン引数などの手段で受け取り,入力のうち末尾のN行だけを表示せよ.確認にはtailコマンドを用いよ.
```
N = input('Input Natural number N -> ')
with open('popular-names.txt', 'r', encoding='utf-8') as f:
N_lines = f.readlines()
N_lines = N_lines[len(N_lines)-int(N)::] # 末尾のN行を抽出
with open('output_py/q15.txt', 'w', encoding='utf8') as f:
f.writelines(N_lines)
# コマンドライン引数の場合 ... 10 -> $1
!tail -n 10 popular-names.txt > output/q15.txt
```
## 16. ファイルをN分割する
自然数Nをコマンドライン引数などの手段で受け取り,入力のファイルを行単位でN分割せよ.同様の処理をsplitコマンドで実現せよ.
```
N = input('Input Natural number N -> ')
with open('popular-names.txt', 'r', encoding='utf8') as f:
all_lines = [line for line in f]
splitting_nums = len(all_lines) // int(N)
i = 0
while len(all_lines) - splitting_nums * i > 0:
with open('output_py/q16_{}.txt'.format(i), 'w', encoding='utf8') as f:
# 最後のループで、スライスの末尾の値が、元のリストの要素数を超える
# -> 自動的に、len(all_lines) - 1まで収めてくれる
f.writelines(all_lines[splitting_nums*i:splitting_nums*(i+1)])
i += 1
# コマンドライン引数の場合 ... 3 -> $1
line_nums = !wc -l popular-names.txt | awk '{print $1}'
print("line_nums: {}".format(line_nums))
N = !expr {line_nums[0]} / 3
print("N: {}".format(N))
!split -l {N[0]} -d popular-names.txt output/q16.txt
```
## 17. 1列目の文字列の異なり
1列目の文字列の種類(異なる文字列の集合)を求めよ.確認にはcut, sort, uniqコマンドを用いよ.
```
with open('popular-names.txt', 'r', encoding='utf8') as f:
col1_texts = [line.split('\t')[0] for line in f]
with open('output_py/q17.txt', 'w', encoding='utf8') as f:
# setで重複除去 -> sorted
f.write('\n'.join(sorted(set(col1_texts))))
!cut -f 1 popular-names.txt | sort | uniq > output/q17.txt
```
## 18. 各行を3コラム目の数値の降順にソート
各行を3コラム目の数値の逆順で整列せよ(注意: 各行の内容は変更せずに並び替えよ).確認にはsortコマンドを用いよ(この問題はコマンドで実行した時の結果と合わなくてもよい).
```
with open('popular-names.txt', 'r', encoding='utf8') as f:
all_lines = [line for line in f]
sorted_lines = sorted(all_lines, key=lambda x: int(x.split('\t')[2]), reverse=True)
with open('output_py/q18.txt', 'w', encoding='utf8') as f:
f.writelines(sorted_lines)
# Ubuntu(dash)以外では、"-t $'\t'"の書き方が使える
!sort -r -k 3 -t \t popular-names.txt > output/q18.txt
```
## 19. 各行の1コラム目の文字列の出現頻度を求め,出現頻度の高い順に並べる
各行の1列目の文字列の出現頻度を求め,その高い順に並べて表示せよ.確認にはcut, uniq, sortコマンドを用いよ.
```
from collections import Counter
with open('popular-names.txt', 'r', encoding='utf8') as f:
all_col1_texts = [line.split('\t')[0] for line in f]
counter = Counter(all_col1_texts)
frequency_col1_texts = ['{}\t{}\n'.format(num, word) for word, num in counter.most_common()]
with open('output_py/q19.txt', 'w', encoding='utf8') as f:
f.writelines(frequency_col1_texts)
!cut -f 1 popular-names.txt | sort | uniq -c | sort -r -k 1 -t ' ' > output/q19.txt
```
| github_jupyter |
# Automatic differentiation with JAX
## Main features
- Numpy wrapper
- Auto-vectorization
- Auto-parallelization (SPMD paradigm)
- Auto-differentiation
- XLA backend and JIT support
## How to compute gradient of your objective?
- Define it as a standard Python function
- Call ```jax.grad``` and voila!
- Do not forget to wrap these functions with ```jax.jit``` to speed up
```
import jax
import jax.numpy as jnp
```
- By default, JAX exploits single-precision numbers ```float32```
- You can enable double precision (```float64```) by hands.
```
from jax.config import config
config.update("jax_enable_x64", True)
@jax.jit
def f(x, A, b):
res = A @ x - b
return res @ res
gradf = jax.grad(f, argnums=0, has_aux=False)
```
## Random numbers in JAX
- JAX focuses on the reproducibility of the runs
- Analogue of random seed is **the necessary argument** of all functions that generate something random
- More details and references on the design of ```random``` submodule are [here](https://github.com/google/jax/blob/master/design_notes/prng.md)
```
n = 1000
x = jax.random.normal(jax.random.PRNGKey(0), (n, ))
A = jax.random.normal(jax.random.PRNGKey(0), (n, n))
b = jax.random.normal(jax.random.PRNGKey(0), (n, ))
print("Check correctness", jnp.linalg.norm(gradf(x, A, b) - 2 * A.T @ (A @ x - b)))
print("Compare speed")
print("Analytical gradient")
%timeit 2 * A.T @ (A @ x - b)
print("Grad function")
%timeit gradf(x, A, b).block_until_ready()
jit_gradf = jax.jit(gradf)
print("Jitted grad function")
%timeit jit_gradf(x, A, b).block_until_ready()
hess_func = jax.jit(jax.hessian(f))
print("Check correctness", jnp.linalg.norm(2 * A.T @ A - hess_func(x, A, b)))
print("Time for hessian")
%timeit hess_func(x, A, b).block_until_ready()
print("Emulate hessian and check correctness",
jnp.linalg.norm(jax.jit(hess_func)(x, A, b) - jax.jacfwd(jax.jacrev(f))(x, A, b)))
print("Time of emulating hessian")
hess_umul_func = jax.jit(jax.jacfwd(jax.jacrev(f)))
%timeit hess_umul_func(x, A, b).block_until_ready()
```
## Forward mode vs. backward mode: $m \ll n$
```
fmode_f = jax.jit(jax.jacfwd(f))
bmode_f = jax.jit(jax.jacrev(f))
print("Check correctness", jnp.linalg.norm(fmode_f(x, A, b) - bmode_f(x, A, b)))
print("Forward mode")
%timeit fmode_f(x, A, b).block_until_ready()
print("Backward mode")
%timeit bmode_f(x, A, b).block_until_ready()
```
## Forward mode vs. backward mode: $m \geq n$
```
def fvec(x, A, b):
y = A @ x + b
return jnp.exp(y - jnp.max(y)) / jnp.sum(jnp.exp(y - jnp.max(y)))
grad_fvec = jax.jit(jax.grad(fvec))
jac_fvec = jax.jacobian(fvec)
fmode_fvec = jax.jit(jax.jacfwd(fvec))
bmode_fvec = jax.jit(jax.jacrev(fvec))
n = 1000
m = 1000
x = jax.random.normal(jax.random.PRNGKey(0), (n, ))
A = jax.random.normal(jax.random.PRNGKey(0), (m, n))
b = jax.random.normal(jax.random.PRNGKey(0), (m, ))
J = jac_fvec(x, A, b)
print(J.shape)
grad_fvec(x, A, b)
print("Check correctness", jnp.linalg.norm(fmode_fvec(x, A, b) - bmode_fvec(x, A, b)))
print("Check shape", fmode_fvec(x, A, b).shape, bmode_fvec(x, A, b).shape)
print("Time forward mode")
%timeit fmode_fvec(x, A, b).block_until_ready()
print("Time backward mode")
%timeit bmode_fvec(x, A, b).block_until_ready()
n = 10
m = 1000
x = jax.random.normal(jax.random.PRNGKey(0), (n, ))
A = jax.random.normal(jax.random.PRNGKey(0), (m, n))
b = jax.random.normal(jax.random.PRNGKey(0), (m, ))
print("Check correctness", jnp.linalg.norm(fmode_fvec(x, A, b) - bmode_fvec(x, A, b)))
print("Check shape", fmode_fvec(x, A, b).shape, bmode_fvec(x, A, b).shape)
print("Time forward mode")
%timeit fmode_fvec(x, A, b).block_until_ready()
print("Time backward mode")
%timeit bmode_fvec(x, A, b).block_until_ready()
```
## Hessian-by-vector product
```
def hvp(f, x, z, *args):
def g(x):
return f(x, *args)
return jax.jvp(jax.grad(g), (x,), (z,))[1]
n = 3000
x = jax.random.normal(jax.random.PRNGKey(0), (n, ))
A = jax.random.normal(jax.random.PRNGKey(0), (n, n))
b = jax.random.normal(jax.random.PRNGKey(0), (n, ))
z = jax.random.normal(jax.random.PRNGKey(0), (n, ))
print("Check correctness", jnp.linalg.norm(2 * A.T @ (A @ z) - hvp(f, x, z, A, b)))
print("Time for hvp by hands")
%timeit (2 * A.T @ (A @ z)).block_until_ready()
print("Time for hvp via jvp, NO jit")
%timeit hvp(f, x, z, A, b).block_until_ready()
print("Time for hvp via jvp, WITH jit")
%timeit jax.jit(hvp, static_argnums=0)(f, x, z, A, b).block_until_ready()
```
## Summary
- JAX is a simple and extensible tool in the problem where autodiff is crucial
- JIT is a key to fast Python code
- Input/output dimensions are important
- Hessian matvec is faster than explicit hessian matrix by vector product
| github_jupyter |
# cuDF Cheat Sheets sample code
(c) 2020 NVIDIA, Blazing SQL
Distributed under Apache License 2.0
### Imports
```
import cudf
import numpy as np
```
### Sample DataFrame
```
df = cudf.DataFrame(
[
(39, 6.88, np.datetime64('2020-10-08T12:12:01'), np.timedelta64(14378,'s'), 'C', 'D', 'data'
, 'RAPIDS.ai is a suite of open-source libraries that allow you to run your end to end data science and analytics pipelines on GPUs.')
, (11, 4.21, None, None , 'A', 'D', 'cuDF'
, 'cuDF is a Python GPU DataFrame (built on the Apache Arrow columnar memory format)')
, (31, 4.71, np.datetime64('2020-10-10T09:26:43'), np.timedelta64(12909,'s'), 'U', 'D', 'memory'
, 'cuDF allows for loading, joining, aggregating, filtering, and otherwise manipulating tabular data using a DataFrame style API.')
, (40, 0.93, np.datetime64('2020-10-11T17:10:00'), np.timedelta64(10466,'s'), 'P', 'B', 'tabular'
, '''If your workflow is fast enough on a single GPU or your data comfortably fits in memory on
a single GPU, you would want to use cuDF.''')
, (33, 9.26, np.datetime64('2020-10-15T10:58:02'), np.timedelta64(35558,'s'), 'O', 'D', 'parallel'
, '''If you want to distribute your workflow across multiple GPUs or have more data than you can fit
in memory on a single GPU you would want to use Dask-cuDF''')
, (42, 4.21, np.datetime64('2020-10-01T10:02:23'), np.timedelta64(20480,'s'), 'U', 'C', 'GPUs'
, 'BlazingSQL provides a high-performance distributed SQL engine in Python')
, (36, 3.01, np.datetime64('2020-09-30T14:36:26'), np.timedelta64(24409,'s'), 'T', 'D', None
, 'BlazingSQL is built on the RAPIDS GPU data science ecosystem')
, (38, 6.44, np.datetime64('2020-10-10T08:34:36'), np.timedelta64(90171,'s'), 'X', 'B', 'csv'
, 'BlazingSQL lets you ETL raw data directly into GPU memory as a GPU DataFrame (GDF)')
, (17, 5.28, np.datetime64('2020-10-09T08:34:40'), np.timedelta64(30532,'s'), 'P', 'D', 'dataframes'
, 'Dask is a flexible library for parallel computing in Python')
, (10, 8.28, np.datetime64('2020-10-03T03:31:21'), np.timedelta64(23552,'s'), 'W', 'B', 'python'
, None)
]
, columns = ['num', 'float', 'datetime', 'timedelta', 'char', 'category', 'word', 'string']
)
df['category'] = df['category'].astype('category')
```
---
# Functions
---
## <span style="color:blue">String functions</span>
#### cudf.core.column.string.StringMethods.contains()
```
df['string'].str.contains('GPU')
df['string'].str.contains('\.+')
df['string'].str.contains('[a-z]+flow')
```
#### cudf.core.column.string.StringMethods.extract()
```
df['string'].str.extract('(cuDF)')
df['string'].str.extract('([a-z]+flow)')
```
#### cudf.core.column.string.StringMethods.findall()
```
df['string'].str.findall('(cuDF)')
df['string'].str.findall('([a-z]+flow)')
df['string'].str.findall('(GPU)')
```
#### cudf.core.column.string.StringMethods.len()
```
df['string'].str.len()
```
#### cudf.core.column.string.StringMethods.lower()
```
df['string'].str.lower()
```
#### cudf.core.column.string.StringMethods.match()
```
df['word'].str.match('(c)+')
```
#### cudf.core.column.string.StringMethods.ngrams_tokenize()
```
df['string'].str.ngrams_tokenize(n=2, separator='_')
```
#### cudf.core.column.string.StringMethods.pad()
```
df['word'].str.pad(width=10)
df['word'].str.pad(width=10, side='right', fillchar='#')
df['word'].str.pad(width=10, side='both', fillchar='-')
```
#### cudf.core.column.string.StringMethods.replace()
```
df['word'].str.replace('da..', 'tada')
df['word'].str.replace('da..', 'tada', regex=False)
```
#### cudf.core.column.string.StringMethods.split()
```
df['string'].str.split(' ')
df['string'].str.split(' ', n=4)
```
#### cudf.core.column.string.StringMethods.subword_tokenize()
```
tokens, masks, metadata = df['string'].str.subword_tokenize('hash.txt')
tokens, masks, metadata = df['string'].str.subword_tokenize('hash.txt', max_length=10, stride=10)
tokens, masks, metadata = df['string'].str.subword_tokenize('hash.txt', do_lower=True)
```
#### cudf.core.column.string.StringMethods.upper()
```
df['string'].str.upper()
```
## <span style="color:blue">Categorical functions</span>
#### cudf.core.column.categorical.CategoricalAccessor.add_categories()
```
df['category'].cat.add_categories(['A', 'E'])
df['category'].cat.add_categories(['A', 'E'], inplace=True)
df['category']
```
#### cudf.core.column.categorical.CategoricalAccessor.categories()
```
df['category'].cat.categories
```
#### cudf.core.column.categorical.CategoricalAccessor.remove_categories()
```
df['category'].cat.remove_categories(['A', 'E'])
df['category'].cat.remove_categories(['A', 'E'], inplace=True)
```
## <span style="color:blue">Date and time functions</span>
#### cudf.core.series.DatetimeProperties.day()
```
df['datetime'].dt.day
```
#### cudf.core.series.DatetimeProperties.dayofweek()
```
df['datetime'].dt.dayofweek
```
#### cudf.core.series.DatetimeProperties.year()
```
df['datetime'].dt.year
```
## <span style="color:blue">Mathematical and statistical functions</span>
#### cudf.core.dataframe.DataFrame.corr()
```
df[['num', 'float']].corr()
```
#### cudf.core.dataframe.DataFrame.cumsum()
```
df['num'].cumsum()
```
| github_jupyter |
# The biharmonic equation on the Torus
The biharmonic equation is given as
$$
\nabla^4 u = f,
$$
where $u$ is the solution and $f$ is a function. In this notebook we will solve this equation inside a torus with homogeneous boundary conditions $u(r=1)=u'(r=1)=0$ on the outer surface. We solve the equation with the spectral Galerkin method in curvilinear coordinates.
<img src="https://cdn.jsdelivr.net/gh/spectralDNS/spectralutilities@master/figures/torus2.png">
The torus is parametrized by
\begin{align*}
x(r, \theta, \phi) &= (R + r \cos \theta) \cos \phi \\
y(r, \theta, \phi) &= (R + r \cos \theta) \sin \phi \\
z(r, \theta, \phi) &= r \sin \theta
\end{align*}
where the Cartesian domain is $\Omega = \{(x, y, z): \left(\sqrt{x^2+y^2} - R^2\right)^2 + z^2 < 1\}$ and the computational domain is $(r, \theta, \phi) \in D = [0, 1] \times [0, 2\pi] \times [0, 2\pi]$. Hence $\theta$ and $\phi$ are angles which make a full circle, so that their values start and end at the same point, $R$ is the distance from the center of the tube to the center of the torus,
$r$ is the radius of the tube. Note that $\theta$ is the angle in the small circle (around its center), whereas $\phi$ is the angle of the large circle, around origo.
We start the implementation by importing necessary functionality from shenfun and sympy and then defining the coordinates of the surface of the torus.
```
from shenfun import *
from shenfun.la import SolverGeneric2ND
import sympy as sp
from IPython.display import Math
N = 24
R = 3
r, theta, phi = psi = sp.symbols('x,y,z', real=True, positive=True)
rv = ((R + r*sp.cos(theta))*sp.cos(phi), (R + r*sp.cos(theta))*sp.sin(phi), r*sp.sin(theta))
def discourage_powers(expr):
POW = sp.Symbol('POW')
count = sp.count_ops(expr, visual=True)
count = count.replace(POW, 100)
count = count.replace(sp.Symbol, type(sp.S.One))
return count
B0 = FunctionSpace(N, 'L', basis='UpperDirichletNeumann', domain=(0, 1))
B1 = FunctionSpace(N, 'F', dtype='D', domain=(0, 2*np.pi))
B2 = FunctionSpace(N, 'F', dtype='d', domain=(0, 2*np.pi))
T = TensorProductSpace(comm, (B0, B1, B2), coordinates=(psi, rv, sp.Q.positive(r*sp.cos(theta)+R), (), discourage_powers))
T.coors.sg
```
We use Fourier basis functions for the two periodic directions, and a Legendre basis that satisfies the homogeneous boundary conditions for the radial direction.
Note that `rv` represents the position vector $\vec{r}=x\mathbf{i} + y\mathbf{j} + z\mathbf{k}$ and that `T.hi` now contains the 3 scaling factors for the torus coordinates:
\begin{align*}
h_r &= \left|\frac{\partial \vec{r}}{\partial r}\right| = 1\\
h_{\theta} &= \left|\frac{\partial \vec{r}}{\partial \theta}\right| = r\\
h_{\phi} &= \left|\frac{\partial \vec{r}}{\partial \phi}\right| = r\cos \theta + R\\
\end{align*}
The covariant basis vectors used by shenfun are
```
T.coors.sg
Math(T.coors.latex_basis_vectors(covariant=True, symbol_names={r: 'r', theta: '\\theta', phi: '\\phi'}))
```
Now check what the biharmonic operator looks like for the torus. Simplify equation using the integral measure $\sqrt{g}$, found as `T.coors.sg`
$$
\sqrt{g} = r (r \cos \theta + R)
$$
```
u = TrialFunction(T)
v = TestFunction(T)
du = div(grad(div(grad(u))))
g = sp.Symbol('g', real=True, positive=True)
replace = [(r*sp.cos(theta)+R, sp.sqrt(g)/r), (2*r*sp.cos(theta)+R, 2*sp.sqrt(g)/r-R)] # to simplify the look
Math((du*T.coors.sg**4).tolatex(symbol_names={r: 'r', theta: '\\theta', phi: '\\phi'}, replace=replace))
```
Glad you're not doing this by hand?
To solve this equation we need to get a variational form that is separable. To get a variational form we multiply the equation by a weight $\omega$ and the complex conjugate of a test function $\overline{v}$, and integrate over the domain by switching to computational coordinates
\begin{align*}
\int_{\Omega} \nabla^4 u\, \overline{v} \omega dV &= \int_{\Omega} f \, \overline{v} \omega dV \\
\int_{D} \nabla^4 u \, \overline{v} \omega \sqrt{g} dr d\theta d\phi &= \int_{D} f \, \overline{v} \omega \sqrt{g} dr d\theta d\phi
\end{align*}
<div class="alert alert-warning">
Note that the functions in the last equation now actually are transformed to computational space, i.e., $u=u(\mathbf{x}(r, \theta, \phi))$ and the same for the rest. We should probably use a new name for the transformed functions, but we keep the same here to keep it simple. Whether the function is transformed or not should be evident from context. If the integral is in computational space, then the functions are transformed.
</div>
For Legendre and Fourier test functions the weight $\omega$ is normally a constant. However, we see that the denominator in some terms above contains $g^2=r^4(r\cos \theta +R)^4$. The term in parenthesis $(r\cos \theta +R)$ makes the variational form above unseparable. If, on the other hand, we change the weight $\omega$ to $g^{3/2}$, then the misbehaving denominator disappears and the variational form becomes separable.
$$
\int_{D} \nabla^4 u \, \overline{v} \, g^2 dr d\theta d\phi = \int_{D} f \, \overline{v} \, g^2 dr d\theta d\phi
$$
Alternatively, we can aim at only removing the $(r\cos \theta +R)$ term from the denominator by using weight $(r\cos \theta +R)^3$
$$
\int_{D} \nabla^4 u \, \overline{v} \, r (r\cos \theta +R)^4 dr d\theta d\phi = \int_{D} f \, \overline{v} \, r \,(r\cos \theta + R)^4 dr d\theta d\phi.
$$
The first actually leads to a coefficient matrix of fewer bands than the second. However, the condition number is larger and round-off errors more severe. In the code below we use the first approach by default, but it can be easily changed with the commented out code.
We verify the implementation by using a manufactured solution that satisfies the boundary conditions. Note that the Legendre basis `ShenBiPolar0Basis`, chosen using `bc='BiPolar0'` with the `Basis`, currently is the only function space in shenfun that can satisfy $u(r=1, \theta, \phi)=u'(r=1, \theta, \phi)=u'(0, \theta, \phi)=0$, where the latter is a pole condition inherited from [Shen's paper on cylindrical coordinates](https://epubs.siam.org/doi/abs/10.1137/S1064827595295301). With the current weights the pole condition is probably not needed.
```
#ue = sp.sin(theta*2)*sp.cos(4*phi)*((1-r))**2 #+B0.sympy_basis(4, x=r)
#ue = (1-sp.exp(-(1-r)**2))**2*sp.cos(4*phi)
xx = r*sp.cos(theta); yy = r*sp.sin(theta)
ue = ((1-r)*sp.exp(-(xx-0.4)**2-(yy-0.3)**2))**2*sp.cos(2*phi)
f = div(grad(div(grad(u)))).tosympy(basis=ue, psi=psi)
fj = Array(T, buffer=f*T.coors.sg**3)
#fj = Array(T, buffer=f*T.hi[2]**3)
f_hat = Function(T)
f_hat = inner(v, fj, output_array=f_hat)
#M = inner(v*T.hi[2]**3, div(grad(div(grad(u)))))
#M = inner(v*T.coors.sg**3, div(grad(div(grad(u)))))
M = inner(div(grad(v*T.coors.sg**3)), div(grad(u)))
u_hat = Function(T)
sol = la.SolverGeneric2ND(M)
u_hat = sol(f_hat, u_hat)
uj = u_hat.backward()
uq = Array(T, buffer=ue)
print('Error =', np.sqrt(inner(1, (uj-uq)**2)))
```
Note that the variational form contains
```
len(M)
```
tensorproduct matrices, but some differ only in the scales. The solver `SolverGeneric2ND` loops over and solves for one Fourier coefficient in the $\phi$-direction at the time, because all submatrices in the $\phi$-direction are diagonal. The matrices in the $\theta$-direction are not necessarily diagonal because of the weight $(r\cos \theta + 3)$. The sparsity pattern of the matrix can be inspected as follows
```
import matplotlib.pyplot as plt
%matplotlib notebook
B = sol.diags(4)
#print(np.linalg.cond(B.toarray()))
plt.spy(B, markersize=0.1)
plt.show()
```
A baded matrix in deed, but quite a large number of bands.
A slice of the solution can be visualized. Here we use $\phi=0$, because that lies in the Cartesian $x-z$-plane.
```
u_hat2 = u_hat.refine([N*3, N*3, N])
ur = u_hat2.backward()
us = ur.get((slice(None), slice(None), 0))
xx, yy, zz = u_hat2.function_space().local_cartesian_mesh(uniform=True)
# Wrap periodic plot around since it looks nicer
xp = np.hstack([xx[:, :, 0], xx[:, 0, 0][:, None]])
zp = np.hstack([zz[:, :, 0], zz[:, 0, 0][:, None]])
up = np.hstack([us, us[:, 0][:, None]])
# plot
plt.figure()
plt.contourf(xp, zp, up)
plt.colorbar()
```
Now print the solution at approximately half the radius
```
from mayavi import mlab
u_hat3 = u_hat.refine([N, N*3, N*3])
ux = u_hat3.backward()
X = u_hat3.function_space().local_mesh(broadcast=True, uniform=True)
print('radius =',X[0][N//2,0,0])
```
Get the $\theta-\phi$ mesh for given radius
```
xj = []
for rv in T.coors.coordinates[1]:
xj.append(sp.lambdify(psi, rv)(X[0][N//2], X[1][N//2], X[2][N//2]))
xx, yy, zz = xj
us = ux[N//2]
```
Wrap around periodic direction to make it nicer
```
xx = np.hstack([xx, xx[:, 0][:, None]])
yy = np.hstack([yy, yy[:, 0][:, None]])
zz = np.hstack([zz, zz[:, 0][:, None]])
us = np.hstack([us, us[:, 0][:, None]])
xx = np.vstack([xx, xx[0]])
yy = np.vstack([yy, yy[0]])
zz = np.vstack([zz, zz[0]])
us = np.vstack([us, us[0]])
mlab.figure(bgcolor=(1, 1, 1))
mlab.mesh(xx, yy, zz, scalars=us, colormap='jet')
mlab.show()
```
## Vector Laplacian
Finally, we look at the vector Laplacian and verify the following
$$
\nabla^2 \vec{u} = \nabla \nabla \cdot \vec{u} - \nabla \times \nabla \times \vec{u}
$$
The vector Laplace $\nabla^2 \vec{u}$ looks like:
```
V = VectorSpace(T)
p = TrialFunction(V)
du = div(grad(p))
replace = [(r*sp.cos(theta)+R, sp.sqrt(g)/r), (2*r*sp.cos(theta)+R, 2*sp.sqrt(g)/r-R)] # to simplify the look
Math(du.tolatex(symbol_names={r: 'r', theta: '\\theta', phi: '\\phi'}, replace=replace))
```
And if we subtract $\nabla \nabla \cdot \vec{u} - \nabla \times \nabla \times \vec{u}$ we should get the zero vector.
```
dv = grad(div(p)) - curl(curl(p))
dw = du-dv
dw.simplify()
Math(dw.tolatex(symbol_names={r: 'r', theta: '\\theta', phi: '\\phi'}))
```
| github_jupyter |
<h1 style="padding-top: 25px;padding-bottom: 25px;text-align: left; padding-left: 10px; background-color: #DDDDDD;
color: black;"> <img style="float: left; padding-right: 10px; width: 45px" src="https://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/iacs.png"> AC295: Advanced Practical Data Science </h1>
## Lecture 7: Distillation and Compression
**Harvard University**<br/>
**Spring 2020**<br/>
**Instructors**: Pavlos Protopapas <br>
**TF**: Michael Emanuel, Andrea Porelli and Giulia Zerbini <br>
**Author**: Andrea Porelli and Pavlos Protopapas
<hr style='height:2px'>
# Table of Contents
* [Lecture 7: Distillation and Compression](#Lecture-7:-Distillation-and-Compression)
* [Part 1: Knowledge distillation: Teacher student learning](#Part-1:-Knowledge-distillation:-Teacher-student-learning)
* [1.1 Matching logits is a special case of distillation](#1.1-Matching-logits-is-a-special-case-of-distillation)
* [1.2 Temperature](#1.2-Temperature)
* [1.3 Examples from the paper](#1.3-Examples-from-the-paper)
* [Part 2: Use Cases](#Part-2:-Use-Cases)
* [2.1 Transfer learning through Network Distillation](#2.1-Transfer-learning-through-Network-Distillation)
* [2.2 Another use case?](#2.2-Another-use-case?)
## Part 1: Knowledge distillation: Teacher student learning
Geoffrey Hinton's words:
- Many insects have two very different forms:
- a larval form: optimised to extract energy and nutrients from environment
- an adult form: optimized for traveling and reproduction
- ML typically uses the same model for training stage and the deployment stage! Despite very different requirements:
- Training: should extract structure, should not be real time, thus can use a huge amount of computation.
- Deployment: large number of users, more stringent requirements on latency and computational resources.
**Question:** is it possible to distill and compress the *knowledge* of the large and complex training model (the teacher) into a small and simple deployment model (the student)?
**Brings us to the question what is knowledge (in a NN)?**
- The weights of network?
- The mapping from input to output?
**Goal:** train a student model to generalize in the same way as the large model.
### 1.1 Matching logits is a special case of distillation
- Normal training objective is to maximize the average log probability of the correct class.
- Yet Hinton:
- "*Relative probabilities of incorrect answers tell us a lot about how the teacher model tends to generalize.*"
- Ex.: "*An image of a BMW, may only have a very small chance of being mistaken for a garbage truck, but that mistake is still many times more probable than mistaking it for a carrot.*"
<img src="https://i.imgur.com/zvTR1r7.png" alt="https://towardsdatascience.com/knowledge-distillation-simplified-dd4973dbc764" width=60%/>
- **The predictions of the teacher model contain a lot of usefull information regarding the generalization!**
- **Thus our student networks tries to match the teacher network predictions.**
<img src="https://i.imgur.com/l80RVDT.jpg" alt="https://towardsdatascience.com/knowledge-distillation-simplified-dd4973dbc764" width=80%/>
**The final loss-function of the student network ( $\mathscr{L}_\text{student }$ ) is a combination of:**
1. Standard cross entropy with correct labels ( $\mathscr{L}_\text{correct labels }$ )
- ex. match label: 100% BWM
2. Cross entropy with the soft targets from the teacher network predictions ( $\mathscr{L}_\text{soft teacher predictions }$ )
- ex. match teacher prediction: 99.5% BWM, 0.4% garbage truk, ... , 0.000001% carrot
How these two parts of the loss function should be weighted is determined by the hyperparameter $\lambda$:
$$\mathscr{L}_\text{student} = \mathscr{L}_\text{correct labels} + \lambda \mathscr{L}_\text{soft teacher predictions}$$
## **1.2 Temperature**
Much information resides in the ratios of very small probabilities in the predictions:
ex.: one version of a 2 may be given a probability of $10^{-6}$ of being a 3 and $10^{-9}$ of being a 7 , whereas for another version it may be the other way around.
- Since most probabilities are very close to zero we expect very little influence on the cross-entropy cost function.
- **How to fix this?**
- Raise the **"temperature" of the final softmax** until the teacher model produces a soft set of targets ($z_i$ are logits, T is Temperature):
$$q_i = \dfrac{\exp(z_i/T)}{\sum_j \exp(z_j/T)}$$
- Using a higher value for $T$ produces a softer probability distribution over classes. Illustrating:
```
import numpy as np
import matplotlib.pyplot as plt
z_i = np.array([0.5, 8 , 1.5, 3, 6 ,
11 , 2.5, 0.01 , 5, 0.2 ])
# Tested probabilities
Temperatures = [1, 4, 20]
plt.figure(figsize=(20, 4))
for i, T in enumerate(Temperatures):
plt.subplot(1, 4, i+1)
# Temperature adjusted soft probabilities:
q_i = np.exp(z_i/T)/np.sum(np.exp(z_i/T))
# Plotting the barchart
plt.bar(range(0,10), q_i)
plt.title('Temperature = '+ str(T), size=15)
plt.xticks(range(10) , range(10), size=10)
plt.xlabel('Classes', size=12)
plt.ylabel('Class Probabilities', size=12)
plt.axhline(y=1, linestyle = '--', color = 'r')
plt.subplot(1, 4, 4)
plt.bar(range(0,10), z_i/30)
plt.axhline(y=1, linestyle = '--', color = 'r')
plt.ylim(0,1.05)
plt.title('Logits ')
```
## **1.3 Examples from the paper**
- Experiment 1: simple MNIST
- Large Teacher network - 2 layers of **1200 neurons** hidden units: **67**/10000 test errors.
- Original student network - 2 layers of **800 neurons** hidden units: **146**/10000 test errors.
- Distilled student network - 2 layers of **800 neurons** hidden units: **74**/10000 test error.
<br/><br/>
- Experiment 2: Distillation can even teach a student network about classes it has never seen:
- During training all the "3" digits are hidden for the student network.
- So "3" is a mythical digit the student network never has seen!
- Still using distillation it manages to correctly classify 877 out of 1010 "3"s in the test set!
- After adjusting the bias term 997/1010 3's are correctly classified!
## Part 2: Use Cases
Let's use Transfer Learning, to build some applications. It is convenient to run the applications on Google Colab. Check out the links below.
### 2.1Transfer learning through Network Distillation
- In distillation a small simple (*student*) network tries to extract or distill knowledge from a large and complex (*teacher*) network.
- This is also known as student-teacher networks or compression, as we try to compress a large model into a small model.
- Goal:
- Understand Knowledge Distillation
- Force a small segmentation network (based on Mobilenet) to learn from a large network (deeplab_v3).
- Find more on the colab notebook [Lecture 7: Use Case Distillation and Compression](https://colab.research.google.com/drive/1l8qVX9-CsV9oae02Kb9NXDmWUjNd79G6)
| github_jupyter |
# Changepoint Detection
Think Bayes, Second Edition
Copyright 2020 Allen B. Downey
License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/)
```
# If we're running on Colab, install empiricaldist
# https://pypi.org/project/empiricaldist/
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
!pip install empiricaldist
# Get utils.py
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(filename):
from urllib.request import urlretrieve
local, _ = urlretrieve(url, filename)
print('Downloaded ' + local)
download('https://github.com/AllenDowney/ThinkBayes2/raw/master/soln/utils.py')
import numpy as np
import pandas as pd
n = 60
t1 = 30
t2 = n-t1
lam1 = 4
lam2 = 2
from scipy.stats import poisson
before = poisson(lam1).rvs(t1)
before
after = poisson(lam2).rvs(t2)
after
data = np.concatenate([before, after])
n = len(data)
lam = 2
lams = np.linspace(0, 10, 51)
D, L = np.meshgrid(data, lams)
like1 = poisson.pmf(D, L).prod(axis=1)
like1 /= like1.sum()
like2 = poisson.pmf(np.sum(data), n*lams)
like2 /= like2.sum()
import matplotlib.pyplot as plt
plt.plot(lams, like1)
plt.plot(lams, like2)
np.sum(lams * like1), np.sum(lams * like2)
poisson.pmf(before, 4)
poisson.pmf(after, 2)
t = 7
def likelihood1(data, t, lam1, lam2):
before = data[:t]
after = data[t:]
like1 = poisson.pmf(before, lam1).prod()
like2 = poisson.pmf(after, lam2).prod()
return like1
like1 = likelihood1(data, t, 4, 2)
like1
from scipy.special import binom
def combos(data):
data = np.asarray(data)
n = data.sum()
k = len(data)
print(n, k)
ns = n - np.cumsum(data) + data
print(ns)
print(data)
cs = binom(ns, data)
print(cs)
return cs.prod() / k**n
combos(data[:t])
from scipy.special import binom
def likelihood2(data, t, lam1, lam2):
before = data[:t].sum()
like1 = poisson.pmf(before, lam1*t) * combos(data[:t])
after = data[t:].sum()
t2 = len(data) - t
n, k = after, t2
like2 = poisson.pmf(after, lam2*t2)
return like1
like2 = likelihood2(data, t, 4, 2)
like2
like2 / like1
from empiricaldist import Pmf
ts = range(1, len(data))
prior_t = Pmf(1, ts)
lams1 = np.linspace(0, 10, 51)
prior_lam1 = Pmf(1, lams1)
lams2 = np.linspace(0, 10, 41)
prior_lam2 = Pmf(1, lams2)
from utils import make_joint
def make_joint3(pmf1, pmf2, pmf3):
"""Make a joint distribution with three parameters."""
joint2 = make_joint(pmf2, pmf1).stack()
joint3 = make_joint(pmf3, joint2).stack()
return Pmf(joint3)
joint_prior = make_joint3(prior_t, prior_lam1, prior_lam2)
joint_prior.head()
```
## Likelihood
```
ts
lams1
T, L = np.meshgrid(ts, lams1)
M = T * L
M.shape
C = np.cumsum(data)[:-1]
C.shape
from scipy.special import binom
like1 = poisson.pmf(C, M) / binom(C+T-1, T-1)
like1.shape
ts2 = len(data) - np.array(ts)
ts2
T2, L2 = np.meshgrid(ts2, lams2)
M2 = T2 * L2
M2.shape
C2 = sum(data) - C
C2.shape
like2 = poisson.pmf(C2, M2) / binom(C2+T2-1, T2-1)
like2.shape
like = like1.T[:, :, None] * like2.T[:, None, :]
like.shape
like.flatten().shape
from utils import normalize
joint_posterior = joint_prior * like.reshape(-1)
normalize(joint_posterior)
from utils import pmf_marginal
posterior_t = pmf_marginal(joint_posterior, 0)
posterior_t.head(3)
posterior_t.plot()
posterior_lam1 = pmf_marginal(joint_posterior, 1)
posterior_lam2 = pmf_marginal(joint_posterior, 2)
posterior_lam1.plot()
posterior_lam2.plot()
```
## Doing it the long way
```
likelihood = joint_prior.copy().unstack().unstack()
likelihood.head()
t = 30
row = likelihood.loc[t].unstack()
row.head()
lams = row.columns
lams.shape
lam_mesh, data_mesh = np.meshgrid(lams, data[:t])
probs = poisson.pmf(data_mesh, lam_mesh)
probs.shape
likelihood1 = probs.prod(axis=0)
likelihood1.shape
lams = row.index
lams.shape
lam_mesh, data_mesh = np.meshgrid(lams, data[t:])
probs = poisson.pmf(data_mesh, lam_mesh)
probs.shape
likelihood2 = probs.prod(axis=0)
likelihood2.shape
likelihood_row = np.multiply.outer(likelihood2, likelihood1)
likelihood_row.shape
likelihood.loc[t] = likelihood_row.flatten()
likelihood.loc[t]
likelihood = joint_prior.copy().unstack().unstack()
likelihood.head()
for t in likelihood.index:
row = likelihood.loc[t].unstack()
lams = row.columns
lam_mesh, data_mesh = np.meshgrid(lams, data[:t])
probs = poisson.pmf(data_mesh, lam_mesh)
likelihood1 = probs.prod(axis=0)
lams = row.index
lam_mesh, data_mesh = np.meshgrid(lams, data[t:])
probs = poisson.pmf(data_mesh, lam_mesh)
likelihood2 = probs.prod(axis=0)
likelihood_row = np.multiply.outer(likelihood2, likelihood1)
likelihood.loc[t] = likelihood_row.flatten()
from utils import normalize
def update(prior, data):
"""
prior: Pmf representing the joint prior
data: sequence f counts
returns: Pmf representing the joint posterior
"""
likelihood = joint_prior.copy().unstack().unstack()
for t in likelihood.index:
row = likelihood.loc[t].unstack()
lams = row.columns
lam_mesh, data_mesh = np.meshgrid(lams, data[:t])
probs = poisson.pmf(data_mesh, lam_mesh)
likelihood1 = probs.prod(axis=0)
lams = row.index
lam_mesh, data_mesh = np.meshgrid(lams, data[t:])
probs = poisson.pmf(data_mesh, lam_mesh)
likelihood2 = probs.prod(axis=0)
likelihood_row = np.multiply.outer(likelihood2, likelihood1)
likelihood.loc[t] = likelihood_row.flatten()
posterior = prior * likelihood.stack().stack()
normalize(posterior)
return posterior
posterior = update(joint_prior, data)
from utils import pmf_marginal
posterior_t = pmf_marginal(posterior, 0)
posterior_t.head(3)
posterior_t.plot()
posterior_lam1 = pmf_marginal(posterior, 1)
posterior_lam2 = pmf_marginal(posterior, 2)
posterior_lam1.plot()
posterior_lam2.plot()
```
## Using emcee
```
try:
import emcee
except:
!pip install emcee
import emcee
print(emcee.__version__)
try:
import corner
except ImportError:
!pip install corner
try:
import tdqm
except ImportError:
!pip install tdqm
from scipy.stats import poisson
from scipy.stats import gamma
alpha, beta = 3, 1
def log_prior(theta):
t, lam1, lam2 = theta
return gamma.logpdf([lam1, lam2], alpha, beta).sum()
def log_likelihood(theta, data):
t, lam1, lam2 = theta
t = int(t)
k1 = data[:t]
k2 = data[t:]
like1 = poisson.logpmf(k1, lam1).sum()
like2 = poisson.logpmf(k2, lam2).sum()
return like1 + like2
def log_posterior(theta, data):
t, lam1, lam2 = theta
if t < 1 or t >= len(data):
return -np.inf
if lam1 < 0 or lam2 < 0:
return -np.inf
return log_likelihood(theta, data)
ndim = 3 # number of parameters in the model
nwalkers = 50 # number of MCMC walkers
nburn = 500 # "burn-in" period to let chains stabilize
nsteps = 2500 # number of MCMC steps to take
np.random.seed(0)
com = 30, 3, 3
starting_guesses = com + np.random.random((nwalkers, ndim))
sampler = emcee.EnsembleSampler(nwalkers, ndim, log_posterior, args=[data])
state = sampler.run_mcmc(starting_guesses, nsteps, progress=True)
flat_samples = sampler.get_chain(discard=100, thin=15, flat=True)
flat_samples.shape
import corner
truths = [30, 4, 2]
labels = ['t', 'lam1', 'lam2']
fig = corner.corner(flat_samples, labels=labels, truths=truths);
stop
```
Based on an example from Chapter 1 of [Bayesian Methods for Hackers](http://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb)
and this example from [Computational Statistics in Python](http://people.duke.edu/~ccc14/sta-663-2016/16C_PyMC3.html#Changepoint-detection)
```
import pymc3 as pm
n = len(data)
t = range(n)
alpha = 1.0 / np.mean(data)
import theano.tensor as T
with pm.Model() as model:
tau = pm.DiscreteUniform('tau', lower=0, upper=n)
lam1 = pm.Exponential('lam1', alpha)
lam2 = pm.Exponential('lam2', alpha)
lam = T.switch(t < tau, lam1, lam2)
Y_obs = pm.Poisson('Y_obs', lam, observed=data)
trace = pm.sample(10000, tune=2000)
pm.traceplot(trace);
tau_sample = trace['tau']
cdf_tau = Cdf(tau_sample)
thinkplot.Cdf(cdf_tau)
lam1_sample = trace['lam1']
cdf_lam1 = Cdf(lam1_sample)
thinkplot.Cdf(cdf_lam1)
lam2_sample = trace['lam2']
cdf_lam2 = Cdf(lam2_sample)
thinkplot.Cdf(cdf_lam2)
stop
# !wget https://raw.githubusercontent.com/baltimore-sun-data/2018-shootings-analysis/master/BPD_Part_1_Victim_Based_Crime_Data.csv
df = pd.read_csv('BPD_Part_1_Victim_Based_Crime_Data.csv', parse_dates=[0])
df.head()
df.shape
shootings = df[df.Description.isin(['HOMICIDE', 'SHOOTING']) & (df.Weapon == 'FIREARM')]
shootings.shape
grouped = shootings.groupby('CrimeDate')
counts = grouped['Total Incidents'].sum()
counts.head()
index = pd.date_range(counts.index[0], counts.index[-1])
counts = counts.reindex(index, fill_value=0)
counts.head()
counts.plot()
thinkplot.decorate(xlabel='Date',
ylabel='Number of shootings')
```
| github_jupyter |
#### New to Plotly?
Plotly's Python library is free and open source! [Get started](https://plotly.com/python/getting-started/) by downloading the client and [reading the primer](https://plotly.com/python/getting-started/).
<br>You can set up Plotly to work in [online](https://plotly.com/python/getting-started/#initialization-for-online-plotting) or [offline](https://plotly.com/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plotly.com/python/getting-started/#start-plotting-online).
<br>We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!
#### Populate a Table Using a Plotly Mouse Selection Event
Create a table FigureWidget that is updated by a selection event in another FigureWidget. The rows in the table correspond to points selected in the selection event.
```
import plotly.graph_objs as go
import plotly.offline as py
import pandas as pd
import numpy as np
from ipywidgets import interactive, HBox, VBox
py.init_notebook_mode()
df = pd.read_csv('https://raw.githubusercontent.com/jonmmease/plotly_ipywidget_notebooks/master/notebooks/data/cars/cars.csv')
f = go.FigureWidget([go.Scatter(y = df['City mpg'], x = df['City mpg'], mode = 'markers')])
scatter = f.data[0]
N = len(df)
scatter.x = scatter.x + np.random.rand(N)/10 *(df['City mpg'].max() - df['City mpg'].min())
scatter.y = scatter.y + np.random.rand(N)/10 *(df['City mpg'].max() - df['City mpg'].min())
scatter.marker.opacity = 0.5
def update_axes(xaxis, yaxis):
scatter = f.data[0]
scatter.x = df[xaxis]
scatter.y = df[yaxis]
with f.batch_update():
f.layout.xaxis.title = xaxis
f.layout.yaxis.title = yaxis
scatter.x = scatter.x + np.random.rand(N)/10 *(df[xaxis].max() - df[xaxis].min())
scatter.y = scatter.y + np.random.rand(N)/10 *(df[yaxis].max() - df[yaxis].min())
axis_dropdowns = interactive(update_axes, yaxis = df.select_dtypes('int64').columns, xaxis = df.select_dtypes('int64').columns)
# Create a table FigureWidget that updates on selection from points in the scatter plot of f
t = go.FigureWidget([go.Table(
header=dict(values=['ID','Classification','Driveline','Hybrid'],
fill = dict(color='#C2D4FF'),
align = ['left'] * 5),
cells=dict(values=[df[col] for col in ['ID','Classification','Driveline','Hybrid']],
fill = dict(color='#F5F8FF'),
align = ['left'] * 5))])
def selection_fn(trace,points,selector):
t.data[0].cells.values = [df.loc[points.point_inds][col] for col in ['ID','Classification','Driveline','Hybrid']]
scatter.on_selection(selection_fn)
# Put everything together
VBox((HBox(axis_dropdowns.children),f,t))
```
<img src='https://raw.githubusercontent.com/michaelbabyn/plot_data/master/mouse-event-figurewidget.gif'>
#### Reference
See [these Jupyter notebooks](https://github.com/jonmmease/plotly_ipywidget_notebooks) for even more FigureWidget examples.
```
help(go.FigureWidget)
from IPython.display import display, HTML
display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">'))
! pip install git+https://github.com/plotly/publisher.git --upgrade
import publisher
publisher.publish(
'selection-events-figure-widget.ipynb', 'python/selection-events/', 'Selection Events with go.FigureWidget',
'Selection Events With FigureWidget',
title = 'Selection Events',
name = 'Selection Events',
has_thumbnail='true', thumbnail='thumbnail/figurewidget-selection-events.gif',
language='python',
display_as='chart_events', order=24,
ipynb= '~notebook_demo/229')
```
| github_jupyter |
```
# Use the Azure Machine Learning data collector to log various metrics
from azureml.logging import get_azureml_logger
logger = get_azureml_logger()
# Use Azure Machine Learning history magic to control history collection
# History is off by default, options are "on", "off", or "show"
# %azureml history on
# The purpose of this notebook is to apply the **Gradient Boosting** model trained using Word2Vec on testing data and show the performance of the model for sentiment polarity prediction.
import numpy as np
import pandas as pd
import os
import io
random_seed=1
np.random.seed(random_seed)
import tensorflow as tf
import keras
from keras import backend as K
from keras.models import Model
from keras.layers import Input, merge
from keras.layers.core import Lambda
from keras import optimizers
from keras import regularizers
from keras.models import load_model
from keras.callbacks import ModelCheckpoint
from keras.utils.np_utils import to_categorical
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils.np_utils import to_categorical
from keras.models import Sequential
from keras.layers import Input, Dense, Flatten, Embedding , Activation
from nltk.tokenize import TweetTokenizer
import re
import num2words
from timeit import default_timer as timer
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import KFold
from sklearn.externals import joblib
import matplotlib.pyplot as plt
%matplotlib inline
# Path of the test data directory'
data_dir = r'C:\Users\ds1\Documents\AzureML\data'
vectors_file = r'../02_modeling/vectors/embeddings_Word2Vec_Basic.tsv'
model_file = r'../02_modeling/model/evaluation_word2vec_gbm'
# Data Preprocessing
pos_emoticons=["(^.^)","(^-^)","(^_^)","(^_~)","(^3^)","(^o^)","(~_^)","*)",":)",":*",":-*",":]",":^)",":}",
":>",":3",":b",":-b",":c)",":D",":-D",":O",":-O",":o)",":p",":-p",":P",":-P",":Þ",":-Þ",":X",
":-X",";)",";-)",";]",";D","^)","^.~","_)m"," ~.^","<=8","<3","<333","=)","=///=","=]","=^_^=",
"=<_<=","=>.<="," =>.>="," =3","=D","=p","0-0","0w0","8D","8O","B)","C:","d'-'","d(>w<)b",":-)",
"d^_^b","qB-)","X3","xD","XD","XP","ʘ‿ʘ","❤","💜","💚","💕","💙","💛","💓","💝","💖","💞",
"💘","💗","😗","😘","😙","😚","😻","😀","😁","😃","☺","😄","😆","😇","😉","😊","😋","😍",
"😎","😏","😛","😜","😝","😮","😸","😹","😺","😻","😼","👍"]
neg_emoticons=["--!--","(,_,)","(-.-)","(._.)","(;.;)9","(>.<)","(>_<)","(>_>)","(¬_¬)","(X_X)",":&",":(",":'(",
":-(",":-/",":-@[1]",":[",":\\",":{",":<",":-9",":c",":S",";(",";*(",";_;","^>_>^","^o)","_|_",
"`_´","</3","<=3","=/","=\\",">:(",">:-(","💔","☹️","😌","😒","😓","😔","😕","😖","😞","😟",
"😠","😡","😢","😣","😤","😥","😦","😧","😨","😩","😪","😫","😬","😭","😯","😰","😱","😲",
"😳","😴","😷","😾","😿","🙀","💀","👎"]
# Emails
emailsRegex=re.compile(r'[\w\.-]+@[\w\.-]+')
# Mentions
userMentionsRegex=re.compile(r'(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9]+)')
#Urls
urlsRegex=re.compile('r(f|ht)(tp)(s?)(://)(.*)[.|/][^ ]+') # It may not be handling all the cases like t.co without http
#Numerics
numsRegex=re.compile(r"\b\d+\b")
punctuationNotEmoticonsRegex=re.compile(r'(?<=\w)[^\s\w](?![^\s\w])')
emoticonsDict = {} # define desired replacements here
for i,each in enumerate(pos_emoticons):
emoticonsDict[each]=' POS_EMOTICON_'+num2words.num2words(i).upper()+' '
for i,each in enumerate(neg_emoticons):
emoticonsDict[each]=' NEG_EMOTICON_'+num2words.num2words(i).upper()+' '
# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in emoticonsDict.items())
emoticonsPattern = re.compile("|".join(rep.keys()))
def read_data(filename):
"""Read the raw tweet data from a file. Replace Emails etc with special tokens"""
with open(filename, 'r') as f:
all_lines=f.readlines()
padded_lines=[]
for line in all_lines:
line = emoticonsPattern.sub(lambda m: rep[re.escape(m.group(0))], line.lower().strip())
line = userMentionsRegex.sub(' USER ', line )
line = emailsRegex.sub(' EMAIL ', line )
line=urlsRegex.sub(' URL ', line)
line=numsRegex.sub(' NUM ',line)
line=punctuationNotEmoticonsRegex.sub(' PUN ',line)
line=re.sub(r'(.)\1{2,}', r'\1\1',line)
words_tokens=[token for token in TweetTokenizer().tokenize(line)]
line= ' '.join(token for token in words_tokens )
padded_lines.append(line)
return padded_lines
def read_labels(filename):
""" read the tweet labels from the file"""
arr= np.genfromtxt(filename, delimiter='\n')
arr[arr==4]=1 # Encode the positive category as 1
return arr
# Convert Word Vectors to Sentence Vectors
def load_word_embedding(vectors_file):
""" Load the word vectors"""
vectors= np.genfromtxt(vectors_file, delimiter='\t', comments='#--#',dtype=None,
names=['Word']+['EV{}'.format(i) for i in range(1,51)])
# comments have to be changed as some of the tokens are having # in them and then we dont need comments
vectors_dc={}
for x in vectors:
vectors_dc[x['Word'].decode('utf-8','ignore')]=[float(x[each]) for each in ['EV{}'.format(i) for i in range(1,51)]]
return vectors_dc
def get_sentence_embedding(text_data, vectors_dc):
sentence_vectors=[]
for sen in text_data:
tokens=sen.split(' ')
current_vector=np.array([vectors_dc[tokens[0]] if tokens[0] in vectors_dc else vectors_dc['<UNK>']])
for word in tokens[1:]:
if word in vectors_dc:
current_vector=np.vstack([current_vector,vectors_dc[word]])
else:
current_vector=np.vstack([current_vector,vectors_dc['<UNK>']])
min_max_mean=np.hstack([current_vector.min(axis=0),current_vector.max(axis=0),current_vector.mean(axis=0)])
sentence_vectors.append(min_max_mean)
return sentence_vectors
print ('Step1: Loading Testing data')
test_texts=read_data(data_dir+'/testing_text.csv')
test_labels=read_labels(data_dir+'/testing_label.csv')
print ('Step2: Load word vectors')
vectors_dc=load_word_embedding(vectors_file)
print ('Step 3: Convert word vectors to sentence vectors')
test_sentence_vectors=get_sentence_embedding(test_texts, vectors_dc)
print (len(test_sentence_vectors), len(test_labels), len(test_texts))
test_x=np.array(test_sentence_vectors).astype('float32')
test_y=np.array(test_labels)
print ('Step 4: Loading the model')
gbm = joblib.load(model_file)
y_pred = gbm.predict(test_x)
y_pred_pos = gbm.predict_proba(test_x)[:, 1]
print ('Step 5: Getting the results')
print ('\t Accuracy : %.4f' % metrics.accuracy_score(test_y, y_pred))
print ('\t Macro-Average Precision : %.4f' % ((metrics.precision_score(test_y, y_pred, pos_label=0) +
metrics.precision_score(test_y, y_pred, pos_label=1))/2))
print ('\t Macro-Average Recall : %.4f' % ((metrics.recall_score(test_y, y_pred, pos_label=0) +
metrics.recall_score(test_y, y_pred, pos_label=1))/2))
print ('\t Macro-Average F1 : %.4f' % ((metrics.f1_score(test_y, y_pred, pos_label=0)
+ metrics.f1_score(test_y, y_pred, pos_label=1))/2)
)
fpr,tpr,thresh=metrics.roc_curve(test_y, y_pred_pos)
roc_auc=metrics.auc(fpr,tpr,'macro')
print ('fpr {}, tpr {}, auc {}'.format(fpr, tpr, roc_auc))
plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)
plt.legend(loc = 'lower right')
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()
```
| github_jupyter |
```
import numpy as np
import pandas as pd
import seaborn as sns
import scipy as sns
import pandas_profiling
import random
import math
import time
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error,mean_absolute_error
import datetime
import os
import sys
path=('/home/manikanta/Documents/pandas/novel-corona-virus-2019-dataset')
all_files=glob.glob(path+"/*.csv")
li=[]
for filename in all_files:
df=pd.read_csv(filename,index_col=None,header=0)
li.append(df)
frame=pd.concat(li,axis=0,ignore_index=True,sort=False)
frame
recoverd=pd.read_csv('/home/manikanta/Documents/pandas/novel-corona-virus-2019-dataset/time_series_covid_19_recovered.csv')
conformed=pd.read_csv('/home/manikanta/Documents/pandas/novel-corona-virus-2019-dataset/time_series_covid_19_confirmed.csv')
deaths=pd.read_csv('/home/manikanta/Documents/pandas/novel-corona-virus-2019-dataset/time_series_covid_19_deaths.csv')
recoverd.head(2)
conformed.head(2)
deaths.tail(2)
cols1=conformed.keys()
cols1
cols2=recoverd.keys()
cols2
cols3=deaths.keys()
cols3
conformed1=conformed.loc[:,cols[4]:cols[-1]]
conformed1.head()
deaths1=deaths.loc[:,cols3[4]:cols[-1]]
deaths1.head(2)
recoverd1=recoverd.loc[:,cols2[4]:cols[-1]]
recoverd1.head(2)
dates=conformed1.keys()
world_cases=[]
total_deaths=[]
morality_rate=[]
total_recovered=[]
for i in dates:
conformed_sum=conformed1[i].sum()
death_sum=deaths1[i].sum()
recoverd_sum=recoverd1[i].sum()
world_cases.append(conformed_sum)
total_deaths.append(death_sum)
morality_rate.append(death_sum/conformed_sum)
total_recovered.append(recoverd_sum)
len(world_cases),len(total_deaths),len(morality_rate),len(total_recovered)
days_since_1_22=np.array([i for i in range(len(dates))]).reshape(-1,1)
world_cases=np.array(world_cases).reshape(-1,1)
total_deaths=np.array(total_deaths).reshape(-1,1)
total_recovered=np.array(total_recovered).reshape(-1,1)
days_since_1_22
days_in_future=3
future_forcast=np.array([i for i in range(len(dates)+days_in_future)]).reshape(-1,1)
future_forcast[0:5]
start='1/22/2020'
start_date=datetime.datetime.strptime(start,'%m/%d/%Y')
future_forcast_dates=[]
for i in range(len(future_forcast)):
future_forcast_dates.append((start_date+datetime.timedelta(days=i)).strftime('%m/%d/%Y'))
adjusted_dates=future_forcast_dates[:-3]
start_date
adjusted_dates[0:5]
future_forcast_dates[0:5]
from sklearn.model_selection import train_test_split
x_trine_conformed,x_test_conformed,y_trine_conformed,y_test_conformed=train_test_split(days_since_1_22,world_cases,test_size=0.1,shuffle=False)
model=LinearRegression(fit_intercept=False,normalize=True)
model
model.fit(x_trine_conformed,y_trine_conformed)
trine_score=model.score(x_trine_conformed,y_trine_conformed)
trine_score
test_score=model.score(x_test_conformed,y_test_conformed)
test_score
test_linear_pred=model.predict(x_test_conformed)
linear_pred=model.predict(future_forcast)
linear_pred
model.coef_
model.intercept_
import matplotlib.pyplot as plt
plt.plot(y_test_conformed)
plt.plot(test_linear_pred)
plt.figure(figsize=(20,12))
plt.plot(adjusted_dates,world_cases)
plt.title('# of corona virus cases over time',size=30)
plt.xlabel('# Time in days',size=30)
plt.ylabel('# of cases',size=30)
plt.xticks(rotation=90,size=15)
plt.show()
plt.figure(figsize=(20,12))
plt.plot(adjusted_dates,world_cases)
plt.plot(future_forcast_dates,linear_pred,linestyle='dashed')
plt.title('# of corona virus cases over time',size=30)
plt.xlabel('# Time in days',size=30)
plt.ylabel('# of cases',size=30)
plt.legend(['confirmed cases','LinearRegression Predictions'])
plt.xticks(rotation=90,size=15)
plt.show()
plt.figure(figsize=(20,12))
plt.plot(adjusted_dates,total_deaths)
plt.title('# of corona virus Deaths over time',size=30)
plt.xlabel('# Time',size=30)
plt.ylabel('# of Deaths',size=30)
plt.xticks(rotation=90,size=15)
plt.show()
mean_mortality_rate=np.mean(morality_rate)
plt.figure(figsize=(20,12))
plt.plot(adjusted_dates,morality_rate,color='orange')
plt.axhline(y=mean_mortality_rate,linestyle='--',color='black')
plt.title('Mortality Rate of Coronavirus over time',size=30)
plt.legend(['Mortality Rate','y='+str(mean_mortality_rate)])
plt.xlabel('Time',size=30)
plt.ylabel('Mortality Rate',size=30)
plt.xticks(rotation=90,size=15)
plt.show()
```
| github_jupyter |
# PRMT-2116 Generate High level table with new transfer categorisation
We’ve completed work for recategorising transfers, so now we want to regenerate the top level table of GP2GP transfers with these categorisations, so we can prioritise next things to look at. We also want to update the table with more recent data, as we’ve currently got September - Feb 2020.
### Scope
Generate the top level problems table
- With new transfer categorisations
- With March-May data only (excluding three months prior)
- Generate individual for each month
```
import pandas as pd
import numpy as np
transfer_file_location = "s3://prm-gp2gp-data-sandbox-dev/transfers-sample-6/"
transfer_files = [
"2021-3-transfers.parquet",
"2021-4-transfers.parquet",
"2021-5-transfers.parquet",
"2021-6-transfers.parquet",
]
transfer_input_files = [transfer_file_location + f for f in transfer_files]
transfers_raw = pd.concat((
pd.read_parquet(f)
for f in transfer_input_files
))
```
#### TODO: How do we deal with status at exactly 14 or 28 days rather than 14/28 days after the month ended
```
import paths
import data
error_code_lookup_file = pd.read_csv(data.gp2gp_response_codes.path)
transfers = transfers_raw.copy()
transfers["status"] = transfers["status"].str.replace("_", " ").str.title()
outcome_counts = transfers.fillna("N/A").groupby(by=["status", "failure_reason"]).agg({"conversation_id": "count"})
outcome_counts = outcome_counts.rename({"conversation_id": "Number of transfers", "failure_reason": "Failure Reason"}, axis=1)
outcome_counts["% of transfers"] = (outcome_counts["Number of transfers"] / outcome_counts["Number of transfers"].sum()).multiply(100)
outcome_counts.round(2)
transfers['month']=transfers['date_requested'].dt.to_period('M')
def convert_error_list_to_tuple(error_code_list, error_code_type):
return [(error_code_type, error_code) for error_code in set(error_code_list) if not np.isnan(error_code)]
def convert_error_to_tuple(error_code, error_code_type):
if np.isnan(error_code):
return []
else:
return [(error_code_type, error_code)]
def combine_error_codes(row):
sender_list = convert_error_to_tuple(row["sender_error_code"], "Sender")
intermediate_list = convert_error_list_to_tuple(row["intermediate_error_codes"], "COPC")
final_list = convert_error_list_to_tuple(row["final_error_codes"], "Final")
full_error_code_list = sender_list + intermediate_list + final_list
if len(full_error_code_list) == 0:
return [("No Error Code", "No Error")]
else:
return full_error_code_list
transfers["all_error_codes"] = transfers.apply(combine_error_codes, axis=1)
transfers["all_error_codes"]
# We spotted a discrepency - patches of investigative code here - to delete!!
transfers.loc[transfers['failure_reason']=='Contains Fatal Sender Error']
convert_error_to_tuple(14.0, "Sender")
transfers.loc[transfers['failure_reason']=='Contains Fatal Sender Error','all_error_codes'].value_counts()
discrepency_bool=(transfers['failure_reason']=='Contains Fatal Sender Error') & (transfers['sender_error_code'].isna())
transfers_split_by_error_code=transfers.explode("all_error_codes")
total_number_of_error_codes=transfers_split_by_error_code['all_error_codes'].value_counts().drop(('No Error Code','No Error')).sum()
total_number_of_error_codes
def generate_high_level_table(transfers_sample):
# Break up lines by error code
transfers_split_by_error_code=transfers_sample.explode("all_error_codes")
# Create High level table
high_level_table=transfers_split_by_error_code.fillna("N/A").groupby(["requesting_supplier","sending_supplier","status","failure_reason","all_error_codes"]).agg({'conversation_id':'count'})
high_level_table=high_level_table.rename({'conversation_id':'Number of Transfers'},axis=1).reset_index()
# Count % of transfers
total_number_transfers = transfers_sample.shape[0]
high_level_table['% of Transfers']=(high_level_table['Number of Transfers']/total_number_transfers).multiply(100)
# Count by supplier pathway
supplier_pathway_counts = transfers_sample.fillna("Unknown").groupby(by=["sending_supplier", "requesting_supplier"]).agg({"conversation_id": "count"})['conversation_id']
high_level_table['% Supplier Pathway Transfers']=high_level_table.apply(lambda row: row['Number of Transfers']/supplier_pathway_counts.loc[(row['sending_supplier'],row['requesting_supplier'])],axis=1).multiply(100)
# Add in Paper Fallback columns
total_fallback = transfers_sample["failure_reason"].dropna().shape[0]
fallback_bool=high_level_table['status']!='Integrated On Time'
high_level_table.loc[fallback_bool,'% Paper Fallback']=(high_level_table['Number of Transfers']/total_fallback).multiply(100)
# % of error codes column
total_number_of_error_codes=transfers_split_by_error_code['all_error_codes'].value_counts().drop(('No Error Code','No Error')).sum()
error_code_bool=high_level_table['all_error_codes']!=('No Error Code', 'No Error')
high_level_table.loc[error_code_bool,'% of error codes']=(high_level_table['Number of Transfers']/total_number_of_error_codes).multiply(100)
# Adding columns to describe errors
high_level_table['error_type']=high_level_table['all_error_codes'].apply(lambda error_tuple: error_tuple[0])
high_level_table['error_code']=high_level_table['all_error_codes'].apply(lambda error_tuple: error_tuple[1])
high_level_table=high_level_table.merge(error_code_lookup_file[['ErrorCode','ResponseText']],left_on='error_code',right_on='ErrorCode',how='left')
# Select and re-order table
grouping_columns_order=['requesting_supplier','sending_supplier','status','failure_reason','error_type','ResponseText','error_code']
counting_columns_order=['Number of Transfers','% of Transfers','% Supplier Pathway Transfers','% Paper Fallback','% of error codes']
high_level_table=high_level_table[grouping_columns_order+counting_columns_order].sort_values(by='Number of Transfers',ascending=False)
return high_level_table
with pd.ExcelWriter("High Level Tables PRMT-2116.xlsx") as writer:
generate_high_level_table(transfers.copy()).to_excel(writer, sheet_name="All",index=False)
[generate_high_level_table(transfers[transfers['month']==month].copy()).to_excel(writer, sheet_name=str(month),index=False) for month in transfers['month'].unique()]
```
| github_jupyter |
Видосы, которые которые гораздо подробнее этого ноутбука
- [Что такое Python и почему мы выбрали именно его](https://www.coursera.org/learn/mathematics-and-python/lecture/VXRfy/chto-takoie-python-i-pochiemu-my-vybrali-imienno-iegho)
- [Что такое ноутбуки и как ими пользоваться](https://www.coursera.org/learn/mathematics-and-python/lecture/Q9ZCs/chto-takoie-noutbuki-i-kak-imi-pol-zovat-sia)
- [Типы данных](https://www.coursera.org/learn/mathematics-and-python/lecture/yCNAx/tipy-dannykh)
- [Циклы, функции, генераторы, list comprehension](https://www.coursera.org/learn/mathematics-and-python/lecture/Kd7dL/tsikly-funktsii-ghienieratory-list-comprehension)
- [Чтение данных из файлов](https://www.coursera.org/learn/mathematics-and-python/lecture/8Xvwp/chtieniie-dannykh-iz-failov)
- [Запись файлов, изменение файлов](https://www.coursera.org/learn/mathematics-and-python/lecture/vde7k/zapis-failov-izmienieniie-failov)
Чтиво на досуге
- [Работа с ячейками markdown](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html)
# Jupyter notebook
То, куда ты смотришь -- это jupyter notebook. У jupyter notebook есть несколько видов ячеек:
- Ячейки, в которых можно использовать html и [markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet);
- Ячейки, в которых можно писать код и выполнять его;
- Ячейки в plain text (Иногда полезно)
Чтобы выполнить ячейку, надо кликнуть по ней и нажать `shift + enter` или `ctrl + enter` или посмотреть наверх и нажать 
## Markdown+latex in Jupyter notebook
Начнем с первого типа ячеек, в которых можно писать `KPACUBO`.
Чтобы сделать ячейку-markdown: надо опять кликнуть по ней и нажать `m` или опять посмотреть наверх и выбрать markdown

После этого, можно просто открыть [шпаргалку по markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) и писать все красивенько
### Формулы
Чтобы написать формулу в jupyter notebook надо обернуть выражение на `latex` в `$`
Тогда выражение вида `$\underset{x \rightarrow 0}{lim} \frac{sin x}{x} = 1$` будет выглядеть следующим образом: $\underset{x \rightarrow 0}{lim} \frac{sin x}{x} = 1$
Если есть желание сделать формулу по-центру, то достаточно обернуть ее в двойные знаки доллара:
`$$\underset{x \rightarrow 0}{lim} \frac{sin x}{x} = 1$$`
$$\underset{x \rightarrow 0}{lim} \frac{sin x}{x} = 1$$
## Пихтон
### Как обычно
```
print('Hello world!')
```
### Основные типы данных
### Создание переменных
```
# Это комментарий, этот кусок кода не будет выполняться программой
# Это переменная на python
a = 3 # Целочисленная переменная
print(a, type(a))
e = 2.71 # Float
print(e, type(e))
b = 'Hello there!' # Строка 1
print(b, type(b))
d = "General Kenobi!" # Строка 2
print(d, type(d))
# Используя разные кавычки можно оборачивать кавычки внутри строки
w = "Wow I 'did not' expect that"
w = 'Wow I "did not" expect that'
# А такое уже не пройдет
w = "Wow I "did not" expect that"
```
#### Note по типизации (можно пропустить)
Python является динамически типизированным языком. Это значит, что переменная хранит лишь ссылку на объект без привязки к типу. Это значит, что допустимо перезаписывать что угодно в переменную:
```
a = 3
print(a, type(a))
a = 'heck'
print(a, type(a))
```
Есть такая штука, как `type hints`. Они появились в python 3.6. Но все, что они делают -- это дают способ договориться насчет типов переменных, но никаких ошибок не будет, если указать тип, а потом переписать туда что-то другого типа.
```
q: int = 3
print(q, type(q))
q = 'line'
print(q, type(q))
```
Может показаться, что это бесполезный функционал, однако, по мере того, как программа разрастается, становится сложно уследить, что в какой переменной хранится. Плюс современные текстовые редакторы дают подсказки и предупреждения, если дать им возможность.
Больше по [type hints](https://docs.python.org/3/library/typing.html)
### Подсказки по методам
В jupyter notebook просто вывести подсказки об интересующем
Надо просто набрать `function_or_method?`, т.е. добавить вопросительный знак в конце интересующего нечто.
```
print?
```
Одна из многих фичей ноутбуков -- это то, что код можно выполнять непоследовательно, например:
```
# три
a + b
# раз
a = 5
# два
b = 10
```
Как видно, ячейки выполнены в странном порядке. Дело в том, что jupyter хранит практически всё.
Можно создать переменную `c` и удалить ячейку с ней, но переменная не пропадет.
```
# Ячейка с переменной c удалена, так что ошибка при запуске -- это норма с:
c
```
Следует иметь это ввиду и не делать так, поскольку заявленная фича jupyter notebook-ов -- это воспроизводимость исследований. Если поступать так, как описано выше, то воспроизвести результат становится невозможно.
### Функции
_Reading list_
1. https://www.tutorialspoint.com/python/python_functions.htm
Функции в python объявляются следующим образом:
Ключевое слово для начала объявления функции
```python
def
```
Название функции
```python
def function_name
```
Перечисление аргументов функции
Способ 1: Нет аргументов
```python
def function_name():
# Тело функции
```
Способ 2: 1 аргумент
```python
def function_name(fst):
# Тело функции
```
_Optional_ можно добавить тип того, что передаем на вход
```python
def function_name(fst: float):
# Тело функции
```
_Optional_ А также то, что отдаем на выход
```python
def function_name(fst: float) -> int:
# Тело функции
```
Два аргумента
```python
def function_name(fst, snd):
# Тело функции
```
Функция, которая ничего не возвращает
```python
def function_name(fst, snd):
fst + snd
```
Функция, которая возвращает сумму `fst` и `snd`
```python
def function_name(fst, snd):
return fst + snd
```
Функция, которая создает локальные переменные `fst1` и `snd1`, которые копии `fst` и `snd` и возвращает их произведение
```python
def function_name(fst, snd):
fst1 = fst
snd2 = snd
return fst1 * snd2
```
```
def my_func(a, b, c):
d = (a + b) * c
return d
print(my_func(1, 2, 3))
print(my_func(3, 3, 3))
print(my_func(6, 2, 3))
# А что будет в таком случае?
print(my_func('Oh ', 'no ', 3))
```
| github_jupyter |
# the Monte Carlo experiment
```
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
```
A handy routines to store and recover python objects, in particular, the experiment resutls dictionaires.
```
import time, gzip
import os, pickle
def save(obj, path, prefix=None):
prefix_ = "" if prefix is None else "%s_"%(prefix,)
filename_ = os.path.join(path, "%s%s.gz"%(prefix_, time.strftime("%Y%m%d-%H%M%S"),))
with gzip.open(filename_, "wb+", 9) as fout_:
pickle.dump(obj, fout_)
return filename_
def load(filename):
with gzip.open(filename, "rb") as f:
return pickle.load(f)
```
The path analyzer
```
from crossing_tree import structural_statistics
```
Collect a list of results returned by path_analyze into aligned data tensors.
```
from crossing_tree import collect_structural_statistics
```
A function implementing various delta choices.
```
import warnings
def get_delta_method(delta=1.0):
if isinstance(delta, str):
if delta == "std":
# the standard deviation of increments
delta_ = lambda X: np.diff(X).std()
elif delta == "med":
# Use the median absolute difference [Jones, Rolls; 2009] p. 11 (arxiv:0911.5204v2)
delta_ = lambda X: np.median(np.abs(np.diff(X)))
elif delta == "mean":
# Use the mean absolute difference
delta_ = lambda X: np.mean(np.abs(np.diff(X)))
elif delta == "iqr":
# Interquartile range
delta_ = lambda X: np.subtract(*np.percentile(np.diff(X), [75, 25]))
elif delta == "rng":
# Use the range estimate as suggested by Geoffrey on 2015-05-28
warnings.warn("""Use of `range`-based grid resolution """
"""is discouraged since it may cause misaligned """
"""crossing trees.""", RuntimeWarning)
delta_ = lambda X: (X.max() - X.min()) / (2**12)
else:
raise ValueError("""Invalid `delta` setting. Accepted values """
"""are: [`iqr`, `std`, `med`, `rng`, `mean`].""")
elif isinstance(delta, float) and delta > 0:
delta_ = lambda X: delta
else:
raise TypeError("""`delta` must be either a float, or a method """
"""identifier.""")
return delta_
```
An MC experiment kernel.
```
from sklearn.base import clone
def experiment(experiment_id, n_replications, methods, generator):
generator = clone(generator)
generator.start()
deltas = [get_delta_method(method_) for method_ in methods]
results = {method_: list() for method_ in methods}
for j in xrange(n_replications):
T, X = generator.draw()
# Apply all methods to the same sample path.
for delta, method in zip(deltas, methods):
result_ = structural_statistics(X, T, scale=delta(X), origin=X[0])
results[method].append(result_)
generator.finish()
return experiment_id, results
```
## Experiments
```
from joblib import Parallel, delayed
```
A couple of random seeds from [here](https://www.random.org/bytes/).
```
# Extra random seeds should be prepended to the array.
master_seeds = [0xD5F60A17, 0x26F9935C, 0x0E4C1E75, 0xDA7C4291, 0x7ABE722E,
0x126F3E10, 0x045300B1, 0xB0A9AD11, 0xEED05353, 0x824736C7,
0x7AA17C9C, 0xB695D6B1, 0x7E214411, 0x538CDEEF, 0xFD55FF46,
0xE14E1801, 0x872F687C, 0xA58440D9, 0xB8A273FD, 0x0BD1DD28,
0xAB6A6AE6, 0x7180E905, 0x870E7BAB, 0x846D0C7A, 0xAEF0422D,
0x16C53C83, 0xE32EA61D, 0xE0AD0A26, 0xCC90CA9A, 0x7D4020D2,]
```
the Monte Carlo experiemnt is run in parallel batches, with each
initialized to a randomly picked seed.
```
MAX_RAND_SEED = np.iinfo(np.int32).max
```
The folder to store the results in
```
OUTPUT_PATH = "../results/"
```
## fBM experiment
```
from crossing_tree.processes import FractionalBrownianMotion
seed = master_seeds.pop()
print("Using seed %X"%(seed,))
random_state = np.random.RandomState(seed)
skip = False
```
Setup
```
n_samples, methods = 1 << 23, ["med", "std", "iqr", "mean",]
hurst_exponents = [0.500, 0.550, 0.600, 0.650, 0.700, 0.750, 0.800, 0.850, 0.900,
0.910, 0.915, 0.920, 0.925, 0.930, 0.935, 0.940, 0.945, 0.950,
0.990,]
n_per_batch, n_batches = 125, 8
```
Run the experiment for the Fractional Brownian Motion.
```
if not skip:
par_ = Parallel(n_jobs=-1, verbose=0)
for hurst_ in hurst_exponents:
name_ = "FBM-%d-%0.3f-%dx%d"%(n_samples, hurst_, n_per_batch, n_batches)
print(name_,)
# Schedule the experiments
seeds = random_state.randint(MAX_RAND_SEED, size=(n_batches,))
schedule_ = (delayed(experiment)(seed_, n_per_batch, methods,
FractionalBrownianMotion(N=n_samples,
hurst=hurst_,
random_state=seed_))
for seed_ in seeds)
# Run the experiment and collect the results
tick_ = time.time()
experiment_ids = list()
results_ = {method: list() for method in methods}
for id_, dict_ in par_(schedule_):
experiment_ids.append(id_)
for method in methods:
results_[method].extend(dict_[method])
results = {key_: collect_structural_statistics(list_)
for key_, list_ in results_.iteritems()}
tock_ = time.time()
# Save the results and log
filename_ = save((tick_, tock_, experiment_ids, results), OUTPUT_PATH, name_)
print("%0.3fsec."%(tock_ - tick_,), filename_)
```
## Hermite process experiment
```
from crossing_tree.processes import HermiteProcess
seed = master_seeds.pop()
print("Using seed %X"%(seed,))
random_state = np.random.RandomState(seed)
skip = False
```
Setup: use no downsampling.
```
n_samples, n_downsample = 1 << 23, 1
degrees, methods = [2, 3, 4], ["med", "std", "iqr", "mean",]
hurst_exponents = [ 0.550, 0.600, 0.650, 0.700, 0.750, 0.800, 0.850, 0.900,
0.910, 0.915, 0.920, 0.925, 0.930, 0.935, 0.940, 0.945, 0.950,
0.990,]
n_per_batch, n_batches = 125, 8
```
Run the experiment for the Hermite process.
```
if not skip:
par_ = Parallel(n_jobs=-1, verbose=0)
for degree_ in degrees:
for hurst_ in hurst_exponents:
name_ = "HRP%d_%d-%d-%0.3f-%dx%d"%(degree_, n_downsample, n_samples, hurst_, n_per_batch, n_batches)
print(name_,)
# Schedule the experiments
seeds = random_state.randint(MAX_RAND_SEED, size=(n_batches,))
schedule_ = (delayed(experiment)(seed_, n_per_batch, methods,
HermiteProcess(N=n_samples,
degree=degree_,
n_downsample=n_downsample,
hurst=hurst_,
random_state=seed_))
for seed_ in seeds)
# Run the experiment and collect the results
tick_ = time.time()
experiment_ids = list()
results_ = {method: list() for method in methods}
for id_, dict_ in par_(schedule_):
experiment_ids.append(id_)
for method in methods:
results_[method].extend(dict_[method])
results = {key_: collect_structural_statistics(list_)
for key_, list_ in results_.iteritems()}
tock_ = time.time()
# Save the results and log
filename_ = save((tick_, tock_, experiment_ids, results), OUTPUT_PATH, name_)
print("%0.3fsec."%(tock_ - tick_,), filename_)
```
## Weierstrass experiment -- $\lambda_0 = 1.2$
```
from crossing_tree.processes import WeierstrassFunction
seed = master_seeds.pop()
print("Using seed %X"%(seed,))
random_state = np.random.RandomState(seed)
skip = False
```
Setup
```
n_samples, lambda_0 = 1 << 23, 1.2
methods = ["med", "std", "iqr", "mean",]
holder_exponents = [0.500, 0.550, 0.600, 0.650, 0.700, 0.750, 0.800, 0.850, 0.900,
0.910, 0.915, 0.920, 0.925, 0.930, 0.935, 0.940, 0.945, 0.950,
0.990,]
n_per_batch, n_batches = 125, 8
```
Run the experimnet for the random Weierstrass function $[0, 1]\mapsto \mathbb{R}$:
$$ W_H(t) = \sum_{k\geq 0} \lambda_0^{-k H} \bigl(\cos(2 \pi \lambda_0^k t + \phi_k) - \cos \phi_k\bigr)\,, $$
with $(\phi_k)_{k\geq0} \sim \mathbb{U}[0, 2\pi]$, and $\lambda_0 > 1$ -- the fundamental harmonic.
```
if not skip:
par_ = Parallel(n_jobs=-1, verbose=0)
for holder_ in holder_exponents:
name_ = "WEI_%g-%d-%0.3f-%dx%d"%(lambda_0, n_samples, holder_, n_per_batch, n_batches)
print(name_,)
# Schedule the experiments
seeds = random_state.randint(MAX_RAND_SEED, size=(n_batches,))
schedule_ = (delayed(experiment)(seed_, n_per_batch, methods,
WeierstrassFunction(N=n_samples,
lambda_0=lambda_0,
holder=holder_,
random_state=seed_,
one_sided=False))
for seed_ in seeds)
# Run the experiment and collect the results
tick_ = time.time()
experiment_ids = list()
results_ = {method: list() for method in methods}
for id_, dict_ in par_(schedule_):
experiment_ids.append(id_)
for method in methods:
results_[method].extend(dict_[method])
results = {key_: collect_structural_statistics(list_)
for key_, list_ in results_.iteritems()}
tock_ = time.time()
# Save the results and log
filename_ = save((tick_, tock_, experiment_ids, results), OUTPUT_PATH, name_)
print("%0.3fsec."%(tock_ - tick_,), filename_)
```
## Additional experiments
### Hermite process experiment: with downsampling
```
from crossing_tree.processes import HermiteProcess
seed = master_seeds.pop()
print("Using seed %X"%(seed,))
random_state = np.random.RandomState(seed)
skip = False
```
Setup
```
n_samples, n_downsample = 1 << 19, 1 << 4
degrees, methods = [2, 3, 4], ["med", "std", "iqr", "mean",]
hurst_exponents = [ 0.550, 0.600, 0.650, 0.700, 0.750, 0.800, 0.850, 0.900,
0.910, 0.915, 0.920, 0.925, 0.930, 0.935, 0.940, 0.945, 0.950,
0.990,]
n_per_batch, n_batches = 125, 8
```
Run the experiment for the Hermite process.
```
if not skip:
par_ = Parallel(n_jobs=-1, verbose=0)
for degree_ in degrees:
for hurst_ in hurst_exponents:
name_ = "HRP%d_%d-%d-%0.3f-%dx%d"%(degree_, n_downsample, n_samples, hurst_, n_per_batch, n_batches)
print(name_,)
# Schedule the experiments
seeds = random_state.randint(MAX_RAND_SEED, size=(n_batches,))
schedule_ = (delayed(experiment)(seed_, n_per_batch, methods,
HermiteProcess(N=n_samples,
degree=degree_,
n_downsample=n_downsample,
hurst=hurst_,
random_state=seed_))
for seed_ in seeds)
# Run the experiment and collect the results
tick_ = time.time()
experiment_ids = list()
results_ = {method: list() for method in methods}
for id_, dict_ in par_(schedule_):
experiment_ids.append(id_)
for method in methods:
results_[method].extend(dict_[method])
results = {key_: collect_structural_statistics(list_)
for key_, list_ in results_.iteritems()}
tock_ = time.time()
# Save the results and log
filename_ = save((tick_, tock_, experiment_ids, results), OUTPUT_PATH, name_)
print("%0.3fsec."%(tock_ - tick_,), filename_)
```
### Weierstrass experiment -- $\lambda_0 = 3$
```
from crossing_tree.processes import WeierstrassFunction
seed = master_seeds.pop()
print("Using seed %X"%(seed,))
random_state = np.random.RandomState(seed)
skip = True
```
Setup
```
n_samples, lambda_0 = 1 << 23, 3.0
methods = ["med", "std", "iqr", "mean",]
holder_exponents = [0.500, 0.550, 0.600, 0.650, 0.700, 0.750, 0.800, 0.850, 0.900,
0.910, 0.915, 0.920, 0.925, 0.930, 0.935, 0.940, 0.945, 0.950,
0.990,]
n_per_batch, n_batches = 125, 8
```
Run the experimnet for the random Weierstrass function $[0, 1]\mapsto \mathbb{R}$:
$$ W_H(t) = \sum_{k\geq 0} \lambda_0^{-k H} \bigl(\cos(2 \pi \lambda_0^k t + \phi_k) - \cos \phi_k\bigr)\,, $$
with $(\phi_k)_{k\geq0} \sim \mathbb{U}[0, 2\pi]$, and $\lambda_0 > 1$ -- the fundamental harmonic.
```
if not skip:
par_ = Parallel(n_jobs=-1, verbose=0)
for holder_ in holder_exponents:
name_ = "WEI_%g-%d-%0.3f-%dx%d"%(lambda_0, n_samples, holder_, n_per_batch, n_batches)
print(name_,)
# Schedule the experiments
seeds = random_state.randint(MAX_RAND_SEED, size=(n_batches,))
schedule_ = (delayed(experiment)(seed_, n_per_batch, methods,
WeierstrassFunction(N=n_samples,
lambda_0=lambda_0,
holder=holder_,
random_state=seed_,
one_sided=False))
for seed_ in seeds)
# Run the experiment and collect the results
tick_ = time.time()
experiment_ids = list()
results_ = {method: list() for method in methods}
for id_, dict_ in par_(schedule_):
experiment_ids.append(id_)
for method in methods:
results_[method].extend(dict_[method])
results = {key_: collect_structural_statistics(list_)
for key_, list_ in results_.iteritems()}
tock_ = time.time()
# Save the results and log
filename_ = save((tick_, tock_, experiment_ids, results), OUTPUT_PATH, name_)
print("%0.3fsec."%(tock_ - tick_,), filename_)
```
### Weierstrass experiment -- $\lambda_0 = 1.7$
```
from crossing_tree.processes import WeierstrassFunction
seed = master_seeds.pop()
print("Using seed %X"%(seed,))
random_state = np.random.RandomState(seed)
skip = True
```
Setup
```
n_samples, lambda_0 = 1 << 23, 1.7
methods = ["med", "std", "iqr", "mean",]
holder_exponents = [0.500, 0.550, 0.600, 0.650, 0.700, 0.750, 0.800, 0.850, 0.900,
0.910, 0.915, 0.920, 0.925, 0.930, 0.935, 0.940, 0.945, 0.950,
0.990,]
n_per_batch, n_batches = 125, 8
```
Run the experimnet for the random Weierstrass function $[0, 1]\mapsto \mathbb{R}$:
$$ W_H(t) = \sum_{k\geq 0} \lambda_0^{-k H} \bigl(\cos(2 \pi \lambda_0^k t + \phi_k) - \cos \phi_k\bigr)\,, $$
with $(\phi_k)_{k\geq0} \sim \mathbb{U}[0, 2\pi]$, and $\lambda_0 > 1$ -- the fundamental harmonic.
```
if not skip:
par_ = Parallel(n_jobs=-1, verbose=0)
for holder_ in holder_exponents:
name_ = "WEI_%g-%d-%0.3f-%dx%d"%(lambda_0, n_samples, holder_, n_per_batch, n_batches)
print(name_,)
# Schedule the experiments
seeds = random_state.randint(MAX_RAND_SEED, size=(n_batches,))
schedule_ = (delayed(experiment)(seed_, n_per_batch, methods,
WeierstrassFunction(N=n_samples,
lambda_0=lambda_0,
holder=holder_,
random_state=seed_,
one_sided=False))
for seed_ in seeds)
# Run the experiment and collect the results
tick_ = time.time()
experiment_ids = list()
results_ = {method: list() for method in methods}
for id_, dict_ in par_(schedule_):
experiment_ids.append(id_)
for method in methods:
results_[method].extend(dict_[method])
results = {key_: collect_structural_statistics(list_)
for key_, list_ in results_.iteritems()}
tock_ = time.time()
# Save the results and log
filename_ = save((tick_, tock_, experiment_ids, results), OUTPUT_PATH, name_)
print("%0.3fsec."%(tock_ - tick_,), filename_)
```
### fBM experiment: super long
```
from crossing_tree.processes import FractionalBrownianMotion
seed = master_seeds.pop()
print("Using seed %X"%(seed,))
random_state = np.random.RandomState(seed)
skip = True
```
Setup
```
n_samples, methods = 1 << 25, ["med", "std", "iqr", "mean",]
hurst_exponents = [0.500, 0.550, 0.600, 0.650, 0.700, 0.750, 0.800, 0.850, 0.900,
0.910, 0.915, 0.920, 0.925, 0.930, 0.935, 0.940, 0.945, 0.950,
0.990,]
n_per_batch, n_batches, n_threads = 334, 3, 4
```
Run the experiment for the Fractional Brownian Motion.
```
if not skip:
par_ = Parallel(n_jobs=-1, verbose=0)
for hurst_ in hurst_exponents:
name_ = "FBM-%d-%0.3f-%dx%d"%(n_samples, hurst_, n_per_batch, n_batches)
print(name_,)
# Schedule the experiments
seeds = random_state.randint(MAX_RAND_SEED, size=(n_batches,))
schedule_ = (delayed(experiment)(seed_, n_per_batch, methods,
FractionalBrownianMotion(N=n_samples,
hurst=hurst_,
random_state=seed_,
n_threads=n_threads))
for seed_ in seeds)
# Run the experiment and collect the results
tick_ = time.time()
experiment_ids = list()
results_ = {method: list() for method in methods}
for id_, dict_ in par_(schedule_):
experiment_ids.append(id_)
for method in methods:
results_[method].extend(dict_[method])
results = {key_: collect_structural_statistics(list_)
for key_, list_ in results_.iteritems()}
tock_ = time.time()
# Save the results and log
filename_ = save((tick_, tock_, experiment_ids, results), OUTPUT_PATH, name_)
print("%0.3fsec."%(tock_ - tick_,), filename_)
```
| github_jupyter |
# CarND Object Detection Lab
Let's get started!
```
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from PIL import ImageDraw
from PIL import ImageColor
import time
from scipy.stats import norm
%matplotlib inline
plt.style.use('ggplot')
```
## MobileNets
[*MobileNets*](https://arxiv.org/abs/1704.04861), as the name suggests, are neural networks constructed for the purpose of running very efficiently (high FPS, low memory footprint) on mobile and embedded devices. *MobileNets* achieve this with 3 techniques:
1. Perform a depthwise convolution followed by a 1x1 convolution rather than a standard convolution. The 1x1 convolution is called a pointwise convolution if it's following a depthwise convolution. The combination of a depthwise convolution followed by a pointwise convolution is sometimes called a separable depthwise convolution.
2. Use a "width multiplier" - reduces the size of the input/output channels, set to a value between 0 and 1.
3. Use a "resolution multiplier" - reduces the size of the original input, set to a value between 0 and 1.
These 3 techniques reduce the size of cummulative parameters and therefore the computation required. Of course, generally models with more paramters achieve a higher accuracy. *MobileNets* are no silver bullet, while they perform very well larger models will outperform them. ** *MobileNets* are designed for mobile devices, NOT cloud GPUs**. The reason we're using them in this lab is automotive hardware is closer to mobile or embedded devices than beefy cloud GPUs.
### Convolutions
#### Vanilla Convolution
Before we get into the *MobileNet* convolution block let's take a step back and recall the computational cost of a vanilla convolution. There are $N$ kernels of size $D_k * D_k$. Each of these kernels goes over the entire input which is a $D_f * D_f * M$ sized feature map or tensor (if that makes more sense). The computational cost is:
$$
D_g * D_g * M * N * D_k * D_k
$$
Let $D_g * D_g$ be the size of the output feature map. Then a standard convolution takes in a $D_f * D_f * M$ input feature map and returns a $D_g * D_g * N$ feature map as output.
(*Note*: In the MobileNets paper, you may notice the above equation for computational cost uses $D_f$ instead of $D_g$. In the paper, they assume the output and input are the same spatial dimensions due to stride of 1 and padding, so doing so does not make a difference, but this would want $D_g$ for different dimensions of input and output.)

#### Depthwise Convolution
A depthwise convolution acts on each input channel separately with a different kernel. $M$ input channels implies there are $M$ $D_k * D_k$ kernels. Also notice this results in $N$ being set to 1. If this doesn't make sense, think about the shape a kernel would have to be to act upon an individual channel.
Computation cost:
$$
D_g * D_g * M * D_k * D_k
$$

#### Pointwise Convolution
A pointwise convolution performs a 1x1 convolution, it's the same as a vanilla convolution except the kernel size is $1 * 1$.
Computation cost:
$$
D_k * D_k * D_g * D_g * M * N =
1 * 1 * D_g * D_g * M * N =
D_g * D_g * M * N
$$

Thus the total computation cost is for separable depthwise convolution:
$$
D_g * D_g * M * D_k * D_k + D_g * D_g * M * N
$$
which results in $\frac{1}{N} + \frac{1}{D_k^2}$ reduction in computation:
$$
\frac {D_g * D_g * M * D_k * D_k + D_g * D_g * M * N} {D_g * D_g * M * N * D_k * D_k} =
\frac {D_k^2 + N} {D_k^2*N} =
\frac {1}{N} + \frac{1}{D_k^2}
$$
*MobileNets* use a 3x3 kernel, so assuming a large enough $N$, separable depthwise convnets are ~9x more computationally efficient than vanilla convolutions!
### Width Multiplier
The 2nd technique for reducing the computational cost is the "width multiplier" which is a hyperparameter inhabiting the range [0, 1] denoted here as $\alpha$. $\alpha$ reduces the number of input and output channels proportionally:
$$
D_f * D_f * \alpha M * D_k * D_k + D_f * D_f * \alpha M * \alpha N
$$
### Resolution Multiplier
The 3rd technique for reducing the computational cost is the "resolution multiplier" which is a hyperparameter inhabiting the range [0, 1] denoted here as $\rho$. $\rho$ reduces the size of the input feature map:
$$
\rho D_f * \rho D_f * M * D_k * D_k + \rho D_f * \rho D_f * M * N
$$
Combining the width and resolution multipliers results in a computational cost of:
$$
\rho D_f * \rho D_f * a M * D_k * D_k + \rho D_f * \rho D_f * a M * a N
$$
Training *MobileNets* with different values of $\alpha$ and $\rho$ will result in different speed vs. accuracy tradeoffs. The folks at Google have run these experiments, the result are shown in the graphic below:

MACs (M) represents the number of multiplication-add operations in the millions.
### Exercise 1 - Implement Separable Depthwise Convolution
In this exercise you'll implement a separable depthwise convolution block and compare the number of parameters to a standard convolution block. For this exercise we'll assume the width and resolution multipliers are set to 1.
Docs:
* [depthwise convolution](https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)
```
def vanilla_conv_block(x, kernel_size, output_channels):
"""
Vanilla Conv -> Batch Norm -> ReLU
"""
x = tf.layers.conv2d(
x, output_channels, kernel_size, (2, 2), padding='SAME')
x = tf.layers.batch_normalization(x)
return tf.nn.relu(x)
# TODO: implement MobileNet conv block
def mobilenet_conv_block(x, kernel_size, output_channels):
"""
Depthwise Conv -> Batch Norm -> ReLU -> Pointwise Conv -> Batch Norm -> ReLU
"""
pass
```
**[Sample solution](./exercise-solutions/e1.py)**
Let's compare the number of parameters in each block.
```
# constants but you can change them so I guess they're not so constant :)
INPUT_CHANNELS = 32
OUTPUT_CHANNELS = 512
KERNEL_SIZE = 3
IMG_HEIGHT = 256
IMG_WIDTH = 256
with tf.Session(graph=tf.Graph()) as sess:
# input
x = tf.constant(np.random.randn(1, IMG_HEIGHT, IMG_WIDTH, INPUT_CHANNELS), dtype=tf.float32)
with tf.variable_scope('vanilla'):
vanilla_conv = vanilla_conv_block(x, KERNEL_SIZE, OUTPUT_CHANNELS)
with tf.variable_scope('mobile'):
mobilenet_conv = mobilenet_conv_block(x, KERNEL_SIZE, OUTPUT_CHANNELS)
vanilla_params = [
(v.name, np.prod(v.get_shape().as_list()))
for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'vanilla')
]
mobile_params = [
(v.name, np.prod(v.get_shape().as_list()))
for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'mobile')
]
print("VANILLA CONV BLOCK")
total_vanilla_params = sum([p[1] for p in vanilla_params])
for p in vanilla_params:
print("Variable {0}: number of params = {1}".format(p[0], p[1]))
print("Total number of params =", total_vanilla_params)
print()
print("MOBILENET CONV BLOCK")
total_mobile_params = sum([p[1] for p in mobile_params])
for p in mobile_params:
print("Variable {0}: number of params = {1}".format(p[0], p[1]))
print("Total number of params =", total_mobile_params)
print()
print("{0:.3f}x parameter reduction".format(total_vanilla_params /
total_mobile_params))
```
Your solution should show the majority of the parameters in *MobileNet* block stem from the pointwise convolution.
## *MobileNet* SSD
In this section you'll use a pretrained *MobileNet* [SSD](https://arxiv.org/abs/1512.02325) model to perform object detection. You can download the *MobileNet* SSD and other models from the [TensorFlow detection model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) (*note*: we'll provide links to specific models further below). [Paper](https://arxiv.org/abs/1611.10012) describing comparing several object detection models.
Alright, let's get into SSD!
### Single Shot Detection (SSD)
Many previous works in object detection involve more than one training phase. For example, the [Faster-RCNN](https://arxiv.org/abs/1506.01497) architecture first trains a Region Proposal Network (RPN) which decides which regions of the image are worth drawing a box around. RPN is then merged with a pretrained model for classification (classifies the regions). The image below is an RPN:

The SSD architecture is a single convolutional network which learns to predict bounding box locations and classify the locations in one pass. Put differently, SSD can be trained end to end while Faster-RCNN cannot. The SSD architecture consists of a base network followed by several convolutional layers:

**NOTE:** In this lab the base network is a MobileNet (instead of VGG16.)
#### Detecting Boxes
SSD operates on feature maps to predict bounding box locations. Recall a feature map is of size $D_f * D_f * M$. For each feature map location $k$ bounding boxes are predicted. Each bounding box carries with it the following information:
* 4 corner bounding box **offset** locations $(cx, cy, w, h)$
* $C$ class probabilities $(c_1, c_2, ..., c_p)$
SSD **does not** predict the shape of the box, rather just where the box is. The $k$ bounding boxes each have a predetermined shape. This is illustrated in the figure below:

The shapes are set prior to actual training. For example, In figure (c) in the above picture there are 4 boxes, meaning $k$ = 4.
### Exercise 2 - SSD Feature Maps
It would be a good exercise to read the SSD paper prior to a answering the following questions.
***Q: Why does SSD use several differently sized feature maps to predict detections?***
A: Your answer here
**[Sample answer](./exercise-solutions/e2.md)**
The current approach leaves us with thousands of bounding box candidates, clearly the vast majority of them are nonsensical.
### Exercise 3 - Filtering Bounding Boxes
***Q: What are some ways which we can filter nonsensical bounding boxes?***
A: Your answer here
**[Sample answer](./exercise-solutions/e3.md)**
#### Loss
With the final set of matched boxes we can compute the loss:
$$
L = \frac {1} {N} * ( L_{class} + L_{box})
$$
where $N$ is the total number of matched boxes, $L_{class}$ is a softmax loss for classification, and $L_{box}$ is a L1 smooth loss representing the error of the matched boxes with the ground truth boxes. L1 smooth loss is a modification of L1 loss which is more robust to outliers. In the event $N$ is 0 the loss is set 0.
### SSD Summary
* Starts from a base model pretrained on ImageNet.
* The base model is extended by several convolutional layers.
* Each feature map is used to predict bounding boxes. Diversity in feature map size allows object detection at different resolutions.
* Boxes are filtered by IoU metrics and hard negative mining.
* Loss is a combination of classification (softmax) and dectection (smooth L1)
* Model can be trained end to end.
## Object Detection Inference
In this part of the lab you'll detect objects using pretrained object detection models. You can download the latest pretrained models from the [model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md), although do note that you may need a newer version of TensorFlow (such as v1.8) in order to use the newest models.
We are providing the download links for the below noted files to ensure compatibility between the included environment file and the models.
[SSD_Mobilenet 11.6.17 version](http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_11_06_2017.tar.gz)
[RFCN_ResNet101 11.6.17 version](http://download.tensorflow.org/models/object_detection/rfcn_resnet101_coco_11_06_2017.tar.gz)
[Faster_RCNN_Inception_ResNet 11.6.17 version](http://download.tensorflow.org/models/object_detection/faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017.tar.gz)
Make sure to extract these files prior to continuing!
```
# Frozen inference graph files. NOTE: change the path to where you saved the models.
SSD_GRAPH_FILE = 'ssd_mobilenet_v1_coco_11_06_2017/frozen_inference_graph.pb'
RFCN_GRAPH_FILE = 'rfcn_resnet101_coco_11_06_2017/frozen_inference_graph.pb'
FASTER_RCNN_GRAPH_FILE = 'faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017/frozen_inference_graph.pb'
```
Below are utility functions. The main purpose of these is to draw the bounding boxes back onto the original image.
```
# Colors (one for each class)
cmap = ImageColor.colormap
print("Number of colors =", len(cmap))
COLOR_LIST = sorted([c for c in cmap.keys()])
#
# Utility funcs
#
def filter_boxes(min_score, boxes, scores, classes):
"""Return boxes with a confidence >= `min_score`"""
n = len(classes)
idxs = []
for i in range(n):
if scores[i] >= min_score:
idxs.append(i)
filtered_boxes = boxes[idxs, ...]
filtered_scores = scores[idxs, ...]
filtered_classes = classes[idxs, ...]
return filtered_boxes, filtered_scores, filtered_classes
def to_image_coords(boxes, height, width):
"""
The original box coordinate output is normalized, i.e [0, 1].
This converts it back to the original coordinate based on the image
size.
"""
box_coords = np.zeros_like(boxes)
box_coords[:, 0] = boxes[:, 0] * height
box_coords[:, 1] = boxes[:, 1] * width
box_coords[:, 2] = boxes[:, 2] * height
box_coords[:, 3] = boxes[:, 3] * width
return box_coords
def draw_boxes(image, boxes, classes, thickness=4):
"""Draw bounding boxes on the image"""
draw = ImageDraw.Draw(image)
for i in range(len(boxes)):
bot, left, top, right = boxes[i, ...]
class_id = int(classes[i])
color = COLOR_LIST[class_id]
draw.line([(left, top), (left, bot), (right, bot), (right, top), (left, top)], width=thickness, fill=color)
def load_graph(graph_file):
"""Loads a frozen inference graph"""
graph = tf.Graph()
with graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(graph_file, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
return graph
```
Below we load the graph and extract the relevant tensors using [`get_tensor_by_name`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_tensor_by_name). These tensors reflect the input and outputs of the graph, or least the ones we care about for detecting objects.
```
detection_graph = load_graph(SSD_GRAPH_FILE)
# detection_graph = load_graph(RFCN_GRAPH_FILE)
# detection_graph = load_graph(FASTER_RCNN_GRAPH_FILE)
# The input placeholder for the image.
# `get_tensor_by_name` returns the Tensor with the associated name in the Graph.
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
# The classification of the object (integer id).
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
```
Run detection and classification on a sample image.
```
# Load a sample image.
image = Image.open('./assets/sample1.jpg')
image_np = np.expand_dims(np.asarray(image, dtype=np.uint8), 0)
with tf.Session(graph=detection_graph) as sess:
# Actual detection.
(boxes, scores, classes) = sess.run([detection_boxes, detection_scores, detection_classes],
feed_dict={image_tensor: image_np})
# Remove unnecessary dimensions
boxes = np.squeeze(boxes)
scores = np.squeeze(scores)
classes = np.squeeze(classes)
confidence_cutoff = 0.8
# Filter boxes with a confidence score less than `confidence_cutoff`
boxes, scores, classes = filter_boxes(confidence_cutoff, boxes, scores, classes)
# The current box coordinates are normalized to a range between 0 and 1.
# This converts the coordinates actual location on the image.
width, height = image.size
box_coords = to_image_coords(boxes, height, width)
# Each class with be represented by a differently colored box
draw_boxes(image, box_coords, classes)
plt.figure(figsize=(12, 8))
plt.imshow(image)
```
## Timing Detection
The model zoo comes with a variety of models, each its benefits and costs. Below you'll time some of these models. The general tradeoff being sacrificing model accuracy for seconds per frame (SPF).
```
def time_detection(sess, img_height, img_width, runs=10):
image_tensor = sess.graph.get_tensor_by_name('image_tensor:0')
detection_boxes = sess.graph.get_tensor_by_name('detection_boxes:0')
detection_scores = sess.graph.get_tensor_by_name('detection_scores:0')
detection_classes = sess.graph.get_tensor_by_name('detection_classes:0')
# warmup
gen_image = np.uint8(np.random.randn(1, img_height, img_width, 3))
sess.run([detection_boxes, detection_scores, detection_classes], feed_dict={image_tensor: gen_image})
times = np.zeros(runs)
for i in range(runs):
t0 = time.time()
sess.run([detection_boxes, detection_scores, detection_classes], feed_dict={image_tensor: image_np})
t1 = time.time()
times[i] = (t1 - t0) * 1000
return times
with tf.Session(graph=detection_graph) as sess:
times = time_detection(sess, 600, 1000, runs=10)
# Create a figure instance
fig = plt.figure(1, figsize=(9, 6))
# Create an axes instance
ax = fig.add_subplot(111)
plt.title("Object Detection Timings")
plt.ylabel("Time (ms)")
# Create the boxplot
plt.style.use('fivethirtyeight')
bp = ax.boxplot(times)
```
### Exercise 4 - Model Tradeoffs
Download a few models from the [model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) and compare the timings.
## Detection on a Video
Finally run your pipeline on [this short video](https://s3-us-west-1.amazonaws.com/udacity-selfdrivingcar/advanced_deep_learning/driving.mp4).
```
# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
HTML("""
<video width="960" height="600" controls>
<source src="{0}" type="video/mp4">
</video>
""".format('driving.mp4'))
```
### Exercise 5 - Object Detection on a Video
Run an object detection pipeline on the above clip.
```
clip = VideoFileClip('driving.mp4')
# TODO: Complete this function.
# The input is an NumPy array.
# The output should also be a NumPy array.
def pipeline(img):
pass
```
**[Sample solution](./exercise-solutions/e5.py)**
```
with tf.Session(graph=detection_graph) as sess:
image_tensor = sess.graph.get_tensor_by_name('image_tensor:0')
detection_boxes = sess.graph.get_tensor_by_name('detection_boxes:0')
detection_scores = sess.graph.get_tensor_by_name('detection_scores:0')
detection_classes = sess.graph.get_tensor_by_name('detection_classes:0')
new_clip = clip.fl_image(pipeline)
# write to file
new_clip.write_videofile('result.mp4')
HTML("""
<video width="960" height="600" controls>
<source src="{0}" type="video/mp4">
</video>
""".format('result.mp4'))
```
## Further Exploration
Some ideas to take things further:
* Finetune the model on a new dataset more relevant to autonomous vehicles. Instead of loading the frozen inference graph you'll load the checkpoint.
* Optimize the model and get the FPS as low as possible.
* Build your own detector. There are several base model pretrained on ImageNet you can choose from. [Keras](https://keras.io/applications/) is probably the quickest way to get setup in this regard.
| github_jupyter |

<font size=3 color="midnightblue" face="arial">
<h1 align="center">Escuela de Ciencias Básicas, Tecnología e Ingeniería</h1>
</font>
<font size=3 color="navy" face="arial">
<h1 align="center">ECBTI</h1>
</font>
<font size=2 color="darkorange" face="arial">
<h1 align="center">Curso:</h1>
</font>
<font size=2 color="navy" face="arial">
<h1 align="center">Introducción al lenguaje de programación Python</h1>
</font>
<font size=1 color="darkorange" face="arial">
<h1 align="center">Febrero de 2020</h1>
</font>
<h2 align="center">Sesión 04 - Funciones</h2>
## Funciones
<img src="Funcion.png" alt="Drawing" style="width: 200px;"/>
### Matemáticas
$$f(x) = x^2-3$$
- ***Entrada:*** el valor de $x$ (por ejemplo $2$)
- ***Función:*** transforma la entrada $x$ ($2^2-3$)
- ***Salida:*** devuelve el resultado de efectuar dicha transformación del valor de entrada ($f(2)=1$)
### Programación
***Función:*** Fragmento de código con un nombre asociado que realiza una serie de tareas y devuelve un valor.
***Procedimientos:*** Fragmento de código que tienen un nombre asociado y no devuelven valores (scripts).
- En `Python` no existen los procedimientos, ya que cuando el programador no especifica un valor de retorno la función devuelve el valor `None` (nada), equivalente al `null` de Java.
- Además de ayudarnos a programar y depurar dividiendo el programa en partes las funciones también permiten reutilizar código.
- En otros lenguajes las funciones son conocidas con otros nombres, como por ejemplo: subrutinas, rutinas, procedimientos, métodos, subprogramas, etc.
- En `Python` las funciones se declaran de la siguiente forma:
- La lista de parámetros consiste en uno o más parámetros, o incluso, ninguno. A estos parámetros se les llama *argumentos*.
- El cuerpoo de la función consiste de una secuencia de sentencias indentadas, que serán ejecutadas cada vez que la función es llamada.
### Función sin parámetro y sin retorno
Una función puede no tener parámetros de entrada y no contener la sentencia de retorno `return`:
```
def fbienvenida():
print("Hola Mundo")
```
Para llamar la función se escribe el nombre de la función seguida de paréntesis `nombre_Funcion()`
```
fbienvenida()
```
Se observa que lo único que hace esta función es imprimir un mensaje preestablecido como cuerpo de función.
### Función con uno o más parámetros y sin retorno
A una función también se le pueden pasar como argumentos uno o más parámetros
- También podemos encontrarnos con una cadena de texto como primera línea del cuerpo de la función. Estas cadenas se conocen con el nombre de `docstring` (cadena de documentación) y sirven, como su nombre indica, a modo de documentación de la función.
```
def mi_funcion1(param1, param2):
"""Esta función también imprime únicamente los valores de los parámetros
requiere de dos parámetros
Inputs:
param1: puede ser cualquier vaina
param2: también
Outputs:
"""
print('{0} {1}'.format(param1,param2))
mi_funcion1?
```
Para llamar a la función (ejecutar su código) se escribiría:
```
mi_funcion1(1,2)
```
También es posible modificar el orden de los parámetros si indicamos el nombre del parámetro al qué asociar el valor a la hora de llamar a la función:
```
mi_funcion1(param2 = 1, param1 = 2)
```
### Retorno de Valores
- El cuerpo de la función puede contener una o más sentencias de retorno de valores, `return`. Una sentencia de retorno finaliza la ejecución de la función. Si la sentencia de retorno no es una expresión, o no se usa, se retornará el valor especial `None`.
Revisemos el siguiente ejemplo
```
def no_return(x,y):
c = x + y
return c
res = no_return(4,5)
print(res)
```
Ahora incluyamos la palabra reservada `return` para devolver el resultado de lo realizado dentro de la función
```
def sumar(x, y):
c = x + y
return c
```
Llamemos la función `sumar`con los parámetros indicados, `1` y `2`. El valor de la suma `x+y` se almacena en la variable `c` y éste valor se retorna mediante la palabra `return` para ser usada en el cuerpo del programa principal.
```
sumaxy = sumar(1,2)
print(sumaxy)
sumacuadrado = sumaxy ** 2
print(sumacuadrado)
```
Obsérvese que la variable `sumaxy` recibe lo que ha sido regresado de la función `sumar`. El resultado de la evaluación de dicha función se almacena en esa variable que es usada a lo largo del cuerpo del programa principal para efectuar otros cálculos.
El valor especial `None` también se retornará si la palabra `return` no está acompañada de una expresión (situación demasiada frecuente como para ser considerado "error").
```
def sumar(x, y):
c = x + y
return
sumaxy = sumar(1,2)
print(sumaxy)
```
Una función puede ser llamada casi desde cualquier parte del código, por ejemplo, al interior de otra función (`print`) y no necesariamente tiene qué almacenarse el resultado en una variable antes de retornar el valor de su ejecución
```
def dolorosos(t):
""" Devuelve un valor dado en pesos a dólares"""
return t / 3443.63
for valorpesos in (2260, 2580, 27300, 29869):
print('{0} pesos son {1:.2f} dólares'.format(valorpesos,dolorosos(valorpesos)))
```
Obsérvese que en este caso no hubo necesidad de llamar la función aparte, sino que su llamado está incluída dentro de la estructura de la función `print`.
### Retorno de valores múltiples
Una función puede retornar un valor (o mejor, un "objeto", para los amantes de POO). Un objeto puede ser un valor numérico como un entero o un float, pero también puede ser una estructura de datos, como un diccionario o una tupla, por ejemplo.
Si necesitamos retonrar tres valores enteros, se puede hacer a través de una lista o tupla que contiene esos tres valores. Lo que significa que podemos retornar múltiples valores.
Veamos el siguiente ejemplo: Dado un número $x$ determine cuáles serían los valores inmediatamente menor y mayor a este número en la serie de *Fibonacci*.
```
def fib_intervalo(x):
""" Retorna los números de Fibonacci
mayor que x y menor que x"""
if x < 0:
return -1
(ant,post, lub) = (0,1,0)
while True:
if post < x:
lub = post
(ant,post) = (post,ant+post)
else:
return (ant, post)
while True:
x = int(input("Ingrese un número entero >0 (<0 para interrumpir): "))
if x <= 0:
break #interrumpe el programa si x<0
lub, sup = fib_intervalo(x)
print("Mayor número de Fibonacci menor que x: " + str(lub))
print("Menor número de Fibonacci mayor que x: " + str(sup))
```
Obsérves que los valores retornados, y la variable que los recibe, están "empaquetados" en una estrucutra llamada "Tupla" (se verá en una siguiente sesión del curso).
### Número Arbitrario de Parámetros
- Existen situaciones en las que el número exacto de parámetros no puede determinarse a-priori.
- Para definir funciones con un número variable de argumentos colocamos un último parámetro para la función cuyo nombre debe precederse de un signo `*` (asterisco):
```
def varios(param1, param2, *opcionales):
print(type(opcionales))
print(param1)
print(param2)
n = len(opcionales)
for i in range(n):
print(opcionales[i])
varios(1,2)
varios(1,2,3)
varios(1,2,3,4)
varios(1,2,3,4,5,6,7,8,9)
```
Miremos el siguiente ejemplo:
```
def media_aritmetica(*valores):
""" Esta función calcula la media aritmética de un número arbitrario de valores numéricos """
print(float(sum(valores)) / len(valores))
media_aritmetica(5,5,5,5,5,5,5,5)
media_aritmetica(8989.8,78787.78,3453,78778.73)
media_aritmetica(45,55)
media_aritmetica(45)
```
Ahora veamos la situación en la que los datos vienen "empaquetados" en alguna estructura, como por ejemplo, una Lista
```
x = [3, 5, 9, 13, 12, 5, 67, 98]
print(x)
```
Si colocamos el valor de la variable `x` como parámetro en la función se obtendrá el siguiente resultado:
```
media_aritmetica(x)
```
Una primera idea de resolver esta situación sería ingresar los parámetros elemento por elemento mediante su indice...
```
media_aritmetica(x[0], x[1], x[2],x[3], x[4], x[5],x[6],x[7])
```
pero obviamente es completamente impráctico. La solución es recurrir al esquema de una cantidad de parámetros arbitrarios, así estén encapsulados, mediante la inclusión del operador `*`:
```
media_aritmetica(*x)
```
### Variables Locales y Globales
Las variables dentro de las funciones son Locales por defecto. Veamos la siguiente secuencia de ejemplos:
```
def f():
print(s)
s = "Python"
f()
def f():
s = "Perl"
print(s)
f()
s = "Python"
print(s)
def f(ls):
print(ls)
ls = "Perl"
return ls
s = "Python"
print(s)
print(f(s))
def f():
print(s1)
s = "Perl"
print(s)
s1 = "Python"
f()
print(s1)
```
Como se observa, al ejecutar el anterior código se obtuvo el mensaje de errror: `boundLocalError: local variable 's' referenced before assignment`. Esto sucede porque la variable `s` es ambigua en `f()`, es decir, la primera impresión en `f()` la variable global `s` podría ser usada con el valor `Python`. Después de esto, hemos definido la variable local `s` con la asignación `s=Perl`.
En el siguiente código se ha definido la variable `s` como `global` dentro del script. Por lo tanto, todo lo realizado a la variable global `s` dentro del cuerpo de la función `f` es hecho a la variable global `s` afuera de `f`
```
def f():
global s
print(s)
s = "dog"
print(s)
s = "cat"
f()
print(s)
```
### Número arbitrarios de palabras clave como parámetros
En el capítulo anterior se vio cómo pasar un número arbitrario de parámetros posicionales a una función. También es posible pasar un número arbitrario de parámetros de palabras clave (`keywords`) a una función. Para este propósito, tenemos que usar el doble asterisco `**`
```
def f(**kwargs):
print(kwargs)
f()
f(de="German",en="English",fr="French")
```
Un posible caso de uso podría ser
```
def f(a,b,x,y):
print(a,b,x,y)
d = {'a':'append', 'b':'block','x':'extract','y':'yes'}
f(**d)
```
Veamos este último ejemplo:
```
def foo(*posicional, **keywords):
print("Posicional:", posicional)
print("Keywords:", keywords)
```
El argumento `*posicional` almacenará todos los argumentos posicionales pasados a `foo ()`, sin límite de cuántos puede proporcionar.
```
foo('one', 'two', 'three')
```
El argumento `**keywords` almacenará cualquier argumento de palabra clave:
```
foo(a='one', b='two', c='three')
```
Y por supuesto, usar los dos al mismo tiempo
```
foo('one','two',c='three',d='four')
```
## Paso por referencia
Quiénes usan otros lenguaje de programación, se preguntarán por los parámetros por referencia.
En otros lenguajes de programación existe el paso de parámetros por valor y por referencia. En los pasos por valor, una función no puede modificar el valor de las variables que recibe por fuera de su ejecución: un intento por hacerlo simplemente altera las copias locales de dichas variables. Por el contrario, al pasar por referencia, una función obtiene acceso directo a las variables originales, permitiendo así su edición.
En `Python`, en cambio, no se concibe la dialéctica paso por valor/referencia, porque el lenguaje no trabaja con el concepto de variables sino objetos y referencias. Al realizar la asignación `a = 1` no se dice que *a contiene el valor 1* sino que *a referencia a 1*. Así, en comparación con otros lenguajes, podría decirse que ***en `Python` los parámetros siempre se pasan por referencia***.
Ahora bien podríamos preguntar, ¿por qué el siguiente código no modifica los valores originales?
```
def f(a, b, c):
# No altera los objetos originales.
a, b, c = 4, 5, 6
return a,b,c
a, b, c = 1, 2, 3
a,b,c = f(a, b, c)
print(a, b, c) # Imprime 1, 2, 3.
```
La respuesta es que los números enteros (como también los de coma flotante, las cadenas y otros objetos) son inmutables. Es decir, una vez creados, su valor no puede ser modificado. ¿Cómo, no puedo acaso hacer `a = 1` y luego `a = 2`? Claro, pero desde la perspectiva del lenguaje, *no estás cambiando el valor de `a` de `1` a `2` sino quitando la referencia a `1` y poniéndosela a `2`*. En términos más simples, no «cambias» el valor de un objeto sino que le asignas una nueva referencia.
En el código anterior, al ejecutar `a, b, c = 4, 5, 6` estás creando nuevas referencias para los números `4`, `5` y `6` dentro de la función `f` con los nombres `a`, `b` y `c`.
Sin embargo otros objetos, como las listas o diccionarios, son mutables. Veamos un ejemplo:
```
def f(a):
a[0] = "CPython"
a[1] = "PyPy"
a.append("Stackless")
items = ["Perro", "Gato"]
f(items)
items
```
Basta con saber si un objeto es mutable o inmutable para determinar si es posible editarlo dentro de una función y que tenga efecto por fuera de ésta. Aunque no hay necesidad alguna para que se haga así. Por qué?: el paso por referencia es la manera en que los lenguajes que trabajan con variables proveen al programador para retornar más de un valor en una misma función. En cambio, `Python` permite devolver varios objetos utilizando *tuplas* o *listas*. Por ejemplo:
```
a = 1
b = 2
c = 3
def f():
return 4, 5, 6
a, b, c = f()
# Ahora "a" es 4, "b" es 5 y "c" es 6.
```
## Funciones Recursivas
- La Recursión es asociada al concepto de $infinito$.
- El adjetivo "*recursivo*" se origina del verbo latino "*recurrere*", que significa "*volver atrás*". Y esto es lo que una definición recursiva o una función recursiva hace: Es "*volver a funcionar*" o "*volver a sí mismo*".
El factorial es un ejemplo de recursividad:
### Definición de Funciones Recursivas
- La recursividad es un método de programación o codificación de un problema, en el que una función se llama a sí misma una o más veces en su cuerpo.
- Normalmente, está devolviendo el valor devuelto de esta llamada de función.
- Si una definición de función satisface la condición de recursión, llamamos a esta función una *función recursiva*.
### Condición de Finalización
- Una función recursiva tiene que cumplir una condición importante para ser utilizada en un programa: *tiene que terminar*.
- Una función recursiva termina, si con cada llamada recursiva la solución del problema es reducida y se mueve hacia un caso base.
- Un caso base es un caso, donde el problema se puede resolver sin más recursividad.
- Una recursividad puede terminar en un bucle infinito, si el caso base no se cumple en las llamadas.
***Ejemplo:***
Reemplazando los valores calculados dados resulta la siguiente expresión:
### Funciones Recursivas en Python
Una primero implementación del algoritmo del factorial de forma iterativa:
```
def factorial_iterativo(n):
resultado = 1
for i in range(2,n+1):
resultado *= i
return resultado
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
a = 5000
print(factorial_iterativo(a))
print(factorial(a))
def factorial(n):
# print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print "intermediate result for ", n, " * factorial(" ,n-1, "): ",res
return res
print(factorial(5))
```
- Es una práctica común extender la función factorial para $0$ como argumento.
- Tiene sentido definir $0!$ Para ser $1$, porque hay exactamente una permutación de objetos cero, es decir, si nada es permutar, "*todo*" se deja en su lugar.
- Otra razón es que el número de formas de elegir $n$ elementos entre un conjunto de $n$ se calcula como $\frac{n!}{n! \times 0!}$.
- Todo lo que tenemos que hacer para implementar esto es cambiar la condición de la instrucción `if`:
### Las trampas de la recursión
***Sucesión de Fibonacci:*** La $Sucesión$ de $Fibonacci$ es la secuencia de números: $0 , 1, 1, 2, 3, 5, 8, 13, 21, ...$
- Se define por: $F_n = F_{n-1} + F_{n-2} $ , con $F_0 = 0$ y $F_1 = 1$
- La solución iterativa es fácil de implementar:
```
def fib_iter(n):
lfib = [0,1]
if n == 0:
return 0
for i in range(n-1):
lfib = lfib[i] + lfib[i+1]
return lfib
fib_iter(10)
```
La solución recursiva se acerca más a la definición:
```
def fib_recur(n):
if n == 0:
# print n
return 0
elif n == 1:
# print n
return 1
else:
# i = n - 1
# print i
return fib_recur(n-1) + fib_recur(n-2)
fib_recur(27)
```
***Comentario*:*** Observe que la solución recursiva, `fib_rec`, es **MUCHO MÁS RÁPIDA** que la función iterativa, `fib_iter`.
```
%time fib_iter(10)
%time fib_recur(100)
```
Qué sucede de "malo" en los algoritmos presentados?

ref: https://www.python-course.eu/python3_recursive_functions.php
Obsérvese que en esta secuencia, el cálculo de `f(2)` aparece tres veces en esta secuencia. El de `f(3)`, dos veces, etc. A medida que subimos de nivel, es decir, aumentamos la cantidad de datos de la serie, esos mismos cálculos se repetirán mucha más veces.
- Este algoritmo de recursión no "recuerda" que esos valores ya fueron previamente calculados.
- Podemos implementar ahora un algoritmo que "recuerde":
```
memo = {0:0, 1:1}
def fib_memo(n):
if not n in memo:
memo[n] = fib_memo(n-1) + fib_memo(n-2)
return memo[n]
%time fib_memo(10)
```
### COMENTARIOS FINALES IMPORTANTES!!!
- Aunque la recursión se presenta como una solución muy eficiente, lamentablemente (o quizás no...) en *Python* solo lo es para una cantidad de recursiones relativamente pequeña (del órden de 1000).
- En otros lenguajes, la recursión no presenta esta restricción (peligroso!).
- Cuando tenga la necesidad de realizar este tipo de operaciones, lo más recomendable es regresar a la implementación iterativa.
- Para una mayor información al respecto, los invito a visitar [este Blog](http://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html "Recursive to iterative")
## Programación Modular y Módulos
> <strong>Programación Modular:</strong> Técnica de diseño de software, que se basa en el principio general del *diseño modular*.
> El *Diseño Modular* es un enfoque que se ha demostrado como indispensable en la ingeniería incluso mucho antes de las primeras computadoras.
> El *Diseño Modular* significa que un sistema complejo se descompone en partes o componentes más pequeños, es decir módulos. Estos componentes pueden crearse y probarse independientemente. En muchos casos, pueden incluso utilizarse en otros sistemas.
> Si desea desarrollar programas que sean legibles, fiables y mantenibles sin demasiado esfuerzo, debe utilizar algún tipo de diseño de software modular. Especialmente si su aplicación tiene un cierto tamaño.
> Existe una variedad de conceptos para diseñar software en forma modular.
> La programación modular es una técnica de diseño de software para dividir su código en partes separadas. Estas piezas se denominan módulos.
> El enfoque para esta separación debe ser tener módulos con no o sólo algunas dependencias sobre otros módulos. En otras palabras: La minimización de las dependencias es la meta.
> Al crear un sistema modular, varios módulos se construyen por separado y más o menos independientemente. La aplicación ejecutable se creará reuniéndolos.
### Importando Módulos
> Cada archivo, que tiene la extensión de archivo `.py` y consta de código `Python` adecuado, se puede ver o es un módulo!
> No hay ninguna sintaxis especial requerida para hacer que un archivo de este tipo sea un módulo.
> Un módulo puede contener objetos arbitrarios, por ejemplo archivos, clases o atributos. Todos estos objetos se pueden acceder después de una importación.
> Hay diferentes maneras de importar módulos. Demostramos esto con el módulo de matemáticas:
Si quisiéramos obtener la raíz cudrada de un número, o el valor de pi, o alguna función trigonométrica simple...
```
x = sin(2*pi)
V = 4/3*pi*r**3
x = sqrt(4)
```
> Para poder usar estas funciones es necesario importar el módulo correspondiente que las contiene. En este caso sería:
```
import numpy as np
import math as mt
```
> El módulo matemático proporciona constantes y funciones matemáticas, `pi (math.pi)`, la función seno (`math.sin()`) y la función coseno (`math.cos()`). Cada atributo o función sólo se puede acceder poniendo "`math`" delante del nombre:
```
mt.sqrt(4)
mt.sin(mt.pi)
mt.
np.
mathraiz = mt.sqrt(4)
print(mathraiz)
numpyraiz = np.sqrt(4)
print(numpyraiz)
```
> Se puede importar más de un módulo en una misma sentencia de importación. En este caso, los nombres de los módulos se deben separar por comas:
```
import math, random
random.random()
```
> Las sentencias de importación pueden colocarse en cualquier parte del programa, pero es un buen estilo colocarlas directamente al principio de un programa.
> Si sólo se necesitan ciertos objetos de un módulo, se pueden importar únicamente esos:
```
from math import sin, pi, sqrt
```
> Los otros objetos, p.ej. `cos`, no estarán disponibles después de esta importación. Será posible acceder a las funciones `sin` y `pi` directamente, es decir, sin prefijarlos con `math`.
> En lugar de importar explícitamente ciertos objetos de un módulo, también es posible importar todo en el espacio de nombres del módulo de importación. Esto se puede lograr usando un asterisco en la importación:
```
from math import *
e
pi
```
> - No se recomienda utilizar la notación de asterisco en una instrucción de importación, excepto cuando se trabaja en el intérprete interactivo de `Python`.
> - Una de las razones es que el origen de un nombre puede ser bastante oscuro, porque no se puede ver desde qué módulo podría haber sido importado. Demostramos otra complicación seria en el siguiente ejemplo:
```
from numpy import *
sin(3)
from math import *
sin(3)
sin(3)
```
> Es usual la notación de asterisco, porque es muy conveniente. Significa evitar una gran cantidad de mecanografía tediosa.
> Otra forma de reducir el esfuerzo de mecanografía consiste en usar alias.
```
import numpy as np
import matplotlib.pyplot as plt
np.
```
> Ahora se pueden prefijar todos los objetos de `numpy` con `np`, en lugar de `numpy`
```
np.diag([3, 11, 7, 9])
```
### Diseñando y Escribiendo Módulos
> Un módulo en `Python` es simplemente un archivo que contiene definiciones y declaraciones de `Python`.
> El nombre del módulo se obtiene del nombre de archivo eliminando el sufijo `.py`.
> - Por ejemplo, si el nombre del archivo es `fibonacci.py`, el nombre del módulo es `fibonacci`.
> Para convertir las funciones `Fibonacci` en un módulo casi no hay nada que hacer, sólo guardar el siguiente código en un archivo `*.py`.
> - El recién creado módulo `fibonacci` está listo para ser usado ahora.
> - Podemos importar este módulo como cualquier otro módulo en un programa o script.
```
import fibonacci
fibonacci.fib(7)
fibonacci.ifib(7)
```
> - Como podrá ver, es inconveniente si tiene que usar esas funciones a menudo en su programa y siempre hay que escribir el nombre completo, es decir, `fibonacci.fib(7)`.
> - Una solución consiste en asignar un alias para obtener un nombre más corto:
```
fib = fibonacci.ifib
fib(10)
```
## Laboratorio
- Escriba un programa para el cálculo de $f(n) = 3 \times n $ (es decir, los múltiplos de $3$).
- Escriba un programa que genere el [Triángulo de Pascal](https://es.wikipedia.org/wiki/Triángulo_de_Pascal) para una cierta cantidad de números, $n$.
- Escriba un programa que extraiga del Triángulo de Pascal los primeros 10 números de la $Sucesión$ de $Fibonacci$.
- Escriba una función *find_index*(), que retorna el índice de un número en la $Sucesión$ de $Fibonacci$ si el número es un elemento de dicha $Sucesión$ y $-1$ si el número no está en la $Sucesión$.
- La suma de los cuadrados de dos números consecutivos de la $Sucesión$ de $Fibonacci$ también es un número de $Fibonacci$. Por ejemplo $2$ y $3$ son números de la Sucesión y $2^2 + 3^2 = 13$ que corresponde al número $F_7$. Use la función del ejercicio anterior para encontrar la posición de la suma de los cuadrados de dos números consecutivos en la $Secuencia$ de $Fibonacci$.
- $Tamiz$ $de$ $Erastótenes$: es un algoritmo simple para encontrar todos los números primos hasta un entero especificado, $n$:
1. Crear una lista de enteros desde $2$ hasta $n$: $2, 3, 4, \ldots, n$.
2. Comience con un contador en $2$, es decir, el primer número primo.
3. A partir de $i+i$, cuente hasta $i$ y elimine esos números de la lista, es decir, $2*i$, $3*i$,$4*i$, $\ldots$
4. Encuentra el número siguiente de la lista, $i$. Este es el siguiente número primo.
5. Establezca $i$ en el número encontrado en el paso anterior.
6. Repita los pasos $3$ y $4$ hasta que $i$ sea mayor que $n$. (Como una mejora: Es suficiente determinar la raíz cuadrada de $n$)
7. Todos los números, que todavía están en la lista, son números primos.
| github_jupyter |
# Exercise 3 - Quantum error correction
## Historical background
Shor's algorithm gave quantum computers a worthwhile use case—but the inherent noisiness of quantum mechanics meant that building hardware capable of running such an algorithm would be a huge struggle. In 1995, Shor released another landmark paper: a scheme that shared quantum information over multiple qubits in order to reduce errors.[1]
A great deal of progress has been made over the decades since. New forms of error correcting codes have been discovered, and a large theoretical framework has been built around them. The surface codes proposed by Kitaev in 1997 have emerged as the leading candidate, and many variations on the original design have emerged since then. But there is still a lot of progress to make in tailoring codes to the specific details of quantum hardware.[2]
In this exercise we'll consider a case in which artificial 'errors' are inserted into a circuit. Your task is to design the circuit such that these additional gates can be identified.
You'll then need to think about how to implement your circuit on a real device. This means you'll need to tailor your solution to the layout of the qubits. Your solution will be scored on how few entangling gates (the noisiest type of gate) that you use.
### References
1. Shor, Peter W. "Scheme for reducing decoherence in quantum computer memory." Physical review A 52.4 (1995): R2493.
1. Dennis, Eric, et al. "Topological quantum memory." Journal of Mathematical Physics 43.9 (2002): 4452-4505.
## The problem of errors
Errors occur when some spurious operation acts on our qubits. Their effects cause things to go wrong in our circuits. The strange results you may have seen when running on real devices is all due to these errors.
There are many spurious operations that can occur, but it turns out that we can pretend that there are only two types of error: bit flips and phase flips.
Bit flips have the same effect as the `x` gate. They flip the $|0\rangle$ state of a single qubit to $|1\rangle$ and vice-versa. Phase flips have the same effect as the `z` gate, introducing a phase of $-1$ into superpositions. Put simply, they flip the $|+\rangle$ state of a single qubit to $|-\rangle$ and vice-versa.
The reason we can think of any error in terms of just these two is because any error can be represented by some matrix, and any matrix can be written in terms of the matrices $X$ and $Z$. Specifically, for any single qubit matrix $M$,
$$
M = \alpha I + \beta X + \gamma XZ + \delta Z,
$$
for some suitably chosen values $\alpha$, $\beta$, $\gamma$ and $\delta$.
So whenever we apply this matrix to some single qubit state $|\psi\rangle$ we get
$$
M |\psi\rangle = \alpha |\psi\rangle + \beta X |\psi\rangle + \gamma XZ |\psi\rangle + \delta Z |\psi\rangle.
$$
The resulting superposition is composed of the original state, the state we'd have if the error was just a bit flip, the state for just a phase flip and the state for both. If we had some way to measure whether a bit or phase flip happened, the state would then collapse to just one possibility. And our complex error would become just a simple bit or phase flip.
So how do we detect whether we have a bit flip or a phase flip (or both). And what do we do about it once we know? Answering these questions is what quantum error correction is all about.
## An overly simple example
One of the first quantum circuits that most people ever write is to create a pair of entangled qubits. In this journey into quantum error correction, we'll start the same way.
```
from qiskit import QuantumCircuit, Aer
# Make an entangled pair
qc_init = QuantumCircuit(2)
qc_init.h(0)
qc_init.cx(0,1)
# Draw the circuit
display(qc_init.draw('mpl'))
# Get an output
qc = qc_init.copy()
qc.measure_all()
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
```
Here we see the expected result when we run the circuit: the results `00` and `11` occurring with equal probability.
But what happens when we have the same circuit, but with a bit flip 'error' inserted manually.
```
# Make bit flip error
qc_insert = QuantumCircuit(2)
qc_insert.x(0)
# Add it to our original circuit
qc = qc_init.copy()
qc = qc.compose(qc_insert)
# Draw the circuit
display(qc.draw('mpl'))
# Get an output
qc.measure_all()
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
```
Now the results are different: `01` and `10`. The two bit values have gone from always agreeing to always disagreeing. In this way, we detect the effect of the error.
Another way we can detect it is to undo the entanglement with a few more gates. If there are no errors, we return to the initial $|00\rangle$ state.
```
# Undo entanglement
qc_syn = QuantumCircuit(2)
qc_syn.cx(0,1)
qc_syn.h(0)
# Add this after the error
qc = qc_init.copy()
qc = qc.compose(qc_syn)
# Draw the circuit
display(qc.draw('mpl'))
# Get an output
qc.measure_all()
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
```
But what happens if there are errors one of the qubits? Try inserting different errors to find out.
Here's a circuit with all the components we've introduced so far: the initialization `qc_init`, the inserted error in `qc_insert` and the final `qc_syn` which ensures that the final measurement gives a nice definite answer.
```
# Define an error
qc_insert = QuantumCircuit(2)
qc_insert.x(0)
# Undo entanglement
qc_syn = QuantumCircuit(2)
qc_syn.cx(0,1)
qc_syn.h(0)
# Add this after the error
qc = qc_init.copy()
qc = qc.compose(qc_insert)
qc = qc.compose(qc_syn)
# Draw the circuit
display(qc.draw('mpl'))
# Get an output
qc.measure_all()
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
```
You'll find that the output tells us exactly what is going on with the errors. Both the bit and phase flips can be detected. The bit value on the left is `1` only if there is a bit flip (and so if we have inserted an `x(0)` or `x(1)`). The bit on the right similarly tells us there is a phase flip (an inserted `z(0)` or `z(1)`).
This ability to detect and distinguish bit and phase flips is very useful. But it is not quite useful enough. We can only tell *what type* of errors are happening, but not *where*. Without more detail, it is not possible to figure out how to remove the effects of these operations from our computations. For quantum error correction we therefore need something bigger and better.
It's your task to do just that! Here's a list of what you need to submit. Everything here is then explained by the example that follows.
<div class="alert alert-block alert-success">
<b>Goal</b>
Create circuits which can detect `x` and `z` errors on two qubits.
You can come up with a solution of your own. Or just tweak the almost valid solution given below.
</div>
<div class="alert alert-block alert-danger">
<b>What to submit</b>
* You need to supply two circuits:
* `qc_init`: Prepares the qubits (of which there are at least two) in a desired initial state;
* `qc_syn`: Measures a subset of the qubits.
* The artificial errors to be inserted are `x` and `z` gates on two particular qubits. You need to pick the two qubits to be used for this (supplied as the list `error_qubits`).
* There are 16 possible sets of errors to be inserted (including the trivial case of no errors). The measurement result of `qc_syn` should output a unique bit string for each. The grader will return the error message *'Please make sure the circuit is created to the initial layout.'* if this is not satisfied.
* The grader will compile the complete circuit for the backend `ibmq_tokyo` (a retired device). To show that your solution is tailor made for the device, this transpilation should not change the number of `cx` gates. If it does, you will get the error message *'Please make sure the circuit is created to the initial layout.'*
* To guide the transpilation, you'll need to tell the transpiler which qubits on the device should be used as which qubits in your circuit. This is done with an `initial_layout` list.
* You may start with the example given below, which can become a valid answer with a few tweaks.
</div>
## A better example: the surface code
```
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile
import qiskit.tools.jupyter
from qiskit.test.mock import FakeTokyo
```
In this example we'll use 5 qubits that we'll call code qubits. To keep track of them, we'll define a special quantum register.
```
code = QuantumRegister(5,'code')
```
We'll also have an additional four qubits we'll call syndrome qubits.
```
syn = QuantumRegister(4,'syn')
```
Similarly we define a register for the four output bits, used when measuring the syndrome qubits.
```
out = ClassicalRegister(4,'output')
```
We consider the qubits to be laid out as follows, with the code qubits forming the corners of four triangles, and the syndrome qubits living inside each triangle.
```
c0----------c1
| \ s0 / |
| \ / |
| s1 c2 s2 |
| / \ |
| / s3 \ |
c3----------c4
```
For each triangle we associate a stabilizer operation on its three qubits. For the qubits on the sides, the stabilizers are ZZZ. For the top and bottom ones, they are XXX.
The syndrome measurement circuit corresponds to a measurement of these observables. This is done in a similar way to surface code stabilizers (in fact, this code is a small version of a surface code).
<div class="alert alert-block alert-danger">
<b>Warning</b>
You should remove the barriers before submitting the code as it might interfere with transpilation. It is given here for visualization only.
</div>
```
qc_syn = QuantumCircuit(code,syn,out)
# Left ZZZ
qc_syn.cx(code[0],syn[1])
qc_syn.cx(code[2],syn[1])
qc_syn.cx(code[3],syn[1])
qc_syn.barrier()
# Right ZZZ
#qc_syn.cx(code[1],syn[2])
qc_syn.cx(code[2],syn[2])
qc_syn.cx(code[4],syn[2])
qc_syn.barrier()
# Top XXX
qc_syn.h(syn[0])
qc_syn.cx(syn[0],code[0])
qc_syn.cx(syn[0],code[1])
qc_syn.cx(syn[0],code[2])
qc_syn.h(syn[0])
qc_syn.barrier()
# Bottom XXX
qc_syn.h(syn[3])
qc_syn.cx(syn[3],code[2])
qc_syn.cx(syn[3],code[3])
qc_syn.cx(syn[3],code[4])
qc_syn.h(syn[3])
qc_syn.barrier()
# Measure the auxilliary qubits
qc_syn.measure(syn,out)
qc_syn.draw('mpl')
```
The initialization circuit prepares an eigenstate of these observables, such that the output of the syndrome measurement will be `0000` with certainty.
```
qc_init = QuantumCircuit(code,syn,out)
qc_init.h(syn[0])
qc_init.cx(syn[0],code[0])
qc_init.cx(syn[0],code[1])
qc_init.cx(syn[0],code[2])
qc_init.cx(syn[0],syn[2])
qc_init.cx(code[2],syn[0])
qc_init.h(syn[3])
qc_init.cx(syn[3],code[2])
qc_init.cx(syn[3],code[3])
qc_init.cx(syn[3],code[4])
qc_init.cx(code[4],syn[3])
qc_init.barrier()
qc_init.draw('mpl')
```
Let's check that is true.
```
qc = qc_init.compose(qc_syn)
display(qc.draw('mpl'))
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
```
Now let's make a circuit with which we can insert `x` and `z` gates on our two code qubits. For this we'll need to choose which of the 5 code qubits we have will correspond to the two required for the validity condition.
For this code we need to choose opposite corners.
```
error_qubits = [0,4]
```
Here 0 and 4 refer to the positions of the qubits in the following list, and hence are qubits `code[0]` and `code[4]`.
```
qc.qubits
```
To check that the code does as we require, we can use the following function to create circuits for inserting artificial errors. Here the errors we want to add are listed in `errors` as a simple text string, such as `x0` for an `x` on `error_qubits[0]`.
```
def insert(errors,error_qubits,code,syn,out):
qc_insert = QuantumCircuit(code,syn,out)
if 'x0' in errors:
qc_insert.x(error_qubits[0])
if 'x1' in errors:
qc_insert.x(error_qubits[1])
if 'z0' in errors:
qc_insert.z(error_qubits[0])
if 'z1' in errors:
qc_insert.z(error_qubits[1])
return qc_insert
```
Rather than all 16 possibilities, let's just look at the four cases where a single error is inserted.
```
for error in ['x0','x1','z0','z1']:
qc = qc_init.compose(insert([error],error_qubits,code,syn,out)).compose(qc_syn)
job = Aer.get_backend('qasm_simulator').run(qc)
print('\nFor error '+error+':')
counts = job.result().get_counts()
for output in counts:
print('Output was',output,'for',counts[output],'shots.')
```
Here we see that each bit in the output is `1` when a particular error occurs: the leftmost detects `z` on `error_qubits[1]`, then the next detects `x` on `error_qubits[1]`, and so on.
<div class="alert alert-block alert-danger">
<b>Attention</b>
The correct ordering of the output is important for this exercise. Please follow the order as given below:
1. The leftmost output represents `z` on `code[1]`.
2. The second output from left represents `x` on `code[1]`.
3. The third output from left represents `x` on `code[0]`.
4. The rightmost output represents `z` on `code[0]`.
</div>
When more errors affect the circuit, it becomes hard to unambiguously tell which errors occurred. However, by continuously repeating the syndrome readout to get more results and analysing the data through the process of decoding, it is still possible to determine enough about the errors to correct their effects.
These kinds of considerations are beyond what we will look at in this challenge. Instead we'll focus on something simpler, but just as important: the fewer errors you have, and the simpler they are, the better your error correction will be. To ensure this, your error correction procedure should be tailor-made to the device you are using.
In this challenge we'll be considering the device `ibmq_tokyo`. Though the real version of this was retired some time ago, it still lives on as one of the mock backends.
```
# Please use the backend given here
backend = FakeTokyo()
backend
```
As a simple idea of how our original circuit is laid out, let's see how many two-qubit gates it contains.
```
qc = qc_init.compose(qc_syn)
qc = transpile(qc, basis_gates=['u','cx'])
qc.num_nonlocal_gates()
```
If we were to transpile it to the `ibmq_tokyo` backend, remapping would need to occur at the cost of adding for two-qubit gates.
```
qc1 = transpile(qc,backend,basis_gates=['u','cx'], optimization_level=3)
qc1.num_nonlocal_gates()
```
We can control this to an extent by looking at which qubits on the device would be best to use as the qubits in the code. If we look at what qubits in the code need to be connected by two-qubit gates in `qc_syn`, we find the following required connectivity graph.
```
c0....s0....c1
: : :
: : :
s1....c2....s2
: : :
: : :
c3....s3....c4
```
No set of qubits on `ibmq_tokyo` can provide this, but certain sets like 0,1,2,5,6,7,10,11,12 come close. So we can set an `initial_layout` to tell the transpiler to use these.
```
initial_layout = [0,2,6,10,12,1,5,7,11]
```
These tell the transpiler which qubits on the device to use for the qubits in the circuit (for the order they are listed in `qc.qubits`). So the first five entries in this list tell the circuit which qubits to use as the code qubits and the next four entries in this list are similarly for the syndrome qubits. So we use qubit 0 on the device as `code[0]`, qubit 2 as `code[1]` and so on.
Now let's use this for the transpilation.
```
qc2 = transpile(qc,backend,initial_layout=initial_layout, basis_gates=['u','cx'], optimization_level=3)
qc2.num_nonlocal_gates()
```
Though transpilation is a random process, you should typically find that this uses less two-qubit gates than when no initial layout is provided (you might need to re-run both transpilation code multiple times to see it as transpilation is a random process).
Nevertheless, a properly designed error correction scheme should not need any remapping at all. It should be written for the exact device used, and the number of two-qubit gates should remain constant with certainty. This is a condition for a solution to be valid. So you'll not just need to provide an `initial_layout`, but also design your circuits specifically for that layout.
But that part we leave up to you!
```
code = QuantumRegister(5,'code')
syn = QuantumRegister(4,'syn')
out = ClassicalRegister(4,'output')
initial_layout = [0,2,6,10,12,1,5,7,11]
qc_syn = QuantumCircuit(code,syn,out)
# Left ZZZ
qc_syn.cx(code[0],syn[1])
qc_syn.cx(code[2],syn[1])
qc_syn.cx(code[3],syn[1])
qc_syn.barrier()
# Right ZZZ
#qc_syn.cx(code[1],syn[2])
qc_syn.cx(code[2],syn[2])
qc_syn.cx(code[4],syn[2])
qc_syn.barrier()
# Top XXX
qc_syn.h(syn[0])
qc_syn.cx(syn[0],code[0])
qc_syn.cx(syn[0],code[1])
qc_syn.cx(syn[0],code[2])
qc_syn.h(syn[0])
qc_syn.barrier()
# Bottom XXX
qc_syn.h(syn[3])
qc_syn.cx(syn[3],code[2])
qc_syn.cx(syn[3],code[3])
qc_syn.cx(syn[3],code[4])
qc_syn.h(syn[3])
qc_syn.barrier()
# Measure the auxilliary qubits
qc_syn.measure(syn,out)
qc_syn.draw('mpl')
qc_init = QuantumCircuit(code,syn,out)
qc_init.h(syn[0])
qc_init.cx(syn[0],code[0])
qc_init.cx(syn[0],code[1])
qc_init.cx(syn[0],code[2])
qc_init.cx(syn[0],syn[2])
qc_init.cx(code[2],syn[0])
qc_init.h(syn[3])
qc_init.cx(syn[3],code[2])
qc_init.cx(syn[3],code[3])
qc_init.cx(syn[3],code[4])
qc_init.cx(code[4],syn[3])
qc_init.barrier()
qc_init.draw('mpl')
qc = qc_init.compose(qc_syn)
display(qc.draw('mpl'))
job = Aer.get_backend('qasm_simulator').run(qc)
job.result().get_counts()
print(job.result().get_counts())
error_qubits = [0,4]
for error in ['x0','x1','z0','z1']:
qc = qc_init.compose(insert([error],error_qubits,code,syn,out)).compose(qc_syn)
job = Aer.get_backend('qasm_simulator').run(qc)
print('\nFor error '+error+':')
counts = job.result().get_counts()
for output in counts:
print('Output was',output,'for',counts[output],'shots.')
# Check your answer using following code
from qc_grader import grade_ex3
grade_ex3(qc_init,qc_syn,error_qubits,initial_layout)
# Submit your answer. You can re-submit at any time.
from qc_grader import submit_ex3
submit_ex3(qc_init,qc_syn,error_qubits,initial_layout)
```
## Additional information
**Created by:** James Wootton, Rahul Pratap Singh
**Version:** 1.0.0
| github_jupyter |
For this problem set, we'll be using the Jupyter notebook:

---
## Part A (2 points)
Write a function that returns a list of numbers, such that $x_i=i^2$, for $1\leq i \leq n$. Make sure it handles the case where $n<1$ by raising a `ValueError`.
```
def squares(n):
"""Compute the squares of numbers from 1 to n, such that the
ith element of the returned list equals i^2.
"""
### BEGIN SOLUTION
if n < 1:
raise ValueError("n must be greater than or equal to 1")
return [i ** 2 for i in range(1, n + 1)]
### END SOLUTION
```
Your function should print `[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]` for $n=10$. Check that it does:
```
squares(10)
"""Check that squares returns the correct output for several inputs"""
from nose.tools import assert_equal
assert_equal(squares(1), [1])
assert_equal(squares(2), [1, 4])
assert_equal(squares(10), [1, 4, 9, 16, 25, 36, 49, 64, 81, 100])
assert_equal(squares(11), [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121])
"""Check that squares raises an error for invalid inputs"""
from nose.tools import assert_raises
assert_raises(ValueError, squares, 0)
assert_raises(ValueError, squares, -4)
```
---
## Part B (1 point)
Using your `squares` function, write a function that computes the sum of the squares of the numbers from 1 to $n$. Your function should call the `squares` function -- it should NOT reimplement its functionality.
```
def sum_of_squares(n):
"""Compute the sum of the squares of numbers from 1 to n."""
### BEGIN SOLUTION
return sum(squares(n))
### END SOLUTION
```
The sum of squares from 1 to 10 should be 385. Verify that this is the answer you get:
```
sum_of_squares(10)
"""Check that sum_of_squares returns the correct answer for various inputs."""
assert_equal(sum_of_squares(1), 1)
assert_equal(sum_of_squares(2), 5)
assert_equal(sum_of_squares(10), 385)
assert_equal(sum_of_squares(11), 506)
"""Check that sum_of_squares relies on squares."""
orig_squares = squares
del squares
try:
assert_raises(NameError, sum_of_squares, 1)
except AssertionError:
raise AssertionError("sum_of_squares does not use squares")
finally:
squares = orig_squares
```
---
## Part C (1 point)
Using LaTeX math notation, write out the equation that is implemented by your `sum_of_squares` function.
$\sum_{i=1}^n i^2$
---
## Part D (2 points)
Find a usecase for your `sum_of_squares` function and implement that usecase in the cell below.
```
def pyramidal_number(n):
"""Returns the n^th pyramidal number"""
return sum_of_squares(n)
```
| github_jupyter |
# SHAP Interaction
Using the SHAP python package to identify interactions in data
<br>
<b>Dataset:<b> https://www.kaggle.com/conorsully1/interaction-dataset
```
#imports
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import xgboost as xgb
import shap
shap.initjs()
path = "/Users/conorosully/Google Drive/Medium/SHAP Interactions/Figures/{}"
```
## Dataset
```
#import dataset
data = pd.read_csv("../data/interaction_dataset.csv",sep='\t')
y = data['bonus']
X = data.drop('bonus', axis=1)
print(len(data))
data.head()
```
## Modelling
```
#Train model
model = xgb.XGBRegressor(objective="reg:squarederror",max_depth=3)
model.fit(X, y)
#Get predictions
y_pred = model.predict(X)
#Model evaluation
fig, ax = plt.subplots(nrows=1, ncols=1,figsize=(8,8))
plt.scatter(y,y_pred)
plt.plot([0, 400], [0, 400], color='r', linestyle='-', linewidth=2)
plt.ylabel('Predicted',size=20)
plt.xlabel('Actual',size=20)
plt.savefig(path.format('regression_evaluation.png'),dpi=200,bbox_inches='tight')
```
## SHAP interaction values
```
#Get SHAP interaction values
explainer = shap.TreeExplainer(model)
shap_interaction = explainer.shap_interaction_values(X)
#Get shape of interaction values
print(np.shape(shap_interaction))
# SHAP interaction values for first employee
pd.DataFrame(shap_interaction[0],index=X.columns,columns=X.columns)
#Get model predictions
y_pred = model.predict(X)
#Calculate mean prediction
mean_pred = np.mean(y_pred)
#Sum of interaction values for first employee
sum_shap = np.sum(shap_interaction[0])
print("Model prediction: {}".format(y_pred[0]))
print("Mean prediction + interaction values: {}".format(mean_pred+sum_shap))
print(mean_pred, sum_shap)
```
### Absolute mean
```
# Get absolute mean of matrices
mean_shap = np.abs(shap_interaction).mean(0)
df = pd.DataFrame(mean_shap,index=X.columns,columns=X.columns)
# times off diagonal by 2
df.where(df.values == np.diagonal(df),df.values*2,inplace=True)
# display
plt.figure(figsize=(10, 10), facecolor='w', edgecolor='k')
sns.set(font_scale=1.5)
sns.heatmap(df,cmap='coolwarm',annot=True,fmt='.3g',cbar=False)
plt.yticks(rotation=0)
plt.savefig(path.format('abs_mean_shap.png'),dpi=200,bbox_inches='tight')
```
### Summary Plot
```
# Get SHAP values
shap_values = explainer(X)
#Display beeswarm plot
shap.plots.beeswarm(shap_values,show=False)
plt.savefig(path.format('beeswarm.png'),dpi=200,bbox_inches='tight')
#Display summary plot
shap.summary_plot(shap_interaction, X,show=False)
plt.savefig(path.format('summary.png'),dpi=200,bbox_inches='tight')
```
### Dependence plot
```
# Experience-degree depenence plot
shap.dependence_plot(
("experience", "degree"),
shap_interaction, X,
display_features=X,show=False)
plt.savefig(path.format('exp_degree_dependence.png'),dpi=200,bbox_inches='tight')
#Model evaluation
fig, ax = plt.subplots(nrows=1, ncols=1,figsize=(8,8))
plt.scatter('experience','bonus',data=data[data.degree==1],c='#D62728',label='1')
plt.scatter('experience','bonus',data=data[data.degree==0],c='#1F77B4',label='0')
plt.ylabel('bonus',size=20)
plt.xlabel('experience',size=20)
plt.legend(title='degree',fontsize=10)
plt.savefig(path.format('experience_degree_scatter.png'),dpi=200,bbox_inches='tight')
shap.dependence_plot(
("performance", "sales"),
shap_interaction, X,
display_features=X,show=False)
plt.savefig(path.format('perf_sales_dependence.png'),dpi=200,bbox_inches='tight')
```
| github_jupyter |
(pymc3_schema)=
# Example of `InferenceData` schema in PyMC3
The description of the `InferenceData` structure can be found {ref}`here <schema>`.
```
import arviz as az
import pymc3 as pm
import pandas as pd
import numpy as np
import xarray
xarray.set_options(display_style="html");
#read data
data = pd.read_csv("linear_regression_data.csv", index_col=0)
time = data.time.values
slack_comments = data.comments.values
github_commits = data.commits.values
names = data.index.values
N = len(names)
data
# data for out of sample predictions
candidate_devs = ["Francis", "Gerard"]
candidate_devs_time = np.array([3.6, 5.1])
dims={
"slack_comments": ["developer"],
"github_commits": ["developer"],
"time_since_joined": ["developer"],
}
with pm.Model() as model:
time_since_joined = pm.Data("time_since_joined", time)
b_sigma = pm.HalfNormal('b_sigma', sd=300)
c_sigma = pm.HalfNormal('c_sigma', sd=6)
b0 = pm.Normal("b0", mu=0, sd=200)
b1 = pm.Normal("b1", mu=0, sd=200)
c0 = pm.Normal("c0", mu=0, sd=10)
c1 = pm.Normal("c1", mu=0, sd=10)
pm.Normal("slack_comments", mu=b0 + b1 * time_since_joined, sigma=b_sigma, observed=slack_comments)
pm.Normal("github_commits", mu=c0 + c1 * time_since_joined, sigma=c_sigma, observed=github_commits)
trace = pm.sample(400, chains=4)
posterior_predictive = pm.sample_posterior_predictive(trace)
prior = pm.sample_prior_predictive(150)
idata_pymc3 = az.from_pymc3(
trace,
prior=prior,
posterior_predictive=posterior_predictive,
coords={"developer": names},
dims=dims
)
dims_pred={
"slack_comments": ["candidate developer"],
"github_commits": ["candidate developer"],
"time_since_joined": ["candidate developer"],
}
with model:
pm.set_data({"time_since_joined": candidate_devs_time})
predictions = pm.sample_posterior_predictive(trace)
az.from_pymc3_predictions(
predictions,
idata_orig=idata_pymc3,
inplace=True,
coords={"candidate developer": candidate_devs},
dims=dims_pred,
)
idata_pymc3
```
In this example, each variable has as dimension a combination of the following 3: `chain`, `draw` and `developer`. Moreover, each dimension has specific coordinate values. In the case of `chain` and `draw` it is an integer identifier starting at `0`; in the case of `developer` dimension, its coordinate values are the following strings: `["Alice", "Bob", "Cole", "Danielle", "Erika"]`.
```
idata_pymc3.posterior
idata_pymc3.sample_stats
idata_pymc3.log_likelihood
idata_pymc3.posterior_predictive
idata_pymc3.observed_data
idata_pymc3.constant_data
idata_pymc3.prior
idata_pymc3.predictions
idata_pymc3.predictions_constant_data
```
| github_jupyter |
```
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All"
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
!pip install ktrain
from ktrain import text
ts = text.TransformerSummarizer()
sample_doc = """n probability theory and statistics, the negative \
binomial distribution is a discrete probability \
distribution that models the number of successes \
in a sequence of independent and identically distributed \
Bernoulli trials before a specified (non-random) number \
of failures (denoted r) occurs. For example, we can \
define rolling a 6 on a die as a failure, and rolling \
any other number as a success, and ask how many successful \
rolls will occur before we see the third failure (r = 3). \
In such a case, the probability distribution of the number \
of non-6s that appear will be a negative binomial \
distribution.The Pascal distribution (after Blaise Pascal) \
and Polya distribution (for George Pólya) are special cases \
of the negative binomial distribution. A convention among \
engineers, climatologists, and others is to use \
"negative binomial" or "Pascal" for the case of an \
integer-valued stopping-time parameter r, and use "Polya" \
for the real-valued case. For occurrences of associated \
discrete events, like tornado outbreaks, the Polya \
distributions can be used to give more accurate models \
than the Poisson distribution by allowing the mean and \
variance to be different, unlike the Poisson. The negative \
binomial distribution has a variance \
{\displaystyle \mu (1+\mu /r)}{\displaystyle \mu (1+\mu /r)}, \
with the distribution becoming identical to Poisson in the \
limit {\displaystyle r\to \infty }{\displaystyle r\to\infty}\
for a given mean {\displaystyle \mu }\mu . This can make \
the distribution a useful overdispersed alternative to \
the Poisson distribution, for example for a robust modification \
of Poisson regression. In epidemiology it has been used to model \
disease transmission for infectious diseases where the likely \
number of onward infections may vary considerably from individual \
to individual and from setting to setting.[2] More generally it \
may be appropriate where events have positively correlated \
occurrences causing a larger variance than if the occurrences \
were independent, due to a positive covariance term.
Suppose there is a sequence of independent Bernoulli trials.
Thus, each trial has two potential outcomes called "success"
and "failure". In each trial the probability of success is p
and of failure is (1 − p). We are observing this sequence until
a predefined number r of successes have occurred. Then the
random number of failures we have seen, X, will have the negative
binomial (or Pascal) distribution:
{\displaystyle X\sim \operatorname {NB} (r,p)}{\displaystyle X\sim \operatorname {NB} (r,p)}
When applied to real-world problems, outcomes of success and
failure may or may not be outcomes we ordinarily view as good
and bad, respectively. Suppose we used the negative binomial
distribution to model the number of days a certain machine works
before it breaks down. In this case "failure" would be the result
on a day when the machine worked properly, whereas a breakdown
would be a "success". If we used the negative binomial
distribution to model the number of goal attempts an athlete
makes before scoring r goals, though, then each unsuccessful
attempt would be a "failure", and scoring a goal would be
"success". If we are tossing a coin, then the negative binomial
distribution can give the number of tails ("failures") we are
likely to encounter before we encounter a certain number of
heads ("successes"). In the probability mass function below,
p is the probability of success, and (1 − p) is the probability
of failure.
"""
# Now, let's use our TransformerSummarizer instance to summarize the long document.
ts.summarize(sample_doc)
```
| github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.

# Using Azure Machine Learning Pipelines for Batch Inference for CSV Files
In this notebook, we will demonstrate how to make predictions on large quantities of data asynchronously using the ML pipelines with Azure Machine Learning. Batch inference (or batch scoring) provides cost-effective inference, with unparalleled throughput for asynchronous applications. Batch prediction pipelines can scale to perform inference on terabytes of production data. Batch prediction is optimized for high throughput, fire-and-forget predictions for a large collection of data.
> **Tip**
If your system requires low-latency processing (to process a single document or small set of documents quickly), use [real-time scoring](https://docs.microsoft.com/azure/machine-learning/service/how-to-consume-web-service) instead of batch prediction.
In this example we will take use a machine learning model already trained to predict different types of iris flowers and run that trained model on some of the data in a CSV file which has characteristics of different iris flowers. However, the same example can be extended to manipulating data to any embarrassingly-parallel processing through a python script.
The outline of this notebook is as follows:
- Create a DataStore referencing the CSV files stored in a blob container.
- Register the pretrained model into the model registry.
- Use the registered model to do batch inference on the CSV files in the data blob container.
## Prerequisites
If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, make sure you go through the configuration Notebook located at https://github.com/Azure/MachineLearningNotebooks first. This sets you up with a working config file that has information on your workspace, subscription id, etc.
### Connect to workspace
Create a workspace object from the existing workspace. Workspace.from_config() reads the file config.json and loads the details into an object named ws.
```
# Check core SDK version number
import azureml.core
print("SDK version:", azureml.core.VERSION)
from azureml.core import Workspace
ws = Workspace.from_config()
print('Workspace name: ' + ws.name,
'Azure region: ' + ws.location,
'Subscription id: ' + ws.subscription_id,
'Resource group: ' + ws.resource_group, sep = '\n')
```
### Create or Attach existing compute resource
By using Azure Machine Learning Compute, a managed service, data scientists can train machine learning models on clusters of Azure virtual machines. Examples include VMs with GPU support. In this tutorial, you create Azure Machine Learning Compute as your training environment. The code below creates the compute clusters for you if they don't already exist in your workspace.
> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.
**Creation of compute takes approximately 5 minutes. If the AmlCompute with that name is already in your workspace the code will skip the creation process.**
```
import os
from azureml.core.compute import AmlCompute, ComputeTarget
# choose a name for your cluster
compute_name = os.environ.get("AML_COMPUTE_CLUSTER_NAME", "cpu-cluster")
compute_min_nodes = os.environ.get("AML_COMPUTE_CLUSTER_MIN_NODES", 0)
compute_max_nodes = os.environ.get("AML_COMPUTE_CLUSTER_MAX_NODES", 4)
# This example uses CPU VM. For using GPU VM, set SKU to STANDARD_NC6
vm_size = os.environ.get("AML_COMPUTE_CLUSTER_SKU", "STANDARD_D2_V2")
if compute_name in ws.compute_targets:
compute_target = ws.compute_targets[compute_name]
if compute_target and type(compute_target) is AmlCompute:
print('found compute target. just use it. ' + compute_name)
else:
print('creating a new compute target...')
provisioning_config = AmlCompute.provisioning_configuration(vm_size = vm_size,
min_nodes = compute_min_nodes,
max_nodes = compute_max_nodes)
# create the cluster
compute_target = ComputeTarget.create(ws, compute_name, provisioning_config)
# can poll for a minimum number of nodes and for a specific timeout.
# if no min node count is provided it will use the scale settings for the cluster
compute_target.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)
# For a more detailed view of current AmlCompute status, use get_status()
print(compute_target.get_status().serialize())
```
### Create a datastore containing sample images
The input dataset used for this notebook is CSV data which has attributes of different iris flowers. We have created a public blob container `sampledata` on an account named `pipelinedata`, containing iris data set. In the next step, we create a datastore with the name `iris_datastore`, which points to this container. In the call to `register_azure_blob_container` below, setting the `overwrite` flag to `True` overwrites any datastore that was created previously with that name.
This step can be changed to point to your blob container by providing your own `datastore_name`, `container_name`, and `account_name`.
```
from azureml.core.datastore import Datastore
account_name = "pipelinedata"
datastore_name="iris_datastore_data"
container_name="sampledata"
iris_data = Datastore.register_azure_blob_container(ws,
datastore_name=datastore_name,
container_name= container_name,
account_name=account_name,
overwrite=True)
```
### Create a TabularDataset
A [TabularDataSet](https://docs.microsoft.com/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py) references single or multiple files which contain data in a tabular structure (ie like CSV files) in your datastores or public urls. TabularDatasets provides you with the ability to download or mount the files to your compute. By creating a dataset, you create a reference to the data source location. If you applied any subsetting transformations to the dataset, they will be stored in the dataset as well. The data remains in its existing location, so no extra storage cost is incurred.
You can use dataset objects as inputs. Register the datasets to the workspace if you want to reuse them later.
```
from azureml.core.dataset import Dataset
iris_ds_name = 'iris_data'
path_on_datastore = iris_data.path('iris/')
input_iris_ds = Dataset.Tabular.from_delimited_files(path=path_on_datastore, validate=False)
named_iris_ds = input_iris_ds.as_named_input(iris_ds_name)
```
### Intermediate/Output Data
Intermediate data (or output of a Step) is represented by [PipelineData](https://docs.microsoft.com/python/api/azureml-pipeline-core/azureml.pipeline.core.pipelinedata?view=azure-ml-py) object. PipelineData can be produced by one step and consumed in another step by providing the PipelineData object as an output of one step and the input of one or more steps.
```
from azureml.pipeline.core import PipelineData
datastore = ws.get_default_datastore()
output_folder = PipelineData(name='inferences', datastore=datastore)
```
## Registering the Model with the Workspace
Get the pretrained model from a publicly available Azure Blob container, then register it to use in your workspace
```
model_container_name="iris-model"
model_datastore_name="iris_model_datastore"
model_datastore = Datastore.register_azure_blob_container(ws,
datastore_name=model_datastore_name,
container_name= model_container_name,
account_name=account_name,
overwrite=True)
from azureml.core.model import Model
model_datastore.download('iris_model.pkl')
# register downloaded model
model = Model.register(model_path = "iris_model.pkl/iris_model.pkl",
model_name = "iris-prs", # this is the name the model is registered as
tags = {'pretrained': "iris"},
workspace = ws)
```
### Using your model to make batch predictions
To use the model to make batch predictions, you need an **entry script** and a list of **dependencies**:
#### An entry script
This script accepts requests, scores the requests by using the model, and returns the results.
- __init()__ - Typically this function loads the model into a global object. This function is run only once at the start of batch processing per worker node/process. init method can make use of following environment variables (ParallelRunStep input):
1. AZUREML_BI_OUTPUT_PATH – output folder path
- __run(mini_batch)__ - The method to be parallelized. Each invocation will have one minibatch.<BR>
__mini_batch__: Batch inference will invoke run method and pass either a list or Pandas DataFrame as an argument to the method. Each entry in min_batch will be - a filepath if input is a FileDataset, a Pandas DataFrame if input is a TabularDataset.<BR>
__run__ method response: run() method should return a Pandas DataFrame or an array. For append_row output_action, these returned elements are appended into the common output file. For summary_only, the contents of the elements are ignored. For all output actions, each returned output element indicates one successful inference of input element in the input mini-batch.
User should make sure that enough data is included in inference result to map input to inference. Inference output will be written in output file and not guaranteed to be in order, user should use some key in the output to map it to input.
#### Dependencies
Helper scripts or Python/Conda packages required to run the entry script.
## Print inferencing script
```
scripts_folder = "Code"
script_file = "iris_score.py"
# peek at contents
with open(os.path.join(scripts_folder, script_file)) as inference_file:
print(inference_file.read())
```
## Build and run the batch inference pipeline
The data, models, and compute resource are now available. Let's put all these together in a pipeline.
### Specify the environment to run the script
Specify the conda dependencies for your script. This will allow us to install pip packages as well as configure the inference environment.
* Always include **azureml-core** and **azureml-dataset-runtime\[fuse\]** in the pip package list to make ParallelRunStep run properly.
* For TabularDataset, add **pandas** as `run(mini_batch)` uses `pandas.DataFrame` as mini_batch type.
If you're using custom image (`batch_env.python.user_managed_dependencies = True`), you need to install the package to your image.
```
from azureml.core import Environment
from azureml.core.runconfig import CondaDependencies
predict_conda_deps = CondaDependencies.create(pip_packages=["scikit-learn==0.20.3",
"azureml-core", "azureml-dataset-runtime[pandas,fuse]"])
predict_env = Environment(name="predict_environment")
predict_env.python.conda_dependencies = predict_conda_deps
predict_env.spark.precache_packages = False
```
### Create the configuration to wrap the inference script
```
from azureml.pipeline.steps import ParallelRunStep, ParallelRunConfig
# In a real-world scenario, you'll want to shape your process per node and nodes to fit your problem domain.
parallel_run_config = ParallelRunConfig(
source_directory=scripts_folder,
entry_script=script_file, # the user script to run against each input
mini_batch_size='1KB',
error_threshold=5,
output_action='append_row',
append_row_file_name="iris_outputs.txt",
environment=predict_env,
compute_target=compute_target,
node_count=2,
run_invocation_timeout=600
)
```
### Create the pipeline step
Create the pipeline step using the script, environment configuration, and parameters. Specify the compute target you already attached to your workspace as the target of execution of the script. We will use ParallelRunStep to create the pipeline step.
```
distributed_csv_iris_step = ParallelRunStep(
name='example-iris',
inputs=[named_iris_ds],
output=output_folder,
parallel_run_config=parallel_run_config,
arguments=['--model_name', 'iris-prs'],
allow_reuse=False
)
```
### Run the pipeline
At this point you can run the pipeline and examine the output it produced. The Experiment object is used to track the run of the pipeline
```
from azureml.core import Experiment
from azureml.pipeline.core import Pipeline
pipeline = Pipeline(workspace=ws, steps=[distributed_csv_iris_step])
pipeline_run = Experiment(ws, 'iris-prs').submit(pipeline)
```
## View progress of Pipeline run
The pipeline run status could be checked in Azure Machine Learning portal (https://ml.azure.com). The link to the pipeline run could be retrieved by inspecting the `pipeline_run` object.
```
# This will output information of the pipeline run, including the link to the details page of portal.
pipeline_run
```
### Optional: View detailed logs (streaming)
```
## Wait the run for completion and show output log to console
pipeline_run.wait_for_completion(show_output=True)
```
## View Results
In the iris_score.py file above you can see that the Result with the prediction of the iris variety gets returned and then appended to the original input of the row from the csv file. These results are written to the DataStore specified in the PipelineData object as the output data, which in this case is called *inferences*. This contains the outputs from all of the worker nodes used in the compute cluster. You can download this data to view the results ... below just filters to a random 20 rows
```
import pandas as pd
import tempfile
prediction_run = pipeline_run.find_step_run(distributed_csv_iris_step.name)[0]
prediction_output = prediction_run.get_output_data(output_folder.name)
target_dir = tempfile.mkdtemp()
prediction_output.download(local_path=target_dir)
result_file = os.path.join(target_dir, prediction_output.path_on_datastore, parallel_run_config.append_row_file_name)
# cleanup output format
df = pd.read_csv(result_file, delimiter=" ", header=None)
df.columns = ["sepal.length", "sepal.width", "petal.length", "petal.width", "variety"]
print("Prediction has ", df.shape[0], " rows")
random_subset = df.sample(n=20)
random_subset.head(20)
```
## Cleanup compute resources
For re-occurring jobs, it may be wise to keep compute the compute resources and allow compute nodes to scale down to 0. However, since this is just a single run job, we are free to release the allocated compute resources.
```
# uncomment below and run if compute resources are no longer needed
# compute_target.delete()
```
| github_jupyter |
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from scipy import stats
from compton import setup_rc_params
setup_rc_params()
```
In GMP 2016 they use
\begin{align}
\xi^{(s)} & = c_0^{(s)} + c_2^{(s)} \delta^2 + \Delta_2^{(s)} \\
\xi^{(v)} & = c_0^{(v)} + \Delta_0^{(v)}
\end{align}
and find a posterior for $\Delta$ given the convergence pattern as in Furnstahl (2015).
So the first omitted term for the scalar pieces goes as $\delta^3$ and the first omitted term for the vector piece goes as $\delta^1$.
```
# e^2 delta^2, e^2 delta^3, e^2 delta^4-fitted
gamma_e1e1_proton = np.array([-5.68562, -5.45127, -1.1])
gamma_e1e1_neutron = np.array([-5.68562, -5.45127, -4.0227])
# gamma_m1m1_proton = np.array([-1.13712, 1.95882, 2.2])
# gamma_m1m1_neutron = np.array([-1.13712, 1.95882, 1.26474])
# Use a fitted value for NLO...?
gamma_m1m1_proton = np.array([-1.13712, 1.63, 2.2])
gamma_m1m1_neutron = np.array([-1.13712, 1.63, 1.26474])
gamma_e1m2_proton = np.array([1.13712, 0.55244, -0.4])
gamma_e1m2_neutron = np.array([1.13712, 0.55244, -0.1343])
gamma_m1e2_proton = np.array([1.13712, 1.2701, 1.9])
gamma_m1e2_neutron = np.array([1.13712, 1.2701, 2.36763])
gamma_0_proton = - (gamma_e1e1_proton + gamma_m1m1_proton + gamma_e1m2_proton + gamma_m1e2_proton)
gamma_pi_proton = - gamma_e1e1_proton + gamma_m1m1_proton - gamma_e1m2_proton + gamma_m1e2_proton
gamma_0_neutron = - (gamma_e1e1_neutron + gamma_m1m1_neutron + gamma_e1m2_neutron + gamma_m1e2_neutron)
gamma_pi_neutron = - gamma_e1e1_neutron + gamma_m1m1_neutron - gamma_e1m2_neutron + gamma_m1e2_neutron
gamma_0_proton
gamma_pi_proton
gamma_0_neutron
gamma_pi_neutron
# Table 2
# gamma_e1e1_scalar = [-5.7, -2.6]
# gamma_e1e1_vector = [+1.5]
# gamma_m1m1_scalar = [-1.1, +1.8]
# gamma_m1m1_vector = [+0.5]
# gamma_e1m2_scalar = [+1.1, -0.3]
# gamma_e1m2_vector = [-0.1]
# gamma_m1e2_scalar = [+1.1, +2.2]
# gamma_m1e2_vector = [-0.2]
scalar_idxs = [0, -1]
scalar_idxs_m1m1 = [0, 1, 2]
vector_idxs = [-1]
gamma_e1e1_scalar = (gamma_e1e1_proton + gamma_e1e1_neutron)[scalar_idxs] / 2
gamma_e1e1_vector = (gamma_e1e1_proton - gamma_e1e1_neutron)[vector_idxs] / 2
gamma_m1m1_scalar = (gamma_m1m1_proton + gamma_m1m1_neutron)[scalar_idxs_m1m1] / 2
gamma_m1m1_vector = (gamma_m1m1_proton - gamma_m1m1_neutron)[vector_idxs] / 2
gamma_e1m2_scalar = (gamma_e1m2_proton + gamma_e1m2_neutron)[scalar_idxs] / 2
gamma_e1m2_vector = (gamma_e1m2_proton - gamma_e1m2_neutron)[vector_idxs] / 2
gamma_m1e2_scalar = (gamma_m1e2_proton + gamma_m1e2_neutron)[scalar_idxs] / 2
gamma_m1e2_vector = (gamma_m1e2_proton - gamma_m1e2_neutron)[vector_idxs] / 2
gamma_0_scalar = (gamma_0_proton + gamma_0_neutron)[scalar_idxs_m1m1] / 2
gamma_0_vector = (gamma_0_proton - gamma_0_neutron)[vector_idxs] / 2
gamma_pi_scalar = (gamma_pi_proton + gamma_pi_neutron)[scalar_idxs_m1m1] / 2
gamma_pi_vector = (gamma_pi_proton - gamma_pi_neutron)[vector_idxs] / 2
print('gamma E1E1 Scalar:', gamma_e1e1_scalar)
print('gamma E1E1 Vector:', gamma_e1e1_vector)
print('gamma M1M1 Scalar:', gamma_m1m1_scalar)
print('gamma M1M1 Vector:', gamma_m1m1_vector)
print('gamma E1M2 Scalar:', gamma_e1m2_scalar)
print('gamma E1M2 Vector:', gamma_e1m2_vector)
print('gamma M1E2 Scalar:', gamma_m1e2_scalar)
print('gamma M1E2 Vector:', gamma_m1e2_vector)
print('gamma 0 Scalar:', gamma_0_scalar)
print('gamma 0 Vector:', gamma_0_vector)
print('gamma pi Scalar:', gamma_pi_scalar)
print('gamma pi Vector:', gamma_pi_vector)
def compute_coefficients(y, Q, orders=None):
if orders is None:
orders = np.arange(len(y))
y = np.atleast_1d(y)
diffs = np.diff(y)
diffs = np.insert(diffs, 0, y[0])
return diffs / Q ** orders
delta = 0.4 # Eq. (2)
```
Extract coefficients
```
orders_isoscl = np.array([0, 2])
orders_isoscl_m1m1 = np.array([0, 1, 2])
orders_isovec = np.array([0])
coefs_e1e1_scalar = compute_coefficients(gamma_e1e1_scalar, delta, orders=orders_isoscl)
coefs_e1e1_vector = compute_coefficients(gamma_e1e1_vector, delta, orders=orders_isovec)
coefs_m1m1_scalar = compute_coefficients(gamma_m1m1_scalar, delta, orders=orders_isoscl_m1m1)
coefs_m1m1_vector = compute_coefficients(gamma_m1m1_vector, delta, orders=orders_isovec)
coefs_e1m2_scalar = compute_coefficients(gamma_e1m2_scalar, delta, orders=orders_isoscl)
coefs_e1m2_vector = compute_coefficients(gamma_e1m2_vector, delta, orders=orders_isovec)
coefs_m1e2_scalar = compute_coefficients(gamma_m1e2_scalar, delta, orders=orders_isoscl)
coefs_m1e2_vector = compute_coefficients(gamma_m1e2_vector, delta, orders=orders_isovec)
coefs_0_scalar = compute_coefficients(gamma_0_scalar, delta, orders=orders_isoscl_m1m1)
coefs_0_vector = compute_coefficients(gamma_0_vector, delta, orders=orders_isovec)
coefs_pi_scalar = compute_coefficients(gamma_pi_scalar, delta, orders=orders_isoscl_m1m1)
coefs_pi_vector = compute_coefficients(gamma_pi_vector, delta, orders=orders_isovec)
print('Scalar E1E1 c_n:', coefs_e1e1_scalar)
print('Vector E1E1 c_n:', coefs_e1e1_vector)
print('Scalar M1M1 c_n:', coefs_m1m1_scalar)
print('Vector M1M1 c_n:', coefs_m1m1_vector)
print('Scalar E1M2 c_n:', coefs_e1m2_scalar)
print('Vector E1M2 c_n:', coefs_e1m2_vector)
print('Scalar M1E2 c_n:', coefs_m1e2_scalar)
print('Vector M1E2 c_n:', coefs_m1e2_vector)
print('Scalar 0 c_n:', coefs_0_scalar)
print('Vector 0 c_n:', coefs_0_vector)
print('Scalar pi c_n:', coefs_pi_scalar)
print('Vector pi c_n:', coefs_pi_vector)
```
## 2016 Analysis (Set A Epsilon Priors)
```
def compute_A_eps1_posterior(x, c, Q, first_omitted_order=None, verbose=False):
if first_omitted_order is None:
first_omitted_order = len(c)
n_c = len(c)
# n_c = first_omitted_order
max_c = np.max(np.abs(c))
R = max_c * Q**first_omitted_order
if verbose:
print('R', R)
factor = n_c / (n_c + 1.) / (2. * R)
with np.errstate(divide='ignore'):
return factor * np.where(np.abs(x) <= R, 1., (R / np.abs(x)) ** (n_c + 1))
def plot_scalar_and_vector(x, c_s, c_v, Q, first_omitted_order_s, first_omitted_order_v, num_x_minor=5, num_y_minor=5, ax=None):
"""A convenience function to make the same plot easily"""
from matplotlib.ticker import MultipleLocator, AutoMinorLocator
if ax is None:
fig, ax = plt.subplots()
ax.plot(x, compute_A_eps1_posterior(x, c_s, Q, first_omitted_order=first_omitted_order_s, verbose=True), c='b', ls='--')
ax.plot(x, compute_A_eps1_posterior(x, c_v, Q, first_omitted_order=first_omitted_order_v, verbose=True), c='g', ls=':')
# Grid that work well enough for these densities
dense_x = np.linspace(-50, 50, 5000)
post_s = compute_A_eps1_posterior(dense_x, c_s, Q, first_omitted_order=first_omitted_order_s)
post_v = compute_A_eps1_posterior(dense_x, c_v, Q, first_omitted_order=first_omitted_order_v)
conv = np.convolve(post_s, post_v, mode='same')
conv /= np.trapz(conv, dense_x)
conv_interp = np.interp(x, dense_x, conv)
ax.plot(x, conv_interp, c='r')
ax.margins(x=0)
ax.xaxis.set_minor_locator(AutoMinorLocator(num_x_minor))
ax.yaxis.set_minor_locator(AutoMinorLocator(num_y_minor))
ax.tick_params(which='both', top=True, right=True)
ax.set_ylim(0, None)
return ax
N = 500
d_e1e1 = np.linspace(0, 10, N)
d_m1m1 = np.linspace(0, 3, N)
d_e1m2 = np.linspace(0, 3, N)
d_m1e2 = np.linspace(0, 3, N)
d_0 = np.linspace(0, 8, N)
d_pi = np.linspace(0, 8, N)
first_omitted_s = 3
first_omitted_v = 1
fig, axes = plt.subplots(3, 2, figsize=(7, 5))
print('E1E1')
ax_e1e1 = plot_scalar_and_vector(
d_e1e1, coefs_e1e1_scalar, coefs_e1e1_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
ax=axes[0, 0]
)
ax_e1e1.yaxis.set_major_locator(MultipleLocator(0.1))
ax_e1e1.set_ylabel(r'pr$_{\gamma_{E1E1}}(\Delta)$')
print('M1M1')
ax_m1m1 = plot_scalar_and_vector(
d_m1m1, coefs_m1m1_scalar, coefs_m1m1_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
num_y_minor=4, ax=axes[0, 1]
)
ax_m1m1.yaxis.set_major_locator(MultipleLocator(0.2))
ax_m1m1.set_ylabel(r'pr$_{\gamma_{M1M1}}(\Delta)$')
print('E1M2')
ax_e1m2 = plot_scalar_and_vector(
d_e1m2, coefs_e1m2_scalar, coefs_e1m2_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
ax=axes[1, 0]
)
ax_e1m2.set_ylabel(r'pr$_{\gamma_{E1M2}}(\Delta)$')
print('M1E2')
ax_m1e2 = plot_scalar_and_vector(
d_m1e2, coefs_m1e2_scalar, coefs_m1e2_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
ax=axes[1, 1]
)
ax_m1e2.set_ylabel(r'pr$_{\gamma_{M1E2}}(\Delta)$')
print('0')
ax_0 = plot_scalar_and_vector(
d_0, coefs_0_scalar, coefs_0_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
ax=axes[2, 0]
)
ax_0.yaxis.set_major_locator(MultipleLocator(0.1))
ax_0.set_ylabel(r'pr$_{\gamma_0}(\Delta)$')
print('pi')
ax_pi = plot_scalar_and_vector(
d_pi, coefs_pi_scalar, coefs_pi_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
ax=axes[2, 1]
)
ax_pi.yaxis.set_major_locator(MultipleLocator(0.1))
ax_pi.set_ylabel(r'pr$_{\gamma_{\pi}}(\Delta)$')
fig.tight_layout()
fig.savefig('pol_priors_set_Aeps')
```
Not bad! The $\gamma_0$ and $\gamma_\pi$ are still not exactly right. I'm not sure if I got the NLO corrections right.
## Updated Analysis
Here $\nu_0 = 0$ means that the prior is completely uninformative. To mirror the previous results, use that.
```
def compute_nu_and_tau(c, nu0=0, tau0=1):
c = np.atleast_1d(c)
nu = nu0 + len(c)
tau_sq = (nu0 * tau0**2 + c @ c) / nu
return nu, np.sqrt(tau_sq)
def compute_cbar_estimate(c, nu0=0, tau0=1):
nu, tau = compute_nu_and_tau(c, nu0=nu0, tau0=tau0)
# Either get the MAP value or the mean value...
# return tau * np.sqrt(nu / (nu - 2))
return tau * np.sqrt(nu / (nu + 2))
nu_0 = 0
tau_0 = 1
def plot_scalar_and_vector_gaussian(x, c_s, c_v, Q, first_omitted_order_s, first_omitted_order_v, num_x_minor=5, num_y_minor=5, nu0=0, tau0=1, ax=None, full_sum=True):
"""A convenience function to make the same plot easily"""
from matplotlib.ticker import MultipleLocator, AutoMinorLocator
# nu_s, tau_s = compute_nu_and_tau(c_s, nu0=nu0, tau0=tau0)
# nu_v, tau_v = compute_nu_and_tau(c_v, nu0=nu0, tau0=tau0)
cbar_s = compute_cbar_estimate(c_s, nu0=nu0, tau0=tau0)
cbar_v = compute_cbar_estimate(c_v, nu0=nu0, tau0=tau0)
# print('cbar_s:', cbar_s)
# print('cbar_v:', cbar_v)
if full_sum:
Q_sum_s = Q**first_omitted_order_s / np.sqrt(1 - Q**2)
Q_sum_v = Q**first_omitted_order_v / np.sqrt(1 - Q**2)
else:
Q_sum_s = Q**first_omitted_order_s
Q_sum_v = Q**first_omitted_order_v
std_s = cbar_s * Q_sum_s
std_v = cbar_v * Q_sum_v
if ax is None:
fig, ax = plt.subplots()
norm_s = stats.norm(scale=std_s)
norm_v = stats.norm(scale=std_v)
ax.plot(x, norm_s.pdf(x), c='b', ls='--')
ax.plot(x, norm_v.pdf(x), c='g', ls=':')
norm_tot = stats.norm(scale=np.sqrt(std_s**2 + std_v**2))
ax.plot(x, norm_tot.pdf(x), c='r')
ax.margins(x=0)
ax.xaxis.set_minor_locator(AutoMinorLocator(num_x_minor))
ax.yaxis.set_minor_locator(AutoMinorLocator(num_y_minor))
ax.tick_params(which='both', top=True, right=True)
ax.set_ylim(0, None)
return ax
def plot_scalar_and_vector_student(x, c_s, c_v, Q, first_omitted_order_s, first_omitted_order_v, num_x_minor=5, num_y_minor=5, nu0=0, tau0=1, ax=None, full_sum=True):
"""A convenience function to make the same plot easily"""
from matplotlib.ticker import MultipleLocator, AutoMinorLocator
nu_s, tau_s = compute_nu_and_tau(c_s, nu0=nu0, tau0=tau0)
nu_v, tau_v = compute_nu_and_tau(c_v, nu0=nu0, tau0=tau0)
if full_sum:
Q_sum_s = Q**first_omitted_order_s / np.sqrt(1 - Q**2)
Q_sum_v = Q**first_omitted_order_v / np.sqrt(1 - Q**2)
else:
Q_sum_s = Q**first_omitted_order_s
Q_sum_v = Q**first_omitted_order_v
scale_s = tau_s * Q_sum_s
scale_v = tau_v * Q_sum_v
if ax is None:
fig, ax = plt.subplots()
t_s = stats.t(df=nu_s, scale=scale_s)
t_v = stats.t(df=nu_v, scale=scale_v)
ax.plot(x, t_s.pdf(x), c='b', ls='--')
ax.plot(x, t_v.pdf(x), c='g', ls=':')
# Grid that work well enough for these densities
dense_x = np.linspace(-50, 50, 5000)
post_s = t_s.pdf(dense_x)
post_v = t_v.pdf(dense_x)
conv = np.convolve(post_s, post_v, mode='same')
conv /= np.trapz(conv, dense_x)
conv_interp = np.interp(x, dense_x, conv)
ax.plot(x, conv_interp, c='r')
ax.margins(x=0)
ax.xaxis.set_minor_locator(AutoMinorLocator(num_x_minor))
ax.yaxis.set_minor_locator(AutoMinorLocator(num_y_minor))
ax.tick_params(which='both', top=True, right=True)
ax.set_ylim(0, None)
return ax
```
The Gaussian plots below show the problem with using MAP values when you actually have quite long tails! Point estimates are not always representative of the full distribution.
```
for sum_to_inf in [False, True]:
fig, axes = plt.subplots(3, 2, figsize=(7, 5))
ax_e1e1 = plot_scalar_and_vector_gaussian(
d_e1e1, coefs_e1e1_scalar, coefs_e1e1_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
nu0=nu_0, tau0=tau_0, ax=axes[0, 0], full_sum=sum_to_inf
)
ax_e1e1.yaxis.set_major_locator(MultipleLocator(0.1))
ax_e1e1.set_ylabel(r'pr$_{\gamma_{E1E1}}(\Delta)$')
ax_m1m1 = plot_scalar_and_vector_gaussian(
d_m1m1, coefs_m1m1_scalar, coefs_m1m1_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
num_y_minor=4, nu0=nu_0, tau0=tau_0, ax=axes[0, 1], full_sum=sum_to_inf
)
ax_m1m1.yaxis.set_major_locator(MultipleLocator(0.2))
ax_m1m1.set_ylabel(r'pr$_{\gamma_{M1M1}}(\Delta)$')
ax_e1m2 = plot_scalar_and_vector_gaussian(
d_e1m2, coefs_e1m2_scalar, coefs_e1m2_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
nu0=nu_0, tau0=tau_0, ax=axes[1, 0], full_sum=sum_to_inf
)
ax_e1m2.set_ylabel(r'pr$_{\gamma_{E1M2}}(\Delta)$')
ax_m1e2 = plot_scalar_and_vector_gaussian(
d_m1e2, coefs_m1e2_scalar, coefs_m1e2_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
nu0=nu_0, tau0=tau_0, ax=axes[1, 1], full_sum=sum_to_inf
)
ax_m1e2.set_ylabel(r'pr$_{\gamma_{M1E2}}(\Delta)$')
ax_0 = plot_scalar_and_vector_gaussian(
d_0, coefs_0_scalar, coefs_0_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
nu0=nu_0, tau0=tau_0, ax=axes[2, 0], full_sum=sum_to_inf
)
ax_0.yaxis.set_major_locator(MultipleLocator(0.1))
ax_0.set_ylabel(r'pr$_{\gamma_0}(\Delta)$')
ax_pi = plot_scalar_and_vector_gaussian(
d_pi, coefs_pi_scalar, coefs_pi_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
nu0=nu_0, tau0=tau_0, ax=axes[2, 1], full_sum=sum_to_inf
)
ax_pi.yaxis.set_major_locator(MultipleLocator(0.1))
ax_pi.set_ylabel(r'pr$_{\gamma_{\pi}}(\Delta)$')
if sum_to_inf:
fig.suptitle('Gaussian Distribution, Sum to $Q^\infty$', y=1)
else:
fig.suptitle('Gaussian Distribution, First-Omitted Term Approximation', y=1)
fig.tight_layout()
plt.show()
fig.savefig(f'pol_priors_conjugate_gaussian_sum-inf-{sum_to_inf}')
```
The integrated distributions below look much better.
```
for sum_to_inf in [False, True]:
fig, axes = plt.subplots(3, 2, figsize=(7, 5))
ax_e1e1 = plot_scalar_and_vector_student(
d_e1e1, coefs_e1e1_scalar, coefs_e1e1_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
nu0=nu_0, tau0=tau_0, ax=axes[0, 0], full_sum=sum_to_inf
)
ax_e1e1.yaxis.set_major_locator(MultipleLocator(0.1))
ax_e1e1.set_ylabel(r'pr$_{\gamma_{E1E1}}(\Delta)$')
ax_m1m1 = plot_scalar_and_vector_student(
d_m1m1, coefs_m1m1_scalar, coefs_m1m1_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
num_y_minor=4, nu0=nu_0, tau0=tau_0, ax=axes[0, 1], full_sum=sum_to_inf
)
ax_m1m1.yaxis.set_major_locator(MultipleLocator(0.2))
ax_m1m1.set_ylabel(r'pr$_{\gamma_{M1M1}}(\Delta)$')
ax_e1m2 = plot_scalar_and_vector_student(
d_e1m2, coefs_e1m2_scalar, coefs_e1m2_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
nu0=nu_0, tau0=tau_0, ax=axes[1, 0], full_sum=sum_to_inf
)
ax_e1m2.set_ylabel(r'pr$_{\gamma_{E1M2}}(\Delta)$')
ax_m1e2 = plot_scalar_and_vector_student(
d_m1e2, coefs_m1e2_scalar, coefs_m1e2_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
nu0=nu_0, tau0=tau_0, ax=axes[1, 1], full_sum=sum_to_inf
)
ax_m1e2.set_ylabel(r'pr$_{\gamma_{M1E2}}(\Delta)$')
ax_0 = plot_scalar_and_vector_student(
d_0, coefs_0_scalar, coefs_0_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
nu0=nu_0, tau0=tau_0, ax=axes[2, 0], full_sum=sum_to_inf
)
ax_0.yaxis.set_major_locator(MultipleLocator(0.1))
ax_0.set_ylabel(r'pr$_{\gamma_0}(\Delta)$')
ax_pi = plot_scalar_and_vector_student(
d_pi, coefs_pi_scalar, coefs_pi_vector, delta,
first_omitted_order_s=first_omitted_s, first_omitted_order_v=first_omitted_v,
nu0=nu_0, tau0=tau_0, ax=axes[2, 1], full_sum=sum_to_inf
)
ax_pi.yaxis.set_major_locator(MultipleLocator(0.1))
ax_pi.set_ylabel(r'pr$_{\gamma_{\pi}}(\Delta)$')
if sum_to_inf:
fig.suptitle('Student $t$ Distribution, Sum to $Q^\infty$', y=1)
else:
fig.suptitle('Student $t$ Distribution, First-Omitted Term Approximation', y=1)
fig.tight_layout()
plt.show()
fig.savefig(f'pol_priors_conjugate_student_sum-inf-{sum_to_inf}')
```
| github_jupyter |
```
from IPython.core.display import HTML
HTML('''<style>
.container { width:100% !important; }
</style>
''')
```
# Refutational Completeness of the Cut Rule
This notebook implements a number of procedures that are needed in our proof of the <em style="color:blue">refutational completeness</em> of the cut rule.
The function $\texttt{complement}(l)$ computes the <em style="color:blue">complement</em> of a literal $l$.
If $p$ is a propositional variable, we have the following:
<ol>
<li>$\texttt{complement}(p) = \neg p$,
</li>
<li>$\texttt{complement}(\neg p) = p$.
</li>
</ol>
```
def complement(l):
"Compute the complement of the literal l."
if isinstance(l, str): # l is a propositional variable
return ('¬', l)
else: # l = ('¬', 'p')
return l[1] # l[1] = p
complement('p')
complement(('¬', 'p'))
```
The function $\texttt{extractVariable}(l)$ extracts the propositional variable from the literal $l$.
If $p$ is a propositional variable, we have the following:
<ol>
<li>$\texttt{extractVariable}(p) = p$,
</li>
<li>$\texttt{extractVariable}(\neg p) = p$.
</li>
</ol>
```
def extractVariable(l):
"Extract the variable of the literal l."
if isinstance(l, str): # l is a propositional variable
return l
else: # l = ('¬', 'p')
return l[1]
extractVariable('p')
extractVariable(('¬', 'p'))
```
The function $\texttt{collectsVariables}(M)$ takes a set of clauses $M$ as its input and computes the set of all propositional variables occurring in $M$. The clauses in $M$ are represented as sets of literals.
```
def collectVariables(M):
"Return the set of all variables occurring in M."
return { extractVariable(l) for C in M
for l in C
}
C1 = frozenset({ 'p', 'q', 'r' })
C2 = frozenset({ ('¬', 'p'), ('¬', 'q'), ('¬', 's') })
collectVariables({C1, C2})
```
Given two clauses $C_1$ and $C_2$ that are represented as sets of literals, the function $\texttt{cutRule}(C_1, C_2)$ computes all clauses that can be derived from $C_1$ and $C_2$ using the *cut rule*. In set notation, the cut rule is the following rule of inference:
$$
\frac{\displaystyle \;C_1\cup \{l\} \quad C_2 \cup \bigl\{\overline{\,l\,}\;\bigr\}}{\displaystyle C_1 \cup C_2}
$$
```
def cutRule(C1, C2):
"Return the set of all clauses that can be deduced by the cut rule from c1 and c2."
return { C1 - {l} | C2 - {complement(l) } for l in C1
if complement(l) in C2
}
C1 = frozenset({ 'p', 'q' })
C2 = frozenset({ ('¬', 'p'), ('¬', 'q') })
cutRule(C1, C2)
```
In the expression $\texttt{saturate}(\texttt{Clauses})$ below, $\texttt{Clauses}$ is a set of clauses represented as sets of literals. The call $\texttt{saturate}(\texttt{Clauses})$ computes all clauses that can be derived from clauses in the set $\texttt{Clauses}$ using the cut rule. The function keeps applying the cut rule until either no new clauses can be derived, or the empty clause $\{\}$ is derived. The resulting set of Clauses is <em style="color:blue">saturated</em> in the following sense: If $C_1$ and $C_2$ are clauses from the set $\texttt{Clauses}$ and the clause $D$ can be derived from $C_1$ and $C_2$ via the cut rule, then $D \in \texttt{Clauses}$.
```
def saturate(Clauses):
while True:
Derived = { C for C1 in Clauses
for C2 in Clauses
for C in cutRule(C1, C2)
}
if frozenset() in Derived:
return { frozenset() } # This is the set notation of ⊥.
Derived -= Clauses # remove clauses that were present before
if Derived == set(): # no new clauses have been found
return Clauses
Clauses |= Derived
C1 = frozenset({ 'p', 'q' })
C2 = frozenset({ ('¬', 'p') })
C3 = frozenset({ ('¬', 'p'), ('¬', 'q') })
saturate({C1, C2, C3})
```
The function $\texttt{findValuation}(\texttt{Clauses})$ takes a set of clauses as input. The function tries to compute a variable interpretation that makes all of the clauses true. If this is successful, a set of literals is returned. This set of literals does not contain any complementary literals and therefore corresponds to a variable assignment satisfying all clauses. If $\texttt{Clauses}$ is unsatisfiable, <tt>False</tt> is returned.
```
def findValuation(Clauses):
"Given a set of Clauses, find a propositional valuation satisfying all of these clauses."
Variables = collectVariables(Clauses)
Clauses = saturate(Clauses)
if frozenset() in Clauses: # The set Clauses is inconsistent.
return False
Literals = set()
for p in Variables:
if any(C for C in Clauses
if p in C and C - {p} <= { complement(l) for l in Literals }
):
Literals |= { p }
else:
Literals |= { ('¬', p) }
return Literals
```
The function $\texttt{toString}(S)$ takes a set $S$ as input. The set $S$ is a set of frozensets and the function converts $S$ into a string that looks like a set of sets.
```
C1 = frozenset({ 'r', 'p', 's' })
C2 = frozenset({ 'r', 's' })
C3 = frozenset({ 'p', 'q', 's' })
C4 = frozenset({ ('¬', 'p'), ('¬', 'q') })
C5 = frozenset({ ('¬', 'p'), 's', ('¬', 'r') })
C6 = frozenset({ 'p', ('¬', 'q'), 'r'})
C7 = frozenset({ ('¬', 'r'), ('¬', 's'), 'q' })
C8 = frozenset({ ('¬', 'p'), ('¬', 's')})
C9 = frozenset({ 'p', ('¬', 'r'), ('¬', 'q') })
C0 = frozenset({ ('¬', 'p'), 'r', 'q', ('¬', 's') })
Clauses = { C0, C1, C2, C3, C4, C5, C6, C7, C8, C9 }
findValuation(Clauses)
```
| github_jupyter |
```
import torch
from torch.autograd import Variable
import warnings
from torch import nn
from collections import OrderedDict
import os
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
import data as data
from data.BehavioralDataset import BehavioralDataset
from data.BehavioralHmSamples import BehavioralHmSamples
import scipy
from sklearn.preprocessing import MinMaxScaler
warnings.filterwarnings("ignore")
def load_netG(path, isize, nz, nc, ngf, n_extra_layers):
assert isize % 16 == 0, "isize has to be a multiple of 16"
cngf, tisize = ngf//2, 4
while tisize != isize:
cngf = cngf * 2
tisize = tisize * 2
main = nn.Sequential()
# input is Z, going into a convolution
main.add_module('initial:{0}-{1}:convt'.format(nz, cngf),
nn.ConvTranspose2d(nz, cngf, 4, 1, 0, bias=False))
main.add_module('initial:{0}:batchnorm'.format(cngf),
nn.BatchNorm2d(cngf))
main.add_module('initial:{0}:relu'.format(cngf),
nn.ReLU(True))
csize, cndf = 4, cngf
while csize < isize//2:
main.add_module('pyramid:{0}-{1}:convt'.format(cngf, cngf//2),
nn.ConvTranspose2d(cngf, cngf//2, 4, 2, 1, bias=False))
main.add_module('pyramid:{0}:batchnorm'.format(cngf//2),
nn.BatchNorm2d(cngf//2))
main.add_module('pyramid:{0}:relu'.format(cngf//2),
nn.ReLU(True))
cngf = cngf // 2
csize = csize * 2
# Extra layers
for t in range(n_extra_layers):
main.add_module('extra-layers-{0}:{1}:conv'.format(t, cngf),
nn.Conv2d(cngf, cngf, 3, 1, 1, bias=False))
main.add_module('extra-layers-{0}:{1}:batchnorm'.format(t, cngf),
nn.BatchNorm2d(cngf))
main.add_module('extra-layers-{0}:{1}:relu'.format(t, cngf),
nn.ReLU(True))
main.add_module('final:{0}-{1}:convt'.format(cngf, nc),
nn.ConvTranspose2d(cngf, nc, 4, 2, 1, bias=False))
main.add_module('final:{0}:tanh'.format(nc),
nn.Tanh())
state_dict = torch.load(path, map_location=torch.device('cpu'))
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k[5:] # remove `main.`
new_state_dict[name] = v
main.load_state_dict(new_state_dict, strict=False)
return main
def load_netG_mlp(path, isize, nz, nc, ngf):
main = nn.Sequential(
# Z goes into a linear of size: ngf
nn.Linear(nz, ngf),
nn.ReLU(True),
nn.Linear(ngf, ngf),
nn.ReLU(True),
nn.Linear(ngf, ngf),
nn.ReLU(True),
nn.Linear(ngf, nc * isize * isize),
)
state_dict = torch.load(path, map_location=torch.device('cpu'))
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k[5:] # remove `main.`
new_state_dict[name] = v
main.load_state_dict(new_state_dict, strict=False)
return main
def load_netD(path, isize, nc, ndf, n_extra_layers):
assert isize % 16 == 0, "isize has to be a multiple of 16"
main = nn.Sequential()
# input is nc x isize x isize
main.add_module('initial:{0}-{1}:conv'.format(nc, ndf),
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False))
main.add_module('initial:{0}:relu'.format(ndf),
nn.LeakyReLU(0.2, inplace=True))
csize, cndf = isize / 2, ndf
# Extra layers
for t in range(n_extra_layers):
main.add_module('extra-layers-{0}:{1}:conv'.format(t, cndf),
nn.Conv2d(cndf, cndf, 3, 1, 1, bias=False))
main.add_module('extra-layers-{0}:{1}:batchnorm'.format(t, cndf),
nn.BatchNorm2d(cndf))
main.add_module('extra-layers-{0}:{1}:relu'.format(t, cndf),
nn.LeakyReLU(0.2, inplace=True))
while csize > 4:
in_feat = cndf
out_feat = cndf * 2
main.add_module('pyramid:{0}-{1}:conv'.format(in_feat, out_feat),
nn.Conv2d(in_feat, out_feat, 4, 2, 1, bias=False))
main.add_module('pyramid:{0}:batchnorm'.format(out_feat),
nn.BatchNorm2d(out_feat))
main.add_module('pyramid:{0}:relu'.format(out_feat),
nn.LeakyReLU(0.2, inplace=True))
cndf = cndf * 2
csize = csize / 2
# state size. K x 4 x 4
main.add_module('final:{0}-{1}:conv'.format(cndf, 1),
nn.Conv2d(cndf, 1, 4, 1, 0, bias=False))
state_dict = torch.load(path, map_location=torch.device('cpu'))
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k[5:] # remove `module.`
new_state_dict[name] = v
main.load_state_dict(new_state_dict, strict=False)
return main
def load_netD_mlp(path, isize, nc, ndf):
main = nn.Sequential(
# Z goes into a linear of size: ndf
nn.Linear(nc * isize * isize, ndf),
nn.ReLU(True),
nn.Linear(ndf, ndf),
nn.ReLU(True),
nn.Linear(ndf, ndf),
nn.ReLU(True),
nn.Linear(ndf, 1),
)
state_dict = torch.load(path, map_location=torch.device('cpu'))
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k[5:] # remove `module.`
new_state_dict[name] = v
main.load_state_dict(new_state_dict, strict=False)
return main
def reshape_mlp_input(input_sample):
return input_sample.view(input_sample.size(0),
input_sample.size(1) * input_sample.size(2) * input_sample.size(3))
def sample_wrapper(samples):
input = torch.FloatTensor(samples.shape[0], 1, 32, 32)
input.resize_as_(samples).copy_(samples)
return Variable(input)
# load in all needed data
# load real samples
num_models = 10
real_samples_list = []
for i in range(num_models):
dataset = BehavioralDataset(isCnnData=True, isScoring=True, auto_number=i, niter=50)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=3, shuffle=True, num_workers=1)
data_iter = iter(dataloader)
data = data_iter.next()
next_samples, _ = data
real_samples_list.append(next_samples)
# load fake samples
h_models_samples_list = []
for i in range(1,6):
dataset = BehavioralHmSamples(modelNum=i, isCnnData=True, isScoring=True)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=1000, shuffle=True, num_workers=1)
data_iter = iter(dataloader)
data = data_iter.next()
next_samples, _ = data
h_models_samples_list.append(next_samples)
# read in discriminators
num_nets = 10
dataset = 'behavioral'
netD_list = [load_netD('./loss_curves/netD_{0}_50k_{1}_automated.pth'.format(dataset, i), isize=32, nc=1, ndf=64, n_extra_layers=0) for i in range(num_nets)]
# score hierarchical models
# old way of calculating scores
num_h_models = 5
num_real_samples = real_samples_list[0].shape[0]
scores = np.zeros((num_h_models, num_nets))
for j, netD in enumerate(netD_list):
# score real samples
real_samples_scores = netD(sample_wrapper(real_samples)).data.numpy()
for i, fake_samples in enumerate(fake_samples_list):
fake_samples_scores = netD(sample_wrapper(fake_samples)).data.numpy()
# see how many fake samples were scored as more real than each real samples
num_right = sum([np.sum(fake_samples_scores < real_samples_scores[k]) for k in range(num_real_samples)])
# print('index: ({0}, {1})'.format(i,j))
# print(num_right)
# print(np.sum(fake_samples_scores < real_samples_scores[0]))
# print(np.sum(fake_samples_scores < real_samples_scores[1]))
# print(np.sum(fake_samples_scores < real_samples_scores[2]))
# print(num_right / (1000 * real_samples_scores.shape[0]))
# print('-----------------------')
scores[i,j] = num_right / (1000 * num_real_samples)
# calculate wins array
# wins indices:
# i is the index for the real triple and net number
# j corresponds to the fake sample index in a given fake sample vector
# k corresponds to the hierarchical model
num_h_models = 5
num_real_samples = len(real_samples_list)
num_real_samples_per_set = real_samples_list[0].shape[0]
num_fake_samples = h_models_samples_list[0].shape[0]
array_list = [np.zeros((num_real_samples, num_fake_samples)) for i in range(num_h_models)]
wins = np.dstack(array_list)
for k, h_model_samples in enumerate(h_models_samples_list):
for i, real_samples in enumerate(real_samples_list):
netD = netD_list[i]
real_samples_scores = netD(sample_wrapper(real_samples)).data.numpy()
fake_samples_scores = netD(sample_wrapper(h_model_samples)).data.numpy()
for j in range(num_fake_samples):
wins_for_sample = 0
for m in range(num_real_samples_per_set):
if fake_samples_scores[j] < real_samples_scores[m]:
wins_for_sample += 1
wins[i,j,k] = wins_for_sample
np.save('./data/behavioral_wins.npy', wins)
wins = np.load('./data/behavioral_wins.npy')
import json
pd.Series(wins.tolist()).to_json('./data/behavioral_wins.json', orient='records')
with open('./data/behavioral_wins2.json', 'w+') as f:
f.write(json.dumps(wins.tolist()))
wins[0,0:20,0]
wins[1,0:20,1]
wins[0:20,0,0]
import codecs, json
file_path = "./data/behavioral_wins3.json" ## your path variable
json.dump(wins.tolist(), codecs.open(file_path, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4)
```
# Visualizations of Wins
```
wins.shape
means_rs_by_hm = np.mean(wins/3, axis=1)
means_rs_by_hm
model_num = []
mean_correct_for_sample = []
for j in range(means_rs_by_hm.shape[1]):
for i in range(means_rs_by_hm.shape[0]):
model_num.append(j+1)
mean_correct_for_sample.append(means_rs_by_hm[i,j])
correct_df = pd.DataFrame(list(zip(model_num, mean_correct_for_sample)), columns=['Hierarchical Model', 'Average Win Percentage'])
import seaborn as sns
sns.set()
ax = sns.scatterplot(x="Hierarchical Model", y="Average Win Percentage", data=correct_df)
ax.set_title('Average Win Percentage by Hierarchical Model')
ax.set_xticklabels(np.linspace(0.5, 5, 10))
# code to modify xticks taken from here:
# https://stackoverflow.com/questions/38947115/how-to-decrease-the-density-of-x-ticks-in-seaborn
for ind, label in enumerate(ax.get_xticklabels()):
if (ind + 1) % 2 == 0: # every 10th label is kept
label.set_visible(True)
else:
label.set_visible(False)
np.median(means_rs_by_hm, axis=0)
np.mean(means_rs_by_hm, axis=0)
np.var(means_rs_by_hm, axis=0)
scipy.stats.sem(means_rs_by_hm, axis=0)
```
# Analysis of Gammas from R
$x_{i,j,k}:=$# of wins for fake sample $j$ from model $k$ over real sample set $i$.
\begin{align*}
x_{i,j,k}&\sim Poisson(\theta_{i,k})\\
\theta_{i,k}&=exp(\mu_{i}+\gamma_{k})
\end{align*}
```
gamma = pd.read_csv('./data/behavioral_gamma.csv').to_numpy()
mu = pd.read_csv('./data/behavioral_mu.csv').to_numpy()
gamma
mu
index_to_model = {i:'Model {0}'.format(i+1) for i in range(num_h_models)}
places = {i:{j+1:0 for j in range(num_h_models)} for i in index_to_model.values()}
for i in range(gamma.shape[0]):
ranked_indices = np.argsort(gamma[i,:])[::-1]
placement = 1
for next_best in ranked_indices:
places[index_to_model[next_best]][placement]+=1
placement += 1
places
model_num = []
gamma_list = []
for j in range(gamma.shape[1]):
for i in range(gamma.shape[0]):
model_num.append(j+1)
gamma_list.append(gamma[i,j])
analysis_df = pd.DataFrame(list(zip(model_num, gamma_list)), columns=['Model Number', 'Gamma'])
ax = sns.scatterplot(x="Model Number", y="Gamma", data=analysis_df)
ax.set_title('Gamma vs Model Number')
np.mean(gamma, axis=0)
np.median(gamma, axis=0)
np.var(gamma, axis=0)
scipy.stats.sem(gamma, axis=0)
means = list(np.mean(scores, axis=1))
samp_se_list = list(scipy.stats.sem(scores, axis=1))
var_list = list(np.var(scores, axis=1))
```
Where $\hat{p}$ is the probability of a dog getting shocked.
$X_{1it}$ and $X_{2it}$ are the number of times a dog has respectively been shocked and avoided being shocked in previous trials.
Model 1
\begin{align*}
\hat{p}=\sigma(\beta_{1}+\beta_{2}X_{1it}+\beta_{3}X_{2it})
\end{align*}
Model 2
\begin{align*}
\hat{p}=exp(\beta_{1}X_{1it}+\beta_{2}X_{2it})
\end{align*}
Model 3
\begin{align*}
\hat{p}&=\sigma(\frac{\alpha}{t}+\gamma)&\text{$t$ is the trial number}
\end{align*}
Model 4 is the "switch."
Model 5
\begin{align*}
\hat{p}&=\frac{\alpha}{t}&\text{$t$ is the trial number}
\end{align*}
```
for mean, var, se, i in zip(means, var_list, samp_se_list, range(1,len(means)+1)):
print('Model\t {0} \nMean\t {1}\nSE\t {2}\nVar\t {3}'.format(i, mean, se, var))
print('------------------')
```
# Scaled Scores
```
scaled_scores = scores.copy()
scaler = MinMaxScaler()
scaled_scores = scaler.fit_transform(scaled_scores)
scaled_scores_df = pd.DataFrame(scaled_scores)
scaled_scores_df.to_csv('./data/behavioral_model_scaled_scores.csv', index=False, float_format='%.3f')
scaled_means = list(np.mean(scaled_scores, axis=1))
scaled_samp_se_list = list(scipy.stats.sem(scaled_scores, axis=1))
scaled_var_list = list(np.var(scaled_scores, axis=1))
for mean, var, se, i in zip(scaled_means, scaled_var_list, scaled_samp_se_list, range(1,len(scaled_means)+1)):
print('Model\t {0} \nMean\t {1}\nSE\t {2}\nVar\t {3}'.format(i, mean, se, var))
print('------------------')
a = np.zeros((5,1000))
b = np.zeros((5,1000))
np.dstack((a,b)).shape
fake_samples_list[0].shape[0]
num_real_samples
np.sum(a, axis=1).shape
np.reshape(a, (a.shape[1], a.shape[0])).shape
type(a)
a.shape[0]
```
| github_jupyter |
## Subsurface scattering
This example shows how to:
- setup a glass-like material for subsurface scattering
- enable light emmision in the volume

Glass-like material shader in PlotOptiX can simulate light propagation in a volume with a diffuse scattering. The free path length of the light is set with ``radiation_length``, and the diffusion color is ``subsurface_color``. You can add some color to the surface with ``surface_albedo`` or enable a light emission in the volume to obtain the finest quality materials.
Make some data for a simple scene first:
```
import numpy as np
rx = (-20, 20)
rz = (-20, 20)
n = 100
x = np.linspace(rx[0], rx[1], n)
z = np.linspace(rz[0], rz[1], n)
X, Z = np.meshgrid(x, z)
# positions of blocks
data = np.stack((X.flatten(), np.full(n*n, -2), Z.flatten())).T
# XZ sizes
size_u = 0.96 * (rx[1] - rx[0]) / (n - 1)
size_w = 0.96 * (rz[1] - rz[0]) / (n - 1)
```
Setup the raytracer using Tkinter GUI as the output target. Note, it is important to select the **background mode** which supports scattering in volumes: ``AmbientAndVolume``, ``TextureFixed``, or ``TextureEnvironment``.
```
from plotoptix import TkOptiX
optix = TkOptiX()
optix.set_param(min_accumulation_step=4, # set more accumulation frames to get rid of the noise
max_accumulation_frames=512,
light_shading="Hard") # use ligth shading best for caustics
optix.set_uint("path_seg_range", 15, 40) # more path segments to improve simulation in the volume
optix.set_background_mode("AmbientAndVolume") # need one of modes supporting scattering in volumes
```
Only *diffuse* material is available by default. Other materials need to be configured before using.
```
from plotoptix.materials import m_clear_glass, m_matt_glass
import copy
m_clear_glass_2 = copy.deepcopy(m_clear_glass)
m_clear_glass_3 = copy.deepcopy(m_clear_glass)
m_clear_glass_4 = copy.deepcopy(m_clear_glass)
m_clear_glass_5 = copy.deepcopy(m_clear_glass)
m_matt_glass_2 = copy.deepcopy(m_matt_glass)
m_light_1 = copy.deepcopy(m_clear_glass)
m_light_2 = copy.deepcopy(m_clear_glass)
optix.setup_material("glass", m_clear_glass) # clear glass
optix.setup_material("glass_2", m_clear_glass_2) # diffuse color
optix.setup_material("glass_3", m_clear_glass_3) # diffuse and albedo color
optix.setup_material("glass_4", m_clear_glass_4) # diffuse slight
optix.setup_material("glass_5", m_clear_glass_5) # diffuse slight, textured
optix.setup_material("matt_glass", m_matt_glass) # matt surface
optix.setup_material("matt_glass_2", m_matt_glass_2) # matt surface, diffuse volume
optix.setup_material("light_1", m_light_1) # emissive
optix.setup_material("light_2", m_light_2) # emissive, textured
```
Add objects to the scene.
```
optix.set_data("blocks", pos=data,
c=0.85 + 0.1*np.random.randint(3, size=data.shape[0]),
u=[size_u, 0, 0], v=[0, -1, 0], w=[0, 0, size_w],
geom="Parallelepipeds")
optix.set_data("c_clear", pos=[-3.5, 0, -5], u=[0.25, 0, 0], v=[0, 4, 0], w=[0, 0, 4], c=10, mat="glass", geom="Parallelepipeds")
optix.rotate_geometry("c_clear", [0, 0, -np.pi/4])
optix.set_data("c_diffuse", pos=[-0.5, 0, -5], u=[0.25, 0, 0], v=[0, 4, 0], w=[0, 0, 4], c=10, mat="glass_2", geom="Parallelepipeds")
optix.rotate_geometry("c_diffuse", [0, 0, -np.pi/4])
optix.set_data("c_light", pos=[2.5, 0, -5], u=[0.25, 0, 0], v=[0, 4, 0], w=[0, 0, 4], c=10, mat="light_1", geom="Parallelepipeds")
optix.rotate_geometry("c_light", [0, 0, -np.pi/4])
optix.set_data("s_light_2", pos=[-3.1, 1.5, 1], r=1.5, c=10, mat="light_2", geom="ParticleSetTextured")
optix.set_data("s_diffuse", pos=[0, 1.5, 1], r=1.5, c=10, mat="glass_2")
optix.set_data("s_diffuse_colored", pos=[3.1, 1.5, 1], r=1.5, c=10, mat="glass_3")
optix.set_data("s_matt", pos=[-3.1, 1.5, 4.1], r=1.5, c=10, mat="matt_glass")
optix.set_data("s_diffuse_less", pos=[0, 1.5, 4.1], r=1.5, c=10, mat="glass_4")
optix.set_data("s_diffuse_tex", pos=[3.1, 1.5, 4.1], r=1.5, c=10, mat="glass_5", geom="ParticleSetTextured")
optix.set_data("s_matt_colored", pos=[-3.1, 1.5, 7.2], r=1.5, c=10, mat="matt_glass_2")
optix.set_data("s_light_1", pos=[0, 1.5, 7.2], r=1.5, c=10, mat="light_1")
optix.set_data("s_clear", pos=[3.1, 1.5, 7.2], r=1.5, c=10, mat="glass")
```
Setup a good point of view, set background and lights.
```
optix.setup_camera("cam1", cam_type="DoF",
eye=[0, 15, 1.55], target=[0, 0, 1.55], up=[1, 0, 0],
aperture_radius=0.01, fov=45, focal_scale=0.8)
optix.setup_light("light1", pos=[5, 8, 7], color=[10, 10, 10], radius=1.9)
optix.setup_light("light2", pos=[-6, 8, -5], color=[10, 11, 12], radius=1.3)
exposure = 1.1; gamma = 2.2
optix.set_float("tonemap_exposure", exposure)
optix.set_float("tonemap_gamma", gamma)
optix.set_float("denoiser_blend", 0.2)
optix.add_postproc("Denoiser") # apply AI denoiser, or
#optix.add_postproc("Gamma") # use gamma correction
optix.set_background(0)
optix.set_ambient(0)
```
Open the GUI.
```
optix.start()
```
Modify materials:
```
m_clear_glass_2["VarFloat"]["radiation_length"] = 0.1 # short w.r.t. the object size
m_clear_glass_2["VarFloat3"]["subsurface_color"] = [ 0.7, 0.85, 1 ]
optix.update_material("glass_2", m_clear_glass_2)
m_clear_glass_3["VarFloat"]["radiation_length"] = 0.1
m_clear_glass_3["VarFloat3"]["subsurface_color"] = [ 0.7, 0.85, 1 ]
m_clear_glass_3["VarFloat3"]["surface_albedo"] = [ 0.6, 0.8, 1 ] # add some color to reflections
optix.update_material("glass_3", m_clear_glass_3)
m_clear_glass_4["VarFloat"]["radiation_length"] = 1.0 # comparable to the object size
m_clear_glass_4["VarFloat3"]["subsurface_color"] = [ 1, 0.85, 0.7 ]
optix.update_material("glass_4", m_clear_glass_4)
optix.load_texture("rainbow", r"data/rainbow.jpg")
m_clear_glass_5["VarFloat"]["radiation_length"] = 1.0
m_clear_glass_5["VarFloat3"]["subsurface_color"] = [ 1, 0.85, 0.7 ]
m_clear_glass_5["VarFloat3"]["surface_albedo"] = [ 0.9, 1, 1 ]
m_clear_glass_5["ColorTextures"] = [ "rainbow" ]
optix.update_material("glass_5", m_clear_glass_5)
m_matt_glass_2["VarFloat"]["radiation_length"] = 1.0
m_matt_glass_2["VarFloat3"]["subsurface_color"] = [ 1, 0.8, 1 ]
optix.update_material("matt_glass_2", m_matt_glass_2)
m_light_1["VarFloat"]["radiation_length"] = 1.5
m_light_1["VarFloat"]["light_emission"] = 0.02 # add light on each scattering
m_light_1["VarFloat3"]["subsurface_color"] = [ 0.9, 1, 1 ] # diffuse and emission base color
optix.update_material("light_1", m_light_1)
optix.load_texture("wood", r"data/wood.jpg")
m_light_2["VarFloat"]["radiation_length"] = 1.5
m_light_2["VarFloat"]["light_emission"] = 0.02
m_light_2["VarFloat3"]["subsurface_color"] = [ 1, 1, 1 ] # leave the (default) neutral color
m_light_2["ColorTextures"] = [ "wood" ]
optix.update_material("light_2", m_light_2, refresh=True)
```
Close GUI window, release resources.
```
optix.close()
```
| github_jupyter |
# Lab: TfTransform #
**Learning Objectives**
1. Preprocess data and engineer new features using TfTransform
1. Create and deploy Apache Beam pipeline
1. Use processed data to train taxifare model locally then serve a prediction
## Introduction
While Pandas is fine for experimenting, for operationalization of your workflow it is better to do preprocessing in Apache Beam. This will also help if you need to preprocess data in flight, since Apache Beam allows for streaming. In this lab we will pull data from BigQuery then use Apache Beam TfTransform to process the data.
Only specific combinations of TensorFlow/Beam are supported by tf.transform so make sure to get a combo that works. In this lab we will be using:
* TFT 0.24.0
* TF 2.3.0
* Apache Beam [GCP] 2.24.0
Each learning objective will correspond to a __#TODO__ in the [student lab notebook](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/deepdive2/feature_engineering/labs/5_tftransform_taxifare.ipynb) -- try to complete that notebook first before reviewing this solution notebook.
```
# Run the chown command to change the ownership
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Install the necessary dependencies
!pip install tensorflow==2.3.0 tensorflow-transform==0.24.0 apache-beam[gcp]==2.24.0
```
**NOTE**: You may ignore specific incompatibility errors and warnings. These components and issues do not impact your ability to complete the lab.
Download .whl file for tensorflow-transform. We will pass this file to Beam Pipeline Options so it is installed on the DataFlow workers
```
!pip download tensorflow-transform==0.24.0 --no-deps
```
<b>Restart the kernel</b> (click on the reload button above).
```
%%bash
# Output installed packages in requirements format.
pip freeze | grep -e 'flow\|beam'
# Import data processing libraries
import tensorflow as tf
import tensorflow_transform as tft
# Python shutil module enables us to operate with file objects easily and without diving into file objects a lot.
import shutil
# Show the currently installed version of TensorFlow
print(tf.__version__)
# change these to try this notebook out
BUCKET = 'cloud-example-labs'
PROJECT = 'project-id'
REGION = 'us-central1'
# The OS module in python provides functions for interacting with the operating system.
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
%%bash
# gcloud config set - set a Cloud SDK property
gcloud config set project $PROJECT
gcloud config set compute/region $REGION
%%bash
# Create bucket
if ! gsutil ls | grep -q gs://${BUCKET}/; then
gsutil mb -l ${REGION} gs://${BUCKET}
fi
```
## Input source: BigQuery
Get data from BigQuery but defer the majority of filtering etc. to Beam.
Note that the dayofweek column is now strings.
```
# Import Google BigQuery API client library
from google.cloud import bigquery
def create_query(phase, EVERY_N):
"""Creates a query with the proper splits.
Args:
phase: int, 1=train, 2=valid.
EVERY_N: int, take an example EVERY_N rows.
Returns:
Query string with the proper splits.
"""
base_query = """
WITH daynames AS
(SELECT ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'] AS daysofweek)
SELECT
(tolls_amount + fare_amount) AS fare_amount,
daysofweek[ORDINAL(EXTRACT(DAYOFWEEK FROM pickup_datetime))] AS dayofweek,
EXTRACT(HOUR FROM pickup_datetime) AS hourofday,
pickup_longitude AS pickuplon,
pickup_latitude AS pickuplat,
dropoff_longitude AS dropofflon,
dropoff_latitude AS dropofflat,
passenger_count AS passengers,
'notneeded' AS key
FROM
`nyc-tlc.yellow.trips`, daynames
WHERE
trip_distance > 0 AND fare_amount > 0
"""
if EVERY_N is None:
if phase < 2:
# training
query = """{0} AND ABS(MOD(FARM_FINGERPRINT(CAST
(pickup_datetime AS STRING), 4)) < 2""".format(base_query)
else:
query = """{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(
pickup_datetime AS STRING), 4)) = {1}""".format(base_query, phase)
else:
query = """{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(
pickup_datetime AS STRING)), {1})) = {2}""".format(
base_query, EVERY_N, phase)
return query
query = create_query(2, 100000)
```
Let's pull this query down into a Pandas DataFrame and take a look at some of the statistics.
```
df_valid = bigquery.Client().query(query).to_dataframe()
# `head()` function is used to get the first n rows of dataframe
display(df_valid.head())
# `describe()` is use to get the statistical summary of the DataFrame
df_valid.describe()
```
## Create ML dataset using tf.transform and Dataflow
Let's use Cloud Dataflow to read in the BigQuery data and write it out as TFRecord files. Along the way, let's use tf.transform to do scaling and transforming. Using tf.transform allows us to save the metadata to ensure that the appropriate transformations get carried out during prediction as well.
`transformed_data` is type `pcollection`.
```
# Import a module named `datetime` to work with dates as date objects.
import datetime
# Import data processing libraries and modules
import tensorflow as tf
import apache_beam as beam
import tensorflow_transform as tft
import tensorflow_metadata as tfmd
from tensorflow_transform.beam import impl as beam_impl
def is_valid(inputs):
"""Check to make sure the inputs are valid.
Args:
inputs: dict, dictionary of TableRow data from BigQuery.
Returns:
True if the inputs are valid and False if they are not.
"""
try:
pickup_longitude = inputs['pickuplon']
dropoff_longitude = inputs['dropofflon']
pickup_latitude = inputs['pickuplat']
dropoff_latitude = inputs['dropofflat']
hourofday = inputs['hourofday']
dayofweek = inputs['dayofweek']
passenger_count = inputs['passengers']
fare_amount = inputs['fare_amount']
return fare_amount >= 2.5 and pickup_longitude > -78 \
and pickup_longitude < -70 and dropoff_longitude > -78 \
and dropoff_longitude < -70 and pickup_latitude > 37 \
and pickup_latitude < 45 and dropoff_latitude > 37 \
and dropoff_latitude < 45 and passenger_count > 0
except:
return False
def preprocess_tft(inputs):
"""Preprocess the features and add engineered features with tf transform.
Args:
dict, dictionary of TableRow data from BigQuery.
Returns:
Dictionary of preprocessed data after scaling and feature engineering.
"""
import datetime
print(inputs)
result = {}
result['fare_amount'] = tf.identity(inputs['fare_amount'])
# build a vocabulary
# TODO 1
result['dayofweek'] = tft.string_to_int(inputs['dayofweek'])
result['hourofday'] = tf.identity(inputs['hourofday']) # pass through
# scaling numeric values
# TODO 2
result['pickuplon'] = (tft.scale_to_0_1(inputs['pickuplon']))
result['pickuplat'] = (tft.scale_to_0_1(inputs['pickuplat']))
result['dropofflon'] = (tft.scale_to_0_1(inputs['dropofflon']))
result['dropofflat'] = (tft.scale_to_0_1(inputs['dropofflat']))
result['passengers'] = tf.cast(inputs['passengers'], tf.float32) # a cast
# arbitrary TF func
result['key'] = tf.as_string(tf.ones_like(inputs['passengers']))
# engineered features
latdiff = inputs['pickuplat'] - inputs['dropofflat']
londiff = inputs['pickuplon'] - inputs['dropofflon']
# Scale our engineered features latdiff and londiff between 0 and 1
# TODO 3
result['latdiff'] = tft.scale_to_0_1(latdiff)
result['londiff'] = tft.scale_to_0_1(londiff)
dist = tf.sqrt(latdiff * latdiff + londiff * londiff)
result['euclidean'] = tft.scale_to_0_1(dist)
return result
def preprocess(in_test_mode):
"""Sets up preprocess pipeline.
Args:
in_test_mode: bool, False to launch DataFlow job, True to run locally.
"""
import os
import os.path
import tempfile
from apache_beam.io import tfrecordio
from tensorflow_transform.coders import example_proto_coder
from tensorflow_transform.tf_metadata import dataset_metadata
from tensorflow_transform.tf_metadata import dataset_schema
from tensorflow_transform.beam import tft_beam_io
from tensorflow_transform.beam.tft_beam_io import transform_fn_io
job_name = 'preprocess-taxi-features' + '-'
job_name += datetime.datetime.now().strftime('%y%m%d-%H%M%S')
if in_test_mode:
import shutil
print('Launching local job ... hang on')
OUTPUT_DIR = './preproc_tft'
shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
EVERY_N = 100000
else:
print('Launching Dataflow job {} ... hang on'.format(job_name))
OUTPUT_DIR = 'gs://{0}/taxifare/preproc_tft/'.format(BUCKET)
import subprocess
subprocess.call('gsutil rm -r {}'.format(OUTPUT_DIR).split())
EVERY_N = 10000
options = {
'staging_location': os.path.join(OUTPUT_DIR, 'tmp', 'staging'),
'temp_location': os.path.join(OUTPUT_DIR, 'tmp'),
'job_name': job_name,
'project': PROJECT,
'num_workers': 1,
'max_num_workers': 1,
'teardown_policy': 'TEARDOWN_ALWAYS',
'no_save_main_session': True,
'direct_num_workers': 1,
'extra_packages': ['tensorflow_transform-0.24.0-py3-none-any.whl']
}
opts = beam.pipeline.PipelineOptions(flags=[], **options)
if in_test_mode:
RUNNER = 'DirectRunner'
else:
RUNNER = 'DataflowRunner'
# Set up raw data metadata
raw_data_schema = {
colname: dataset_schema.ColumnSchema(
tf.string, [], dataset_schema.FixedColumnRepresentation())
for colname in 'dayofweek,key'.split(',')
}
raw_data_schema.update({
colname: dataset_schema.ColumnSchema(
tf.float32, [], dataset_schema.FixedColumnRepresentation())
for colname in
'fare_amount,pickuplon,pickuplat,dropofflon,dropofflat'.split(',')
})
raw_data_schema.update({
colname: dataset_schema.ColumnSchema(
tf.int64, [], dataset_schema.FixedColumnRepresentation())
for colname in 'hourofday,passengers'.split(',')
})
raw_data_metadata = dataset_metadata.DatasetMetadata(
dataset_schema.Schema(raw_data_schema))
# Run Beam
with beam.Pipeline(RUNNER, options=opts) as p:
with beam_impl.Context(temp_dir=os.path.join(OUTPUT_DIR, 'tmp')):
# Save the raw data metadata
(raw_data_metadata |
'WriteInputMetadata' >> tft_beam_io.WriteMetadata(
os.path.join(
OUTPUT_DIR, 'metadata/rawdata_metadata'), pipeline=p))
# Read training data from bigquery and filter rows
raw_data = (p | 'train_read' >> beam.io.Read(
beam.io.BigQuerySource(
query=create_query(1, EVERY_N),
use_standard_sql=True)) |
'train_filter' >> beam.Filter(is_valid))
raw_dataset = (raw_data, raw_data_metadata)
# Analyze and transform training data
# TODO 4
transformed_dataset, transform_fn = (
raw_dataset | beam_impl.AnalyzeAndTransformDataset(
preprocess_tft))
transformed_data, transformed_metadata = transformed_dataset
# Save transformed train data to disk in efficient tfrecord format
transformed_data | 'WriteTrainData' >> tfrecordio.WriteToTFRecord(
os.path.join(OUTPUT_DIR, 'train'), file_name_suffix='.gz',
coder=example_proto_coder.ExampleProtoCoder(
transformed_metadata.schema))
# Read eval data from bigquery and filter rows
# TODO 5
raw_test_data = (p | 'eval_read' >> beam.io.Read(
beam.io.BigQuerySource(
query=create_query(2, EVERY_N),
use_standard_sql=True)) | 'eval_filter' >> beam.Filter(
is_valid))
raw_test_dataset = (raw_test_data, raw_data_metadata)
# Transform eval data
transformed_test_dataset = (
(raw_test_dataset, transform_fn) | beam_impl.TransformDataset()
)
transformed_test_data, _ = transformed_test_dataset
# Save transformed train data to disk in efficient tfrecord format
(transformed_test_data |
'WriteTestData' >> tfrecordio.WriteToTFRecord(
os.path.join(OUTPUT_DIR, 'eval'), file_name_suffix='.gz',
coder=example_proto_coder.ExampleProtoCoder(
transformed_metadata.schema)))
# Save transformation function to disk for use at serving time
(transform_fn |
'WriteTransformFn' >> transform_fn_io.WriteTransformFn(
os.path.join(OUTPUT_DIR, 'metadata')))
# Change to True to run locally
preprocess(in_test_mode=False)
```
This will take __10-15 minutes__. You cannot go on in this lab until your DataFlow job has successfully completed.
**Note**: The above command may fail with an error **`Workflow failed. Causes: There was a problem refreshing your credentials`**. In that case, `re-run` the command again.
```
%%bash
# ls preproc_tft
# `ls` command show the full list or content of your directory
gsutil ls gs://${BUCKET}/taxifare/preproc_tft/
```
## Train off preprocessed data ##
Now that we have our data ready and verified it is in the correct location we can train our taxifare model locally.
```
%%bash
# Train our taxifare model locally
rm -r ./taxi_trained
export PYTHONPATH=${PYTHONPATH}:$PWD
python3 -m tft_trainer.task \
--train_data_path="gs://${BUCKET}/taxifare/preproc_tft/train*" \
--eval_data_path="gs://${BUCKET}/taxifare/preproc_tft/eval*" \
--output_dir=./taxi_trained \
# `ls` command show the full list or content of your directory
!ls $PWD/taxi_trained/export/exporter
```
Now let's create fake data in JSON format and use it to serve a prediction with gcloud ai-platform local predict
```
%%writefile /tmp/test.json
{"dayofweek":0, "hourofday":17, "pickuplon": -73.885262, "pickuplat": 40.773008, "dropofflon": -73.987232, "dropofflat": 40.732403, "passengers": 2.0}
%%bash
sudo find "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/command_lib/ml_engine" -name '*.pyc' -delete
%%bash
# Serve a prediction with gcloud ai-platform local predict
model_dir=$(ls $PWD/taxi_trained/export/exporter/)
gcloud ai-platform local predict \
--model-dir=./taxi_trained/export/exporter/${model_dir} \
--json-instances=/tmp/test.json
```
Copyright 2020 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
| github_jupyter |
<font size="+5">#02 | Master the Python Syntax</font>
<div class="alert alert-warning">
<ul>
<li>
Follow the Author on Twitter: <a href="https://twitter.com/jsulopz"><b>@jsulopz</b></a>
</li>
<li>
<b>Python</b> + <b>Data Science</b> Tutorials in ↓
<ul>
<li>
<a href="https://www.youtube.com/c/PythonResolver?sub_confirmation=1"
>YouTube</a
>
</li>
<li>
<a href="https://blog.pythonresolver.com/">Blog</a>
</li>
</ul>
</li>
</ul>
</div>
<a href="https://colab.research.google.com/github/jsulopz/resolving-python/blob/main/02_Master%20the%20Python%20Syntax/02_syntax_session_solution.ipynb">
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a>
# The starting *thing*
- [ ] How can we play around with the `DataFrame`?
# The use of `variables` - `instances`
- A `variable` is an `instance` of `Class`
- We'll refer to the *created variable* as an **instance**
## The `string` object-instance
### Using the `object` Directly
### Using the `instance`
<div class="alert alert-info">
<b>Tip</b>
<br>❌ You don't need to create variables if you won't use the data later
<br>✅ Create a variable if you think you will repeat the code to reproduce the same data
</div>
## Practical Recommendation
### Using the `object` Directly
### Using the `instance`
- [ ] Which way do you prefer?
## The `DataFrame` object
```
pd.DataFrame(data=[[1.80, 51], [2.0, 52]],
index=['joseph', 'mary'],
columns=['height', 'weight'])#!
```
### Using the `object` Directly
### Using the `instance`
```
df = pd.DataFrame(data=[[1.80, 51], [2.0, 52]], #!
index=['joseph', 'mary'],
columns=['height', 'weight'])
```
## Exploiting the `DataFrame` instance
- [ ] Can you do the `.average()` of the `DataFrame`?
- [ ] Why?
- [ ] Is there a way to know which `.functions()` we can use with `instances`?
<div class="alert alert-info">
<b>Tip</b>
<br>Use the <b>autocompletion</b> tool <code>df. + [tab]</code>
</div>
# Working with the `instance`
- Objects are **data structures** that store information
- [ ] Which [**syntax**](https://github.com/jsulopz/00-python-resolver-discipline/blob/main/01_Code%20of%20Discipline/00_The%20Elements%20of%20Programming.md) do you write to exploit the `object`?
```
df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/mpg.csv', index_col='name').drop(columns='origin') #!
```
- [ ] Can you compute the *sum*?
- [ ] Can you compute the *average*?
- [ ] Can you compute the *correlation*?
- [ ] Can you create a *histogram*?
- [ ] Can you use the brackets `[]` for a `function[]`?
- [ ] Why?
- [ ] Is there a rule to put `[]` vs `()`?
<div class="alert alert-success">
<b>Python Fundamentals</b>
<ul>
<li><code>[]</code> are used to access already created data within the <code>instance[]</code>
<li><code>()</code> are used to call a <code>function()</code> and execute several lines of code <i>behind the curtains</i>
</ul>
</div>
# Brackets `[]` vs Parenthesis `()`
## Accessing the `instance[access]`
<div class="alert alert-info">
<b>Tip</b>
<br>❌ You can't use <code>()</code> to access a created element within the <code>instance</code>
</div>
## Execute the `instance.function()`
<div class="alert alert-info">
<b>Tip</b>
<br>❌ You can't use <code>[]</code> to <b>call* the function</b>
<br>✅ You use the <code>()</code>
<br>*Execute the instructions of code within the computer
</div>
`~/miniforge3/lib/python3.9/site-packages/pandas/core/frame.py`
```
df.head(5) #!
```
- [ ] Can you access the column `mpg` with the position number?
- [ ] Why?
<div class="alert alert-success">
<b>Python Fundamentals</b>
<ul>
<li>❌ The position of the column is not a key of the <code>DataFrame</code></li>
<li>✅ The <code>keys</code> of the <code>DataFrame</code> are name of the columns</li>
</ul>
</div>
<div class="alert alert-info">
<b>Tip</b>
<br>Use the error as feedback to get the result you want
</div>
```
df.hist(column='horsepowerr') #!
```
## Different ways to *Access* an instance
### `list[index]`
### `dict[key]`
<div class="alert alert-success">
<b>Python Fundamentals</b>
<ul>
<li>The <code>list</code> automatically generates a key corresponding to the position of the element</li>
<li>The <code>dictionary</code> needs the <code>{key:value}</code></li>
</ul>
</div>
### `DataFrame[key]`
- [ ] But... there must be a way of accessing the `DataFrame` by the position number!
- [ ] How could you know you had to put `[]` vs `()`?
<div class="alert alert-success">
<b>Python Fundamentals</b>
<ul>
<li><code>instance[key]</code></li>
<li><code>function()</code></li>
</ul>
</div>
<div class="alert alert-info">
<b>Tip</b>
<br>Use the <b>autocompletion tool</b> to know which Python element you are working with
</div>
<div class="alert alert-success">
<b>Python Fundamentals</b>
<br><u>Subscriptable</u> means you can access the <code>element[key]</code>
</div>
<div class="alert alert-info">
<b>Tip</b>
<br>Be curious and note everything you don't know
<br>Don't be too picky
</div>

- [ ] Could have you searched this in Google?
- [ ] Can you access the instance and execute a `function()` in the same line?
# Chaining Functions
## Using the `object` Directly
<div class="alert alert-success">
<b>Python Fundamentals</b>
<ul>
<li>❌ You can't apply any function to any object</li>
<li>✅ You can chain functions as long as the resultant object <code>df.describe()</code> can perform the function you are about to call <code>df.describe().sum()</code></li>
</ul>
</div>
## Using the `instance`
```
df.head() #!
```
- [ ] Can we execute the `mean()` function from `pandas` library?
- [ ] Why?
# `library.functions()` vs `object.functions()`
<div class="alert alert-info">
<b>Tip</b>
<br>Apply the <a href="https://github.com/jsulopz/python-resolver-discipline/blob/main/01_Code%20of%20Discipline/03_Google%20Method.md">Python Resolver Discipline</a> to look for the function in Google
</div>
- [ ] What are you working with?
- [ ] What is the technical name of it?
- Let's reconnect with the challenge...
# Working with the `module`
- [ ] Create the same type of visualization with
- the function `scatter()`
- within the `plotly` module
- [ ] Try again ↓
- the function `scatter()`
- within `express` module
- within the `plotly` module
<div class="alert alert-info">
<b>Tip</b>
<br>❌ You don't need to know this beforehand
<br>✅ Google it and deduce how it works ↓
<br><i>"plotly scatter python"</i>
</div>
- [ ] Create a histogram with `mpg` column
<div class="alert alert-info">
<b>Tip</b>
<br>Be lazy and <b>ali<code>as</code></b> the <code>import</code>
</div>
- [ ] Alias the module `express` as `px`
- [ ] Execute the following line & diagnose the error
```
px.scatter(x='weight', y='mpg') #!
```
- [ ] Why?
# Put the previous knowledge to work
```
px.scatter(x=[1,2,3], y=[1,2,1]) #!
```
<div class="alert alert-success">
<b>Python Fundamentals</b>
<ul>
<li>❌ You cannot just throw a random <code>string</code> to the <code>.scatter()</code></li>
<li>✅ This function <code>.scatter()</code> works with numerical data</li>
</ul>
</div>
```
px.scatter(x='weight', y='mpg') #!
```
- [ ] Which created instance contains the numbers?
```
df.head() #!
```
- [ ] Do you reference this instance in the `.scatter()`?
## Accessing with the `keys`
## Accesing with the `instance`
- [ ] Is it a way to omit the repetition of `df`?
# The Most Important [Elements of Programming](https://github.com/jsulopz/00-python-resolver-discipline/blob/main/01_Code%20of%20Discipline/00_The%20Elements%20of%20Programming.md)
## The `function()`
The **function** contains nothing
- ` `; it's the endpoint of programming
```python
pandas.read_csv()
```
## The `instance`
The **instance** (object) may contain:
- `function`
```python
df.describe()
```
- more `instance`s
```python
df.columns
```
## The `module`
The **module** may contain:
- `module` (subfolder)
- `function`
- object `class` **to be created**
- object `instance` **(object) already created**
- [ ] What's the most important element of programming? Why?
# Apply the Knowledge & Uncover the Solution
```
#! ??
```
# The Uncovered Solution
1. Give the `weight` Series with `instance[key]`
2. Give the `str` `'mpg'` to reference a `key` from...
3. The `instance` passed to the parameter `data_frame`
4. Give the points a color with the `instance` `.origin` from the `DataFrame`
5. Pass the `index` instance of from the `DataFrame` to `hover_name`
```
import pandas as pd #!
import plotly.express as px
url = 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/mpg.csv'
df = pd.read_csv(url, index_col='name')
px.scatter(x=df['weight'], y=df.mpg, data_frame=df,
color=df['origin'], hover_name=df.index)
```
| github_jupyter |
# Parameters in QCoDeS
```
import qcodes as qc
import numpy as np
```
QCoDeS provides 3 classes of parameter built in:
- `Parameter` represents a single value at a time
- Example: voltage
- `ArrayParameter` represents an array of values of all the same type that are returned all at once
- Example: voltage vs time waveform
- `MultiParameter` represents a collection of values with different meaning and possibly different dimension
- Example: I and Q, or I vs time and Q vs time
which are described in the "Creating Instrument Drivers" tutorial.
## Parameter
Most of the time you can use `Parameter` directly; even if you have custom `get`/`set` functions, but sometimes it's useful to subclass `Parameter`. Note that since the superclass `Parameter` actually wraps these functions (to include some extra nice-to-have functionality), your subclass should define `get_raw` and `set_raw` rather than `get` and `set`.
```
class MyCounter(qc.Parameter):
def __init__(self, name):
# only name is required
super().__init__(name, label='Times this has been read',
vals=qc.validators.Ints(min_value=0),
docstring='counts how many times get has been called '
'but can be reset to any integer >= 0 by set')
self._count = 0
# you must provide a get method, a set method, or both.
def get_raw(self):
self._count += 1
return self._count
def set_raw(self, val):
self._count = val
c = MyCounter('c')
c2 = MyCounter('c2')
# c() is equivalent to c.get()
print('first call:', c())
print('second call:', c())
# c2(val) is equivalent to c2.set(val)
c2(22)
```
## ArrayParameter
For actions that create a whole array of values at once. When you use it in a `Loop`, it makes a single `DataArray` with the array returned by `get` nested inside extra dimension(s) for the loop.
`ArrayParameter` is, for now, only gettable.
```
class ArrayCounter(qc.ArrayParameter):
def __init__(self):
# only name and shape are required
# the setpoints I'm giving here are identical to the defaults
# this param would get but I'll give them anyway for
# demonstration purposes
super().__init__('array_counter', shape=(3, 2),
label='Total number of values provided',
unit='',
# first setpoint array is 1D, second is 2D, etc...
setpoints=((0, 1, 2), ((0, 1), (0, 1), (0, 1))),
setpoint_names=('index0', 'index1'),
setpoint_labels=('Outer param index', 'Inner param index'),
docstring='fills a 3x2 array with increasing integers')
self._val = 0
def get_raw(self):
# here I'm returning a nested list, but any sequence type will do.
# tuple, np.array, DataArray...
out = [[self._val + 2 * i + j for j in range(2)] for i in range(3)]
self._val += 6
return out
array_counter = ArrayCounter()
# simple get
print('first call:', array_counter())
```
## MultiParameter
Return multiple items at once, where each item can be a single value or an array.
NOTE: Most of the kwarg names here are the plural of those used in `Parameter` and `ArrayParameter`. In particular, `MultiParameter` is the ONLY one that uses `units`, all the others use `unit`.
`MultiParameter` is, for now, only gettable.
```
class SingleIQPair(qc.MultiParameter):
def __init__(self, scale_param):
# only name, names, and shapes are required
# this version returns two scalars (shape = `()`)
super().__init__('single_iq', names=('I', 'Q'), shapes=((), ()),
labels=('In phase amplitude', 'Quadrature amplitude'),
units=('V', 'V'),
# including these setpoints is unnecessary here, but
# if you have a parameter that returns a scalar alongside
# an array you can represent the scalar as an empty sequence.
setpoints=((), ()),
docstring='param that returns two single values, I and Q')
self._scale_param = scale_param
def get_raw(self):
scale_val = self._scale_param()
return (scale_val, scale_val / 2)
scale = qc.ManualParameter('scale', initial_value=2)
iq = SingleIQPair(scale_param=scale)
# simple get
print('simple get:', iq())
class IQArray(qc.MultiParameter):
def __init__(self, scale_param):
# names, labels, and units are the same
super().__init__('iq_array', names=('I', 'Q'), shapes=((5,), (5,)),
labels=('In phase amplitude', 'Quadrature amplitude'),
units=('V', 'V'),
# note that EACH item needs a sequence of setpoint arrays
# so a 1D item has its setpoints wrapped in a length-1 tuple
setpoints=(((0, 1, 2, 3, 4),), ((0, 1, 2, 3, 4),)),
docstring='param that returns two single values, I and Q')
self._scale_param = scale_param
self._indices = np.array([0, 1, 2, 3, 4])
def get_raw(self):
scale_val = self._scale_param()
return (self._indices * scale_val, self._indices * scale_val / 2)
iq_array = IQArray(scale_param=scale)
scale(1)
# simple get
print('simple get', iq_array())
```
| github_jupyter |
Some notes on downsampling data for display
=======================
The smaller the time step of a simulation, the more accurate it is. Empirically, for the Euler method, it looks like 0.001 JD per step (or about a minute) is decent for our purposes. This means that we now have 365.25 / 0.001 = {{365.25 / 0.001}} points per simulation object, or {{12 * 365.25 / 0.001}} bytes. However, we don't really need such dense points for display. On the other hand, 4MB is not that much and we could probably let it go, but just for fun let's explore some different downsampling schemes.
_Note: We can do both adaptive time steps for the simulation as well as use a better intergrator/gravity model to get by with larger time steps, but I haven't explored this yet as it requires a deeper understanding of such models and my intuition is that it still won't downsample the points to the extent that we want, not to mention being more complicated to program. We'll leave that for version 2.0 of the simulator._
We'll set up a simple simulation with the aim of generating some interesting trajectories. The main property we are looking for are paths that have different curvatures as we expect in simulations we will do - since spacecraft will engage/disengage engines and change attitude.
```
import numpy as np
import numpy.linalg as ln
import matplotlib.pyplot as plt
%matplotlib inline
class Body:
def __init__(self, _mass, _pos, _vel):
self.mass = _mass
self.pos = _pos
self.vel = _vel
self.acc = np.zeros(3)
def setup_sim(self, steps=1000):
self.trace = np.empty((steps, 3), dtype=float)
def update(self, dt, n):
self.pos += self.vel * dt
self.vel += self.acc * dt
self.acc = np.zeros(3)
self.trace[n, :] = self.pos
def plot_xy(self, ax):
ax.plot(self.trace[:, 0], self.trace[:, 1])
def acc_ab(a, b):
r = a.pos - b.pos
r2 = np.dot(r, r)
d = r / ln.norm(r)
Fb = d * (a.mass * b.mass) / r2
Fa = -Fb
a.acc += Fa / a.mass
b.acc += Fb / b.mass
def sim_step(bodies, dt, n):
for n1, b1 in enumerate(bodies):
for b2 in bodies[n1 + 1:]:
acc_ab(b1, b2)
for b1 in bodies:
b1.update(dt, n)
def run_sim(bodies, steps, dt):
for b in bodies:
b.setup_sim(steps)
for n in range(steps):
sim_step(bodies, dt, n)
bodyA = Body(100, np.array([0.0, 1.0, 0.0]), np.array([0.0, -10.0, 0.0]))
bodyB = Body(100, np.array([0.0, -1.0, 0.0]), np.array([10.0, 0.0, 0.0]))
bodyC = Body(100, np.array([1.0, 0.0, 0.0]), np.array([0.0, 10.0, 0.0]))
N = 100000
dt = 1e-5
run_sim([bodyA, bodyB, bodyC], N, dt)
plt.figure(figsize=(20,10))
ax = plt.gca()
#bodyA.plot_xy(ax)
bodyB.plot_xy(ax)
#bodyC.plot_xy(ax)
_ = plt.axis('scaled')
```
Simple decimation
----------------
Let us try a simple decimation type downsampler, taking every Nth point of the simulation
```
def downsample_decimate(body, every=20):
return body.trace[::every, :]
decimated_trace = downsample_decimate(bodyB, every=2000)
def plot_compare(body, downsampled_trace):
ds = downsampled_trace
plt.figure(figsize=(20,10))
plt.plot(ds[:, 0], ds[:, 1], 'ko:')
ax = plt.gca()
body.plot_xy(ax)
plt.title('{} -> {}'.format(body.trace.shape[0], ds.shape[0]))
_ = plt.axis('scaled')
plot_compare(bodyB, decimated_trace)
```
This is unsatisfactory because we are doing **poorly on the loop the loops.** It does not adapt itself to different curvatures. So we either have to have a lot of points when we don't need it - on the straight stretches, or have too few points on the tight curves. Can we do better?
Saturating maximum deviation
--------------------------
This scheme looks at the maximum deviation between the actual trace and the linear-interpolation between the points and adaptively downsamples to keep that deviation under a given threashold.
```
def perp_dist(x, y, z):
"""x, z are endpoints, y is a point on the curve"""
a = y - x
a2 = np.dot(a, a)
b = y - z
b2 = np.dot(b, b)
l = z - x
l2 = np.dot(l, l)
l = l2**0.5
return (a2 - ((l2 + a2 - b2)/(2*l))**2)**0.5
# # Here we'll compute the value for each point, but using just the mid point is probably
# # a pretty good heurstic
# def max_dist(pos, n0, n1):
# return np.array([perp_dist(pos[n0, :], pos[n2, :], pos[n1, :]) for n2 in range(n0, n1)]).max()
# Here we'll just use the midpoint for speed
def mid_dist(pos, n0, n1):
return perp_dist(pos[n0, :], pos[int((n1 + n0)/2), :], pos[n1, :])
def max_deviation_downsampler(pos, thresh=0.1):
adaptive_pos = [pos[0, :]]
last_n = 0
for n in range(1, pos.shape[0]):
#print(pos[last_n,:])
if n == last_n: continue
#print(pos[n, :])
if mid_dist(pos, last_n, n) > thresh:
adaptive_pos.append(pos[n - 1, :])
last_n = n - 1
return np.vstack(adaptive_pos)
max_dev_trace = max_deviation_downsampler(bodyB.trace, thresh=0.005)
plot_compare(bodyB, max_dev_trace)
```
Hey, this is pretty good! One thing that bothers me about this scheme is that it requires memory. It's hidden in how I did the simulation here in the prototype, but we have to keep storing every point during the simulation in a temporary buffer until we can select a point for the ouput trace. **Can we come up with a scheme that is memory less?**
Fractal downsampling
-------------------
Ok, I call this frcatal downsampling because I was inspired by the notion of fractals where the length of a line depends on the scale of measurement. It's possibly more accurately described as length difference threshold downsampling, and that's no fun to say.
In this scheme I keep a running to total of the length of the original trace since the last sampled point and compare it to the length of the straight line segment if we use the current point as the next sampled point. If the ratio between the original length and the downsampled length goes above a given threshold, we use that as the next sampled point.
This discards the requirement for a (potentially very large) scratch buffer, but is it any good?
```
def fractal_downsampler(pos, ratio_thresh=2.0):
d = np.diff(pos, axis=0)
adaptive_pos = [pos[0, :]]
last_n = 0
for n in range(1, pos.shape[0]):
if n == last_n: continue
line_d = ln.norm(pos[n, :] - pos[last_n, :])
curve_d = ln.norm(d[last_n:n,:], axis=1).sum()
if curve_d / line_d > ratio_thresh:
adaptive_pos.append(pos[n - 1, :])
last_n = n - 1
adaptive_pos.append(pos[-1, :])
return np.vstack(adaptive_pos)
fractal_trace = fractal_downsampler(bodyB.trace, ratio_thresh=1.001)
plot_compare(bodyB, fractal_trace)
```
Darn it, not as good as the max deviation downsampler. We do well in the high curvature regions, but are insensitive on the long stretches. This is because we are using a ratio, and the longer the stretch, the more we can drift. I think the soluton to this may be to have an absolute distance difference threshold in addition to the ratio threshold and make this an OR operation - if the ratio OR the absolute distance threshold are exceeded, take a sample.
The ratio threshold takes care of the tight curves and the absolute threshold takes care of the gentle curves.
So ...
```
def fractal_downsampler2(pos, ratio_thresh=1.001, abs_thresh=0.1):
d = np.diff(pos, axis=0)
adaptive_pos = [pos[0, :]]
last_n = 0
for n in range(1, pos.shape[0]):
if n == last_n: continue
line_d = ln.norm(pos[n, :] - pos[last_n, :])
curve_d = ln.norm(d[last_n:n,:], axis=1).sum()
if curve_d / line_d > ratio_thresh or abs(curve_d - line_d) > abs_thresh:
adaptive_pos.append(pos[n - 1, :])
last_n = n - 1
adaptive_pos.append(pos[-1, :])
return np.vstack(adaptive_pos)
fractal_trace2 = fractal_downsampler2(bodyB.trace, ratio_thresh=1.005, abs_thresh=0.0001)
plot_compare(bodyB, fractal_trace2)
```
This looks like a good downsampling scheme. It's nice to have two knobs to control: one for the tight curves and one for the less curvy stretches. This allows us to get close to the max deviation downsampler without needing a ton of memory
| github_jupyter |
## Importing necessary libraries
```
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.neighbors import KNeighborsClassifier as KNN
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
#Loading dataset
data = pd.read_csv("indian_liver_patient.csv")
df=data_raw.describe()
df.to_csv('cardio.csv')
df = pd.DataFrame(data)
df.head()
df.shape
df.info()
```
### Null Values
```
#Showing column wise %ge of NaN values they contains
null_col = []
for i in df.columns:
print(i, df[i].isna().mean()*100)
if df[i].isna().mean()*100 > 0:
null_col.append(i)
```
> Filling null values of column *Albumin_and_Globulin_Ratio* with mean of column (as it is only column with few Nan values)
```
for i in null_col:
df[i] = df[i].fillna(df[i].mean())
# lets check for null values again
for i in df.columns:
print(i, df[i].isna().mean()*100)
# Checking dataset balance or not
plt.figure(figsize=(5,5))
ax = sns.countplot(x='Dataset', data=df)
for p in ax.patches:
ax.annotate('{}'.format(p.get_height()), (p.get_x()+0.1, p.get_height()+50))
```
> The bar graph easily shows how data is imbalanced. Less than 30% data is in class . So, first, we have to balance the data in to get more precise predictions.
> For that I am using Over sampling it may have over fitting but under sampling result in low accurate.
### Over sampling
```
from imblearn.over_sampling import RandomOverSampler
oversample = RandomOverSampler()
x, y = oversample.fit_resample(df.drop(['Dataset'], axis=1), df['Dataset'])
new_df = pd.DataFrame(x, columns=df.drop(['Dataset'], axis=1).columns)
new_df['Dataset'] = y
new_df.head()
plt.figure(figsize=(5,5))
ax = sns.countplot(x='Dataset', data=new_df)
for p in ax.patches:
ax.annotate('{}'.format(p.get_height()), (p.get_x()+0.1, p.get_height()+50))
```
> Here we can see that all the classes are balanced.
### Lebel Encoding Gender
```
from sklearn.preprocessing import LabelEncoder
enc = LabelEncoder()
new_df['Gender'] = enc.fit_transform(new_df['Gender'].astype('str'))
new_df.head()
new_df.shape
new_df.info()
```
> Since due to over sampling some of columns get converted in *objec* type, lets convert them back in numericals
```
for i in new_df.select_dtypes(include=['object']).columns:
new_df[i] = new_df[i].astype(str).astype(float)
```
### Correlation Matrix
```
cormap = new_df.corr()
fig, ax = plt.subplots(figsize=(15,15))
sns.heatmap(cormap, annot = True)
# Pair plot
sns.pairplot(data=new_df, hue='Dataset', corner=True)
```
## **KNN**
```
X = new_df.drop(['Dataset'], axis=1)
y = new_df['Dataset']
X.describe()
print("\nInfo\n")
print(X.info())
print("\nMaximum\n")
print(X.max())
print("\nMinimum\n")
print(X.min())
# Scale the data to be between -1 and 1
scaler = StandardScaler()
X = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)
X.head()
```
### Spliting Dataset into train and test set
```
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1)
```
### Model Training
```
model= KNN()
model.fit(X_train, y_train)
model.get_params()
```
### Hyper parameter tunning
```
from sklearn.model_selection import GridSearchCV
n_neighbors = [x for x in range(5, 86, 2)]
algorithm = ['auto', 'ball_tree', 'kd_tree', 'brute']
weights = ['uniform', 'distance']
grid = {'n_neighbors': n_neighbors,
'algorithm': algorithm,
'weights': weights}
new_model = KNN()
knn_grid = GridSearchCV(estimator = new_model, param_grid = grid, cv = 7, verbose=0)
knn_grid.fit(X_train, y_train)
knn_grid.best_params_
y_pred = knn_grid.best_estimator_.predict(X_test)
mat = confusion_matrix(y_test, y_pred)
fig, ax = plt.subplots(figsize=(5,5))
sns.heatmap(mat, annot = True)
print("Accuracy Score {}".format(accuracy_score(y_test,y_pred)))
print("Classification report: {}".format(classification_report(y_test,y_pred)))
```
### Saving Model
```
import pickle
pickle.dump(knn_grid.best_estimator_, open("Liver_disease.sav", 'wb'))
```
### Loading Model
```
import joblib
loaded_model = joblib.load("Liver_disease.sav")
X.columns
df=pd.read_csv("indian_liver_patient.csv",usecols=['Age', 'Gender', 'Total_Bilirubin', 'Direct_Bilirubin',
'Alkaline_Phosphotase', 'Alamine_Aminotransferase',
'Aspartate_Aminotransferase', 'Total_Protiens', 'Albumin',
'Albumin_and_Globulin_Ratio',"Dataset"])
df.tail(2)
df=pd.read_csv("indian_liver_patient.csv",usecols=['Age', 'Gender', 'Total_Bilirubin', 'Direct_Bilirubin',
'Alkaline_Phosphotase', 'Alamine_Aminotransferase',
'Aspartate_Aminotransferase', 'Total_Protiens', 'Albumin',
'Albumin_and_Globulin_Ratio'])
df["Gender"]=1
df["Gender"]=1
X1=[df.iloc[581].values]
X2=[df.iloc[582].values]
print("X1 if person who is having liver problem:\n",X1)
print("\nX1 prediction is: ",loaded_model.predict(X1))
```
> X1 prediction is 1 means person having liver disease
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.