text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
<a href="https://colab.research.google.com/github/john-s-butler-dit/Numerical-Analysis-Python/blob/master/Chapter%2004%20-%20Multistep%20Methods/403_Adams%20Moulton%20Example.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Adams Moulton
#### John S Butler
john.s.butler@tudublin.ie
[Course Notes](https://johnsbutler.netlify.com/files/Teaching/Numerical_Analysis_for_Differential_Equations.pdf) [Github](https://github.com/john-s-butler-dit/Numerical-Analysis-Python)
The Adams Moulton method is an implicit multistep method. This notebook illustrates the 2 step Adams Moulton method for a linear initial value problem of the form
\begin{equation} y^{'}=t-y, \ \ (0 \leq t \leq 2)\end{equation}
with the initial condition
\begin{equation}y(0)=1.\end{equation}
The video below walks through the notebook.
```
from IPython.display import HTML
HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/L1IrVMykC6k" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>')
```
## Python Libraries
```
import numpy as np
import math
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt # side-stepping mpl backend
import matplotlib.gridspec as gridspec # subplots
import warnings
```
### Defining the function
\begin{equation} f(t,y)=t-y.\end{equation}
```
def myfun_ty(t,y):
return t-y
```
## Discrete Interval
Defining the step size $h$ from the interval range $a\leq t \leq b$ and number of steps $N$
\begin{equation}h=\frac{b−a}{N}.\end{equation}
This gives the discrete time steps,
\begin{equation}t_i=t_0+ih,\end{equation}
where $t_0=a.$
Here the interval is $0≤t≤2$ and number of step 4
\begin{equation}h=\frac{2−0}{4}=0.5.\end{equation}
This gives the discrete time steps,
\begin{equation}t_i=0+i0.5,\end{equation}
for $i=0,1,⋯,4.$
```
# Start and end of interval
b=2
a=0
# Step size
N=4
h=(b-a)/(N)
t=np.arange(a,b+h,h)
fig = plt.figure(figsize=(10,4))
plt.plot(t,0*t,'o:',color='red')
plt.xlim((0,2))
plt.title('Illustration of discrete time points for h=%s'%(h))
```
## Exact Solution
The initial value problem has the exact solution
\begin{equation}y(t)=2e^{-t}+t-1.\end{equation}
The figure below plots the exact solution.
```
IC=1 # Intial condtion
y=(IC+1)*np.exp(-t)+t-1
fig = plt.figure(figsize=(6,4))
plt.plot(t,y,'o-',color='black')
plt.title('Exact Solution ')
plt.xlabel('time')
```
## 2-step Adams Moulton
The general 2-step Adams Moulton difference equation is
\begin{equation}w_{i+1} = w_{i} + \frac{h}{12}(5f(t_{i+1},w_{i+1})+8f(t_{i},w_{i})-f(t_{i-1},w_{i-1})). \end{equation}
For the specific intial value problem the 2-step Adams Moiulton difference equation is
\begin{equation}w_{i+1} = w_{i} + \frac{h}{12}(5(t_{i+1}-w_{i+1})+8(t_{i}-w_{i})-(t_{i-1}-w_{i-1})). \end{equation}
for $i=0$ the difference equation is:
\begin{equation}w_{1} = w_{0} + \frac{h}{12}(5(t_{1}-w_{1})+8(t_{0}-w_{0})-(t_{-1}-w_{-1})).\end{equation}
this is not solvable as <font color='red'> $w_{1}, \ w_{-1}$ </font> are unknown.
for $i=1$ the difference equation is:
\begin{equation}w_{2} = w_{1} + \frac{h}{12}(5(t_{2}-w_{2})+8(t_{1}-w_{1})-(t_{0}-w_{0})). \end{equation}
this is not solvable as <font color='red'> $w_{1}$ and $w_{2}$ </font> are unknown. $w_1$ can be approximated using a one step method. Here, as the exact solution is known,
\begin{equation}w_1=2e^{-t_1}+t_1-1.\end{equation}
As the intial value problem is linear the difference equation can be rearranged such that $w_2$ is on the right hand side:
\begin{equation}w_{2}+\frac{5h}{12}w_{2} = w_{1} + \frac{h}{12}(5(t_{2})+8f(t_{1}-w_{1})-(t_{0}-w_{0})), \end{equation}
\begin{equation}w_{2} = \frac{w_{1} + \frac{h}{12}(5(t_{2})+8f(t_{1}-w_{1})-(t_{0}-w_{0}))}{1+\frac{5h}{12}}. \end{equation}
```
### Initial conditions
w=np.zeros(len(t))
w[0]=IC
w[1]=y[1] # NEEDED FOR THE METHOD
```
### Loop
```
for k in range (1,N):
w[k+1]=(w[k]+h/12.0*(5*t[k+1]+8*myfun_ty(t[k],w[k])-myfun_ty(t[k-1],w[k-1])))/(1+5*h/12)
```
### Plotting solution
```
def plotting(t,w,y):
fig = plt.figure(figsize=(10,4))
plt.plot(t,y, 'o-',color='black',label='Exact')
plt.plot(t,w,'s:',color='blue',label='Adams-Moulton')
plt.xlabel('time')
plt.legend()
plt.show
```
The plot below shows the exact solution (black) and the 2 step Adams-Moulton approximation (red) of the intial value problem
```
plotting(t,w,y)
```
## Local Error
The Error for the 2 step Adams Moulton is:
\begin{equation}y_{n+1}=y_n+\frac{h}{12}[5f(t_{n+1},w_{n+1})+8f(t_{n},w_{n})-f(t_{n-1},w_{n-1})] +\frac{-h^4}{24}y^{(4)}(\eta),\end{equation}
where $\eta \in [t_{n-1},t_{n+1}]$.
Rearranging the equations gives
\begin{equation}\frac{y_{n+1}-y_{n}}{h}=\frac{1}{12}[5f(t_{n+1},w_{n+1})+8f(t_{n},w_{n})-f(t_{n-1},w_{n-1})] +\frac{-h^3}{24}y^{(4)}(\eta),\end{equation}
For our specific initial value problem the error is of the form:
\begin{equation}\frac{-h^3}{24}y'''(\eta)=\frac{h^3}{24}2e^{-\eta} \leq\frac{(0.3)^3}{24} 2\leq 0.01042.\end{equation}
```
d = {'time t_i': t, 'Adams Bashforth w_i': w,'Exact y(t_i)':y,'Error |y(t_i)-w_i|':np.abs(y-w),'LTE':round(2*0.5**3/24,5)}
df = pd.DataFrame(data=d)
df
```
| github_jupyter |
# Building your Deep Neural Network: Step by Step
Welcome to your week 4 assignment (part 1 of 2)! You have previously trained a 2-layer Neural Network (with a single hidden layer). This week, you will build a deep neural network, with as many layers as you want!
- In this notebook, you will implement all the functions required to build a deep neural network.
- In the next assignment, you will use these functions to build a deep neural network for image classification.
**After this assignment you will be able to:**
- Use non-linear units like ReLU to improve your model
- Build a deeper neural network (with more than 1 hidden layer)
- Implement an easy-to-use neural network class
**Notation**:
- Superscript $[l]$ denotes a quantity associated with the $l^{th}$ layer.
- Example: $a^{[L]}$ is the $L^{th}$ layer activation. $W^{[L]}$ and $b^{[L]}$ are the $L^{th}$ layer parameters.
- Superscript $(i)$ denotes a quantity associated with the $i^{th}$ example.
- Example: $x^{(i)}$ is the $i^{th}$ training example.
- Lowerscript $i$ denotes the $i^{th}$ entry of a vector.
- Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the $l^{th}$ layer's activations).
Let's get started!
### <font color='darkblue'> Updates to Assignment <font>
#### If you were working on a previous version
* The current notebook filename is version "4a".
* You can find your work in the file directory as version "4".
* To see the file directory, click on the Coursera logo at the top left of the notebook.
#### List of Updates
* compute_cost unit test now includes tests for Y = 0 as well as Y = 1. This catches a possible bug before students get graded.
* linear_backward unit test now has a more complete unit test that catches a possible bug before students get graded.
## 1 - Packages
Let's first import all the packages that you will need during this assignment.
- [numpy](www.numpy.org) is the main package for scientific computing with Python.
- [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.
- dnn_utils provides some necessary functions for this notebook.
- testCases provides some test cases to assess the correctness of your functions
- np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work. Please don't change the seed.
```
import numpy as np
import h5py
import matplotlib.pyplot as plt
from testCases_v4a import *
from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
%load_ext autoreload
%autoreload 2
np.random.seed(1)
```
## 2 - Outline of the Assignment
To build your neural network, you will be implementing several "helper functions". These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. Each small helper function you will implement will have detailed instructions that will walk you through the necessary steps. Here is an outline of this assignment, you will:
- Initialize the parameters for a two-layer network and for an $L$-layer neural network.
- Implement the forward propagation module (shown in purple in the figure below).
- Complete the LINEAR part of a layer's forward propagation step (resulting in $Z^{[l]}$).
- We give you the ACTIVATION function (relu/sigmoid).
- Combine the previous two steps into a new [LINEAR->ACTIVATION] forward function.
- Stack the [LINEAR->RELU] forward function L-1 time (for layers 1 through L-1) and add a [LINEAR->SIGMOID] at the end (for the final layer $L$). This gives you a new L_model_forward function.
- Compute the loss.
- Implement the backward propagation module (denoted in red in the figure below).
- Complete the LINEAR part of a layer's backward propagation step.
- We give you the gradient of the ACTIVATE function (relu_backward/sigmoid_backward)
- Combine the previous two steps into a new [LINEAR->ACTIVATION] backward function.
- Stack [LINEAR->RELU] backward L-1 times and add [LINEAR->SIGMOID] backward in a new L_model_backward function
- Finally update the parameters.
<img src="images/final outline.png" style="width:800px;height:500px;">
<caption><center> **Figure 1**</center></caption><br>
**Note** that for every forward function, there is a corresponding backward function. That is why at every step of your forward module you will be storing some values in a cache. The cached values are useful for computing gradients. In the backpropagation module you will then use the cache to calculate the gradients. This assignment will show you exactly how to carry out each of these steps.
## 3 - Initialization
You will write two helper functions that will initialize the parameters for your model. The first function will be used to initialize parameters for a two layer model. The second one will generalize this initialization process to $L$ layers.
### 3.1 - 2-layer Neural Network
**Exercise**: Create and initialize the parameters of the 2-layer neural network.
**Instructions**:
- The model's structure is: *LINEAR -> RELU -> LINEAR -> SIGMOID*.
- Use random initialization for the weight matrices. Use `np.random.randn(shape)*0.01` with the correct shape.
- Use zero initialization for the biases. Use `np.zeros(shape)`.
```
# GRADED FUNCTION: initialize_parameters
def initialize_parameters(n_x, n_h, n_y):
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
parameters -- python dictionary containing your parameters:
W1 -- weight matrix of shape (n_h, n_x)
b1 -- bias vector of shape (n_h, 1)
W2 -- weight matrix of shape (n_y, n_h)
b2 -- bias vector of shape (n_y, 1)
"""
np.random.seed(1)
### START CODE HERE ### (≈ 4 lines of code)
W1 = None
b1 = None
W2 = None
b2 = None
### END CODE HERE ###
assert(W1.shape == (n_h, n_x))
assert(b1.shape == (n_h, 1))
assert(W2.shape == (n_y, n_h))
assert(b2.shape == (n_y, 1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
parameters = initialize_parameters(3,2,1)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
```
**Expected output**:
<table style="width:80%">
<tr>
<td> **W1** </td>
<td> [[ 0.01624345 -0.00611756 -0.00528172]
[-0.01072969 0.00865408 -0.02301539]] </td>
</tr>
<tr>
<td> **b1**</td>
<td>[[ 0.]
[ 0.]]</td>
</tr>
<tr>
<td>**W2**</td>
<td> [[ 0.01744812 -0.00761207]]</td>
</tr>
<tr>
<td> **b2** </td>
<td> [[ 0.]] </td>
</tr>
</table>
### 3.2 - L-layer Neural Network
The initialization for a deeper L-layer neural network is more complicated because there are many more weight matrices and bias vectors. When completing the `initialize_parameters_deep`, you should make sure that your dimensions match between each layer. Recall that $n^{[l]}$ is the number of units in layer $l$. Thus for example if the size of our input $X$ is $(12288, 209)$ (with $m=209$ examples) then:
<table style="width:100%">
<tr>
<td> </td>
<td> **Shape of W** </td>
<td> **Shape of b** </td>
<td> **Activation** </td>
<td> **Shape of Activation** </td>
<tr>
<tr>
<td> **Layer 1** </td>
<td> $(n^{[1]},12288)$ </td>
<td> $(n^{[1]},1)$ </td>
<td> $Z^{[1]} = W^{[1]} X + b^{[1]} $ </td>
<td> $(n^{[1]},209)$ </td>
<tr>
<tr>
<td> **Layer 2** </td>
<td> $(n^{[2]}, n^{[1]})$ </td>
<td> $(n^{[2]},1)$ </td>
<td>$Z^{[2]} = W^{[2]} A^{[1]} + b^{[2]}$ </td>
<td> $(n^{[2]}, 209)$ </td>
<tr>
<tr>
<td> $\vdots$ </td>
<td> $\vdots$ </td>
<td> $\vdots$ </td>
<td> $\vdots$</td>
<td> $\vdots$ </td>
<tr>
<tr>
<td> **Layer L-1** </td>
<td> $(n^{[L-1]}, n^{[L-2]})$ </td>
<td> $(n^{[L-1]}, 1)$ </td>
<td>$Z^{[L-1]} = W^{[L-1]} A^{[L-2]} + b^{[L-1]}$ </td>
<td> $(n^{[L-1]}, 209)$ </td>
<tr>
<tr>
<td> **Layer L** </td>
<td> $(n^{[L]}, n^{[L-1]})$ </td>
<td> $(n^{[L]}, 1)$ </td>
<td> $Z^{[L]} = W^{[L]} A^{[L-1]} + b^{[L]}$</td>
<td> $(n^{[L]}, 209)$ </td>
<tr>
</table>
Remember that when we compute $W X + b$ in python, it carries out broadcasting. For example, if:
$$ W = \begin{bmatrix}
j & k & l\\
m & n & o \\
p & q & r
\end{bmatrix}\;\;\; X = \begin{bmatrix}
a & b & c\\
d & e & f \\
g & h & i
\end{bmatrix} \;\;\; b =\begin{bmatrix}
s \\
t \\
u
\end{bmatrix}\tag{2}$$
Then $WX + b$ will be:
$$ WX + b = \begin{bmatrix}
(ja + kd + lg) + s & (jb + ke + lh) + s & (jc + kf + li)+ s\\
(ma + nd + og) + t & (mb + ne + oh) + t & (mc + nf + oi) + t\\
(pa + qd + rg) + u & (pb + qe + rh) + u & (pc + qf + ri)+ u
\end{bmatrix}\tag{3} $$
**Exercise**: Implement initialization for an L-layer Neural Network.
**Instructions**:
- The model's structure is *[LINEAR -> RELU] $ \times$ (L-1) -> LINEAR -> SIGMOID*. I.e., it has $L-1$ layers using a ReLU activation function followed by an output layer with a sigmoid activation function.
- Use random initialization for the weight matrices. Use `np.random.randn(shape) * 0.01`.
- Use zeros initialization for the biases. Use `np.zeros(shape)`.
- We will store $n^{[l]}$, the number of units in different layers, in a variable `layer_dims`. For example, the `layer_dims` for the "Planar Data classification model" from last week would have been [2,4,1]: There were two inputs, one hidden layer with 4 hidden units, and an output layer with 1 output unit. This means `W1`'s shape was (4,2), `b1` was (4,1), `W2` was (1,4) and `b2` was (1,1). Now you will generalize this to $L$ layers!
- Here is the implementation for $L=1$ (one layer neural network). It should inspire you to implement the general case (L-layer neural network).
```python
if L == 1:
parameters["W" + str(L)] = np.random.randn(layer_dims[1], layer_dims[0]) * 0.01
parameters["b" + str(L)] = np.zeros((layer_dims[1], 1))
```
```
# GRADED FUNCTION: initialize_parameters_deep
def initialize_parameters_deep(layer_dims):
"""
Arguments:
layer_dims -- python array (list) containing the dimensions of each layer in our network
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])
bl -- bias vector of shape (layer_dims[l], 1)
"""
np.random.seed(3)
parameters = {}
L = len(layer_dims) # number of layers in the network
for l in range(1, L):
### START CODE HERE ### (≈ 2 lines of code)
parameters['W' + str(l)] = None
parameters['b' + str(l)] = None
### END CODE HERE ###
assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))
assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))
return parameters
parameters = initialize_parameters_deep([5,4,3])
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
```
**Expected output**:
<table style="width:80%">
<tr>
<td> **W1** </td>
<td>[[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]
[-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]
[-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]
[-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]</td>
</tr>
<tr>
<td>**b1** </td>
<td>[[ 0.]
[ 0.]
[ 0.]
[ 0.]]</td>
</tr>
<tr>
<td>**W2** </td>
<td>[[-0.01185047 -0.0020565 0.01486148 0.00236716]
[-0.01023785 -0.00712993 0.00625245 -0.00160513]
[-0.00768836 -0.00230031 0.00745056 0.01976111]]</td>
</tr>
<tr>
<td>**b2** </td>
<td>[[ 0.]
[ 0.]
[ 0.]]</td>
</tr>
</table>
## 4 - Forward propagation module
### 4.1 - Linear Forward
Now that you have initialized your parameters, you will do the forward propagation module. You will start by implementing some basic functions that you will use later when implementing the model. You will complete three functions in this order:
- LINEAR
- LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid.
- [LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID (whole model)
The linear forward module (vectorized over all the examples) computes the following equations:
$$Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}\tag{4}$$
where $A^{[0]} = X$.
**Exercise**: Build the linear part of forward propagation.
**Reminder**:
The mathematical representation of this unit is $Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}$. You may also find `np.dot()` useful. If your dimensions don't match, printing `W.shape` may help.
```
# GRADED FUNCTION: linear_forward
def linear_forward(A, W, b):
"""
Implement the linear part of a layer's forward propagation.
Arguments:
A -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
b -- bias vector, numpy array of shape (size of the current layer, 1)
Returns:
Z -- the input of the activation function, also called pre-activation parameter
cache -- a python tuple containing "A", "W" and "b" ; stored for computing the backward pass efficiently
"""
### START CODE HERE ### (≈ 1 line of code)
Z = None
### END CODE HERE ###
assert(Z.shape == (W.shape[0], A.shape[1]))
cache = (A, W, b)
return Z, cache
A, W, b = linear_forward_test_case()
Z, linear_cache = linear_forward(A, W, b)
print("Z = " + str(Z))
```
**Expected output**:
<table style="width:35%">
<tr>
<td> **Z** </td>
<td> [[ 3.26295337 -1.23429987]] </td>
</tr>
</table>
### 4.2 - Linear-Activation Forward
In this notebook, you will use two activation functions:
- **Sigmoid**: $\sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}}$. We have provided you with the `sigmoid` function. This function returns **two** items: the activation value "`a`" and a "`cache`" that contains "`Z`" (it's what we will feed in to the corresponding backward function). To use it you could just call:
``` python
A, activation_cache = sigmoid(Z)
```
- **ReLU**: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. We have provided you with the `relu` function. This function returns **two** items: the activation value "`A`" and a "`cache`" that contains "`Z`" (it's what we will feed in to the corresponding backward function). To use it you could just call:
``` python
A, activation_cache = relu(Z)
```
For more convenience, you are going to group two functions (Linear and Activation) into one function (LINEAR->ACTIVATION). Hence, you will implement a function that does the LINEAR forward step followed by an ACTIVATION forward step.
**Exercise**: Implement the forward propagation of the *LINEAR->ACTIVATION* layer. Mathematical relation is: $A^{[l]} = g(Z^{[l]}) = g(W^{[l]}A^{[l-1]} +b^{[l]})$ where the activation "g" can be sigmoid() or relu(). Use linear_forward() and the correct activation function.
```
# GRADED FUNCTION: linear_activation_forward
def linear_activation_forward(A_prev, W, b, activation):
"""
Implement the forward propagation for the LINEAR->ACTIVATION layer
Arguments:
A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
b -- bias vector, numpy array of shape (size of the current layer, 1)
activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
Returns:
A -- the output of the activation function, also called the post-activation value
cache -- a python tuple containing "linear_cache" and "activation_cache";
stored for computing the backward pass efficiently
"""
if activation == "sigmoid":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
### START CODE HERE ### (≈ 2 lines of code)
Z, linear_cache = None
A, activation_cache = None
### END CODE HERE ###
elif activation == "relu":
# Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
### START CODE HERE ### (≈ 2 lines of code)
Z, linear_cache = None
A, activation_cache = None
### END CODE HERE ###
assert (A.shape == (W.shape[0], A_prev.shape[1]))
cache = (linear_cache, activation_cache)
return A, cache
A_prev, W, b = linear_activation_forward_test_case()
A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "sigmoid")
print("With sigmoid: A = " + str(A))
A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "relu")
print("With ReLU: A = " + str(A))
```
**Expected output**:
<table style="width:35%">
<tr>
<td> **With sigmoid: A ** </td>
<td > [[ 0.96890023 0.11013289]]</td>
</tr>
<tr>
<td> **With ReLU: A ** </td>
<td > [[ 3.43896131 0. ]]</td>
</tr>
</table>
**Note**: In deep learning, the "[LINEAR->ACTIVATION]" computation is counted as a single layer in the neural network, not two layers.
### d) L-Layer Model
For even more convenience when implementing the $L$-layer Neural Net, you will need a function that replicates the previous one (`linear_activation_forward` with RELU) $L-1$ times, then follows that with one `linear_activation_forward` with SIGMOID.
<img src="images/model_architecture_kiank.png" style="width:600px;height:300px;">
<caption><center> **Figure 2** : *[LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID* model</center></caption><br>
**Exercise**: Implement the forward propagation of the above model.
**Instruction**: In the code below, the variable `AL` will denote $A^{[L]} = \sigma(Z^{[L]}) = \sigma(W^{[L]} A^{[L-1]} + b^{[L]})$. (This is sometimes also called `Yhat`, i.e., this is $\hat{Y}$.)
**Tips**:
- Use the functions you had previously written
- Use a for loop to replicate [LINEAR->RELU] (L-1) times
- Don't forget to keep track of the caches in the "caches" list. To add a new value `c` to a `list`, you can use `list.append(c)`.
```
# GRADED FUNCTION: L_model_forward
def L_model_forward(X, parameters):
"""
Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation
Arguments:
X -- data, numpy array of shape (input size, number of examples)
parameters -- output of initialize_parameters_deep()
Returns:
AL -- last post-activation value
caches -- list of caches containing:
every cache of linear_activation_forward() (there are L-1 of them, indexed from 0 to L-1)
"""
caches = []
A = X
L = len(parameters) // 2 # number of layers in the neural network
# Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list.
for l in range(1, L):
A_prev = A
### START CODE HERE ### (≈ 2 lines of code)
A, cache = None
None
### END CODE HERE ###
# Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list.
### START CODE HERE ### (≈ 2 lines of code)
AL, cache = None
None
### END CODE HERE ###
assert(AL.shape == (1,X.shape[1]))
return AL, caches
X, parameters = L_model_forward_test_case_2hidden()
AL, caches = L_model_forward(X, parameters)
print("AL = " + str(AL))
print("Length of caches list = " + str(len(caches)))
```
<table style="width:50%">
<tr>
<td> **AL** </td>
<td > [[ 0.03921668 0.70498921 0.19734387 0.04728177]]</td>
</tr>
<tr>
<td> **Length of caches list ** </td>
<td > 3 </td>
</tr>
</table>
Great! Now you have a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in "caches". Using $A^{[L]}$, you can compute the cost of your predictions.
## 5 - Cost function
Now you will implement forward and backward propagation. You need to compute the cost, because you want to check if your model is actually learning.
**Exercise**: Compute the cross-entropy cost $J$, using the following formula: $$-\frac{1}{m} \sum\limits_{i = 1}^{m} (y^{(i)}\log\left(a^{[L] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right)) \tag{7}$$
```
# GRADED FUNCTION: compute_cost
def compute_cost(AL, Y):
"""
Implement the cost function defined by equation (7).
Arguments:
AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)
Returns:
cost -- cross-entropy cost
"""
m = Y.shape[1]
# Compute loss from aL and y.
### START CODE HERE ### (≈ 1 lines of code)
cost = None
### END CODE HERE ###
cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).
assert(cost.shape == ())
return cost
Y, AL = compute_cost_test_case()
print("cost = " + str(compute_cost(AL, Y)))
```
**Expected Output**:
<table>
<tr>
<td>**cost** </td>
<td> 0.2797765635793422</td>
</tr>
</table>
## 6 - Backward propagation module
Just like with forward propagation, you will implement helper functions for backpropagation. Remember that back propagation is used to calculate the gradient of the loss function with respect to the parameters.
**Reminder**:
<img src="images/backprop_kiank.png" style="width:650px;height:250px;">
<caption><center> **Figure 3** : Forward and Backward propagation for *LINEAR->RELU->LINEAR->SIGMOID* <br> *The purple blocks represent the forward propagation, and the red blocks represent the backward propagation.* </center></caption>
<!--
For those of you who are expert in calculus (you don't need to be to do this assignment), the chain rule of calculus can be used to derive the derivative of the loss $\mathcal{L}$ with respect to $z^{[1]}$ in a 2-layer network as follows:
$$\frac{d \mathcal{L}(a^{[2]},y)}{{dz^{[1]}}} = \frac{d\mathcal{L}(a^{[2]},y)}{{da^{[2]}}}\frac{{da^{[2]}}}{{dz^{[2]}}}\frac{{dz^{[2]}}}{{da^{[1]}}}\frac{{da^{[1]}}}{{dz^{[1]}}} \tag{8} $$
In order to calculate the gradient $dW^{[1]} = \frac{\partial L}{\partial W^{[1]}}$, you use the previous chain rule and you do $dW^{[1]} = dz^{[1]} \times \frac{\partial z^{[1]} }{\partial W^{[1]}}$. During the backpropagation, at each step you multiply your current gradient by the gradient corresponding to the specific layer to get the gradient you wanted.
Equivalently, in order to calculate the gradient $db^{[1]} = \frac{\partial L}{\partial b^{[1]}}$, you use the previous chain rule and you do $db^{[1]} = dz^{[1]} \times \frac{\partial z^{[1]} }{\partial b^{[1]}}$.
This is why we talk about **backpropagation**.
!-->
Now, similar to forward propagation, you are going to build the backward propagation in three steps:
- LINEAR backward
- LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the ReLU or sigmoid activation
- [LINEAR -> RELU] $\times$ (L-1) -> LINEAR -> SIGMOID backward (whole model)
### 6.1 - Linear backward
For layer $l$, the linear part is: $Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}$ (followed by an activation).
Suppose you have already calculated the derivative $dZ^{[l]} = \frac{\partial \mathcal{L} }{\partial Z^{[l]}}$. You want to get $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$.
<img src="images/linearback_kiank.png" style="width:250px;height:300px;">
<caption><center> **Figure 4** </center></caption>
The three outputs $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$ are computed using the input $dZ^{[l]}$.Here are the formulas you need:
$$ dW^{[l]} = \frac{\partial \mathcal{J} }{\partial W^{[l]}} = \frac{1}{m} dZ^{[l]} A^{[l-1] T} \tag{8}$$
$$ db^{[l]} = \frac{\partial \mathcal{J} }{\partial b^{[l]}} = \frac{1}{m} \sum_{i = 1}^{m} dZ^{[l](i)}\tag{9}$$
$$ dA^{[l-1]} = \frac{\partial \mathcal{L} }{\partial A^{[l-1]}} = W^{[l] T} dZ^{[l]} \tag{10}$$
**Exercise**: Use the 3 formulas above to implement linear_backward().
```
# GRADED FUNCTION: linear_backward
def linear_backward(dZ, cache):
"""
Implement the linear portion of backward propagation for a single layer (layer l)
Arguments:
dZ -- Gradient of the cost with respect to the linear output (of current layer l)
cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer
Returns:
dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
dW -- Gradient of the cost with respect to W (current layer l), same shape as W
db -- Gradient of the cost with respect to b (current layer l), same shape as b
"""
A_prev, W, b = cache
m = A_prev.shape[1]
### START CODE HERE ### (≈ 3 lines of code)
dW = None
db = None
dA_prev = None
### END CODE HERE ###
assert (dA_prev.shape == A_prev.shape)
assert (dW.shape == W.shape)
assert (db.shape == b.shape)
return dA_prev, dW, db
# Set up some test inputs
dZ, linear_cache = linear_backward_test_case()
dA_prev, dW, db = linear_backward(dZ, linear_cache)
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db))
```
** Expected Output**:
```
dA_prev =
[[-1.15171336 0.06718465 -0.3204696 2.09812712]
[ 0.60345879 -3.72508701 5.81700741 -3.84326836]
[-0.4319552 -1.30987417 1.72354705 0.05070578]
[-0.38981415 0.60811244 -1.25938424 1.47191593]
[-2.52214926 2.67882552 -0.67947465 1.48119548]]
dW =
[[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716]
[ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808]
[ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]]
db =
[[-0.14713786]
[-0.11313155]
[-0.13209101]]
```
### 6.2 - Linear-Activation backward
Next, you will create a function that merges the two helper functions: **`linear_backward`** and the backward step for the activation **`linear_activation_backward`**.
To help you implement `linear_activation_backward`, we provided two backward functions:
- **`sigmoid_backward`**: Implements the backward propagation for SIGMOID unit. You can call it as follows:
```python
dZ = sigmoid_backward(dA, activation_cache)
```
- **`relu_backward`**: Implements the backward propagation for RELU unit. You can call it as follows:
```python
dZ = relu_backward(dA, activation_cache)
```
If $g(.)$ is the activation function,
`sigmoid_backward` and `relu_backward` compute $$dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}) \tag{11}$$.
**Exercise**: Implement the backpropagation for the *LINEAR->ACTIVATION* layer.
```
# GRADED FUNCTION: linear_activation_backward
def linear_activation_backward(dA, cache, activation):
"""
Implement the backward propagation for the LINEAR->ACTIVATION layer.
Arguments:
dA -- post-activation gradient for current layer l
cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently
activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
Returns:
dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
dW -- Gradient of the cost with respect to W (current layer l), same shape as W
db -- Gradient of the cost with respect to b (current layer l), same shape as b
"""
linear_cache, activation_cache = cache
if activation == "relu":
### START CODE HERE ### (≈ 2 lines of code)
dZ = None
dA_prev, dW, db = None
### END CODE HERE ###
elif activation == "sigmoid":
### START CODE HERE ### (≈ 2 lines of code)
dZ = None
dA_prev, dW, db = None
### END CODE HERE ###
return dA_prev, dW, db
dAL, linear_activation_cache = linear_activation_backward_test_case()
dA_prev, dW, db = linear_activation_backward(dAL, linear_activation_cache, activation = "sigmoid")
print ("sigmoid:")
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db) + "\n")
dA_prev, dW, db = linear_activation_backward(dAL, linear_activation_cache, activation = "relu")
print ("relu:")
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db))
```
**Expected output with sigmoid:**
<table style="width:100%">
<tr>
<td > dA_prev </td>
<td >[[ 0.11017994 0.01105339]
[ 0.09466817 0.00949723]
[-0.05743092 -0.00576154]] </td>
</tr>
<tr>
<td > dW </td>
<td > [[ 0.10266786 0.09778551 -0.01968084]] </td>
</tr>
<tr>
<td > db </td>
<td > [[-0.05729622]] </td>
</tr>
</table>
**Expected output with relu:**
<table style="width:100%">
<tr>
<td > dA_prev </td>
<td > [[ 0.44090989 0. ]
[ 0.37883606 0. ]
[-0.2298228 0. ]] </td>
</tr>
<tr>
<td > dW </td>
<td > [[ 0.44513824 0.37371418 -0.10478989]] </td>
</tr>
<tr>
<td > db </td>
<td > [[-0.20837892]] </td>
</tr>
</table>
### 6.3 - L-Model Backward
Now you will implement the backward function for the whole network. Recall that when you implemented the `L_model_forward` function, at each iteration, you stored a cache which contains (X,W,b, and z). In the back propagation module, you will use those variables to compute the gradients. Therefore, in the `L_model_backward` function, you will iterate through all the hidden layers backward, starting from layer $L$. On each step, you will use the cached values for layer $l$ to backpropagate through layer $l$. Figure 5 below shows the backward pass.
<img src="images/mn_backward.png" style="width:450px;height:300px;">
<caption><center> **Figure 5** : Backward pass </center></caption>
** Initializing backpropagation**:
To backpropagate through this network, we know that the output is,
$A^{[L]} = \sigma(Z^{[L]})$. Your code thus needs to compute `dAL` $= \frac{\partial \mathcal{L}}{\partial A^{[L]}}$.
To do so, use this formula (derived using calculus which you don't need in-depth knowledge of):
```python
dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # derivative of cost with respect to AL
```
You can then use this post-activation gradient `dAL` to keep going backward. As seen in Figure 5, you can now feed in `dAL` into the LINEAR->SIGMOID backward function you implemented (which will use the cached values stored by the L_model_forward function). After that, you will have to use a `for` loop to iterate through all the other layers using the LINEAR->RELU backward function. You should store each dA, dW, and db in the grads dictionary. To do so, use this formula :
$$grads["dW" + str(l)] = dW^{[l]}\tag{15} $$
For example, for $l=3$ this would store $dW^{[l]}$ in `grads["dW3"]`.
**Exercise**: Implement backpropagation for the *[LINEAR->RELU] $\times$ (L-1) -> LINEAR -> SIGMOID* model.
```
# GRADED FUNCTION: L_model_backward
def L_model_backward(AL, Y, caches):
"""
Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group
Arguments:
AL -- probability vector, output of the forward propagation (L_model_forward())
Y -- true "label" vector (containing 0 if non-cat, 1 if cat)
caches -- list of caches containing:
every cache of linear_activation_forward() with "relu" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)
the cache of linear_activation_forward() with "sigmoid" (it's caches[L-1])
Returns:
grads -- A dictionary with the gradients
grads["dA" + str(l)] = ...
grads["dW" + str(l)] = ...
grads["db" + str(l)] = ...
"""
grads = {}
L = len(caches) # the number of layers
m = AL.shape[1]
Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL
# Initializing the backpropagation
### START CODE HERE ### (1 line of code)
dAL = None
### END CODE HERE ###
# Lth layer (SIGMOID -> LINEAR) gradients. Inputs: "dAL, current_cache". Outputs: "grads["dAL-1"], grads["dWL"], grads["dbL"]
### START CODE HERE ### (approx. 2 lines)
current_cache = None
grads["dA" + str(L-1)], grads["dW" + str(L)], grads["db" + str(L)] = None
### END CODE HERE ###
# Loop from l=L-2 to l=0
for l in reversed(range(L-1)):
# lth layer: (RELU -> LINEAR) gradients.
# Inputs: "grads["dA" + str(l + 1)], current_cache". Outputs: "grads["dA" + str(l)] , grads["dW" + str(l + 1)] , grads["db" + str(l + 1)]
### START CODE HERE ### (approx. 5 lines)
current_cache = None
dA_prev_temp, dW_temp, db_temp = None
grads["dA" + str(l)] = None
grads["dW" + str(l + 1)] = None
grads["db" + str(l + 1)] = None
### END CODE HERE ###
return grads
AL, Y_assess, caches = L_model_backward_test_case()
grads = L_model_backward(AL, Y_assess, caches)
print_grads(grads)
```
**Expected Output**
<table style="width:60%">
<tr>
<td > dW1 </td>
<td > [[ 0.41010002 0.07807203 0.13798444 0.10502167]
[ 0. 0. 0. 0. ]
[ 0.05283652 0.01005865 0.01777766 0.0135308 ]] </td>
</tr>
<tr>
<td > db1 </td>
<td > [[-0.22007063]
[ 0. ]
[-0.02835349]] </td>
</tr>
<tr>
<td > dA1 </td>
<td > [[ 0.12913162 -0.44014127]
[-0.14175655 0.48317296]
[ 0.01663708 -0.05670698]] </td>
</tr>
</table>
### 6.4 - Update Parameters
In this section you will update the parameters of the model, using gradient descent:
$$ W^{[l]} = W^{[l]} - \alpha \text{ } dW^{[l]} \tag{16}$$
$$ b^{[l]} = b^{[l]} - \alpha \text{ } db^{[l]} \tag{17}$$
where $\alpha$ is the learning rate. After computing the updated parameters, store them in the parameters dictionary.
**Exercise**: Implement `update_parameters()` to update your parameters using gradient descent.
**Instructions**:
Update parameters using gradient descent on every $W^{[l]}$ and $b^{[l]}$ for $l = 1, 2, ..., L$.
```
# GRADED FUNCTION: update_parameters
def update_parameters(parameters, grads, learning_rate):
"""
Update parameters using gradient descent
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients, output of L_model_backward
Returns:
parameters -- python dictionary containing your updated parameters
parameters["W" + str(l)] = ...
parameters["b" + str(l)] = ...
"""
L = len(parameters) // 2 # number of layers in the neural network
# Update rule for each parameter. Use a for loop.
### START CODE HERE ### (≈ 3 lines of code)
for l in range(L):
parameters["W" + str(l+1)] = None
parameters["b" + str(l+1)] = None
### END CODE HERE ###
return parameters
parameters, grads = update_parameters_test_case()
parameters = update_parameters(parameters, grads, 0.1)
print ("W1 = "+ str(parameters["W1"]))
print ("b1 = "+ str(parameters["b1"]))
print ("W2 = "+ str(parameters["W2"]))
print ("b2 = "+ str(parameters["b2"]))
```
**Expected Output**:
<table style="width:100%">
<tr>
<td > W1 </td>
<td > [[-0.59562069 -0.09991781 -2.14584584 1.82662008]
[-1.76569676 -0.80627147 0.51115557 -1.18258802]
[-1.0535704 -0.86128581 0.68284052 2.20374577]] </td>
</tr>
<tr>
<td > b1 </td>
<td > [[-0.04659241]
[-1.28888275]
[ 0.53405496]] </td>
</tr>
<tr>
<td > W2 </td>
<td > [[-0.55569196 0.0354055 1.32964895]]</td>
</tr>
<tr>
<td > b2 </td>
<td > [[-0.84610769]] </td>
</tr>
</table>
## 7 - Conclusion
Congrats on implementing all the functions required for building a deep neural network!
We know it was a long assignment but going forward it will only get better. The next part of the assignment is easier.
In the next assignment you will put all these together to build two models:
- A two-layer neural network
- An L-layer neural network
You will in fact use these models to classify cat vs non-cat images!
| github_jupyter |
# Analysis of Gray code vs one-hot tomography results for level 2 and level 3 optimization
```
import warnings
warnings.filterwarnings(action='once')
import numpy as np
np.warnings.filterwarnings('ignore')
import pickle
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
sns.set(rc={'figure.figsize':(16,8)})
trace_dists_gc_measmit = np.load("gray-code-tomo-noise-measmit-alloptlevels.npy")
trace_dists_oh_measmit = np.load("one-hot-tomo-noise-measmit-alloptlevels.npy")
min_trotter_steps = 1
max_trotter_steps = 100
T = 1
colours = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red']
fig, ax = plt.subplots(4, 1, sharex=True, sharey=True, figsize=(12, 16))
for opt_level in range(4):
ax[opt_level].scatter(range(min_trotter_steps, max_trotter_steps+1),
trace_dists_gc_measmit[opt_level,:],
color=colours[0], marker='o', label=f"GC")
ax[opt_level].scatter(range(min_trotter_steps, max_trotter_steps+1),
trace_dists_oh_measmit[opt_level,:],
color=colours[1], marker='x', label=f"OH")
ax[opt_level].set_xlabel("Trotter steps", fontsize=14)
ax[opt_level].set_ylabel("Trace distance", fontsize=14)
ax[opt_level].set_title(f"Opt. level {opt_level}", fontsize=14)
ax[opt_level].legend(fontsize=15)
plt.suptitle(f"Gray code, N=4, Hamiltonian evolution time t = {T}", fontsize=15)
plt.tight_layout()
#plt.savefig("FIG-REDONE-combined-measmit-tomography-hw-noise.pdf")
min_trotter_steps = 1
max_trotter_steps = 100
T = 1
sns.set(rc={'figure.figsize':(12,6)})
plt.rcParams['axes.facecolor'] = 'white'
sns.set_style('whitegrid')
plt.scatter(range(min_trotter_steps, max_trotter_steps+1),
np.log10(trace_dists_gc_measmit[2,:]), color=colours[0], marker='o', label=f"Gray code")
plt.scatter(range(min_trotter_steps, max_trotter_steps+1),
np.log10(trace_dists_oh_measmit[2,:]), color=colours[1], marker='x', label=f"One-hot")
plt.xticks(fontsize=13)
plt.yticks(fontsize=13)
plt.xlabel("Trotter steps", fontsize=14)
plt.ylabel("log10(Trace distance)", fontsize=14)
plt.legend(fontsize=15)
plt.title("Trace distance of N=4 Hamiltonian evolution of time t=1, Vigo noise model, 10000 shots (level 2)", fontsize=16)
plt.tight_layout()
plt.savefig("fig10b-level2.pdf")
plt.scatter(range(min_trotter_steps, max_trotter_steps+1),
np.log10(trace_dists_gc_measmit[3,:]), color=colours[0], marker='o', label=f"Gray code")
plt.scatter(range(min_trotter_steps, max_trotter_steps+1),
np.log10(trace_dists_oh_measmit[3,:]), color=colours[1], marker='x', label=f"One-hot")
plt.xticks(fontsize=13)
plt.yticks(fontsize=13)
plt.xlabel("Trotter steps", fontsize=14)
plt.ylabel("log10(Trace distance)", fontsize=14)
plt.legend(fontsize=15)
plt.title("Trace distance of N=4 Hamiltonian evolution of time t=1, Vigo noise model, 10000 shots (level 3)", fontsize=16)
plt.tight_layout()
plt.savefig("fig10c-level3.pdf")
```
| github_jupyter |
# k-Nearest Neighbor (kNN) implementation
*Credits: this notebook is deeply based on Stanford CS231n course assignment 1. Source link: http://cs231n.github.io/assignments2019/assignment1/*
The kNN classifier consists of two stages:
- During training, the classifier takes the training data and simply remembers it
- During testing, kNN classifies every test image by comparing to all training images and transfering the labels of the k most similar training examples
- The value of k is cross-validated
In this exercise you will implement these steps and understand the basic Image Classification pipeline and gain proficiency in writing efficient, vectorized code.
We will work with the handwritten digits dataset. Images will be flattened (8x8 sized image -> 64 sized vector) and treated as vectors.
```
'''
If you are using Google Colab, uncomment the next line to download `k_nearest_neighbor.py`.
You can open and change it in Colab using the "Files" sidebar on the left.
'''
# !wget https://raw.githubusercontent.com/girafe-ai/ml-mipt/basic_s20/homeworks_basic/assignment0_01_kNN/k_nearest_neighbor.py
from sklearn import datasets
dataset = datasets.load_digits()
print(dataset.DESCR)
# First 100 images will be used for testing. This dataset is not sorted by the labels, so it's ok
# to do the split this way.
# Please be careful when you split your data into train and test in general.
test_border = 100
X_train, y_train = dataset.data[test_border:], dataset.target[test_border:]
X_test, y_test = dataset.data[:test_border], dataset.target[:test_border]
print('Training data shape: ', X_train.shape)
print('Training labels shape: ', y_train.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
num_test = X_test.shape[0]
# Run some setup code for this notebook.
import random
import numpy as np
import matplotlib.pyplot as plt
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%matplotlib inline
plt.rcParams['figure.figsize'] = (14.0, 12.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# Some more magic so that the notebook will reload external python modules;
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
# Visualize some examples from the dataset.
# We show a few examples of training images from each class.
classes = list(np.arange(10))
num_classes = len(classes)
samples_per_class = 7
for y, cls in enumerate(classes):
idxs = np.flatnonzero(y_train == y)
idxs = np.random.choice(idxs, samples_per_class, replace=False)
for i, idx in enumerate(idxs):
plt_idx = i * num_classes + y + 1
plt.subplot(samples_per_class, num_classes, plt_idx)
plt.imshow(X_train[idx].reshape((8, 8)).astype('uint8'))
plt.axis('off')
if i == 0:
plt.title(cls)
plt.show()
```
Autoreload is a great stuff, but sometimes it does not work as intended. The code below aims to fix than. __Do not forget to save your changes in the `.py` file before reloading the `KNearestNeighbor` class.__
```
# This dirty hack might help if the autoreload has failed for some reason
try:
del KNearestNeighbor
except:
pass
from k_nearest_neighbor import KNearestNeighbor
# Create a kNN classifier instance.
# Remember that training a kNN classifier is a noop:
# the Classifier simply remembers the data and does no further processing
classifier = KNearestNeighbor()
classifier.fit(X_train, y_train)
X_train.shape
```
We would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps:
1. First we must compute the distances between all test examples and all train examples.
2. Given these distances, for each test example we find the k nearest examples and have them vote for the label
Lets begin with computing the distance matrix between all training and test examples. For example, if there are **Ntr** training examples and **Nte** test examples, this stage should result in a **Nte x Ntr** matrix where each element (i,j) is the distance between the i-th test and j-th train example.
**Note: For the three distance computations that we require you to implement in this notebook, you may not use the np.linalg.norm() function that numpy provides.**
First, open `k_nearest_neighbor.py` and implement the function `compute_distances_two_loops` that uses a (very inefficient) double loop over all pairs of (test, train) examples and computes the distance matrix one element at a time.
```
# Open k_nearest_neighbor.py and implement
# compute_distances_two_loops.
# Test your implementation:
dists = classifier.compute_distances_two_loops(X_test)
print(dists.shape)
# We can visualize the distance matrix: each row is a single test example and
# its distances to training examples
plt.imshow(dists, interpolation='none')
plt.show()
```
**Inline Question 1**
Notice the structured patterns in the distance matrix, where some rows or columns are visible brighter. (Note that with the default color scheme black indicates low distances while white indicates high distances.)
- What in the data is the cause behind the distinctly bright rows?
- What causes the columns?
$\color{blue}{\textit Your Answer:}$ *fill this in.*
```
# Now implement the function predict_labels and run the code below:
# We use k = 1 (which is Nearest Neighbor).
y_test_pred = classifier.predict_labels(dists, k=1)
# Compute and print the fraction of correctly predicted examples
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))
```
You should expect to see approximately `95%` accuracy. Now lets try out a larger `k`, say `k = 5`:
```
y_test_pred = classifier.predict_labels(dists, k=5)
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))
```
Accuracy should slightly decrease with `k = 5` compared to `k = 1`.
**Inline Question 2**
We can also use other distance metrics such as L1 distance.
For pixel values $p_{ij}^{(k)}$ at location $(i,j)$ of some image $I_k$,
the mean $\mu$ across all pixels over all images is $$\mu=\frac{1}{nhw}\sum_{k=1}^n\sum_{i=1}^{h}\sum_{j=1}^{w}p_{ij}^{(k)}$$
And the pixel-wise mean $\mu_{ij}$ across all images is
$$\mu_{ij}=\frac{1}{n}\sum_{k=1}^np_{ij}^{(k)}.$$
The general standard deviation $\sigma$ and pixel-wise standard deviation $\sigma_{ij}$ is defined similarly.
Which of the following preprocessing steps will not change the performance of a Nearest Neighbor classifier that uses L1 distance? Select all that apply.
1. Subtracting the mean $\mu$ ($\tilde{p}_{ij}^{(k)}=p_{ij}^{(k)}-\mu$.)
2. Subtracting the per pixel mean $\mu_{ij}$ ($\tilde{p}_{ij}^{(k)}=p_{ij}^{(k)}-\mu_{ij}$.)
3. Subtracting the mean $\mu$ and dividing by the standard deviation $\sigma$.
4. Subtracting the pixel-wise mean $\mu_{ij}$ and dividing by the pixel-wise standard deviation $\sigma_{ij}$.
5. Rotating the coordinate axes of the data.
$\color{blue}{\textit Your Answer:}$
$\color{blue}{\textit Your Explanation:}$
```
# Now lets speed up distance matrix computation by using partial vectorization
# with one loop. Implement the function compute_distances_one_loop and run the
# code below:
dists_one = classifier.compute_distances_one_loop(X_test)
# To ensure that our vectorized implementation is correct, we make sure that it
# agrees with the naive implementation. There are many ways to decide whether
# two matrices are similar; one of the simplest is the Frobenius norm. In case
# you haven't seen it before, the Frobenius norm of two matrices is the square
# root of the squared sum of differences of all elements; in other words, reshape
# the matrices into vectors and compute the Euclidean distance between them.
difference = np.linalg.norm(dists - dists_one, ord='fro')
print('One loop difference was: %f' % (difference, ))
if difference < 0.001:
print('Good! The distance matrices are the same')
else:
print('Uh-oh! The distance matrices are different')
# Now implement the fully vectorized version inside compute_distances_no_loops
# and run the code
dists_two = classifier.compute_distances_no_loops(X_test)
# check that the distance matrix agrees with the one we computed before:
difference = np.linalg.norm(dists - dists_two, ord='fro')
print('No loop difference was: %f' % (difference, ))
if difference < 0.001:
print('Good! The distance matrices are the same')
else:
print('Uh-oh! The distance matrices are different')
```
### Comparing handcrafted and `sklearn` implementations
In this section we will just compare the performance of handcrafted and `sklearn` kNN algorithms. The predictions should be the same. No need to write any code in this section.
```
from sklearn import neighbors
implemented_knn = KNearestNeighbor()
implemented_knn.fit(X_train, y_train)
n_neighbors = 1
external_knn = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors)
external_knn.fit(X_train, y_train)
print('sklearn kNN (k=1) implementation achieves: {} accuracy on the test set'.format(
external_knn.score(X_test, y_test)
))
y_predicted = implemented_knn.predict(X_test, k=n_neighbors).astype(int)
accuracy_score = sum((y_predicted==y_test).astype(float)) / num_test
print('Handcrafted kNN (k=1) implementation achieves: {} accuracy on the test set'.format(accuracy_score))
assert np.array_equal(
external_knn.predict(X_test),
y_predicted
), 'Labels predicted by handcrafted and sklearn kNN implementations are different!'
print('\nsklearn and handcrafted kNN implementations provide same predictions')
print('_'*76)
n_neighbors = 5
external_knn = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors)
external_knn.fit(X_train, y_train)
print('sklearn kNN (k=5) implementation achieves: {} accuracy on the test set'.format(
external_knn.score(X_test, y_test)
))
y_predicted = implemented_knn.predict(X_test, k=n_neighbors).astype(int)
accuracy_score = sum((y_predicted==y_test).astype(float)) / num_test
print('Handcrafted kNN (k=5) implementation achieves: {} accuracy on the test set'.format(accuracy_score))
assert np.array_equal(
external_knn.predict(X_test),
y_predicted
), 'Labels predicted by handcrafted and sklearn kNN implementations are different!'
print('\nsklearn and handcrafted kNN implementations provide same predictions')
print('_'*76)
```
### Measuring the time
Finally let's compare how fast the implementations are.
To make the difference more noticable, let's repeat the train and test objects (there is no point but to compute the distance between more pairs).
```
X_train_big = np.vstack([X_train]*5)
X_test_big = np.vstack([X_test]*5)
y_train_big = np.hstack([y_train]*5)
y_test_big = np.hstack([y_test]*5)
classifier_big = KNearestNeighbor()
classifier_big.fit(X_train_big, y_train_big)
# Let's compare how fast the implementations are
def time_function(f, *args):
"""
Call a function f with args and return the time (in seconds) that it took to execute.
"""
import time
tic = time.time()
f(*args)
toc = time.time()
return toc - tic
two_loop_time = time_function(classifier_big.compute_distances_two_loops, X_test_big)
print('Two loop version took %f seconds' % two_loop_time)
one_loop_time = time_function(classifier_big.compute_distances_one_loop, X_test_big)
print('One loop version took %f seconds' % one_loop_time)
no_loop_time = time_function(classifier_big.compute_distances_no_loops, X_test_big)
print('No loop version took %f seconds' % no_loop_time)
# You should see significantly faster performance with the fully vectorized implementation!
# NOTE: depending on what machine you're using,
# you might not see a speedup when you go from two loops to one loop,
# and might even see a slow-down.
```
The improvement seems significant. (On some hardware one loop version may take even more time, than two loop, but no loop should definitely be the fastest.
**Inline Question 3**
Which of the following statements about $k$-Nearest Neighbor ($k$-NN) are true in a classification setting, and for all $k$? Select all that apply.
1. The decision boundary (hyperplane between classes in feature space) of the k-NN classifier is linear.
2. The training error of a 1-NN will always be lower than that of 5-NN.
3. The test error of a 1-NN will always be lower than that of a 5-NN.
4. The time needed to classify a test example with the k-NN classifier grows with the size of the training set.
5. None of the above.
$\color{blue}{\textit Your Answer:}$
$\color{blue}{\textit Your Explanation:}$
### Submitting your work
To submit your work you need to log into Yandex contest (link will be provided later) and upload the `k_nearest_neighbor.py` file for the corresponding problem
| github_jupyter |
# prev
### test = 1:1
```
!cat /home/kesci/data/competition_A/train_set.csv | head -n 2
!cat /home/kesci/data/competition_A/test_set.csv | head -n 1
!./kesci_submit -token ***************** -file /home/kesci/work/sub.csv
```
# data_pre
## train
```
import pandas as pd
import gc
train = pd.read_csv('/home/kesci/data/competition_A/train_set.csv').replace(' ', -1).fillna(-1)
# print(train.columns)
# print(train.isnull().values.any())
# print(set(train['Gender\n性别'].values.tolist()))
train_group = train.groupby('护理来源')
del train
gc.collect()
# from sklearn.preprocessing import OneHotEncoder
# enc = OneHotEncoder(sparse = False)
# result = enc.fit_transform(train[['Source of Care\n护理来源']])
# enc.fit([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]])
# result = enc.transform(data[[41]])
dic_1 = {'Private Hospital':1, -1:2, 'Governament Hospital':3, 'Never Counsulted':4, 'clinic':5}
buf_1 = pd.DataFrame()
for name,group in train_group:
group['护理来源'] = dic_1[name]
buf_1 = pd.concat([buf_1,group],ignore_index=True)
dic_2 = {'F':1, 'M':2}
buf_1_group = buf_1.groupby('性别')
buf_2 = pd.DataFrame()
for name,group in buf_1_group:
group['性别'] = dic_2[name]
buf_2 = pd.concat([buf_2,group],ignore_index=True)
dic_3 = {'north':1, 'east':2, 'south':3, 'west':4}
buf_3 = pd.DataFrame()
buf_2_group = buf_2.groupby('区域')
for name,group in buf_2_group:
group['区域'] = dic_3[name]
buf_3 = pd.concat([buf_3,group],ignore_index=True)
buf_3 = buf_3.astype(float)
cat_list = ['肥胖腰围',
'教育', '未婚',
'护理来源', '视力不佳',
'饮酒', '高血压',
'家庭高血压', '糖尿病',
'家族糖尿病', '肝炎', '家族肝炎',
'慢性疲劳']
for i in cat_list:
buf_3[i] = buf_3[i].astype(int)
buf_3.to_csv('train_.csv',index=0)
```
## test
```
import pandas as pd
import gc
train = pd.read_csv('/home/kesci/data/competition_A/test_set.csv').replace(' ', -1).fillna(-1)
# print(train.columns)
# print(train.isnull().values.any())
# print(set(train['Gender\n性别'].values.tolist()))
train_group = train.groupby('护理来源')
del train
gc.collect()
# from sklearn.preprocessing import OneHotEncoder
# enc = OneHotEncoder(sparse = False)
# result = enc.fit_transform(train[['Source of Care\n护理来源']])
# enc.fit([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]])
# result = enc.transform(data[[41]])
dic_1 = {'Private Hospital':1, -1:2, 'Governament Hospital':3, 'Never Counsulted':4, 'clinic':5}
buf_1 = pd.DataFrame()
for name,group in train_group:
group['护理来源'] = dic_1[name]
buf_1 = pd.concat([buf_1,group],ignore_index=True)
dic_2 = {'F':1, 'M':2}
buf_1_group = buf_1.groupby('性别')
buf_2 = pd.DataFrame()
for name,group in buf_1_group:
group['性别'] = dic_2[name]
buf_2 = pd.concat([buf_2,group],ignore_index=True)
dic_3 = {'north':1, 'east':2, 'south':3, 'west':4}
buf_3 = pd.DataFrame()
buf_2_group = buf_2.groupby('区域')
for name,group in buf_2_group:
group['区域'] = dic_3[name]
buf_3 = pd.concat([buf_3,group],ignore_index=True)
buf_3 = buf_3.astype(float)
cat_list = ['肥胖腰围',
'教育', '未婚',
'护理来源', '视力不佳',
'饮酒', '高血压',
'家庭高血压', '糖尿病',
'家族糖尿病', '家族肝炎',
'慢性疲劳']
for i in cat_list:
buf_3[i] = buf_3[i].astype(int)
buf_3.to_csv('test_.csv',index=0)
```
# ctb
```
from catboost import CatBoostClassifier,CatBoostRegressor
import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
data = pd.read_csv('train_.csv').sort_values(by=['肝炎'])
train_ = data.drop(columns=['ID','肝炎'])
label_ = data['肝炎']
train, val, label, val_label = train_test_split(train_,label_,test_size=0.1, random_state=1234)
categorical_features_indices = np.where(train.dtypes != np.float)[0]
categorical_features_indices
model = CatBoostClassifier(iterations=1,
depth=10,
one_hot_max_size=10,
cat_features=categorical_features_indices,
loss_function='Logloss',
eval_metric='AUC',
logging_level='Verbose',)
model.fit(train,label,eval_set=(val, val_label),plot=True)
import matplotlib.pyplot as plt
from matplotlib import cm
%matplotlib inline
score = pd.DataFrame()
score['fea_name'] = model.feature_names_
score['fea']=model.feature_importances_
score = score.sort_values(['fea'], ascending=False)
temp = pd.DataFrame()
temp = score[:60]
color = cm.jet(temp['fea']/temp['fea'].max())
plt.figure(figsize=(10, 15))
plt.barh(temp['fea_name'],temp['fea'],height =0.8,color=color,alpha=0.8)
plt.show()
test_ = pd.read_csv('test_.csv')
ans = model.predict(test_.drop(columns=['ID']))
ans.mean()
ans.shape
ans_sub = pd.DataFrame({'ID':test_['ID'].astype(int),'hepatitis':ans.astype(int)})
set(ans.tolist())
ans_sub.to_csv('sub.csv',index=0)
```
| github_jupyter |
# Using `tables_io.TableDict`
The class `tables_io.TableDict` is just an Ordered Dictionary of Tables.
The Tables can be in any of the formats that `tables_io` supports, see more on that in the notebook below.
Let's have a look
```
# Standard imports
import os
import numpy as np
import tables_io
from tables_io.testUtils import make_test_data
```
### Some test data.
Ok, lets make some test data and have a look at it
```
data = make_test_data()
data
```
### Building a table dict
We can using any Mapping (i.e., something that allows use to iterate over key-value pairs) to build a `TableDict`.
So lets make a `TableDict`
```
td = tables_io.TableDict(data)
td
```
`TableDict` inherits from the `collections.OrderedDict` class, so it has the standard interface for python dictionaries
```
td.keys()
td['data']
td['md']
```
### `TableDict` will not take non tables
```
try:
td['bad'] = 'a'
except TypeError as msg:
print("Caught attempt to add non table to TableDict: %s" % msg)
```
# Supported Table types and converting between them
`TableDict` supports several different types of tables. These include:
1. astropy Tables: `astropy.table.Table` objects
2. Mapping of `str`, `numpy.array`
3. pandas DataFrames: `pandas.DataFrame` objects
Let's convert to each of these
```
td_ap = td.convert(tables_io.types.AP_TABLE)
td_ap
td_np = td.convert(tables_io.types.NUMPY_DICT)
td_np
td_pd = td.convert(tables_io.types.PD_DATAFRAME)
td_pd
```
# File IO with `TableDict`
We can write tables into several different formats. These include:
1. fits: Writing `astropy.table.Table` objects to FITS files (with the suffix 'fits')
2. hf5: Writing `astropy.table.Table` objects to HDF5 files (with the suffix 'hf5')
3. hfd5: Writing `numpy.array` objects to HDF5 files (with the suffix 'hdf5')
4. h5: Writing `pandas.DataFrame` objects to HDF5 files (with the suffix 'h5')
5. pq: Writing `pandas.DataFrame` objects to parquet files (with the suffix 'pq')
Also, each table type has a 'native' format that we use as a default. Setting the `fmt` to `None` in function calls will typically use the 'native' format.
```
all_fmts = list(tables_io.types.FILE_FORMAT_SUFFIXS.keys()) + [None]
print(all_fmts)
```
# Ok let's write the data to different files
```
for fmt in all_fmts:
if fmt is None:
basename = 'test_native'
else:
basename = 'test_out'
print("Writing to %s using format %s" % (basename, fmt))
try:
os.unlink('%s.%s' % (basename, fmt))
except:
pass
try:
td.write(basename, fmt)
except ImportError as msg:
print("Skipping format %s because %s" % (fmt, msg))
! ls test_*
```
# Ok, now let's read things back
```
td_r_fits = tables_io.TableDict.read("test_out.fits")
td_r_fits
td_r_hdf5 = tables_io.TableDict.read("test_out.hdf5")
td_r_hdf5
td_r_hf5 = tables_io.TableDict.read("test_out.hf5")
td_r_hf5
td_r_pq = tables_io.TableDict.read("test_out.pq", keys=list(td.keys()))
td_r_pq
td_r_h5 = tables_io.TableDict.read("test_out.h5")
td_r_h5
td_native = tables_io.TableDict.read("test_out.hf5")
td_native
```
| github_jupyter |
```
%pylab inline
%load_ext autoreload
%autoreload 2
import os
import sprinter
import getpass
qfib_dir = '/home/'+getpass.getuser()+'/Dropbox/TRAKODATA/qfib-data/'
qfib_ext = '.tck'
dpy_dir = '/home/'+getpass.getuser()+'/Dropbox/TRAKODATA/qfib-data/'
dpy_ext = '.tck'
tko_dir = '/home/'+getpass.getuser()+'/Dropbox/TRAKODATA/qfib-data/'
tko_ext = '.vtk'
files = '''/home/d/Downloads/tracto60kiFOD10.1.tck,/home/d/Downloads/tracto60kSD_STREAM0.1.tck,
/home/d/Downloads/tracto60kiFOD10.2.tck,/home/d/Downloads/tracto60kSD_STREAM0.2.tck,
/home/d/Downloads/tracto60kiFOD10.5.tck,/home/d/Downloads/tracto60kSD_STREAM0.5.tck,
/home/d/Downloads/tracto60kiFOD11.tck,/home/d/Downloads/tracto60kSD_STREAM1.tck'''
files = files.replace('/home/d/Downloads/','').replace('.tck','').replace('\n','').split(',')
# files = files[0:2]
input_size = 0
for f in files:
print(os.path.join(tko_dir, f+tko_ext), os.path.getsize(os.path.join(tko_dir, f+tko_ext)))
input_size += os.path.getsize(os.path.join(tko_dir, f+tko_ext))
input_size /= float(len(files))
qfib_files = [(qfib_dir, f+qfib_ext) for f in files]
qfib_bits = [8, 16]
tko_files = [(tko_dir, f+tko_ext) for f in files]
tko_bits = [9,10]
dpy_files = [(dpy_dir, f+dpy_ext) for f in files]
files
dpy_sizes, dpy_errors, dpy_stds, dpy_advstats = sprinter.Sprinter.run_dpy(qfib_files)
qfib_sizes, qfib_errors, qfib_stds, qfib_advstats = sprinter.Sprinter.run_qfib(qfib_files, qfib_bits)
runs = {}
config = {
'POSITION': {
'position':True,
'sequential':True,
'quantization_bits':None,
'compression_level':10,
'quantization_range':-1,
'quantization_origin':None
},
'INDICES': {
'position':False,
'sequential':True,
'quantization_bits':None,
'compression_level':10,
'quantization_range':-1,
'quantization_origin':None
},
'name': 'qbi{bits}'
}
tko_sizes, tko_errors, tko_stds, tko_advstats = sprinter.Sprinter.run_trako(config, tko_files, tko_bits, binary=False)
runs[config['name']] = [tko_sizes, tko_errors, tko_stds, tko_advstats]
config = {
'POSITION': {
'position':True,
'sequential':True,
'quantization_bits':None,
'compression_level':10,
'quantization_range':-1,
'quantization_origin':None
},
'INDICES': {
'position':False,
'sequential':True,
'quantization_bits':None,
'compression_level':10,
'quantization_range':-1,
'quantization_origin':None
},
'name': 'qbi{bits}_binary'
}
tko_sizes, tko_errors, tko_stds, tko_advstats = sprinter.Sprinter.run_trako(config, tko_files, tko_bits, binary=True)
runs[config['name']] = [tko_sizes, tko_errors, tko_stds, tko_advstats]
# sprinter.Sprinter.bitsplot(plt, tkoruns=runs, qfibruns=[qfib_sizes, qfib_errors, qfib_stds], ylim=(0,1), filename='/tmp/out.pdf')
sprinter.Sprinter.bitsplot(plt, tkoruns=runs, filename='/tmp/qfib_full.pdf')
print(input_size/1000000)
qfib_sizes, qfib_errors, qfib_stds, qfib_advstats = sprinter.Sprinter.run_qfib(qfib_files, qfib_bits)
sprinter.Sprinter.createtable('qfib-data', input_size, {'qfib': [qfib_sizes, qfib_errors, qfib_stds, qfib_advstats]}, selector=1)
sprinter.Sprinter.createtable('qfib-data', input_size, {'dpy': [dpy_sizes, dpy_errors, dpy_stds, dpy_advstats]}, selector=0)
sprinter.Sprinter.createtable('qfib-data', input_size, runs, selector=1)
DATASETNAME = 'qfib-data'
import collections
all_runs = collections.OrderedDict()
all_runs['qfib (8bit)'] = [0, qfib_sizes, qfib_errors, qfib_stds, qfib_advstats]
all_runs['qfib (16bit)'] = [1, qfib_sizes, qfib_errors, qfib_stds, qfib_advstats]
all_runs['zfib'] = [0, dpy_sizes, dpy_errors, dpy_stds, dpy_advstats]
for r in runs.keys():
all_runs[r] = [1] + runs[r]
sprinter.Sprinter.createfulltable(DATASETNAME, input_size, all_runs)
```
| github_jupyter |
# Amazon SageMaker Notebook for ProcGen Starter Kit with homogeneous scaling of multiple CPU instances
```
import os
import time
import yaml
import sagemaker
from sagemaker.rl import RLEstimator, RLToolkit, RLFramework
import boto3
from IPython.display import HTML, Markdown
from source.common.docker_utils import build_and_push_docker_image
from source.common.markdown_helper import generate_help_for_s3_endpoint_permissions, create_s3_endpoint_manually
with open(os.path.join("config", "sagemaker_config.yaml")) as f:
sagemaker_config = yaml.safe_load(f)
```
## Initialize Amazon SageMaker
```
sm_session = sagemaker.session.Session()
s3_bucket = sagemaker_config["S3_BUCKET"]
s3_output_path = 's3://{}/'.format(s3_bucket)
print("S3 bucket path: {}".format(s3_output_path))
job_name_prefix = 'sm-ray-cpu-distributed-procgen'
role = sagemaker.get_execution_role()
print(role)
```
#### Note that `local_mode = True` does not work with heterogeneous scaling
```
instance_type = sagemaker_config["CPU_TRAINING_INSTANCE"]
```
# Configure the framework you want to use
Set `framework` to `"tf"` or `"torch"` for tensorflow or pytorch respectively.
You will also have to edit your entry point i.e., `train-sagemaker-distributed-cpu.py` with the configuration parameter `"use_pytorch"` to match the framework that you have selected.
```
framework = "tf"
```
# Train your homogeneous scaling job here
### Edit the training code
The training code is written in the file `train-sagemaker-distributed-cpu.py` which is uploaded in the /source directory.
*Note that ray will automatically set `"ray_num_cpus"` and `"ray_num_gpus"` in `_get_ray_config`*
```
!pygmentize source/train-sagemaker-distributed-cpu.py
```
### Train the RL model using the Python SDK Script mode
When using SageMaker for distributed training, you can select a GPU or CPU instance. The RLEstimator is used for training RL jobs.
1. Specify the source directory where the environment, presets and training code is uploaded.
2. Specify the entry point as the training code
3. Specify the image (CPU or GPU) to be used for the training environment.
4. Define the training parameters such as the instance count, job name, S3 path for output and job name.
5. Define the metrics definitions that you are interested in capturing in your logs. These can also be visualized in CloudWatch and SageMaker Notebooks.
#### CPU docker image
```
# Build CPU image
cpu_repository_short_name = "sagemaker-procgen-ray-%s" % "cpu"
docker_build_args = {
'CPU_OR_GPU': "cpu",
'AWS_REGION': boto3.Session().region_name,
'FRAMEWORK': framework
}
image_name = build_and_push_docker_image(cpu_repository_short_name, build_args=docker_build_args)
print("Using CPU ECR image %s" % image_name)
metric_definitions = [
{'Name': 'training_iteration', 'Regex': 'training_iteration: ([-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?)'},
{'Name': 'episodes_total', 'Regex': 'episodes_total: ([-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?)'},
{'Name': 'num_steps_trained', 'Regex': 'num_steps_trained: ([-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?)'},
{'Name': 'timesteps_total', 'Regex': 'timesteps_total: ([-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?)'},
{'Name': 'training_iteration', 'Regex': 'training_iteration: ([-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?)'},
{'Name': 'episode_reward_max', 'Regex': 'episode_reward_max: ([-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?)'},
{'Name': 'episode_reward_mean', 'Regex': 'episode_reward_mean: ([-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?)'},
{'Name': 'episode_reward_min', 'Regex': 'episode_reward_min: ([-+]?[0-9]*[.]?[0-9]+([eE][-+]?[0-9]+)?)'},
]
```
### Ray homogeneous scaling - Specify `train_instance_count` > 1
Homogeneous scaling allows us to use multiple instances of the same type.
Spot instances are unused EC2 instances that could be used at 90% discount compared to On-Demand prices (more information about spot instances can be found [here](https://aws.amazon.com/ec2/spot/?cards.sort-by=item.additionalFields.startDateTime&cards.sort-order=asc) and [here](https://docs.aws.amazon.com/sagemaker/latest/dg/model-managed-spot-training.html))
To use spot instances, set `train_use_spot_instances = True`. To use On-Demand instances, `train_use_spot_instances = False`.
```
train_instance_count = 2
train_use_spot_instances = False
# Select which procgen environments to run in `envs_to_run`
'''
envs_to_run = ["coinrun", "bigfish", "bossfight", "caveflyer",
"chaser", "climber", "coinrun", "dodgeball",
"fruitbot", "heist", "jumper", "leaper", "maze",
"miner", "ninja", "plunder", "starpilot"]
'''
envs_to_run = ["coinrun"]
for env in envs_to_run:
if train_use_spot_instances:
print('*** Using spot instances ... ')
job_name = 'sm-ray-distributed-procgen-spot-' + time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime()) + "-" + env
checkpoint_s3_uri = 's3://{}/sagemaker-procgen/checkpoints/{}'.format(s3_bucket, job_name)
training_params = {"train_use_spot_instances": True,
"train_max_run": 3600 * 5,
"train_max_wait": 7200 * 5,
"checkpoint_s3_uri": checkpoint_s3_uri
}
hyperparameters = {
"rl.training.upload_dir": checkpoint_s3_uri, #Necessary for syncing between spot instances
"rl.training.config.env_config.env_name": env,
}
else:
training_params = {"base_job_name": job_name_prefix + "-" + env}
hyperparameters = {
#"rl.training.upload_dir": s3_output_path + "/tensorboard_sync", # Uncomment to view tensorboard
"rl.training.config.env_config.env_name": env,
}
# Defining the RLEstimator
estimator = RLEstimator(entry_point="train-sagemaker-distributed-cpu.py",
source_dir='source',
dependencies=["source/utils", "source/common/", "neurips2020-procgen-starter-kit/"],
image_uri=image_name,
role=role,
instance_type=instance_type,
instance_count=train_instance_count,
output_path=s3_output_path,
metric_definitions=metric_definitions,
hyperparameters=hyperparameters,
**training_params
)
if train_use_spot_instances:
estimator.fit(job_name=job_name, wait=False)
else:
estimator.fit(wait=False)
print(' ')
print(estimator.latest_training_job.job_name)
print('type=', instance_type, 'count=', train_instance_count )
print(' ')
```
| github_jupyter |
# NOAA HRES Optimum Interpolated V2 SST Data (Daily Update)
```
%matplotlib inline
#using xarray for data read
import xarray as xa
#using Cartopy for mapping
import matplotlib.pyplot as plt
import cmocean
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.io import shapereader
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
def make_map(projection=ccrs.PlateCarree()):
fig, ax = plt.subplots(figsize=(13, 8),
subplot_kw=dict(projection=projection))
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
return fig, ax
land_50m = cfeature.NaturalEarthFeature('physical', 'land', '50m',
edgecolor='face',
facecolor='1.0')
import datetime
print("Last run {0}".format(datetime.datetime.now()))
```
## Last 7 Days
```
year = '2018'
threddspath='https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2.highres/sst.day.mean.'+year+'.v2.nc'
cmap = cmocean.cm.thermal
with xa.open_dataset(threddspath) as xadf:
pd = xadf.isel(time=slice(-7,None), lat=slice(-180,-45), lon=slice(-750,-500)) #last seven days
facet = pd['sst'].plot(x='lon', y='lat', col='time',col_wrap=7,robust=True,figsize=(14,2),cmap=cmap)
threddspath='https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2.highres/sst.day.anom.'+year+'.v2.nc'
cmap = cmocean.cm.thermal
with xa.open_dataset(threddspath) as xadf:
pd = xadf.isel(time=slice(-7,None), lat=slice(-180,-45), lon=slice(-750,-500)) #last seven days
facet = pd['anom'].plot(x='lon', y='lat', col='time',col_wrap=7,robust=True,figsize=(14,2))
threddspath='https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2.highres/sst.day.err.'+year+'.v2.nc'
cmap = cmocean.cm.thermal
with xa.open_dataset(threddspath) as xadf:
pd = xadf.isel(time=slice(-7,None), lat=slice(-180,-45), lon=slice(-750,-500)) #last seven days
facet = pd['err'].plot(x='lon', y='lat', col='time',col_wrap=7,robust=True,figsize=(14,2))
threddspath='https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2.highres/icec.day.mean.'+year+'.v2.nc'
cmap = cmocean.cm.ice
with xa.open_dataset(threddspath) as xadf:
pd = xadf.isel(time=slice(-7,None), lat=slice(-180,-45), lon=slice(-750,-500)) #last seven days
facet = pd['icec'].plot(x='lon', y='lat', col='time',col_wrap=7,robust=True,figsize=(14,2),cmap=cmap)
```
## Last Day
```
extent = [-180, -135, 45, 75]
threddspath='https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2.highres/sst.day.mean.'+year+'.v2.nc'
cmap = cmocean.cm.thermal
with xa.open_dataset(threddspath) as xadf:
fig,ax = make_map(projection=ccrs.PlateCarree(-160))
xadf['sst'].isel(time=-1,lat=slice(-180,-45),lon=slice(-750,-500)).plot(x='lon', y='lat',robust=True,ax=ax, transform=ccrs.PlateCarree(),cmap=cmap)
ax.add_feature(land_50m)
ax.coastlines(resolution='50m')
ax.set_extent(extent)
threddspath='https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2.highres/sst.day.anom.'+year+'.v2.nc'
with xa.open_dataset(threddspath) as xadf:
fig,ax = make_map(projection=ccrs.PlateCarree(-160))
xadf['anom'].isel(time=-1,lat=slice(-180,-45),lon=slice(-750,-500)).plot(x='lon', y='lat',robust=True,ax=ax, transform=ccrs.PlateCarree())
ax.add_feature(land_50m)
ax.coastlines(resolution='50m')
ax.set_extent(extent)
threddspath='https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2.highres/icec.day.mean.'+year+'.v2.nc'
cmap = cmocean.cm.ice
with xa.open_dataset(threddspath) as xadf:
fig,ax = make_map(projection=ccrs.PlateCarree(-160))
xadf['icec'].isel(time=-1,lat=slice(-180,-45),lon=slice(-750,-500)).plot(x='lon', y='lat',
robust=True,ax=ax,
transform=ccrs.PlateCarree(),
cmap=cmap)
ax.add_feature(land_50m)
ax.coastlines(resolution='50m')
ax.set_extent(extent)
threddspath='https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/noaa.oisst.v2.highres/sst.day.err.'+year+'.v2.nc'
cmap = cmocean.cm.amp
with xa.open_dataset(threddspath) as xadf:
fig,ax = make_map(projection=ccrs.PlateCarree(-160))
xadf['err'].isel(time=-1,lat=slice(-180,-45),lon=slice(-750,-500)).plot(x='lon', y='lat',
robust=True,ax=ax,
transform=ccrs.PlateCarree(),
cmap=cmap)
ax.add_feature(land_50m)
ax.coastlines(resolution='50m')
ax.set_extent(extent)
```
| github_jupyter |
# Keras's Finetune
keras 实现线性模型
```
from utils import *
from keras.optimizers import SGD, RMSprop, Adam
x = random((30, 2))
x[:3]
y = x.dot([2., 3.]) + 1.
y[:3]
lm = Sequential([Dense(1, input_shape=(2,))])
lm.compile(optimizer=SGD(lr=.1), loss='mse')
lm.fit(x, y, nb_epoch=10, batch_size=1)
lm.get_weights()
```
VGG change
```
import vgg16
from vgg16 import Vgg16
vgg = Vgg16()
# path = 'data/redux/'
path = 'data/redux/sample/'
model_path = path + 'models/'
BATCH_SIZE = 8
val_batches = get_batches(path + 'valid', shuffle=False, batch_size=BATCH_SIZE)
batches = get_batches(path + 'train', shuffle=False, batch_size=BATCH_SIZE)
#batches.nb_sample
#batches.next()
import bcolz
def save_array(fname, arr): c=bcolz.carray(arr, rootdir=fname, mode='w'); c.flush()
def load_array(fname): return bcolz.open(fname)[:]
def onehot(x): return np.array(OneHotEncoder().fit_transform(x.reshape(-1,1)).todense())
# val_batches
# val_data = get_data(path + 'valid')
# trn_data = get_data(path + 'train')
# save_array(model_path + 'train_data.bc', trn_data)
# save_array(model_path + 'valid_data.bc', val_data)
# trn_data = load_array(model_path + 'train_data.bc')
# val_data = load_array(model_path + 'valid_data.bc')
# trn_data.shape
val_classes = val_batches.classes
trn_classes = batches.classes
val_labels = onehot(val_classes)
trn_labels = onehot(trn_classes)
trn_labels.shape
# trn_features = model.predict(trn_data, batch_size=BATCH_SIZE)
# trn_features
# val_features = model.predict(val_data, batch_size=BATCH_SIZE)
# val_features
val_features = vgg.model.predict_generator(val_batches, val_batches.nb_sample)
val_features.shape
trn_features = vgg.model.predict_generator(batches, batches.nb_sample)
trn_features.shape
# vgg.compile()
# vgg.fit(batches, val_batches, nb_epoch=1)
save_array(model_path + 'train_lastlayer_features.bc', trn_features)
save_array(model_path + 'valid_lastlayer_features.bc', val_features)
trn_features = load_array(model_path + 'train_lastlayer_features.bc')
val_features = load_array(model_path + 'valid_lastlayer_features.bc')
lm = Sequential([Dense(2, activation='softmax', input_shape=(1000, ))])
lm.compile(optimizer=RMSprop(lr=.1), loss='categorical_crossentropy', metrics=['accuracy'])
lm.fit(trn_features, trn_labels, nb_epoch=3, batch_size=BATCH_SIZE, validation_data=(val_features, val_labels))
lm.fit(trn_features, trn_labels, nb_epoch=6, batch_size=BATCH_SIZE, validation_data=(val_features, val_labels))
lm.summary()
vgg.model.pop()
for layer in vgg.model.layers: layer.trainable=False
vgg.model.add(Dense(2, activation='softmax'))
# gen=image.ImageDataGenerator()
# batches = gen.flow(trn_data, trn_labels, batch_size=BATCH_SIZE, shuffle=True)
# val_batches = gen.flow(val_data, val_labels,)
def fit_model(model, batches, val_batches, nb_epoch=1):
model.fit_generator(batches, samples_per_epoch=batches.nb_sample, nb_epoch=nb_epoch, validation_data=val_batches, nb_val_samples=val_batches.nb_sample)
opt = RMSprop(lr=.1)
vgg.model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
fit_model(vgg.model, batches, val_batches, nb_epoch=3)
```
| github_jupyter |
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
# Train your own Model and Deploy to Device
**NOTE**
* Warning: copying *.pb, *.bin, or, *.blob using the web interface can corrupt the files. If needed download and use Azure storage explorer or the CL.
* You can run all the cells (after you manually do the first one), but do note that the deployment ones will require some input specific to your device.
This notebook shows how to create a Tensorflow object detection model, how to convert the model to the appropriate format for the Perception Development
Kit, and how to deploy the model to your kit.
This notebook takes a transfer learning approach, using a pre-trained Tensorflow Mobilenet model with custom dataset
and SSDLite layers that we will train to detect bowls.
We use the [Tensorflow object detection API](https://github.com/tensorflow/models/tree/master/research/object_detection).
The trained model will be deployed to the Azure Percept Devkit using the Module Twin Update method.
# Setting up the GPU for Tensorflow 1.15
We will be using Tensorflow 1.15 for this example, and Tensorflow 2.x examples should be coming soon.
The datascience notebook VMs do not come with the appropriate libraries installed for this version of Tensorflow, and so we will need to
install them. If your compute node/cluster is a GPU machine, you will want to make sure the appropriate version of CUDA is installed
into your VM so that Tensorflow can use it to accelerate training substantially.
If you are using a GPU-enabled compute device, you will want to follow these steps. Otherwise, feel free to skip this cell.
1. Start your compute instance if it is not already started.
1. Select Open Terminal, which should be a button next to your compute and kernel selection boxes.
1. Run `conda info -e` to list the available conda environments. There should be an azureml_py36 environment.
1. Select azureml_py36 by running `conda activate azureml_py36`
1. Uninstall Pytorch and Tensorflow (which depend on the wrong version of CUDA) and the wrong version of CUDA with `conda uninstall cudatoolkit pytorch`
1. Install the correct version of CUDA with `conda install cudatoolkit=10.0`
You may now close the terminal tab. We will install Tensorflow in a cell of this notebook later.
## Collecting the data
In this notebook, we use a custom dataset that will be used to train a model that detects bowls.
To compile this dataset, we have a couple of options. First, we could use a labeling tool like [VoTT](https://github.com/microsoft/VoTT) or
[LabelImg](https://github.com/tzutalin/labelImg). Just make sure to export the dataset to Pascal VOC format. There should be one XML file for
each image, and the XML files should be under annotations/xmls.
The other option for compiling a dataset is to use an already existing dataset like COCO and then filter out all the images and annotations
that we don't care about. This is the approach we take here.
**NOTE:**
The first cell in this notebook contains the code necessary to get the dataset and convert it to the format we need. This will involve downloading
the entire COCO dataset (train and validation splits for 2017), which is tens of GBs in size. This may not fit in your Azure ML compute's storage.
Our recommendation is to run this cell locally (i.e., copy and paste the commands into your own shell and run them), then upload
the resulting dataset to Azure via [Azure Storage Explorer](https://azure.microsoft.com/en-us/features/storage-explorer/).
```
# Install tqdm for Python:
# pip install --user tqdm
# First, get the Advanced Code Repository
#!wget https://github.com/microsoft/azure-percept-advanced-development/archive/main.zip -O azure-percept-advanced-development-main.zip
#!unzip azure-percept-advanced-development-main.zip
#!rm azure-percept-advanced-development-main.zip
#!cd azure-percept-advanced-development-main/machine-learning-notebooks/transfer-learning/scripts
# Get the data
#!mkdir -p coco/images
# Get the 2017 training split
#!wget http://images.cocodataset.org/zips/train2017.zip
#!unzip train2017.zip
#!rm train2017.zip
#!mv train2017 coco/images/
# Get the 2017 validation split
#!wget http://images.cocodataset.org/zips/val2017.zip
#!unzip val2017.zip
#!rm val2017.zip
#!mv val2017 coco/images/
# Get all the annotations
#!wget http://images.cocodataset.org/annotations/annotations_trainval2017.zip
#!unzip annotations_trainval2017.zip
#!rm annotations_trainval2017.zip
#!mv annotations coco/annotations
# Filter the annotations down to a JSON that only contains images that contain at least one bowl
#!python filter_coco.py -i coco/annotations/instances_train2017.json -o coco_train2017_bowls.json -c bowl
#!python filter_coco.py -i coco/annotations/instances_val2017.json -o coco_val2017_bowls.json -c bowl
# Now create a filtered version of the coco train and val split based on their annotation JSONs
#!python create_coco_subset.py -i coco_train2017_bowls.json coco_val2017_bowls.json -g coco/images/train2017 coco/images/val2017 -o coco_filtered
# Create Pascal VOC formatted dataset from the COCO subset
#!python convert_coco_to_voc.py coco_filtered --target bowls_voc
# You should now have a data folder called bowls_voc, which should look like this:
# bowls_voc/
# - annotations/
# - xmls/
# - images/
# Now upload 'bowls_voc' to your workspace using the Azure Storage Explorer.
# To do so, please follow these instructions:
# 1. Install Azure Storage Explorer and set it up according to the instructions found here: https://azure.microsoft.com/en-us/features/storage-explorer/
# 2. Once your account is linked, you should be able to open Azure Storage Explorer, select the appropriate subscription, storage account, and file share.
# 3. Upload 'bowls_voc' to /Users/<your user>/percept-transfer-learning under the appropriate file share.
# 4. Make sure that this notebook is in the same folder (/Users/<your user>/percept-transfer-learning)
# Save current directory for later reference
modelroot = !pwd
modelroot = modelroot[0]
modelroot
# Setup workspace for Azure ML
!pip install azureml.core
import azureml.core
from azureml.core import Workspace
print(azureml.core.VERSION)
# Install tensorflow v1.15 required for OpenVINO model conversion
!pip install tensorflow-gpu==1.15
# Install Tensor flow models and scripts.
repository = '--depth 1 --branch v1.13.0 https://github.com/tensorflow/models.git'
!pip install tf-slim
!git clone $repository
# Install required TF packages
!sudo -s apt-get install -qq protobuf-compiler python-tk
!pip install Cython contextlib2 pillow lxml matplotlib PyDrive pycocotools build utils dataclasses install azure-iot-device azure-iot-hub numpy==1.17
# Setup python path for TF object detection API and TF-Slim
import os
import sys
cwd = os.getcwd()
sys.path.append(cwd)
research = cwd + '/models/research'
sys.path.append(research)
slim = cwd + '/models/research/slim'
sys.path.append(slim)
%set_env PYTHONPATH=''
os.environ['PYTHONPATH'] = research + ":" + slim + ":" + cwd
os.environ['PYTHONPATH']
# Update protocol buffers for TF object detection API
!curl -OL 'https://github.com/google/protobuf/releases/download/v3.2.0/protoc-3.2.0-linux-x86_64.zip'
# Unzip it
unzipcmd = '-o protoc-3.2.0-linux-x86_64.zip -d protoc3'
!unzip $unzipcmd
# Put it into /usr/local/bin to put it in the system path
movecmd = 'mv protoc3/bin/* /usr/local/bin/'
!sudo $movecmd
# Add header files to the linker's include path
movecmd = 'mv protoc3/include/* /usr/local/include/'
!sudo $movecmd
# Jump into the tensorflow object detection API research directory
researchfolder = modelroot + '/models/research'
%cd $researchfolder
# As per their installation instructions, compile everything in the protos folder using protoc
protoccmd = '/usr/local/bin/protoc ' + 'object_detection/protos/*.proto --python_out=.'
!$protoccmd
# Check Tensorflow version. OpenVINO currently requires TF 1.x, so that's what we use
import tensorflow.compat.v1 as tf
print(tf.__version__)
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
# Run setup for TF object detection API
args = researchfolder + '/setup.py build'
!python $args
# Install TF object detection API
args = researchfolder + '/setup.py install'
!python $args
# Run tensorflow model builder test just to make sure we have TF object detection API set up correctly
args = modelroot + '/models/research/object_detection/builders/model_builder_test.py'
!python $args
# Create data folder for training dataset and model
%cd $modelroot
!mv $modelroot/bowls_voc $modelroot/data
%cd data
# This is a little wonky, but we are later on using a script from the TF object detection API,
# create_pet_tf_record.py to generate a TF record. This script requires certain things in the
# dataset that we don't have, and which we don't use. We create those things here.
from PIL import Image
image_files = os.listdir('images')
im_files = [os.path.splitext(x)[0] for x in image_files]
with open('annotations/trainval.txt', 'w') as text_file:
for row in im_files:
text_file.write(row + '\n')
%cd ./annotations
!mkdir trimaps
image = Image.new('RGB', (640, 480))
for fname in os.listdir("xmls"):
fname, _ = os.path.splitext(fname)
image.save(os.path.join("trimaps", fname + ".png"))
# Create category labels file for Tensorflow training and validation files (label map)
label_map_fpath = modelroot + '/models/research/object_detection/data/bowls.pbtxt'
print(label_map_fpath)
%%writefile $label_map_fpath
item {
id: 1
name: 'bowl'
}
# Fix to remove ^M nonprintable char from end of string lines in file created above
# to see issue run "!cat -v $label_map_fname" before and after fix
with open(label_map_fpath, 'r') as file:
label_map_file = file.read()
update_file = open(label_map_fpath, "w")
update_file.writelines(label_map_file)
update_file.close()
# Create Tensorflow training data record files by co-opting this create_pet_tf_record.py script for our purposes
# This will take a while (tens of minutes probably)
%cd $modelroot/data
script = modelroot + "/models/research/object_detection/dataset_tools/create_pet_tf_record.py"
args = f"{script} --label_map_path={label_map_fpath} --data_dir=./ --output_dir=./ --num_shards=1"
!python $args
# Now update the names of the output files
!mv pet_faces_train.record-00000-of-00001 tf_train.record
!mv pet_faces_val.record-00000-of-00001 tf_val.record
# Download pretrained model for transfer learning: SSD Lite MobileNet V2 COCO
!curl -OL 'http://download.tensorflow.org/models/object_detection/ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz'
model_file = os.path.join(modelroot, "data", "ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz")
# Uncompress model
import os
import shutil
import glob
import urllib
import tarfile
import urllib.request
tar = tarfile.open(model_file)
tar.extractall()
tar.close()
# Prepare model config file paths and tensorflow configuration file for SSDLiteV2 Model
config_fname = modelroot + '/models/research/object_detection/samples/configs/ssdlite_mobilenet_retrained.config'
fine_tune_checkpoint = '"' + modelroot + '/data/ssdlite_mobilenet_v2_coco_2018_05_09/model.ckpt' + '"'
input_path_train = '"' + modelroot + '/data/tf_train.record' + '"'
label_map_path = '"' + modelroot + '/models/research/object_detection/data/bowls.pbtxt' + '"'
input_path_eval = '"' + modelroot + '/data/tf_val.record' + '"'
%%writefile $config_fname
model {
ssd {
num_classes: 1
box_coder {
faster_rcnn_box_coder {
y_scale: 10.0
x_scale: 10.0
height_scale: 5.0
width_scale: 5.0
}
}
matcher {
argmax_matcher {
matched_threshold: 0.5
unmatched_threshold: 0.5
ignore_thresholds: false
negatives_lower_than_unmatched: true
force_match_for_each_row: true
}
}
similarity_calculator {
iou_similarity {
}
}
anchor_generator {
ssd_anchor_generator {
num_layers: 6
min_scale: 0.2
max_scale: 0.95
aspect_ratios: 1.0
aspect_ratios: 2.0
aspect_ratios: 0.5
aspect_ratios: 3.0
aspect_ratios: 0.3333
}
}
image_resizer {
fixed_shape_resizer {
height: 300
width: 300
}
}
box_predictor {
convolutional_box_predictor {
min_depth: 0
max_depth: 0
num_layers_before_predictor: 0
use_dropout: false
dropout_keep_probability: 0.8
kernel_size: 3
use_depthwise: true
box_code_size: 4
apply_sigmoid_to_scores: false
conv_hyperparams {
activation: RELU_6,
regularizer {
l2_regularizer {
weight: 0.00004
}
}
initializer {
truncated_normal_initializer {
stddev: 0.03
mean: 0.0
}
}
batch_norm {
train: true,
scale: true,
center: true,
decay: 0.9997,
epsilon: 0.001,
}
}
}
}
feature_extractor {
type: 'ssd_mobilenet_v2'
min_depth: 16
depth_multiplier: 1.0
use_depthwise: true
conv_hyperparams {
activation: RELU_6,
regularizer {
l2_regularizer {
weight: 0.00004
}
}
initializer {
truncated_normal_initializer {
stddev: 0.03
mean: 0.0
}
}
batch_norm {
train: true,
scale: true,
center: true,
decay: 0.9997,
epsilon: 0.001,
}
}
}
loss {
classification_loss {
weighted_sigmoid {
}
}
localization_loss {
weighted_smooth_l1 {
}
}
hard_example_miner {
num_hard_examples: 3000
iou_threshold: 0.99
loss_type: CLASSIFICATION
max_negatives_per_positive: 3
min_negatives_per_image: 3
}
classification_weight: 1.0
localization_weight: 1.0
}
normalize_loss_by_num_matches: true
post_processing {
batch_non_max_suppression {
score_threshold: 1e-8
iou_threshold: 0.6
max_detections_per_class: 100
max_total_detections: 100
}
score_converter: SIGMOID
}
}
}
train_config: {
batch_size: 24
optimizer {
rms_prop_optimizer: {
learning_rate: {
exponential_decay_learning_rate {
initial_learning_rate: 0.004
decay_steps: 800720
decay_factor: 0.95
}
}
momentum_optimizer_value: 0.9
decay: 0.9
epsilon: 1.0
}
}
fine_tune_checkpoint: $fine_tune_checkpoint
fine_tune_checkpoint_type: "detection"
num_steps: 200000
data_augmentation_options {
random_horizontal_flip {
}
}
data_augmentation_options {
ssd_random_crop {
}
}
}
train_input_reader: {
tf_record_input_reader {
input_path: $input_path_train
}
label_map_path: $label_map_path
}
eval_config: {
num_examples: 8000
# Note: The below line limits the evaluation process to 10 evaluations.
# Remove the below line to evaluate indefinitely.
max_evals: 10
}
eval_input_reader: {
tf_record_input_reader {
input_path: $input_path_eval
}
label_map_path: $label_map_path
shuffle: false
num_readers: 1
}
# Update config file paths
with open(config_fname, 'r') as f:
config_file = f.read()
config_file = config_file.replace('$fine_tune_checkpoint', fine_tune_checkpoint)
config_file = config_file.replace('$label_map_path', label_map_path)
config_file = config_file.replace('$input_path_train', input_path_train)
config_file = config_file.replace('$input_path_eval', input_path_eval)
update_file = open(config_fname, 'w')
update_file.writelines(config_file)
update_file.close()
# Run tensorflow fine tuning training.
# To train on CPU instead of GPU uncomment the 'CUDA_VISIBLE_DEVICES' line below
#
# Note that we train for 30k steps here. This is sufficient to get reasonable results, though you may prefer to train for longer.
# **This will take several hours on a GPU compute node, and days on a CPU machine. It would be preferable to run on GPU for faster training. **
# If your kernel disconnects, don't worry, the code checkpoints periodically, click rerun all cells and it will pick up the latest checkpoint.
%cd $modelroot
model_dir = os.path.join(modelroot, "data", "retrained")
!mkdir $model_dir
import os
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
!python ./models/research/object_detection/model_main.py --pipeline_config_path=$config_fname --model_dir=$model_dir --alsologtostderr --num_train_steps=30000 --num_eval_steps=30000
# Get the last checkpoint to use for exporting a frozen graph
import re
%cd $modelroot/data
lst = os.listdir('retrained')
lf = filter(lambda k: 'model.ckpt-' in k, lst)
fileList = str(list(lf))
checkPointNumbers = re.findall(r'[0-9]+', fileList)
checkPointNumbers = [int(i) for i in checkPointNumbers]
last_model = 'model.ckpt-' + str(max(checkPointNumbers))
print(last_model)
# Export frozen graph
!python $modelroot/models/research/object_detection/export_inference_graph.py --input_type=image_tensor --pipeline_config_path=$config_fname --output_directory=fine_tuned_model --trained_checkpoint_prefix=retrained/$last_model
# Test inference on photo using frozen graph
import tensorflow.compat.v1 as tf
import numpy as np
import os
import cv2
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
from matplotlib import pyplot as plt
from PIL import Image
# Path to the frozen graph:
PATH_TO_FROZEN_GRAPH = modelroot + '/data/fine_tuned_model/frozen_inference_graph.pb'
# Path to the label map
PATH_TO_LABEL_MAP = modelroot + '/models/research/object_detection/data/bowls.pbtxt'
# Bowl image
# Note that because the train/eval split is randomized, it is possible this image was in the train split.
IMAGE_PATH = modelroot + '/data/images/bowl_000000084259.jpg'
# Number of classes
NUM_CLASSES = 1
# Minimum confidence value needed to display the bounding box on the image. In range [0.0, 1.0].
MIN_THRESHOLD = 0.40
# Read the frozen graph
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
label_map = label_map_util.load_labelmap(PATH_TO_LABEL_MAP)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
# Detection
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
# Read in the image and convert BGR to RGB
image_np = cv2.imread(IMAGE_PATH)[:,:,::-1]
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
# Extract image tensor
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Extract detection boxes
boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Extract detection scores
scores = detection_graph.get_tensor_by_name('detection_scores:0')
# Extract detection classes
classes = detection_graph.get_tensor_by_name('detection_classes:0')
# Extract number of detections
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
# Actual detection.
boxes, scores, classes, num_detections = sess.run([boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded})
print(f"BOXES (shaped {boxes.shape}):\n{boxes}")
print(f"SCORES (shaped {scores.shape}):\n{scores}")
print(f"CLASSES (shaped {classes.shape}):\n{classes}")
print(f"NDETECTIONS (shaped {num_detections.shape}):\n{num_detections}")
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates=True,
line_thickness=3,
min_score_thresh=MIN_THRESHOLD
)
# Display test inference photo
from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image
%matplotlib inline
plt.figure(figsize = (12, 8))
imshow(image_np)
```
## OpenVINO
At this point, you should have a model exported from Tensorflow and it should be providing good bounding boxes on bowls.
The rest of this notebook will show you how to convert the model into the format that the EyeSOM dev kit requires,
and then how to download it to your device.
```
# Use OpenVINO to convert the frozen graph PB to IR format
%cd $modelroot
convertCMD = "docker run --rm -v `pwd`:/working -w /working openvino/ubuntu18_dev:2021.1 "
convertCMD += '/opt/intel/openvino/deployment_tools/model_optimizer/mo_tf.py '
convertCMD += '--input_model /working/data/fine_tuned_model/frozen_inference_graph.pb '
convertCMD += '--tensorflow_object_detection_api_pipeline_config /working/data/fine_tuned_model/pipeline.config '
convertCMD += '--tensorflow_use_custom_operations_config /opt/intel/openvino/deployment_tools/model_optimizer/extensions/front/tf/ssd_v2_support.json '
convertCMD += '--reverse_input_channels'
print(convertCMD)
!$convertCMD
%%writefile $modelroot/compile.sh
#!/bin/bash
# OpenVINO compilation script
source /opt/intel/openvino_2021/bin/setupvars.sh
/opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/myriad_compile \
-m /working/frozen_inference_graph.xml -o /working/ssdlite_mobilenet_v2.blob -VPU_NUMBER_OF_SHAVES 8 -VPU_NUMBER_OF_CMX_SLICES 8 -ip U8 -op FP32
# Use OpenVINO to compile IR format to blob
%cd $modelroot
# Run compilation in the container (ignore all the XLink warnings)
!docker run --rm -v `pwd`:/working -w /working openvino/ubuntu18_dev:2021.1 /bin/bash compile.sh
print(convertCMD)
!$convertCMD
# Package up blob for delevery to devkit
# Clean recreate directory if it exists and create it if not
!rm -rf blob
!mkdir blob
!cp $modelroot/ssdlite_mobilenet_v2.blob blob/ssdlite_mobilenet_v2.blob
%%writefile $modelroot/blob/labels.txt
zeroindex
bowl
%%writefile $modelroot/blob/config.json
{
"DomainType": "ssd100",
"LabelFileName": "labels.txt",
"ModelFileName": "ssdlite_mobilenet_v2.blob"
}
# Package up model and support files for dev kit
!cd $modelroot/blob && zip -r model.zip ./*
%cd $modelroot
!mv $modelroot/blob/model.zip ./
# Use the default datasore associated with the current workspace
from azureml.core import Workspace
from azureml.core import Dataset
ws = Workspace.from_config()
ds = ws.get_default_datastore()
print(ds.name, ds.datastore_type, ds.account_name, ds.container_name)
# Set model as unencrypted by default
MODEL_ENCRYPTED = False
# Optional - protect the model with Azure Percept SDK
# install Azure Percept SDK
!pip install sczpy
# Declare the Azure account and model management variables to be used for model protection.
AZURE_CLIENT_ID='<ENTER YOUR SERVICE PRINCIPAL CLIENT ID>'
AZURE_CLIENT_SECRET='<ENTER YOUR SERVICE PRINCIPAL CLIENT SECRET>'
AZURE_TENANT_ID='<ENTER YOUR SERVICE PRINCIPAL TENANT ID>'
SERVER_URL='<ENTER YOUR AZUURE PERCEPT MM SERVER URL>'
MODEL_NAME='<ENTER YOUR MODEL NAME>'
MODEL_VERSION='<ENTER YOUR MODEL VERSION>'
# Protect the model
import sczpy
import os
os.environ["AZURE_CLIENT_ID"] = AZURE_CLIENT_ID
os.environ["AZURE_CLIENT_SECRET"] = AZURE_CLIENT_SECRET
os.environ["AZURE_TENANT_ID"] = AZURE_TENANT_ID
client = sczpy.SCZClient(SERVER_URL)
client.register_model(MODEL_NAME, MODEL_VERSION)
os.rename("model.zip", "model.unencrypted.zip")
client.encrypt(MODEL_NAME, MODEL_VERSION, "model.unencrypted.zip", "model.zip")
client.upload_model(MODEL_NAME, MODEL_VERSION, "model.zip")
# Set the model tag as encrypted
MODEL_ENCRYPTED = True
# Upload the model.zip file to the datastore
ds.upload_files(['model.zip'], target_path='transfer-learning-models', overwrite=True)
# Install Azure Storage tools
%pip install azure-storage-blob==2.1.0 msrest
# Generate download SAS URL for model.zip
from datetime import datetime, timedelta
from azure.storage.blob import (
BlockBlobService,
ContainerPermissions,
BlobPermissions,
PublicAccess,
)
AZURE_ACC_NAME = ds.account_name
AZURE_PRIMARY_KEY = ds.account_key
AZURE_CONTAINER = ds.container_name
AZURE_BLOB=ds.name
AZURE_File='transfer-learning-models/model.zip'
block_blob_service = BlockBlobService(account_name=AZURE_ACC_NAME, account_key=AZURE_PRIMARY_KEY)
sas_url = block_blob_service.generate_blob_shared_access_signature(AZURE_CONTAINER,
AZURE_File,
permission=BlobPermissions.READ,
expiry= datetime.utcnow() + timedelta(hours=30*24))
downloadurl ='https://'+AZURE_ACC_NAME+'.blob.core.windows.net/'+AZURE_CONTAINER+'/'+AZURE_File+'?'+sas_url
print(downloadurl)
# Install Azure Iot Hub tools
%pip install azure-iot-hub
import sys
from azure.iot.hub import IoTHubRegistryManager
from azure.iot.hub.models import Twin, TwinProperties
# Incorporate the connection string, device_id and the module_id values from your IoT Hub
# Go to https://portal.azure.com
# Select your IoT Hub
# Click on Shared access policies
# Click 'service' policy on the right (or another policy having 'service connect' permission)
# Copy Connection string--primary key
CONNECTION_STRING = "<YOUR-CONNECTION-STRING>"
DEVICE_ID = "<YOUR-DEV-ID>" # Change this to your device's name as found in the IoT Azure Portal
MODULE_ID = "azureeyemodule" # Make sure this is what your azureeyemodule is called (check your IoT device in the Azure Portal)
iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
module_twin = iothub_registry_manager.get_module_twin(DEVICE_ID, MODULE_ID)
print ( "" )
print ( "Module twin properties before update :" )
print ( "{0}".format(module_twin.properties) )
# Update twin
twin_patch = Twin()
if MODEL_ENCRYPTED == True:
twin_patch.properties = TwinProperties(desired={"ModelZipUrl": downloadurl,
"SecureAILifecycleEnabled": True,
"SCZ_MODEL_NAME": MODEL_NAME,
"SCZ_MODEL_VERSION": MODEL_VERSION,
"SCZ_MM_SERVER_URL": SERVER_URL,
"DownloadSecuredModelFromMMServer": False})
else:
twin_patch.properties = TwinProperties(desired={"ModelZipUrl": downloadurl,
"SecureAILifecycleEnabled": False})
updated_module_twin = iothub_registry_manager.update_module_twin(DEVICE_ID, MODULE_ID, twin_patch, module_twin.etag)
print ( "" )
print ( "Module twin properties after update :" )
print ( "{0}".format(updated_module_twin.properties) )
```
The trained model will get pushed to the IoT Edge device via module twin update method
Check model inferencing by connecting monitor to the devkit or by installing VLC media player:
Install VLC from https://www.videolan.org/vlc/
Check video stream in VLC:
1. Select Media -> Open Network Stream…
1. Input the network stream: “rtsp://ip-address-of-your-device:8554/result” then click “Play” button.
| github_jupyter |
# Variability in the Arm Endpoint Stiffness
In this notebook, we will calculate the feasible endpoint stiffness of a
simplified arm model for an arbitrary movement. The calculation of the feasible
muscle forces and the generation of the movement is presented in
feasible_muscle_forces.ipynb. The steps are as follows:
1. Generate a movement using task space projection
2. Calculate the feasible muscle forces that satisfy the movement
3. Calculate the feasible endpoint stiffness
```
# notebook general configuration
%load_ext autoreload
%autoreload 2
# imports and utilities
import numpy as np
import sympy as sp
from IPython.display import display, Image
sp.interactive.printing.init_printing()
import logging
logging.basicConfig(level=logging.INFO)
# plot
%matplotlib inline
from matplotlib.pyplot import *
rcParams['figure.figsize'] = (10.0, 6.0)
# utility for displaying intermediate results
enable_display = True
def disp(*statement):
if (enable_display):
display(*statement)
```
## Step 1: Task Space Inverse Dynamics Controller
The task space position ($x_t$) is given as a function of the generalized
coordinates ($q$)
\begin{equation}\label{equ:task-position}
x_t = g(q), x_t \in \Re^{d}, q \in \Re^{n}, d \leq n
\end{equation}
The first and second derivatives with respect to time (the dot notation depicts
a derivative with respect to time) are given by
\begin{equation}\label{equ:task-joint-vel}
\dot{x}_t = J_t(q) \dot{q}, \; J_t(q) =
\begin{bmatrix}
\frac{\partial g_1}{\partial q_1} & \cdots & \frac{\partial g_1}{\partial q_n} \\
\vdots & \ddots & \vdots \\
\frac{\partial g_d}{\partial q_1} & \cdots & \frac{\partial g_d}{\partial q_n}
\end{bmatrix}
\in \Re^{d\times n}
\end{equation}
\begin{equation}\label{equ:task-joint-acc}
\ddot{x}_t = \dot{J}_t\dot{q} + J_t\ddot{q}
\end{equation}
The task Jacobian defines a dual relation between motion and force
quantities. The virtual work principle can be used to establish the link between
task and join space forces (augmented by the null space)
\begin{equation}\label{equ:joint-task-forces-vw}
\begin{aligned}
\tau^T \delta q &= f_t^T \delta x_t \\
\tau^T \delta q &= f_t^T J_t \delta q \\
\tau &= J_t^T f_t + N_{J_t} \tau_0, \; N_{J_t} = (I - J_t^T \bar{J}_t^T)
\end{aligned}
\end{equation}
where $N_{J_t} \in \Re^{n \times n}$ represents the right null space of $J_t$
and $\bar{J}_t$ the generalized inverse. Let the joint space equations of motion
(EoMs) have the following form
\begin{equation}\label{equ:eom-joint-space}
\begin{gathered}
M(q) \ddot{q} + f(q, \dot{q}) = \tau \\
f(q, \dot{q}) = \tau_g(q) + \tau_c(q, \dot{q}) + \tau_{o}(q, \dot{q})
\end{gathered}
\end{equation}
where $M \in \Re^{n \times n}$ denotes the symmetric, positive definite joint
space inertia mass matrix, $n$ the number of DoFs of the model and ${q, \dot{q},
\ddot{q}} \in \Re^{n}$ the joint space generalized coordinates and their
derivatives with respect to time. The term $f \in \Re^{n}$ is the sum of all
joint space forces, $\tau_g \in \Re^{n}$ is the gravity, $\tau_c \in \Re^{n}$
the Coriolis and centrifugal and $\tau_{o} \in \Re^{n}$ other generalized
forces. Term $\tau \in \Re^{n}$ denotes a vector of applied generalized forces
that actuate the model.
We can project the joint space EoMs in the task space by multiplying both sides
from the left with $J_t M^{-1}$
\begin{equation}\label{equ:eom-task-space}
\begin{gathered}
J_t M^{-1}M \ddot{q} + J_t M^{-1}f = J_t M^{-1}\tau \\
\ddot{x}_t - \dot{J}_t\dot{q} + J_t M^{-1}f = J_t M^{-1} (J^T_t f_t + N_{J_t} \tau_0) \\
\Lambda_t(\ddot{x}_t + b_t) + \bar{J}_t^T f = f_t
\end{gathered}
\end{equation}
where $\Lambda_t=(J_tM^{-1}J_t^T)^{-1} \in \Re^{d \times d}$ represents the task
space inertia mass matrix, $b_t = - \dot{J}_t\dot{q}$ the task bias term and
$\bar{J}_t^T = \Lambda_m RM^{-1} \in \Re^{d \times n}$ the generalized inverse
transpose of $J_t$ that is used to project joint space quantities in the task
space. Note that $\bar{J}_t^T N_{J_t} \tau_0 = 0$.
The planning will be performed in task space in combination with a Proportional
Derivative (PD) tracking scheme
\begin{equation}\label{equ:pd-controller}
\ddot{x}_t = \ddot{x}_d + k_p (x_d - x_t) + k_d (\dot{x}_d - x_t)
\end{equation}
where $x_d, \dot{x}_d, \ddot{x}_d$ are the desired position, velocity and
acceleration of the task and $k_p = 50, k_d = 5$ the tracking gains.
The desired task goal is derived from a smooth sigmoid function that produces
bell-shaped velocity profiles in any direction around the initial position of
the end effector
\begin{equation}\label{equ:sigmoid}
\begin{gathered}
x_d(t) = [x_{t,0}(0) + a (tanh(b (t - t_0 - 1)) + 1) / 2, x_{t,1}(0)]^T, \;
\dot{x}_d(t) = \frac{d x_d(t)}{dt}, \; \ddot{x}_d(t) = \frac{d \dot{x}_d(t)}{dt} \\
x_d^{'} = H_z(\gamma) x_d, \; \dot{x}_d^{'} = H_z(\gamma) \dot{x}_d,
\; \ddot{x}_d^{'} = H_z(\gamma) \ddot{x}_d
\end{gathered}
\end{equation}
where $x_{t, 0}$, $x_{t, 1}$ represent the $2D$ components of $x_t$, $a = 0.3$,
$b = 4$ and $t_0 = 0$. Different directions of movement are achieved by
transforming the goals with $H_z(\gamma)$, which defines a rotation around
the $z$-axis of an angle $\gamma$.
```
# import necessary modules
from model import ArmModel
from projection import TaskSpace
from controller import TaskSpaceController
from simulation import Simulation
# construct model gravity disabled to improve execution time during numerical
# integration note that if enabled, different PD gains are required to track the
# movement accurately
model = ArmModel(use_gravity=0, use_coordinate_limits=1, use_viscosity=1)
model.pre_substitute_parameters()
# simulation parameters
t_end = 2.0
angle = np.pi # direction of movement
fig_name = 'results/feasible_stiffness/feasible_forces_ts180'
# define the end effector position in terms of q's
end_effector = sp.Matrix(model.ee)
disp('x_t = ', end_effector)
# task space controller
task = TaskSpace(model, end_effector)
controller = TaskSpaceController(model, task, angle=angle)
# numerical integration
simulation = Simulation(model, controller)
simulation.integrate(t_end)
# plot simulation results
fig, ax = subplots(2, 3, figsize=(15, 10))
simulation.plot_simulation(ax[0])
controller.reporter.plot_task_space_data(ax[1])
fig.tight_layout()
fig.savefig(fig_name + '.pdf', format='pdf', dpi=300)
fig.savefig(fig_name + '.eps', format='eps', dpi=300)
```
## Step 2: Calculation of the Feasible Muscle Force Space
The feasible muscle forces are calculated below. Initially, the moment arm and
maximum muscle force quantities are computed for each instance of the
movement. Then the following inequality is formed assuming a linear muscle model
\begin{equation}\label{equ:linear-muscle-null-space-inequality}
\begin{gathered}
f_m = f_{max} \circ a_m = f_m^{\parallel} +
N_{R} f_{m0},\; 0 \preceq a_m \preceq 1
\rightarrow \\
\begin{bmatrix}
- N_{R} \\
\hdashline
N_{R}
\end{bmatrix}
f_{m0} \preceq
\begin{bmatrix}
f_m^{\parallel} \\
\hdashline
f_{max} - f_m^{\parallel}
\end{bmatrix} \\
Z f_{m0} \preceq \beta
\end{gathered}
\end{equation}
where $a_m \in \Re^{m}$ represents a vector of muscle activations, $f_{max} \in
\Re^{m}$ a vector specifying the maximum muscle forces, $\circ$ the Hadamard
(elementwise) product, $f_m^{\parallel}$ the particular muscle force solution
that satisfies the action, $N_{R}$ the moment arm null space and $f_{m0}$ the
null space forces.
The next step is to sample the inequality $Z f_{m0} \leq \beta$. This is the
bottleneck of the analysis. The *convex_bounded_vertex_enumeration* uses the
lsr method, which is a vertex enumeration algorithm for finding the vertices
of a polytope in $O(v m^3)$.
```
# import necessary modules
from analysis import FeasibleMuscleSetAnalysis
# initialize feasible muscle force analysis
feasible_muscle_set = FeasibleMuscleSetAnalysis(model, controller.reporter)
```
## Step 3: Calculate the Feasible Task Stiffness
In the following section, we will introduce a method for calculating the
feasible muscle forces that satisfy the motion and the physiological muscle
constraints. As the muscles are the main actors of the system, it is important
to examine the effect of muscle redundancy on the calculation of limbs'
stiffness.
The muscle stiffness is defined as
\begin{equation}\label{equ:muscle-stiffness}
K_m = \frac{\partial f_m}{\partial l_{m}},\; K_m \in \Re^{m \times m}
\end{equation}
where $f_m \in \Re^{m}$ represents the muscle forces, $l_{m} \in \Re^{m}$ the
musculotendon lengths and $m$ the number of muscles. The joint stiffness is
defined as
\begin{equation}\label{equ:joint-stiffness}
K_j = \frac{\partial \tau}{\partial q},\; K_j \in \Re^{n \times n}
\end{equation}
where $\tau \in \Re^{n}$, $q \in \Re^{n}$ are the generalized forces and
coordinates, respectively and $n$ the DoFs of the system. Finally, the task
stiffness is defined as
\begin{equation}\label{equ:task-stiffness}
K_t = \frac{\partial f_t}{\partial x_t},\; K_t \in \Re^{d \times d}
\end{equation}
where $f_t \in \Re^{d}$ denotes the forces, $x_t \in \Re^{d}$ the positions and
$d$ the DoFs of the task.
The derivation starts with a model for computing the muscle stiffness matrix
$K_m$. The two most adopted approaches are to either use the force-length
characteristics of the muscle model or to approximate it using the definition of
the short range stiffness, where the latter is shown to explain most of the
variance in the experimental measurements. The short range stiffness is
proportional to the force developed by the muscle ($f_m$)
\begin{equation}\label{equ:short-range-stiffness}
k_{s} = \gamma \frac{f_m}{l_m^o}
\end{equation}
where $\gamma = 23.4$ is an experimentally determined constant and $l_m^o$ the
optimal muscle length. This definition will be used to populate the diagonal
elements of the muscle stiffness matrix, whereas inter-muscle coupling
(non-diagonal elements) will be assumed zero since it is difficult to measure
and model in practice.
The joint stiffness is related to the muscle stiffness through the following
relationship
\begin{equation}\label{equ:joint-muscle-stiffness}
K_j = -\frac{\partial R^T}{\partial q} \bullet_2 f_m - R^T K_m R
\end{equation}
where the first term captures the varying effect of the muscle moment arm ($R
\in \Re^{m \times n}$), while the second term maps the muscle space stiffness to
joint space. The notation $\bullet_2$ denotes a product of a rank-3 tensor
($\frac{\partial R^T}{\partial q} \in \Re^{n \times m \times n}$, a 3D matrix)
and a rank-1 tensor ($f_m \in \Re^{m}$, a vector), where the index $2$ specifies
that the tensor dimensional reduction (by summation) is performed across the
second dimension, resulting in a reduced rank-2 tensor of dimensions $n \times
n$.
In a similar manner, the task stiffness is related to the muscle stiffness
through the following relationship
\begin{equation}\label{equ:task-muscle-stiffness}
K_t = -J_t^{+T} \left(\frac{\partial J_t^T}{\partial q} \bullet_2
f_t + \frac{\partial R^T}{\partial q} \bullet_2 f_m + R^T
K_m R\right) J_t^{+}
\end{equation}
where the task Jacobian matrix ($J_t \in \Re^{d \times n}$) describes the
mapping from joint to task space ($\Re^{n} \rightarrow \Re^{d}$), $+$ stands for
the Moore-Penrose pseudoinverse and $+T$ the transposed pseudoinverse operator.
Algorithm for calculating the feasible joint stiffness:
**Step 1:** Calculate the feasible muscle forces $f_m^{\oplus}$ that satisfy the
task and the physiological muscle constraints
**Step 2:** Calculate the muscle stiffness matrix $K_m$ using the short range
stiffness model
\begin{equation*}\label{equ:short-range-stiffness-2}
k_s = \gamma \frac{f_m}{l_m^o},\; \gamma = 23.4
\end{equation*}
**Step 3:** Calculate the task $K_t$ and joint $K_j$ stiffness
\begin{equation*}
\begin{gathered}
K_j = -\frac{\partial R^T}{\partial q} \bullet_2 f_m - R^T K_m R \\
K_t = -J_t^{+T} \left(\frac{\partial J_t^T}{\partial q} \bullet_2
f_t + \frac{\partial R^T}{\partial q} \bullet_2 f_m + R^T
K_m R\right) J_t^{+}
\end{gathered}
\end{equation*}
```
# import necessary modules
from analysis import StiffnessAnalysis
from util import calculate_stiffness_properties
base_name = 'results/feasible_stiffness/feasible_stiffness_ts180_'
# initialize stiffness analysis
stiffness_analysis = StiffnessAnalysis(model, task, controller.reporter,
feasible_muscle_set)
# calculate feasible stiffness
calculate_stiffness_properties(stiffness_analysis, base_name, 0, t_end, 0.2, 500)
Image(url=base_name + 'anim.gif')
```
The left diagram shows the feasible major and minor axes of the endpoint
stiffness using scaled ($\text{scaling} = 0.0006$) ellipses (ellipses are
omitted for visibility reasons). The ellipse is a common way to visualize the
task stiffness, where the major axis (red) of the ellipse is oriented along the
maximum stiffness and the area is proportional to the determinant of $K_t$,
conveying the stiffness amplitude. The stiffness capacity (area) is increased in
the last pose, since the arm has already reached its final position and muscle
forces are not needed for it to execute any further motion. The second diagram
(middle) depicts the distribution of ellipse parameters (area and orientation
$\phi$). Finally, the rightmost box plot shows the feasible joint stiffness
distribution at three distinct time instants. Experimental measurements have
showed that the orientation of stiffness ellipses varies in a range of about
$30^{\circ}$. While our simulation results confirm this, they also reveal a
tendency of fixation towards specific directions for higher stiffness
amplitudes. The large variation of feasible stiffness verifies that this type of
analysis conveys important findings that complement experimental observations.
| github_jupyter |
### Minimum Spanning Tree
Minimum spanning tree is a subset of a graph, where every vertex is connected to at least one other vertex, but at most connected to two other vertices, that indicates no cycle, and the total weight of the graph is the minimum possible. Lol, long definition!
```
import os
os.chdir('K:/ecole/github')
#graph adt
#check the below link for more details
# https://github.com/je-suis-tm/graph-theory/blob/master/graph.py
import graph
#we need an undirected graph
#in another word, vertices with edge connections
#are mutually connected to each other
ADT=graph.graph()
ADT.append(1,2,6)
ADT.append(1,3,5)
ADT.append(2,1,6)
ADT.append(2,4,8)
ADT.append(2,6,3)
ADT.append(3,1,5)
ADT.append(3,4,2)
ADT.append(3,5,7)
ADT.append(4,2,8)
ADT.append(4,3,2)
ADT.append(4,5,7)
ADT.append(5,3,3)
ADT.append(5,4,7)
ADT.append(5,7,9)
ADT.append(6,2,3)
ADT.append(6,7,5)
ADT.append(7,5,9)
ADT.append(7,6,5)
ADT.append(7,8,13)
ADT.append(8,7,13)
```

### Prim's Algorithm
Prim's algorithm is perfect for a minimum spanning tree problem. The algorithm is somewhat similar to BFS. We start from one vertex and check its child vertices. In BFS, we pop vertices by left to right order. In Prim, we only pop the vertex with minimum weight and ignore the rest. When all available vertices have been popped, we obtain a minimum spanning tree.
Details of Prim's algorithm can be found in the following link
http://interactivepython.org/runestone/static/pythonds/Graphs/PrimsSpanningTreeAlgorithm.html
Details of BFS can be found in the following link
https://github.com/je-suis-tm/graph-theory/blob/master/BFS%20DFS%20on%20DCG.ipynb
```
#different starting point may end up with a different tree
def prim(ADT,start):
"""Prim's Algorithm to find a minimum spanning tree"""
#we use a dictionary instead of a list as queue
#cuz we need to pop the vertex with minimum weight on the edge
queue={}
queue[start]=0
#route keeps track of how we travel from one vertex to another
route={}
route[start]=start
#result is a list that keeps the order of vertices we have visited
result=[]
while queue:
#note that when we have two vertices with the same minimum weights
#the dictionary would pop the one with the smallest key
current=min(queue,key=queue.get)
queue.pop(current)
result.append(current)
ADT.visit(current)
#BFS
for i in ADT.edge(current):
if i not in queue and ADT.go(i)==0:
queue[i]=ADT.weight(current,i)
route[i]=current
#every time we find a smaller weight
#we need to update the smaller weight in queue
if i in queue and queue[i]>ADT.weight(current,i):
queue[i]=ADT.weight(current,i)
route[i]=current
#create minimum spanning tree
subset=graph.graph()
for i in result:
if i!=start:
subset.append(route[i],i,ADT.weight(route[i],i))
subset.append(i,route[i],ADT.weight(route[i],i))
return subset
MST=prim(ADT,1)
ADT.clear(whole=True)
MST.reveal()
```

### Kruskal's Algorithm
Kruskal is another algorithm to get minimum spanning tree. Unlike Prim, Kruskal cannot select where to expand the tree. Kruskal requires all edges in the graph ADT to be sorted. Those edges are stored inside a queue by ascending order. The algorithm iterates through the queue and picks out the edge with the smallest weight, as long as the edge doesn't create a cycle in the subset, the edge will be added into the subset. When the iteration stops, a minimum spanning tree is born.
```
#use disjoint set to detect cycle
def trace_root(disjointset,target):
"""Use recursion to trace root in a disjoint set"""
if disjointset[target]!=target:
trace_root(disjointset,disjointset[target])
else:
return target
#unlike prim, kruskal does not require starting vertex
#it always starts with the edge with the minimum weight
def kruskal(ADT):
"""Kruskal's Algorithm to find the minimum spanning tree"""
#use dictionary to sort edges by weight
D={}
for i in ADT.vertex():
for j in ADT.edge(i):
#convert edge into string
#as the graph is bidirected
#we only need one edge for each pair of two vertices
if f'{j}-{i}' not in D.keys():
D[f'{i}-{j}']=ADT.weight(i,j)
sort_edge_by_weight=sorted(D.items(), key=lambda x:x[1])
result=[]
#to achieve minimum spanning tree
#we need to avoid cycles
#here we use disjointset to detect cycle
#for more details, you can go to geeksforgeeks
# https://www.geeksforgeeks.org/union-find/
disjointset={}
#lets skip the part where default=-1
for i in ADT.vertex():
disjointset[i]=i
for i in sort_edge_by_weight:
parent=int(i[0].split('-')[0])
child=int(i[0].split('-')[1])
#first we need to check disjoint set
#if it already has indicated cycle
#trace_root function will go to infinite loops
if disjointset[parent]!=disjointset[child]:
#if we trace back to the root of the tree
#and it indicates no cycle
#we update the disjoint set and add edge into result
if trace_root(disjointset,parent)!=trace_root(disjointset,child):
disjointset[child]=parent
result.append([parent,child])
#create minimum spanning tree
subset=graph.graph()
for i in result:
subset.append(i[0],i[1],ADT.weight(i[0],i[1]))
subset.append(i[1],i[0],ADT.weight(i[0],i[1]))
return subset
MST=kruskal(ADT)
ADT.clear(whole=True)
MST.reveal()
```

### Borůvka's Algorithm
Borůvka is the oldest algorithm for minimum spanning tree. The logic is very similar to Kruskal. We can almost say Kruskal is based upon Borůvka. Basically for each vertex, we try to find its edge with the minimum weight
after the first iteration. We will end up with a few connected components. The second iteration is similar to the first. For each pair of connected components, we try to find the edge with minimum weight to connect. After two rounds of iterations, we are left with a minimum spanning tree.
```
#borůvka requires another algorithm to detect connected components
#here i use dfs
def boruvka(ADT):
"""Borůvka's Algorithm to find the minimum spanning tree"""
subset=graph.graph()
#get the edge with minimum weight for each vertex
for i in ADT.vertex():
minimum=float('inf')
target=None
for j in ADT.edge(i):
if ADT.weight(i,j)<minimum:
minimum=ADT.weight(i,j)
target=[i,j]
#as the graph is undirected
#we append both edges
subset.append(target[0],target[1],ADT.weight(target[0],target[1]))
subset.append(target[1],target[0],ADT.weight(target[0],target[1]))
#use dfs topological sort to find connected components
#details of topological sort can be found in the following link
# https://github.com/je-suis-tm/graph-theory/blob/master/topological%20sort.ipynb
connected_components=[]
for i in subset.vertex():
#avoid duplicates of connected components
#use jump to break out of multiple loops
jump=False
for j in connected_components:
if i in j:
jump=True
break
if jump:
continue
connected_components.append(list(graph.dfs_topo_sort(subset,i)))
#connect 2 connected components with minimum weight
#same logic as the first iteration
for i in range(len(connected_components)):
for j in range(i+1,len(connected_components)):
minimum=float('inf')
target=None
for k in connected_components[i]:
for l in ADT.edge(k):
if l in connected_components[j]:
if ADT.weight(k,l)<minimum:
minimum=ADT.weight(k,l)
target=[k,l]
subset.append(target[0],target[1],minimum)
subset.append(target[1],target[0],minimum)
return subset
MST=boruvka(ADT)
ADT.clear(whole=True)
MST.reveal()
```

### Time Complexity Comparison
See how Prim revolutionized the minimum spanning tree?
```
%%timeit
MST=graph.prim(ADT,1)
ADT.clear(whole=True)
%%timeit
MST=graph.kruskal(ADT)
ADT.clear(whole=True)
%%timeit
MST=graph.boruvka(ADT)
ADT.clear(whole=True)
```
| github_jupyter |
# Cavity flow with Navier-Stokes
The final two steps will both solve the Navier–Stokes equations in two dimensions, but with different boundary conditions.
The momentum equation in vector form for a velocity field v⃗
is:
$$ \frac{\partial \overrightarrow{v}}{\partial t} + (\overrightarrow{v} \cdot \nabla ) \overrightarrow{v} = -\frac{1}{\rho}\nabla p + \nu \nabla^2 \overrightarrow{v}$$
This represents three scalar equations, one for each velocity component (u,v,w). But we will solve it in two dimensions, so there will be two scalar equations.
Remember the continuity equation? This is where the Poisson equation for pressure comes in!
Here is the system of differential equations: two equations for the velocity components u,v and one equation for pressure:
$$ \frac{\partial u}{\partial t} + u \frac{\partial u}{\partial x} + v \frac{\partial u}{\partial y}= -\frac{1}{\rho}\frac{\partial p}{\partial x} + \nu \left[ \frac{\partial^2 u}{\partial x^2} +\frac{\partial^2 u}{\partial y^2} \right] $$
$$ \frac{\partial v}{\partial t} + u \frac{\partial v}{\partial x} + v \frac{\partial v}{\partial y}= -\frac{1}{\rho}\frac{\partial p}{\partial y} + \nu \left[ \frac{\partial^2 v}{\partial x^2} +\frac{\partial^2 v}{\partial y^2} \right] $$
$$
\frac{\partial^2 p}{\partial x^2} +\frac{\partial^2 p}{\partial y^2} =
\rho \left[\frac{\partial}{\partial t} \left(\frac{\partial u}{\partial x} + \frac{\partial v}{\partial y} \right) - \left(\frac{\partial u}{\partial x}\frac{\partial u}{\partial x}+2\frac{\partial u}{\partial y}\frac{\partial v}{\partial x}+\frac{\partial v}{\partial y}\frac{\partial v}{\partial y} \right) \right]
$$
From the previous steps, we already know how to discretize all these terms. Only the last equation is a little unfamiliar. But with a little patience, it will not be hard!
Our stencils look like this:
First the momentum equation in the u direction
$$
\begin{split}
u_{i,j}^{n+1} = u_{i,j}^{n} & - u_{i,j}^{n} \frac{\Delta t}{\Delta x} \left(u_{i,j}^{n}-u_{i-1,j}^{n}\right) - v_{i,j}^{n} \frac{\Delta t}{\Delta y} \left(u_{i,j}^{n}-u_{i,j-1}^{n}\right) \\
& - \frac{\Delta t}{\rho 2\Delta x} \left(p_{i+1,j}^{n}-p_{i-1,j}^{n}\right) \\
& + \nu \left(\frac{\Delta t}{\Delta x^2} \left(u_{i+1,j}^{n}-2u_{i,j}^{n}+u_{i-1,j}^{n}\right) + \frac{\Delta t}{\Delta y^2} \left(u_{i,j+1}^{n}-2u_{i,j}^{n}+u_{i,j-1}^{n}\right)\right)
\end{split}
$$
Second the momentum equation in the v direction
$$
\begin{split}
v_{i,j}^{n+1} = v_{i,j}^{n} & - u_{i,j}^{n} \frac{\Delta t}{\Delta x} \left(v_{i,j}^{n}-v_{i-1,j}^{n}\right) - v_{i,j}^{n} \frac{\Delta t}{\Delta y} \left(v_{i,j}^{n}-v_{i,j-1}^{n})\right) \\
& - \frac{\Delta t}{\rho 2\Delta y} \left(p_{i,j+1}^{n}-p_{i,j-1}^{n}\right) \\
& + \nu \left(\frac{\Delta t}{\Delta x^2} \left(v_{i+1,j}^{n}-2v_{i,j}^{n}+v_{i-1,j}^{n}\right) + \frac{\Delta t}{\Delta y^2} \left(v_{i,j+1}^{n}-2v_{i,j}^{n}+v_{i,j-1}^{n}\right)\right)
\end{split}
$$
Finally the pressure-Poisson equation
$$\begin{split}
p_{i,j}^{n} = & \frac{\left(p_{i+1,j}^{n}+p_{i-1,j}^{n}\right) \Delta y^2 + \left(p_{i,j+1}^{n}+p_{i,j-1}^{n}\right) \Delta x^2}{2\left(\Delta x^2+\Delta y^2\right)} \\
& -\frac{\rho\Delta x^2\Delta y^2}{2\left(\Delta x^2+\Delta y^2\right)} \\
& \times \left[\frac{1}{\Delta t}\left(\frac{u_{i+1,j}-u_{i-1,j}}{2\Delta x}+\frac{v_{i,j+1}-v_{i,j-1}}{2\Delta y}\right)-\frac{u_{i+1,j}-u_{i-1,j}}{2\Delta x}\frac{u_{i+1,j}-u_{i-1,j}}{2\Delta x}\right. \\
& \left. -2\frac{u_{i,j+1}-u_{i,j-1}}{2\Delta y}\frac{v_{i+1,j}-v_{i-1,j}}{2\Delta x}-\frac{v_{i,j+1}-v_{i,j-1}}{2\Delta y}\frac{v_{i,j+1}-v_{i,j-1}}{2\Delta y} \right]
\end{split}
$$
The initial condition is $u,v,p=0$
everywhere, and the boundary conditions are:
$u=1$ at $y=1$ (the "lid");
$u,v=0$ on the other boundaries;
$\frac{\partial p}{\partial y}=0$ at $y=0,1$;
$\frac{\partial p}{\partial x}=0$ at $x=0,1$
$p=0$ at $(0,0)$
Interestingly these boundary conditions describe a well known problem in the Computational Fluid Dynamics realm, where it is known as the lid driven square cavity flow problem.
## Numpy Implementation
```
import numpy as np
from matplotlib import pyplot, cm
%matplotlib inline
nx = 41
ny = 41
nt = 1000
nit = 50
c = 1
dx = 1. / (nx - 1)
dy = 1. / (ny - 1)
x = np.linspace(0, 1, nx)
y = np.linspace(0, 1, ny)
Y, X = np.meshgrid(x, y)
rho = 1
nu = .1
dt = .001
u = np.zeros((nx, ny))
v = np.zeros((nx, ny))
p = np.zeros((nx, ny))
```
The pressure Poisson equation that's written above can be hard to write out without typos. The function `build_up_b` below represents the contents of the square brackets, so that the entirety of the Poisson pressure equation is slightly more manageable.
```
def build_up_b(b, rho, dt, u, v, dx, dy):
b[1:-1, 1:-1] = (rho * (1 / dt *
((u[2:, 1:-1] - u[0:-2, 1:-1]) /
(2 * dx) + (v[1:-1, 2:] - v[1:-1, 0:-2]) / (2 * dy)) -
((u[2:, 1:-1] - u[0:-2, 1:-1]) / (2 * dx))**2 -
2 * ((u[1:-1, 2:] - u[1:-1, 0:-2]) / (2 * dy) *
(v[2:, 1:-1] - v[0:-2, 1:-1]) / (2 * dx))-
((v[1:-1, 2:] - v[1:-1, 0:-2]) / (2 * dy))**2))
return b
```
The function `pressure_poisson` is also defined to help segregate the different rounds of calculations. Note the presence of the pseudo-time variable nit. This sub-iteration in the Poisson calculation helps ensure a divergence-free field.
```
def pressure_poisson(p, dx, dy, b):
pn = np.empty_like(p)
pn = p.copy()
for q in range(nit):
pn = p.copy()
p[1:-1, 1:-1] = (((pn[2:, 1:-1] + pn[0:-2, 1:-1]) * dy**2 +
(pn[1:-1, 2:] + pn[1:-1, 0:-2]) * dx**2) /
(2 * (dx**2 + dy**2)) -
dx**2 * dy**2 / (2 * (dx**2 + dy**2)) *
b[1:-1,1:-1])
p[-1, :] = p[-2, :] # dp/dx = 0 at x = 2
p[:, 0] = p[:, 1] # dp/dy = 0 at y = 0
p[0, :] = p[1, :] # dp/dx = 0 at x = 0
p[:, -1] = p[:, -2] # p = 0 at y = 2
p[0, 0] = 0
return p, pn
```
Finally, the rest of the cavity flow equations are wrapped inside the function `cavity_flow`, allowing us to easily plot the results of the cavity flow solver for different lengths of time.
```
def cavity_flow(nt, u, v, dt, dx, dy, p, rho, nu):
un = np.empty_like(u)
vn = np.empty_like(v)
b = np.zeros((nx, ny))
for n in range(0,nt):
un = u.copy()
vn = v.copy()
b = build_up_b(b, rho, dt, u, v, dx, dy)
p = pressure_poisson(p, dx, dy, b)[0]
pn = pressure_poisson(p, dx, dy, b)[1]
u[1:-1, 1:-1] = (un[1:-1, 1:-1]-
un[1:-1, 1:-1] * dt / dx *
(un[1:-1, 1:-1] - un[0:-2, 1:-1]) -
vn[1:-1, 1:-1] * dt / dy *
(un[1:-1, 1:-1] - un[1:-1, 0:-2]) -
dt / (2 * rho * dx) * (p[2:, 1:-1] - p[0:-2, 1:-1]) +
nu * (dt / dx**2 *
(un[2:, 1:-1] - 2 * un[1:-1, 1:-1] + un[0:-2, 1:-1]) +
dt / dy**2 *
(un[1:-1, 2:] - 2 * un[1:-1, 1:-1] + un[1:-1, 0:-2])))
v[1:-1,1:-1] = (vn[1:-1, 1:-1] -
un[1:-1, 1:-1] * dt / dx *
(vn[1:-1, 1:-1] - vn[0:-2, 1:-1]) -
vn[1:-1, 1:-1] * dt / dy *
(vn[1:-1, 1:-1] - vn[1:-1, 0:-2]) -
dt / (2 * rho * dy) * (p[1:-1, 2:] - p[1:-1, 0:-2]) +
nu * (dt / dx**2 *
(vn[2:, 1:-1] - 2 * vn[1:-1, 1:-1] + vn[0:-2, 1:-1]) +
dt / dy**2 *
(vn[1:-1, 2:] - 2 * vn[1:-1, 1:-1] + vn[1:-1, 0:-2])))
u[:, 0] = 0
u[0, :] = 0
u[-1, :] = 0
u[:, -1] = 1 # Set velocity on cavity lid equal to 1
v[:, 0] = 0
v[:, -1] = 0
v[0, :] = 0
v[-1, :] = 0
return u, v, p, pn
#NBVAL_IGNORE_OUTPUT
u = np.zeros((nx, ny))
v = np.zeros((nx, ny))
p = np.zeros((nx, ny))
b = np.zeros((nx, ny))
nt = 1000
# Store the output velocity and pressure fields in the variables a, b and c.
# This is so they do not clash with the devito outputs below.
a, b, c, d = cavity_flow(nt, u, v, dt, dx, dy, p, rho, nu)
fig = pyplot.figure(figsize=(11, 7), dpi=100)
pyplot.contourf(X, Y, c, alpha=0.5, cmap=cm.viridis)
pyplot.colorbar()
pyplot.contour(X, Y, c, cmap=cm.viridis)
pyplot.quiver(X[::2, ::2], Y[::2, ::2], a[::2, ::2], b[::2, ::2])
pyplot.xlabel('X')
pyplot.ylabel('Y');
```
### Validation
Marchi et al (2009)$^1$ compared numerical implementations of the lid driven cavity problem with their solution on a 1024 x 1024 nodes grid. We will compare a solution using both NumPy and Devito with the results of their paper below.
1. https://www.scielo.br/scielo.php?pid=S1678-58782009000300004&script=sci_arttext
```
# Import u values at x=L/2 (table 6, column 2 rows 12-26) in Marchi et al.
Marchi_Re10_u = np.array([[0.0625, -3.85425800e-2],
[0.125, -6.96238561e-2],
[0.1875, -9.6983962e-2],
[0.25, -1.22721979e-1],
[0.3125, -1.47636199e-1],
[0.375, -1.71260757e-1],
[0.4375, -1.91677043e-1],
[0.5, -2.05164738e-1],
[0.5625, -2.05770198e-1],
[0.625, -1.84928116e-1],
[0.6875, -1.313892353e-1],
[0.75, -3.1879308e-2],
[0.8125, 1.26912095e-1],
[0.875, 3.54430364e-1],
[0.9375, 6.50529292e-1]])
# Import v values at y=L/2 (table 6, column 2 rows 27-41) in Marchi et al.
Marchi_Re10_v = np.array([[0.0625, 9.2970121e-2],
[0.125, 1.52547843e-1],
[0.1875, 1.78781456e-1],
[0.25, 1.76415100e-1],
[0.3125, 1.52055820e-1],
[0.375, 1.121477612e-1],
[0.4375, 6.21048147e-2],
[0.5, 6.3603620e-3],
[0.5625,-5.10417285e-2],
[0.625, -1.056157259e-1],
[0.6875,-1.51622101e-1],
[0.75, -1.81633561e-1],
[0.8125,-1.87021651e-1],
[0.875, -1.59898186e-1],
[0.9375,-9.6409942e-2]])
#NBVAL_IGNORE_OUTPUT
# Check results with Marchi et al 2009.
npgrid=[nx,ny]
x_coord = np.linspace(0, 1, npgrid[0])
y_coord = np.linspace(0, 1, npgrid[1])
fig = pyplot.figure(figsize=(12, 6))
ax1 = fig.add_subplot(121)
ax1.plot(a[int(npgrid[0]/2),:],y_coord[:])
ax1.plot(Marchi_Re10_u[:,1],Marchi_Re10_u[:,0],'ro')
ax1.set_xlabel('$u$')
ax1.set_ylabel('$y$')
ax1 = fig.add_subplot(122)
ax1.plot(x_coord[:],b[:,int(npgrid[1]/2)])
ax1.plot(Marchi_Re10_v[:,0],Marchi_Re10_v[:,1],'ro')
ax1.set_xlabel('$x$')
ax1.set_ylabel('$v$')
pyplot.show()
```
## Devito Implementation
```
from devito import Grid
grid = Grid(shape=(nx, ny), extent=(1., 1.))
x, y = grid.dimensions
t = grid.stepping_dim
```
Reminder: here are our equations
$$ \frac{\partial u}{\partial t} + u \frac{\partial u}{\partial x} + v \frac{\partial u}{\partial y}= -\frac{1}{\rho}\frac{\partial p}{\partial x} + \nu \left[ \frac{\partial^2 u}{\partial x^2} +\frac{\partial^2 u}{\partial y^2} \right] $$
$$ \frac{\partial v}{\partial t} + u \frac{\partial v}{\partial x} + v \frac{\partial v}{\partial y}= -\frac{1}{\rho}\frac{\partial p}{\partial y} + \nu \left[ \frac{\partial^2 v}{\partial x^2} +\frac{\partial^2 v}{\partial y^2} \right] $$
$$
\frac{\partial^2 p}{\partial x^2} +\frac{\partial^2 p}{\partial y^2} =
\rho \left[\frac{\partial}{\partial t} \left(\frac{\partial u}{\partial x} + \frac{\partial v}{\partial y} \right) - \left(\frac{\partial u}{\partial x}\frac{\partial u}{\partial x}+2\frac{\partial u}{\partial y}\frac{\partial v}{\partial x}+\frac{\partial v}{\partial y}\frac{\partial v}{\partial y} \right) \right]
$$
Note that p has no time dependence, so we are going to solve for p in pseudotime then move to the next time step and solve for u and v. This will require two operators, one for p (using p and pn) in pseudotime and one for u and v in time.
As shown in the Poisson equation tutorial, a TimeFunction can be used despite the lack of a time-dependence. This will cause Devito to allocate two grid buffers, which we can addressed directly via the terms pn and pn.forward. The internal time loop can be controlled by supplying the number of pseudotime steps (iterations) as a time argument to the operator.
The time steps are advanced through a Python loop where a separator operator calculates u and v.
Also note that we need to use first order spatial derivatives for the velocites and these derivatives are not the maximum spatial derivative order (2nd order) in these equations. This is the first time we have seen this in this tutorial series (previously we have only used a single spatial derivate order).
To use a first order derivative of a devito function, we use the syntax `function.dxc` or `function.dyc` for the x and y derivatives respectively.
```
from devito import TimeFunction, Function, \
Eq, solve, Operator, configuration
# Build Required Functions and derivatives:
# --------------------------------------
# |Variable | Required Derivatives |
# --------------------------------------
# | u | dt, dx, dy, dx**2, dy**2 |
# | v | dt, dx, dy, dx**2, dy**2 |
# | p | dx, dy, dx**2, dy**2 |
# | pn | dx, dy, dx**2, dy**2 |
# --------------------------------------
u = TimeFunction(name='u', grid=grid, space_order=2)
v = TimeFunction(name='v', grid=grid, space_order=2)
p = TimeFunction(name='p', grid=grid, space_order=2)
#Variables are automatically initalized at 0.
# First order derivatives will be handled with p.dxc
eq_u =Eq(u.dt + u*u.dx + v*u.dy, -1./rho * p.dxc + nu*(u.laplace), subdomain=grid.interior)
eq_v =Eq(v.dt + u*v.dx + v*v.dy, -1./rho * p.dyc + nu*(v.laplace), subdomain=grid.interior)
eq_p =Eq(p.laplace,rho*(1./dt*(u.dxc+v.dyc)-(u.dxc*u.dxc)+2*(u.dyc*v.dxc)+(v.dyc*v.dyc)), subdomain=grid.interior)
# NOTE: Pressure has no time dependence so we solve for the other pressure buffer.
stencil_u =solve(eq_u , u.forward)
stencil_v =solve(eq_v , v.forward)
stencil_p=solve(eq_p, p)
update_u =Eq(u.forward, stencil_u)
update_v =Eq(v.forward, stencil_v)
update_p =Eq(p.forward, stencil_p)
# Boundary Conds. u=v=0 for all sides
bc_u = [Eq(u[t+1, 0, y], 0)]
bc_u += [Eq(u[t+1, nx-1, y], 0)]
bc_u += [Eq(u[t+1, x, 0], 0)]
bc_u += [Eq(u[t+1, x, ny-1], 1)] # except u=1 for y=2
bc_v = [Eq(v[t+1, 0, y], 0)]
bc_v += [Eq(v[t+1, nx-1, y], 0)]
bc_v += [Eq(v[t+1, x, ny-1], 0)]
bc_v += [Eq(v[t+1, x, 0], 0)]
bc_p = [Eq(p[t+1, 0, y],p[t+1, 1,y])] # dpn/dx = 0 for x=0.
bc_p += [Eq(p[t+1,nx-1, y],p[t+1,nx-2, y])] # dpn/dx = 0 for x=2.
bc_p += [Eq(p[t+1, x, 0],p[t+1,x ,1])] # dpn/dy = 0 at y=0
bc_p += [Eq(p[t+1, x, ny-1],p[t+1, x, ny-2])] # pn=0 for y=2
bc_p += [Eq(p[t+1, 0, 0], 0)]
bc=bc_u+bc_v
optime=Operator([update_u, update_v]+bc_u+bc_v)
oppres=Operator([update_p]+bc_p)
# Silence non-essential outputs from the solver.
configuration['log-level'] = 'ERROR'
# This is the time loop.
for step in range(0,nt):
if step>0:
oppres(time_M = nit)
optime(time_m=step, time_M=step, dt=dt)
#NBVAL_IGNORE_OUTPUT
fig = pyplot.figure(figsize=(11,7), dpi=100)
# Plotting the pressure field as a contour.
pyplot.contourf(X, Y, p.data[0], alpha=0.5, cmap=cm.viridis)
pyplot.colorbar()
# Plotting the pressure field outlines.
pyplot.contour(X, Y, p.data[0], cmap=cm.viridis)
# Plotting velocity field.
pyplot.quiver(X[::2,::2], Y[::2,::2], u.data[0,::2,::2], v.data[0,::2,::2])
pyplot.xlabel('X')
pyplot.ylabel('Y');
```
### Validation
```
#NBVAL_IGNORE_OUTPUT
# Again, check results with Marchi et al 2009.
fig = pyplot.figure(figsize=(12, 6))
ax1 = fig.add_subplot(121)
ax1.plot(u.data[0,int(grid.shape[0]/2),:],y_coord[:])
ax1.plot(Marchi_Re10_u[:,1],Marchi_Re10_u[:,0],'ro')
ax1.set_xlabel('$u$')
ax1.set_ylabel('$y$')
ax1 = fig.add_subplot(122)
ax1.plot(x_coord[:],v.data[0,:,int(grid.shape[0]/2)])
ax1.plot(Marchi_Re10_v[:,0],Marchi_Re10_v[:,1],'ro')
ax1.set_xlabel('$x$')
ax1.set_ylabel('$v$')
pyplot.show()
```
The Devito implementation produces results consistent with the benchmark solution. There is a small disparity in a few of the velocity values, but this is expected as the Devito 41 x 41 node grid is much coarser than the benchmark on a 1024 x 1024 node grid.
## Comparison
```
#NBVAL_IGNORE_OUTPUT
fig = pyplot.figure(figsize=(12, 6))
ax1 = fig.add_subplot(121)
ax1.plot(a[int(npgrid[0]/2),:],y_coord[:])
ax1.plot(u.data[0,int(grid.shape[0]/2),:],y_coord[:],'--')
ax1.plot(Marchi_Re10_u[:,1],Marchi_Re10_u[:,0],'ro')
ax1.set_xlabel('$u$')
ax1.set_ylabel('$y$')
ax1 = fig.add_subplot(122)
ax1.plot(x_coord[:],b[:,int(npgrid[1]/2)])
ax1.plot(x_coord[:],v.data[0,:,int(grid.shape[0]/2)],'--')
ax1.plot(Marchi_Re10_v[:,0],Marchi_Re10_v[:,1],'ro')
ax1.set_xlabel('$x$')
ax1.set_ylabel('$v$')
ax1.legend(['numpy','devito','Marchi (2009)'])
pyplot.show()
#Pressure norm check
tol = 1e-3
assert np.sum((c[:,:]-d[:,:])**2/ np.maximum(d[:,:]**2,1e-10)) < tol
assert np.sum((p.data[0]-p.data[1])**2/np.maximum(p.data[0]**2,1e-10)) < tol
```
Overlaying all the graphs together shows how the Devito, NumPy and Marchi et al (2009)$^1$
solutions compare with each other. A final accuracy check is done which is to test whether the pressure norm has exceeded a specified tolerance.
| github_jupyter |
```
import cmath
import math
import numpy as np
import qiskit
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from typing import Optional, List, Dict
from qiskit_aws_braket_provider.awsprovider import AWSProvider
def compute_rotation(index_state):
if len(index_state) != 2:
return None, None
index_state = np.asarray(index_state)
if abs(np.linalg.norm(index_state)) < 1e-6:
return None, None
index_state = index_state / np.linalg.norm(index_state)
if abs(index_state[0] - index_state[1]) < 1e-6:
return None, None
a_1 = abs(index_state[0])
w_1 = cmath.phase(index_state[0])
a_2 = abs(index_state[1])
w_2 = cmath.phase(index_state[1])
alpha_z = w_2 - w_1
alpha_y = 2 * np.arcsin(abs(a_2) / np.sqrt(a_2 ** 2 + a_1 ** 2))
return alpha_y, alpha_z
def create_swap_test_circuit(index_state, theta, **kwargs):
# type: (List[float], float, Optional[dict]) -> QuantumCircuit
"""
:param index_state:
:param theta:
:param kwargs: use_barriers (bool) and readout_swap (Dict[int, int])
:return:
"""
use_barriers = kwargs.get('use_barriers', False)
readout_swap = kwargs.get('readout_swap', None)
q = qiskit.QuantumRegister(5, "q")
c = qiskit.ClassicalRegister(2, "c")
qc = qiskit.QuantumCircuit(q, c, name="improvement")
# Index on q_0
alpha_y, _ = compute_rotation(index_state)
if alpha_y is None:
qc.h(q[0])
else:
qc.ry(-alpha_y, q[0]).inverse()
if use_barriers: jupyter = qc.barrier()
# Conditionally exite x_1 on data q_2 (center!)
qc.h(q[2])
if use_barriers: qc.barrier()
qc.rz(math.pi, q[2]).inverse()
if use_barriers: qc.barrier()
qc.s(q[2])
if use_barriers: qc.barrier()
qc.cz(q[0], q[2])
if use_barriers: qc.barrier()
# Label y_1
qc.cx(q[0], q[1])
if use_barriers: qc.barrier()
# Ancilla Superposition
qc.h(q[4])
if use_barriers: qc.barrier()
# Unknown data
qc.rx(theta, q[3])
if use_barriers: qc.barrier()
# c-SWAP!!!
# standard.barrier(qc)
qc.cswap(q[4], q[2], q[3])
if use_barriers: qc.barrier()
# Hadamard on ancilla q_4
qc.h(q[4])
if use_barriers: qc.barrier()
# Measure on ancilla q_4 and label q_1
if readout_swap is not None:
qc.barrier()
for i in range(q.size):
j = readout_swap.get(i, i)
if i != j:
qc.swap(q[i], q[j])
else:
readout_swap = {}
qc.barrier()
m1 = readout_swap.get(4, 4)
m2 = readout_swap.get(1, 1)
qiskit.circuit.measure.measure(qc, q[m1], c[0])
qiskit.circuit.measure.measure(qc, q[m2], c[1])
return qc
def extract_classification(counts: Dict[str, int]) -> float:
shots = sum(counts.values())
return (counts.get('00', 0) - counts.get('01', 0) - counts.get('10', 0) + counts.get('11', 0)) / float(shots)
def compare_plot(theta, classification, classification_label=None, compare_classification=None, compare_classification_label=None):
plt.figure(figsize=(10, 7))
theta = theta if len(theta) == len(classification) else range(len(classification))
prefix_label = '{} '.format(classification_label) if classification_label is not None else ''
plt.scatter(x=[xx for xx, p in zip(theta, classification) if p >= 0],
y=[p for p in classification if p >= 0],
label=prefix_label + '$\\tilde{y} = 0$',
c='red',
marker='^',
linewidths=1.0)
plt.scatter(x=[xx for xx, p in zip(theta, classification) if p < 0],
y=[p for p in classification if p < 0],
label=prefix_label + '$\\tilde{y} = 1$',
c='white',
marker='^',
linewidths=1.0, edgecolors='red')
y_lim_lower = min(classification) - 0.1
y_lim_upper = max(classification) + 0.1
if compare_classification is not None and len(compare_classification) == len(classification):
prefix_label = '{} '.format(compare_classification_label) if compare_classification_label is not None else ''
plt.scatter(x=[xx for xx, p in zip(theta, compare_classification) if p >= 0],
y=[p for p in compare_classification if p >= 0],
label=prefix_label + '$\\tilde{y} = 0$',
c='blue',
marker='s',
linewidths=1.0)
plt.scatter(x=[xx for xx, p in zip(theta, compare_classification) if p < 0],
y=[p for p in compare_classification if p < 0],
label=prefix_label + '$\\tilde{y} = 1$',
c='white',
marker='s',
linewidths=1.0, edgecolors='blue')
y_lim_lower = min(min(compare_classification) - 0.1, y_lim_lower)
y_lim_upper = max(max(compare_classification) + 0.1, y_lim_upper)
plt.legend(fontsize=17)
plt.xlabel("$\\theta$ (rad.)", fontsize=22)
plt.ylabel("$\\langle \\sigma_z^{(a)} \\sigma_z^{(l)} \\rangle$", fontsize=22)
plt.tick_params(labelsize=22)
plt.ylim((y_lim_lower, y_lim_upper))
index_state = [np.sqrt(2), np.sqrt(2)]
theta_list = np.arange(start=0, stop=2*np.pi, step=0.2)
qc_list = [create_swap_test_circuit(index_state, theta=theta) for theta in theta_list]
qc_list[0].draw()
provider = AWSProvider(region_name='us-east-1')
backend = provider.get_backend('IonQ Device')
sim_backend = provider.get_backend('SV1')
qc_transpiled_list = qiskit.transpile(qc_list, backend)
qobj = qiskit.assemble(qc_transpiled_list, backend, shots=100)
backend.estimate_costs(qobj), sim_backend.estimate_costs(qobj)
# ATTENTION!!!!!!
# Uncomment to execute
# BE AWARE that this will create costs!
# ATTENTION!!!!!!
# job = backend.run(qobj, extra_data={
# 'index_state': index_state,
# 'theta_list': list(theta_list)
# })
# job_id = job.job_id()
#
# sim_job = sim_backend.run(qobj, extra_data={
# 'index_state': index_state,
# 'theta_list': list(theta_list)
# })
# sim_job_id = sim_job.job_id()
#
# job_id, sim_job_id
# Please input the job ids here
sim_retrieved_job = sim_backend.retrieve_job('<sim_job_id>')
retrieved_job = backend.retrieve_job('<job_id>')
result = retrieved_job.result()
sim_result = sim_retrieved_job.result()
x = retrieved_job.extra_data['theta_list']
experiment_classification = [extract_classification(c) for c in result.get_counts()]
simulation_classification = [extract_classification(c) for c in sim_result.get_counts()]
compare_plot(
theta=theta_list,
classification=experiment_classification, classification_label='experiment',
compare_classification=simulation_classification, compare_classification_label='simulation'
)
```
| github_jupyter |
```
# Initialize OK
from client.api.notebook import Notebook
ok = Notebook('hw01.ok')
# Run this cell, but please don't change it.
# These lines import the Numpy and Datascience modules.
import numpy as np
from datascience import *
np.set_printoptions(threshold=50)
# These lines do some fancy plotting magic
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plots
plots.style.use('fivethirtyeight')
#from client.api.notebook import Notebook
#ok = Notebook('hw01.ok')
#_ = ok.auth(inline=True)
```
# Homework 1: Population Trends
_The examples in this assignment are based directly on Chapters 6.3 and 6.4 of the_ [online textbook](https://www.inferentialthinking.com/chapters/06/3/Example_Trends_in_the_Population_of_the_United_States.html). Some information was removed and new information and questions were added in italics. Feel free to cross-reference the book to figure out how to solve the questions.
### Read all instructions carefully
**To maximize your learning and understanding of the material, we strongly recommend carefully reading the instructions and making an honest attempt at solving the problem yourself (i.e., on your own) before discussing it with anyone or asking for help.**
This assignment should be your own work, done entirely by you using your own words and solutions (using the code provided in the textbook).
By submitting this assignment, you acknowldge that you have read the information on [Academic Integrity](https://studentconduct.sa.ucsb.edu/academic-integrity) and verify that this assignment constitutes your own work.
**Important**: The `ok` tests don't usually tell you that your answer is correct. More often, they help catch careless mistakes. It's up to you to ensure that your answer is correct. If you're not sure, ask someone (not for the answer, but for some guidance about your approach).
Submitting your work:
Once you're finished, select "Save and Checkpoint" in the File menu and then execute the `ok.submit()` cell below. See additional instructions on how to submit your work at the end of this notebook.
# The U.S. Census Data
_Before we begin looking at the files, let's first understand what we are working with and why.
According to the [Decennial Census of Population and Housing](https://www.census.gov/programs-surveys/decennial-census/about.html):
"Every 10 years, the U.S. Census Bureau conducts a census to determine the number of people living in the United States." Read more about it on the linked page and in your own words explain why the census takes place._
<!--
BEGIN QUESTION
name: q1_0
manual: true
-->
<!-- EXPORT TO PDF -->
_Write your explanation here._
# Example: Population Trends
The file below contains "Annual Estimates of the Resident Population by Single Year of Age and Sex for the United States." Notice that `read_table` can read data directly from a URL.
```
# As of Jan 2017, this census file is online here:
data = 'http://www2.census.gov/programs-surveys/popest/datasets/2010-2015/national/asrh/nc-est2015-agesex-res.csv'
# A local copy can be accessed here in case census.gov moves the file:
# data = path_data + 'nc-est2015-agesex-res.csv'
full_census_table_2015 = Table.read_table(data)
full_census_table_2015
# As of Nov 2019, this agesex-res file for 2018 is not yet available, so we'll use 2017 that is online here:
data = 'http://www2.census.gov/programs-surveys/popest/datasets/2010-2017/national/asrh/nc-est2017-agesex-res.csv'
# A local copy can be accessed here in case census.gov moves the file:
# data = path_data + 'nc-est2017-agesex-res.csv'
full_census_table_2017 = Table.read_table(data)
full_census_table_2017
```
Only the first 10 rows of the table are displayed. You can use `.show()` to display the entire table; however, this is typically not useful with large tables.
A [description of the table](http://www2.census.gov/programs-surveys/popest/datasets/2010-2015/national/asrh/nc-est2015-agesex-res.pdf) appears online.
_This information is referred to as "metadata", that is data about the data._
The `SEX` column contains numeric codes: `0` stands for the total, `1` for male, and `2` for female. The `AGE` column contains ages in completed years, but the special value `999` is a sum of the total population. The rest of the columns contain estimates of the US population.
Typically, a public table will contain more information than necessary for a particular investigation or analysis. In this case, let us suppose that we are only interested in the population changes from 2010 to 2014. Let us `select` the relevant columns.
_In this assignment, let's compare the CSV file used by the textbook (2015 estimates) as well as the latest available CSV from 2017. Let's see if the population estimates for 2010 and 2014 are the same in both files._
```
# use full_census_table_2015
partial_census_table_2015 = full_census_table_2015.select(
'SEX', 'AGE', 'POPESTIMATE2010', 'POPESTIMATE2014')
partial_census_table_2015
```
_Now, try loading the estimates for the same years (2010 and 2014) along with the most recent estimates from 2017._
<!--
BEGIN QUESTION
name: q1_1
manual: false
points: 2
-->
```
# use full_census_table_2017
...
partial_census_table_2017
ok.grade("q1_1");
```
We can also simplify the labels of the selected columns.
```
us_pop_2015 = partial_census_table_2015.relabeled('POPESTIMATE2010', '2010').relabeled('POPESTIMATE2014', '2014')
us_pop_2015.show(3)
```
Create a new table using the `partial_census_table_2017` with the correctly relabeled columns.
<!--
BEGIN QUESTION
name: q1_2
manual: false
points: 2
-->
```
us_pop_2017 = ...
us_pop_2017.show(3)
ok.grade("q1_2");
```
We now have a table that is easy to work with. Each column of the table is an array of the same length, and so columns can be combined using arithmetic. Here is the change in population between 2010 and 2014.
```
# the change computed from the 2015 estimation
us_pop_2015.column('2014') - us_pop_2015.column('2010')
```
_Let's see if the change in population between 2010 and 2014 as estimated in 2017 is the same as what was estimated in 2015._
```
# the change between 2010 and 2014 computed from the 2017 estimation
...
```
_How different is the population estimate for 2010 or 2014 between the two files?_
```
us_pop_2015.column('2014') - us_pop_2017.column('2014')
```
_It looks like the population estimates for the same year vary depending on when the prediction was made._
_If we consult the official ["Population and Housing Unit Estimates Tables" website](https://www.census.gov/programs-surveys/popest/data/tables.html), it states that:
"Each new series of data (called vintages) incorporates the latest administrative record data, geographic boundaries, and methodology. Therefore, the entire time series of estimates beginning with the most recent decennial census is revised annually, and estimates from different vintages of data may not be consistent across geography and characteristics detail."_
_Since the numbers for the same year are re-estimated, let us use the most recent estimates from 2017, which are stored in_ `us_pop_2017`.
## Population Change
Let us augment each `us_pop` table with a column that contains these changes, both in absolute terms and as percents relative to the value in 2010.
```
# this is the code from the textbook with the old table name
# change = us_pop.column('2014') - us_pop.column('2010')
# census = us_pop.with_columns(
# 'Change', change,
# 'Percent Change', change/us_pop.column('2010')
# )
# census.set_format('Percent Change', PercentFormatter)
```
_So far we have been copying and pasting the same code and changing the name of the table. Doing so it tells us that we can write a function that uses the name of a table as an argument. Using a function, we can apply the same sequence of steps to different tables and/or to different columns._
```
def add_census_change_column( pop_table, year1, year2 ):
"""
Given the population table `pop_table` and two years
(`year1` and `year2` are strings) compute the change
in column values between those years (year2 > year1).
Create a `census` table and add the computed change
as a column called "Change" and another column
called "Percent Change" with the computed percents
"""
...
return census.set_format('Percent Change', PercentFormatter)
census2015 = add_census_change_column( us_pop_2017, "2010", "2014" ).drop("2017")
census2015.show(5)
census2017 = add_census_change_column( us_pop_2017, "2010", "2017" ).drop("2014")
census2017.show(5)
```
**Sorting the data.** Let us sort the _two resulting tables_ in decreasing order of the absolute change in population.
```
...
...
```
Not surprisingly, the top row of the sorted table is the line that corresponds to the entire population: both sexes and all age groups. From 2010 to 2014, the population of the United States increased by about 9.5 million people, a change of just over 3%.
_How much did the population estimate change in 2017? Is the change larger or smaller than it was in 2014? Are there more males or females?_
<!--
BEGIN QUESTION
name: q2_3
manual: true
-->
<!-- EXPORT TO PDF -->
_Write your answer here._
The next two rows correspond to all the men and all the women respectively. The male population grew more than the female population, both in absolute and percentage terms. Both percent changes were around 3% in 2014.
Now take a look at the next few rows. The percent change jumps from about 3% for the overall population in 2014 to almost 30% for the people in their late sixties and early seventies. This stunning change contributes to what is known as the greying of America.
By far the greatest absolute change was among those in the 64-67 agegroup in 2014. What could explain this large increase? We can explore this question by examining the years in which the relevant groups were born.
- Those who were in the 64-67 age group in 2010 were born in the years 1943 to 1946. The attack on Pearl Harbor was in late 1941, and by 1942 U.S. forces were heavily engaged in a massive war that ended in 1945.
- Those who were 64 to 67 years old in 2014 were born in the years 1947 to 1950, at the height of the post-WWII baby boom in the United States.
The post-war jump in births is the major reason for the large changes that we have observed.
# Example: Trends in Gender
We are now equipped with enough coding skills to examine features and trends in subgroups of the U.S. population. In this example, we will look at the distribution of males and females across age groups. We will continue using the `us_pop_2017` table from the previous section.
```
us_pop = us_pop_2017
us_pop
```
Here is a reminder of what the table contains.
Each row represents an age group. The `SEX` column contains numeric codes: `0` stands for the total, `1` for male, and `2` for female. The `AGE` column contains ages in completed years, but the special value `999` represents the entire population regardless of age. The rest of the columns contain estimates of the US population.
### Understanding `AGE` = 100 ###
As a preliminary, let's interpret data in the final age category in the table, where `AGE` is 100. The code below extracts the rows for the combined group of men and women (`SEX` code 0) for the ages above 97.
<!--
BEGIN QUESTION
name: q_age_100
manual: false
points: 2
-->
```
older_pop = ...
older_pop
ok.grade("q_age_100");
```
Not surprisingly, the numbers of people are smaller at higher ages – for example, there are fewer 99-year-olds than 98-year-olds.
It does come as a surprise, though, that the numbers for `AGE` 100 are quite a bit larger than those for age 99.
_Read the book (or the table documentation) for an explanation of why this is the case. In your own words provide an explanation for this phenomena._
<!--
BEGIN QUESTION
name: q2_1
manual: true
-->
<!-- EXPORT TO PDF -->
_Write your answer here._
### Overall Proportions of Males and Females ###
We will now begin looking at gender ratios in 2014. First, let's look at all the age groups together. Remember that this means looking at the rows where the "age" is coded 999. The table `all_ages` contains this information. There are three rows: one for the total of both genders, one for males (`SEX` code 1), and one for females (`SEX` code 2).
```
us_pop_latest = us_pop.drop('2010')
all_ages = ...
all_ages
```
Row 0 of `all_ages` contains the total U.S. population in each of the two years. The United States had just under 319 million in 2014. _Looks like in 2017 the population increased to 325 million._
_Calculate the overall growth rate for the population between the estimation in 2014 and 2017._
_Hint 1: Use the function you already defined above to add the "Change" and "Percent Change" columns._
_Hint 2: Use the table_ `all_ages` _as the input argument_.
<!--
BEGIN QUESTION
name: q_census_change
manual: false
points: 2
-->
```
census_change = ...
ok.grade("q_census_change");
census_change.show()
```
Row 1 contains the counts for males and Row 2 for females. Compare these two rows to see that in 2014 _and in 2017_, there were more females than males in the United States.
The population counts in Row 1 and Row 2 add up to the total population in Row 0.
For comparability with other quantities, we will need to convert these counts to percents out of the total population. Let's access the total for 2014 and name it. Then, we'll show a population table with a proportion column. _In order to repeat the same analysis for the year 2017 without copy/pasting the code, let's define a new function and use it in order to obtain the proportions._
<!--
BEGIN QUESTION
name: q_add_proportion
manual: false
points: 2
-->
```
def add_proportion( pop_table, year ):
"""
Given the population table `pop_table` and a year
(`year` is a string) compute the proportion for that
year, given the total population in that year .
Add the computed column called "Proportion" and
return the resulting table.
"""
pop_in_year = ...
result_table = pop_table.with_column(
'Proportion', pop_table.column(year) / pop_in_year
).set_format('Proportion', PercentFormatter)
return result_table
ok.grade("q_add_proportion");
pop_2014 = add_proportion(all_ages, "2014")
pop_2014.drop("2017")
pop_2017 = add_proportion(all_ages, "2017")
pop_2017.drop("2014")
```
Consistent with our earlier observation that there were more females than males, about 50.8% of the population in 2014 was female and about 49.2% male in each of the two years.
### Proportions of Boys and Girls among Infants
When we look at infants, however, the opposite is true. Let's define infants to be babies who have not yet completed one year, represented in the row corresponding to `AGE` 0. Here are their numbers in the population (_using the table_ `us_pop_latest`). You can see that male infants outnumbered female infants.
<!--
BEGIN QUESTION
name: q_infants
manual: false
points: 2
-->
```
infants = ...
infants
ok.grade("q_infants");
```
As before, we can convert these counts to percents out of the total numbers of infants. The resulting table shows that in 2014 and 2017, just over 51% of infants in the U.S. were male.
```
infants_2014 = add_proportion(infants, "2014")
infants_2014.drop("2017")
infants_2017 = add_proportion(infants, "2017")
infants_2017.drop("2014")
```
In fact, it has long been observed that the proportion of boys among newborns is slightly more than 1/2. The reason for this is not thoroughly understood, and [scientists are still working on it](http://www.npr.org/sections/health-shots/2015/03/30/396384911/why-are-more-baby-boys-born-than-girls).
### Female:Male Gender Ratio at Each Age ###
We have seen that while there are more baby boys than baby girls, there are more females than males overall. So it's clear that the split between genders must vary across age groups.
To study this variation, we will separate out the data for the females and the males, and eliminate the row where all the ages are aggregated and `AGE` is coded as 999.
The tables `females` and `males` contain the data for each the two genders.
```
females_all_rows = ...
females = ...
females
males_all_rows = ...
males = ...
males
```
The plan now is to compare the number of women and the number of men at each age, for each of the two years. Array and Table methods give us straightforward ways to do this. Both of these tables have one row for each age.
```
males.column('AGE')
females.column('AGE')
```
For any given age, we can get the Female:Male gender ratio by dividing the number of females by the number of males. To do this in one step, we can use `column` to extract the array of female counts and the corresponding array of male counts, and then simply divide one array by the other. Elementwise division will create an array of gender ratios for all the years.
_Let's store the result in a table that has the `AGE`, `2014 F:M RATIO` and `2017 F:M RATIO` columns._
<!--
BEGIN QUESTION
name: q_ratios
manual: false
points: 2
-->
```
ratios = Table().with_columns(
...
)
ratios
ok.grade("q_ratios");
```
You can see from the display that the ratios are all around 0.96 for children aged nine or younger. When the Female:Male ratio is less than 1, there are fewer females than males. Thus what we are seeing is that there were fewer girls than boys in each of the age groups 0, 1, 2, and so on through 9. Moreover, in each of these age groups, there were about 96 girls for every 100 boys.
So how can the overall proportion of females in the population be higher than the males?
Something extraordinary happens when we examine the other end of the age range. Here are the Female:Male ratios for people aged more than 75.
<!--
BEGIN QUESTION
name: q_older_than_75
manual: false
points: 2
-->
```
older_than_75 = ...
older_than_75
ok.grade("q_older_than_75");
```
Not only are all of these ratios greater than 1, signifying more women than men in all of these age groups, many of them are considerably greater than 1.
- At ages 89 and 90 the ratios are close to 2, meaning that there were about twice as many women as men at those ages in 2014.
- At ages 98 and 99, there were about 3.5 to 4 times as many women as men.
If you are wondering how many people there were at these advanced ages, you can use Python to find out:
<!--
BEGIN QUESTION
name: q1_3_1
manual: false
points: 2
-->
```
males_older_than_98 = ...
males_older_than_98
ok.grade("q1_3_1");
```
Do the same for the female counts.
<!--
BEGIN QUESTION
name: q1_3_2
manual: false
points: 2
-->
```
females_older_than_98 = ...
females_older_than_98
ok.grade("q1_3_2");
```
The graph below shows the gender ratios plotted against age. The blue curve shows the 2014 ratio by age; _the gold curve shows the same ratio in 2017_.
The ratios are almost 1 (signifying close to equal numbers of males and females) for ages 0 through 60, but they start shooting up dramatically (more females than males) starting at about age 65.
```
ratios.plot('AGE')
```
_We can zoom-in on the graph above to take a closer look at how the ratios for the estimation in 2014 differ from the 2017 estimations. To do this, we can plot the ratios for the ages 75 and above._
```
ratios.where('AGE', are.above(74)).plot('AGE')
```
# Bonus
We encourage you to look at the information available on the <https://census.gov> website. Load the file(s) in the cells below and see what other insights you can gain from visualizing and analyzing the various data.
```
# Optional portion of the assignment to practice your skills
# and discover new insights.
```
# Submission
To submit:
1. `Save and Checkpoint` from the `File` menu.
2. `Kernel -> Restart & Clear Output` (make sure to save your work first!).
3. `Cell -> Run All` to ensure that you have executed all cells, including the test cells.
4. Read through the notebook to make sure there are **no errors** and you answered **all questions**.
4. Submit using the cell below. The result will contain a link that you can use to check that your assignment has been submitted successfully. If you submit more than once before the deadline, we will only grade your final submission.
# Submit
Make sure you have run all cells in your notebook in order before running the cell below, so that all images/graphs appear in the output.
**Please save before submitting!**
<!-- EXPECT 3 EXPORTED QUESTIONS -->
```
# Save your notebook first, then run this cell to submit.
import jassign.to_pdf
jassign.to_pdf.generate_pdf('hw01.ipynb', 'hw01.pdf')
ok.submit()
```
| github_jupyter |
```
import os
import random
import torch
import torchvision.transforms as standard_transforms
import scipy.io as sio
import matplotlib
import pandas as pd
import misc.transforms as own_transforms
import warnings
from torch.autograd import Variable
from torch.utils.data import DataLoader
from PIL import Image, ImageOps
from matplotlib import pyplot as plt
from tqdm import trange, tqdm
from misc.utils import *
from models.CC import CrowdCounter
from config import cfg
import CCAugmentation as cca
from datasets.SHHB.setting import cfg_data
from load_data import CustomDataset
torch.cuda.set_device(0)
torch.backends.cudnn.benchmark = True
warnings.filterwarnings('ignore')
mean_std = ([0.452016860247, 0.447249650955, 0.431981861591],[0.23242045939, 0.224925786257, 0.221840232611])
img_transform = standard_transforms.Compose([
standard_transforms.ToTensor(),
standard_transforms.Normalize(*mean_std)
])
restore = standard_transforms.Compose([
own_transforms.DeNormalize(*mean_std),
standard_transforms.ToPILImage()
])
pil_to_tensor = standard_transforms.ToTensor()
# model_path = './exp/11-26_08-28_SHHB_CSRNet_1e-05_[noAug]/all_ep_189_mae_11.13_mse_17.04.pth'
# model_path = './exp/11-26_11-30_SHHB_CSRNet_1e-05_[noAug]/all_ep_168_mae_12.35_mse_17.60.pth'
# model_path = './exp/11-26_14-31_SHHB_CSRNet_1e-05_[noAug]/all_ep_185_mae_11.21_mse_16.96.pth'
model_path = './exp/11-29_06-54_SHHB_CSRNet_1e-05/all_ep_241_mae_0.38_mse_0.60.pth'
net = CrowdCounter(cfg.GPU_ID,cfg.NET)
net.load_state_dict(torch.load(model_path))
net.cuda()
net.eval()
val_pipeline = cca.Pipeline(
cca.examples.loading.SHHLoader("/dataset/ShanghaiTech", "test", "B"), []
).execute_generate()
val_loader = DataLoader(CustomDataset(val_pipeline), batch_size=cfg_data.VAL_BATCH_SIZE, num_workers=1, drop_last=False)
val_img = list(val_loader)
start = 0
N = 3
for vi, data in enumerate(val_img[start:start+N], 0):
img, gt_map = data
with torch.no_grad():
img = Variable(img).cuda()
pred_map = net.test_forward(img)
pred_map = pred_map.data.cpu().numpy()
new_img = img.data.cpu().numpy()
new_img = np.moveaxis(new_img, 1, 2)
new_img = np.moveaxis(new_img, 2, 3)
new_img = np.squeeze(new_img)[:,:,::-1]
pred_cnt = np.sum(pred_map[0])/100.0
gt_count = np.sum(gt_map.data.cpu().numpy())/100.0
fg, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(16, 5))
plt.suptitle(' '.join([
'count_label:', str(round(gt_count, 3)),
'count_prediction:', str(round(pred_cnt, 3))
]))
ax0.imshow(np.uint8(new_img))
ax1.imshow(np.squeeze(gt_map), cmap='jet')
ax2.imshow(np.squeeze(pred_map), cmap='jet')
plt.show()
mae = np.empty(len(val_img))
mse = np.empty(len(val_img))
for vi, data in enumerate(tqdm(val_img), 0):
img, gt_map = data
with torch.no_grad():
img = Variable(img).cuda()
pred_map = net.test_forward(img)
pred_map = pred_map.data.cpu().numpy()
pred_cnt = np.sum(pred_map[0])/100.0
gt_count = np.sum(gt_map.data.cpu().numpy())/100.0
mae[vi] = np.abs(gt_count-pred_cnt)
mse[vi] = (gt_count-pred_cnt)**2
print('MAE:', round(mae.mean(),2))
print('MSE:', round(np.sqrt(mse.mean()),2))
```
| github_jupyter |
```
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
# !git pull
import tensorflow as tf
import malaya_speech
import malaya_speech.train
from malaya_speech.train.model import tacotron2_nvidia as tacotron2
import numpy as np
input_ids = tf.placeholder(tf.int32, [1, None])
input_lengths = tf.placeholder(tf.int32, [1])
mel_outputs = tf.placeholder(tf.float32, [1, None, 80])
mel_lengths = tf.placeholder(tf.int32, [1])
_pad = 'pad'
_start = 'start'
_eos = 'eos'
_punctuation = "!'(),.:;? "
_special = '-'
_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
MALAYA_SPEECH_SYMBOLS = (
[_pad, _start, _eos] + list(_special) + list(_punctuation) + list(_letters)
)
model = tacotron2.Model([input_ids, input_lengths],
[mel_outputs, mel_lengths],
len(MALAYA_SPEECH_SYMBOLS), training = False)
r = model.decoder_logits['outputs']
decoder_output, post_mel_outputs, alignment_histories, _, _, _ = r
stop_token_predictions = model.decoder_logits['stop_token_prediction']
stop_token_predictions = stop_token_predictions[:, :, 0]
decoder_output = tf.identity(decoder_output, name = 'decoder_output')
post_mel_outputs = tf.identity(post_mel_outputs, name = 'post_mel_outputs')
alignment_histories = tf.identity(alignment_histories, name = 'alignment_histories')
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
path = 'tacotron2-case-male'
ckpt_path = tf.train.latest_checkpoint(path)
ckpt_path
saver = tf.train.Saver()
saver.restore(sess, ckpt_path)
import re
from unidecode import unidecode
import malaya
# Regular expression matching text enclosed in curly braces:
_curly_re = re.compile(r"(.*?)\{(.+?)\}(.*)")
normalizer = malaya.normalize.normalizer(date = False, time = False)
pad_to = 8
def tts_encode(string: str, add_eos: bool = True):
r = [MALAYA_SPEECH_SYMBOLS.index(c) for c in string if c in MALAYA_SPEECH_SYMBOLS]
if add_eos:
r = r + [MALAYA_SPEECH_SYMBOLS.index('eos')]
return r
def put_spacing_num(string):
string = re.sub('[A-Za-z]+', lambda ele: ' ' + ele[0] + ' ', string)
return re.sub(r'[ ]+', ' ', string).strip()
def convert_to_ascii(string):
return unidecode(string)
def collapse_whitespace(string):
return re.sub(_whitespace_re, ' ', string)
def cleaning(string, normalize = True, add_eos = True):
sequence = []
string = convert_to_ascii(string)
string = string.replace('&', ' dan ')
if normalize:
string = normalizer.normalize(string,
check_english = False,
normalize_entity = False,
normalize_text = False,
normalize_url = True,
normalize_email = True)
string = string['normalize']
else:
string = string
string = string.lower()
string = put_spacing_num(string)
string = re.sub(r'[ ]+', ' ', string).strip()
ids = tts_encode(string, add_eos = add_eos)
text_input = np.array(ids)
num_pad = pad_to - ((len(text_input) + 2) % pad_to)
text_input = np.pad(
text_input, ((1, 1)), 'constant', constant_values = ((1, 2))
)
text_input = np.pad(
text_input, ((0, num_pad)), 'constant', constant_values = 0
)
return string, text_input
import matplotlib.pyplot as plt
t, ids = cleaning('Secara amnya, ini adalah koalisi yang melibatkan Pakatan Harapan, Keadilan, DAP dan Amanah kembali bersama Tun Dr Mahathir Mohamad dan kemnya (partinya Pejuang yang masih belum berdaftar)')
t, ids
o = sess.run(model.decoder_logits,
feed_dict = {input_ids: [ids], input_lengths: [len(ids)]})
o['outputs'][0].shape, o['outputs'][1].shape, o['outputs'][2].shape
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
ax.set_title(f'Alignment steps')
im = ax.imshow(
o['outputs'][2][0],
aspect='auto',
origin='lower',
interpolation='none')
fig.colorbar(im, ax=ax)
xlabel = 'Decoder timestep'
plt.xlabel(xlabel)
plt.ylabel('Encoder timestep')
plt.tight_layout()
plt.show()
mel_outputs_ = np.reshape(o['outputs'][0], [-1, 80])
fig = plt.figure(figsize=(10, 8))
ax1 = fig.add_subplot(311)
ax1.set_title(f'Predicted Mel-before-Spectrogram')
im = ax1.imshow(np.rot90(mel_outputs_), aspect='auto', interpolation='none')
fig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)
plt.show()
mel_outputs_ = np.reshape(o['outputs'][1], [-1, 80])
fig = plt.figure(figsize=(10, 8))
ax1 = fig.add_subplot(311)
ax1.set_title(f'Predicted Mel-after-Spectrogram')
im = ax1.imshow(np.rot90(mel_outputs_), aspect='auto', interpolation='none')
fig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)
plt.show()
import pickle
with open('a.pkl', 'wb') as fopen:
pickle.dump([np.reshape(o['outputs'][0], [-1, 80]), np.reshape(o['outputs'][1], [-1, 80])], fopen)
saver = tf.train.Saver()
saver.save(sess, 'tacotron2-male-output/model.ckpt')
strings = ','.join(
[
n.name
for n in tf.get_default_graph().as_graph_def().node
if ('Variable' in n.op
or 'gather' in n.op.lower()
or 'Placeholder' in n.name
or 'post_mel_outputs' in n.name
or 'decoder_output' in n.name
or 'alignment_histories' in n.name)
and 'adam' not in n.name
and 'global_step' not in n.name
and 'Assign' not in n.name
and 'ReadVariableOp' not in n.name
and 'Gather' not in n.name
]
)
strings.split(',')
def freeze_graph(model_dir, output_node_names):
if not tf.gfile.Exists(model_dir):
raise AssertionError(
"Export directory doesn't exists. Please specify an export "
'directory: %s' % model_dir
)
checkpoint = tf.train.get_checkpoint_state(model_dir)
input_checkpoint = checkpoint.model_checkpoint_path
absolute_model_dir = '/'.join(input_checkpoint.split('/')[:-1])
output_graph = absolute_model_dir + '/frozen_model.pb'
clear_devices = True
with tf.Session(graph = tf.Graph()) as sess:
saver = tf.train.import_meta_graph(
input_checkpoint + '.meta', clear_devices = clear_devices
)
saver.restore(sess, input_checkpoint)
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess,
tf.get_default_graph().as_graph_def(),
output_node_names.split(','),
)
with tf.gfile.GFile(output_graph, 'wb') as f:
f.write(output_graph_def.SerializeToString())
print('%d ops in the final graph.' % len(output_graph_def.node))
freeze_graph('tacotron2-male-output', strings)
def load_graph(frozen_graph_filename):
with tf.gfile.GFile(frozen_graph_filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def)
return graph
g = load_graph('tacotron2-male-output/frozen_model.pb')
output_nodes = ['decoder_output',
'post_mel_outputs',
'alignment_histories']
outputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in output_nodes}
outputs
from tensorflow.tools.graph_transforms import TransformGraph
transforms = ['add_default_attributes',
'remove_nodes(op=Identity, op=CheckNumerics)',
'fold_batch_norms',
'fold_old_batch_norms',
'quantize_weights(fallback_min=-1024, fallback_max=1024)',
'strip_unused_nodes',
'sort_by_execution_order']
pb = 'tacotron2-male-output/frozen_model.pb'
input_graph_def = tf.GraphDef()
with tf.gfile.FastGFile(pb, 'rb') as f:
input_graph_def.ParseFromString(f.read())
transformed_graph_def = TransformGraph(input_graph_def,
['Placeholder', 'Placeholder_1'],
output_nodes, transforms)
with tf.gfile.GFile(f'{pb}.quantized', 'wb') as f:
f.write(transformed_graph_def.SerializeToString())
b2_application_key_id = os.environ['b2_application_key_id']
b2_application_key = os.environ['b2_application_key']
from b2sdk.v1 import *
info = InMemoryAccountInfo()
b2_api = B2Api(info)
application_key_id = b2_application_key_id
application_key = b2_application_key
b2_api.authorize_account("production", application_key_id, application_key)
file_info = {'how': 'good-file'}
b2_bucket = b2_api.get_bucket_by_name('malaya-speech-model')
file = 'tacotron2-male-output/frozen_model.pb'
outPutname = 'v2/tts/tacotron2-male.pb'
b2_bucket.upload_local_file(
local_file=file,
file_name=outPutname,
file_infos=file_info,
)
file = 'tacotron2-male-output/frozen_model.pb.quantized'
outPutname = 'v2/tts/tacotron2-male.pb.quantized'
b2_bucket.upload_local_file(
local_file=file,
file_name=outPutname,
file_infos=file_info,
)
file = '/home/husein/speech-bahasa/male-stats-v3/stats.npy'
outPutname = 'v2/vocoder-stats/male.npy'
b2_bucket.upload_local_file(
local_file=file,
file_name=outPutname,
file_infos=file_info,
)
```
| github_jupyter |
Copyright 2016 Google Inc. All Rights Reserved.
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.
## Gated Feedback Recurrent Neural Network
This notebook contains a Tensorflow (http://www.tensorflow.org) implementation of the Gated Feedback Recurrent Neural Network (the LSTM version) from this paper: http://arxiv.org/pdf/1502.02367v4.pdf
```
import tensorflow as tf
from tensorflow.models.rnn.ptb import reader
import numpy as np
train_data, valid_data, test_data, vocab = reader.ptb_raw_data('simple-examples/data/')
# Hyperparameters
batch_size = 20
num_steps = 20
hidden_size = 200
emb_size = 200 # Note: this is kind of a cheat. This will *not* work if emb_size != hidden_size
vocab_size = 10000
epochs = 2
init_scale = 0.1
num_hidden_layers = 1
lr = tf.placeholder(tf.float32, [])
## Build Model
session = tf.Session()
X = tf.placeholder(tf.int32, [batch_size, num_steps])
targets = tf.placeholder(tf.int64, [batch_size, num_steps])
embedding = tf.Variable(
tf.random_uniform([vocab_size, emb_size], minval=-init_scale, maxval=init_scale),
name="embedding")
# For input gate.
Wi = [tf.Variable(
tf.random_uniform([emb_size, hidden_size], minval=-init_scale, maxval=init_scale),
name="Wi_%d" % i) for i in range(num_hidden_layers)]
Ui = [tf.Variable(
tf.random_uniform([hidden_size, hidden_size], minval=-init_scale, maxval=init_scale),
name="Ui_%d" % i) for i in range(num_hidden_layers)]
# For forget gate.
Wf = [tf.Variable(
tf.random_uniform([emb_size, hidden_size], minval=-init_scale, maxval=init_scale),
name="Wf_%d" % i) for i in range(num_hidden_layers)]
Uf = [tf.Variable(
tf.random_uniform([hidden_size, hidden_size], minval=-init_scale, maxval=init_scale),
name="Uf_%d" % i) for i in range(num_hidden_layers)]
# For content -- Quick note: there's no transformation from content -> state. They are both
# the same size.
Wc = [tf.Variable(
tf.random_uniform([emb_size, hidden_size], minval=-init_scale, maxval=init_scale),
name="Wc_%d" % i) for i in range(num_hidden_layers)]
Uc = [tf.Variable(
tf.random_uniform([hidden_size, hidden_size], minval=-init_scale, maxval=init_scale),
name="Uc_%d" % i) for i in range(num_hidden_layers)]
# For hidden state output gate.
Wo = [tf.Variable(
tf.random_uniform([emb_size, hidden_size], minval=-init_scale, maxval=init_scale),
name="Wo_%d" % i) for i in range(num_hidden_layers)]
Uo = [tf.Variable(
tf.random_uniform([hidden_size, hidden_size], minval=-init_scale, maxval=init_scale),
name="Uo_%d" % i) for i in range(num_hidden_layers)]
# For gated feedback gates (e.g. the contribution of the paper).
Wg = [tf.Variable(
tf.random_uniform([emb_size, 1], minval=-init_scale, maxval=init_scale),
name="Wg_%d" % i) for i in range(num_hidden_layers)]
Ug = [tf.Variable(
tf.random_uniform([hidden_size * num_hidden_layers, 1], minval=-init_scale, maxval=init_scale),
name="Ug_%d" % i) for i in range(num_hidden_layers)]
# For output.
output_weights = tf.Variable(
tf.random_uniform([hidden_size, vocab_size], minval=-init_scale, maxval=init_scale),
name="output_weights")
output_bias = tf.Variable(tf.zeros([vocab_size]), name="output_bias")
X_in = tf.nn.embedding_lookup(embedding, X)
initial_state = tf.zeros([batch_size, hidden_size])
content = initial_state
state = [initial_state] * num_hidden_layers
prev_concat_h = tf.zeros([batch_size, hidden_size * num_hidden_layers])
loss = tf.zeros([])
# TODO: prev concat h
for time_step in range(num_steps):
h_prev = X_in[:, time_step, :]
for layer in range(num_hidden_layers):
input_gate = tf.nn.sigmoid(tf.matmul(h_prev, Wi[layer]) + tf.matmul(state[layer], Ui[layer]))
forget_gate = tf.nn.sigmoid(tf.matmul(h_prev, Wf[layer]) + tf.matmul(state[layer], Uf[layer]))
output_gate = tf.nn.sigmoid(tf.matmul(h_prev, Wo[layer]) + tf.matmul(state[layer], Uo[layer]))
# Main contribution of paper:
gates = [tf.sigmoid(tf.matmul(h_prev, Wg[i]) + tf.matmul(prev_concat_h, Ug[i])) for i in range(num_hidden_layers)]
gated_prev_timestep = [gates[i] * tf.matmul(state[layer], Uc[i]) for i in range(num_hidden_layers)]
new_content = tf.nn.tanh(tf.matmul(h_prev, Wc[layer]) + tf.add_n(gated_prev_timestep))
content = tf.mul(forget_gate, content) + tf.mul(input_gate, new_content)
state[layer] = tf.mul(output_gate, tf.nn.tanh(content))
logits = tf.nn.bias_add(tf.matmul(state[num_hidden_layers-1], output_weights), output_bias)
step_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, targets[:, time_step])
loss += tf.reduce_sum(step_loss)
prev_concat_h = tf.concat(1, state)
final_state = state
cost = loss / batch_size
tf.scalar_summary("cost", cost)
merged = tf.merge_all_summaries()
writer = tf.train.SummaryWriter("summaries/gfrnn", session.graph_def)
# Train Model
session.run(tf.initialize_all_variables())
sgd = tf.train.GradientDescentOptimizer(lr).minimize(cost)
costs = 0.0
iters = 0
for i in range(epochs):
print 'Epoch', i
for step, (x, y) in enumerate(reader.ptb_iterator(train_data, batch_size, num_steps)):
result, step_cost, _, = session.run([merged, cost, sgd],
{X: x, targets: y, lr: 1.0 / (i + 1)})
costs += step_cost
iters += num_steps
if iters % 1000 == 0:
print iters, np.exp(costs / iters)
writer.add_summary(result, iters)
writer.flush()
```
| github_jupyter |
# Evolutionary optimization of a whole-brain model
This notebook provides an example for the use of the evolutionary optimization framework built-in to the library. Under the hood, the implementation of the evolutionary algorithm is powered by `deap` and `pypet` cares about the parallelization and storage of the simulation data for us.
We want to optimize a whole-brain network that should produce simulated BOLD activity (fMRI data) that is similar to the empirical dataset. We measure the fitness of each simulation by computing the `func.matrix_correlation` of the functional connectivity `func.fc(model.BOLD.BOLD)` to the empirical data `ds.FCs`. The ones that are closest to the empirical data get a higher fitness and have a higher chance of reproducing and survival.
```
# change to the root directory of the project
import os
if os.getcwd().split("/")[-1] == "examples":
os.chdir('..')
# This will reload all imports as soon as the code changes
%load_ext autoreload
%autoreload 2
try:
import matplotlib.pyplot as plt
except ImportError:
import sys
!{sys.executable} -m pip install matplotlib seaborn
import matplotlib.pyplot as plt
import numpy as np
import logging
from neurolib.models.aln import ALNModel
from neurolib.utils.parameterSpace import ParameterSpace
from neurolib.optimize.evolution import Evolution
import neurolib.utils.functions as func
from neurolib.utils.loadData import Dataset
ds = Dataset("hcp")
# a nice color map
plt.rcParams['image.cmap'] = 'plasma'
```
We create a brain network model using the empirical dataset `ds`:
```
model = ALNModel(Cmat = ds.Cmat, Dmat = ds.Dmat) # simulates the whole-brain model in 10s chunks by default if bold == True
# Resting state fits
model.params['mue_ext_mean'] = 1.57
model.params['mui_ext_mean'] = 1.6
model.params['sigma_ou'] = 0.09
model.params['b'] = 5.0
model.params['signalV'] = 2
model.params['dt'] = 0.2
model.params['duration'] = 0.2 * 60 * 1000 #ms
# testing: aln.params['duration'] = 0.2 * 60 * 1000 #ms
# real: aln.params['duration'] = 1.0 * 60 * 1000 #ms
```
Our evaluation function will do the following: first it will simulate the model for a short time to see whether there is any sufficient activity. This speeds up the evolution considerably, since large regions of the state space show almost no neuronal activity. Only then do we simulate the model for the full duration and compute the fitness using the empirical dataset.
```
def evaluateSimulation(traj):
rid = traj.id
model = evolution.getModelFromTraj(traj)
defaultDuration = model.params['duration']
invalid_result = (np.nan,)* len(ds.BOLDs)
# -------- stage wise simulation --------
# Stage 1 : simulate for a few seconds to see if there is any activity
# ---------------------------------------
model.params['duration'] = 3*1000.
model.run()
# check if stage 1 was successful
if np.max(model.output[:, model.t > 500]) > 160 or np.max(model.output[:, model.t > 500]) < 10:
return invalid_result, {}
# Stage 2: full and final simulation
# ---------------------------------------
model.params['duration'] = defaultDuration
model.run(chunkwise=True, bold = True)
# -------- fitness evaluation here --------
scores = []
for i, fc in enumerate(ds.FCs):#range(len(ds.FCs)):
fc_score = func.matrix_correlation(func.fc(model.BOLD.BOLD[:, 5:]), fc)
scores.append(fc_score)
meanFitness = np.mean(scores)
fitness_tuple = (meanFitness,)
#print(f"fitness {meanFitness}")
#print(f"scores {scores}")
fitness_tuple = tuple(scores)
return fitness_tuple, {}
```
We specify the parameter space that we want to search.
```
pars = ParameterSpace(['mue_ext_mean', 'mui_ext_mean', 'b', 'sigma_ou', 'Ke_gl', 'signalV'],
[[0.0, 3.0], [0.0, 3.0], [0.0, 100.0], [0.0, 0.3], [0.0, 500.0], [0.0, 400.0]])
```
Note that we chose `algorithm='nsga2'` when we create the `Evolution`. This will use the multi-objective optimization algorithm by Deb et al. 2002. Although we have only one objective here (namely the FC fit), we could in principle add more objectives, like the `FCD` matrix fit or other objectives. For this, we would have to add these values to the fitness in the evaluation function above and add more `weights` in the definition of the `Evolution`. We can use positive weights for that objective to be maximized and negative ones for minimization. Please refer to the [DEAP documentation](https://deap.readthedocs.io/) for more information.
```
evolution = Evolution(evaluateSimulation, pars, algorithm = 'nsga2', weightList = [1.0] * len(ds.BOLDs), model = model, POP_INIT_SIZE=4, POP_SIZE = 4, NGEN=2, filename="example-2.2.hdf")
#testing: evolution = Evolution(evaluateSimulation, pars, algorithm = 'nsga2', weightList = [1.0] * len(ds.BOLDs), model = model, POP_INIT_SIZE=4, POP_SIZE = 4, NGEN=2)
# real: evolution = Evolution(evaluateSimulation, pars, algorithm = 'nsga2', weightList = [1.0] * len(ds.BOLDs), model = model, POP_INIT_SIZE=1600, POP_SIZE = 160, NGEN=100)
```
That's it, we can run the evolution now.
```
evolution.run(verbose = False)
```
We could now save the full evolution object for later analysis using `evolution.saveEvolution()`.
# Analysis
The `info()` method gives us a useful overview of the evolution, like a summary of the evolution parameters, the statistics of the population and also scatterplots of the individuals in our search space.
```
evolution.info()
# This will load results from disk in case the session is
# started newly and the trajectory is not in memory
traj = evolution.loadResults()
gens, all_scores = evolution.getScoresDuringEvolution(reverse=True)
plt.figure(figsize=(8, 4), dpi=200)
plt.plot(gens, np.nanmean(all_scores, axis=1))
plt.fill_between(gens, np.nanmin(all_scores, axis=1), np.nanmax(all_scores, axis=1), alpha=0.3)
plt.xlabel("Generation #")
plt.ylabel("Score")
```
| github_jupyter |
# 04 - Test and deploy a TFX training pipeline to `Vertex Pipelines`
The purpose of this notebook is to test, deploy, and run the `TFX` pipeline on `Vertex Pipelines`. The notebook covers the following tasks:
1. Run the tests locally.
2. Run the `TFX` pipeline using `Vertex Pipelines`
3. Execute the pipeline deployment `CI/CD` steps using `Cloud Build`.
## Setup
### Import libraries
```
import os
import kfp
import tfx
print('TFX:', tfx.__version__)
print('KFP:', kfp.__version__)
```
### Setup Google Cloud project
```
PROJECT_ID = '[your-project-id]' # Change to your project id.
REGION = 'us-central1' # Change to your region.
BUCKET = '[your-bucket-name]' # Change to your bucket name.
SERVICE_ACCOUNT = '[your-service-account]'
if PROJECT_ID == '' or PROJECT_ID is None or PROJECT_ID == '[your-project-id]':
# Get your GCP project id from gcloud
shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
if SERVICE_ACCOUNT == '' or SERVICE_ACCOUNT is None or SERVICE_ACCOUNT == '[your-service-account]':
# Get your GCP project id from gcloud
shell_output = !gcloud config list --format 'value(core.account)' 2>/dev/null
SERVICE_ACCOUNT = shell_output[0]
if BUCKET == '' or BUCKET is None or BUCKET == '[your-bucket-name]':
# Set your bucket name using your GCP project id
BUCKET = PROJECT_ID
# Try to create the bucket if it doesn'exists
! gsutil mb -l $REGION gs://$BUCKET
print('')
print('Project ID:', PROJECT_ID)
print('Region:', REGION)
print('Bucket name:', BUCKET)
print('Service Account:', SERVICE_ACCOUNT)
```
### Set configurations
```
BQ_LOCATION = 'US'
BQ_DATASET_NAME = 'playground_us' # Change to your BQ dataset name.
BQ_TABLE_NAME = 'chicago_taxitrips_prep'
VERSION = 'v1'
DATASET_DISPLAY_NAME = 'chicago-taxi-tips'
MODEL_DISPLAY_NAME = f'{DATASET_DISPLAY_NAME}-classifier-{VERSION}'
PIPELINE_NAME = f'{MODEL_DISPLAY_NAME}-train-pipeline'
CICD_IMAGE_NAME = 'cicd:latest'
CICD_IMAGE_URI = f'gcr.io/{PROJECT_ID}/{CICD_IMAGE_NAME}'
! rm -r src/raw_schema/.ipynb_checkpoints/
```
## 1. Run the CI/CD steps locally
### Set pipeline configurations for the local run
```
os.environ['DATASET_DISPLAY_NAME'] = DATASET_DISPLAY_NAME
os.environ['MODEL_DISPLAY_NAME'] = MODEL_DISPLAY_NAME
os.environ['PIPELINE_NAME'] = PIPELINE_NAME
os.environ['PROJECT'] = PROJECT_ID
os.environ['REGION'] = REGION
os.environ['BQ_LOCATION'] = BQ_LOCATION
os.environ['BQ_DATASET_NAME'] = BQ_DATASET_NAME
os.environ['BQ_TABLE_NAME'] = BQ_TABLE_NAME
os.environ['GCS_LOCATION'] = f'gs://{BUCKET}/{DATASET_DISPLAY_NAME}/e2e_tests'
os.environ['TRAIN_LIMIT'] = '1000'
os.environ['TEST_LIMIT'] = '100'
os.environ['UPLOAD_MODEL'] = '0'
os.environ['ACCURACY_THRESHOLD'] = '0.1'
os.environ['BEAM_RUNNER'] = 'DirectRunner'
os.environ['TRAINING_RUNNER'] = 'local'
from src.tfx_pipelines import config
import importlib
importlib.reload(config)
for key, value in config.__dict__.items():
if key.isupper(): print(f'{key}: {value}')
```
### Run the unit tests for the data and model pipeline components
```
! py.test src/tests/datasource_utils_tests.py -s
! py.test src/tests/model_tests.py -s
```
### Run the e2e pipeline test
```
! py.test src/tests/pipeline_deployment_tests.py::test_e2e_pipeline -s
```
## 2. Run the training pipeline using `Vertex Pipelines`
### Set the pipeline configurations for the `Vertex Pipeline` run
```
os.environ['DATASET_DISPLAY_NAME'] = DATASET_DISPLAY_NAME
os.environ['MODEL_DISPLAY_NAME'] = MODEL_DISPLAY_NAME
os.environ['PIPELINE_NAME'] = PIPELINE_NAME
os.environ['PROJECT'] = PROJECT_ID
os.environ['REGION'] = REGION
os.environ['GCS_LOCATION'] = f'gs://{BUCKET}/{DATASET_DISPLAY_NAME}'
os.environ['TRAIN_LIMIT'] = '85000'
os.environ['TEST_LIMIT'] = '15000'
os.environ['BEAM_RUNNER'] = 'DataflowRunner'
os.environ['TRAINING_RUNNER'] = 'vertex'
os.environ['TFX_IMAGE_URI'] = f'gcr.io/{PROJECT_ID}/{DATASET_DISPLAY_NAME}:{VERSION}'
from src.tfx_pipelines import config
import importlib
importlib.reload(config)
for key, value in config.__dict__.items():
if key.isupper(): print(f'{key}: {value}')
```
### Build the training container image
This is the `TFX` runtime environment for the training pipeline steps.
```
!echo $TFX_IMAGE_URI
!gcloud builds submit --tag $TFX_IMAGE_URI . --timeout=15m --machine-type=e2-highcpu-8
```
### Compile the `TFX` pipeline
```
from src.tfx_pipelines import runner
pipeline_definition_file = f'{config.PIPELINE_NAME}.json'
pipeline_definition = runner.compile_training_pipeline(pipeline_definition_file)
PIPELINES_STORE = f'gs://{BUCKET}/{DATASET_DISPLAY_NAME}/compiled_pipelines/'
! gsutil cp {pipeline_definition_file} {PIPELINES_STORE}
```
### Submit run to Vertex Pipelines
```
from kfp.v2.google.client import AIPlatformClient
pipeline_client = AIPlatformClient(
project_id=PROJECT_ID, region=REGION)
job = pipeline_client.create_run_from_job_spec(
job_spec_path=pipeline_definition_file,
parameter_values={
'learning_rate': 0.003,
'batch_size': 512,
'hidden_units': '128,128',
'num_epochs': 30,
}
)
```
### Extracting pipeline runs metadata
```
from google.cloud import aiplatform as vertex_ai
pipeline_df = vertex_ai.get_pipeline_df(PIPELINE_NAME)
pipeline_df = pipeline_df[pipeline_df.pipeline_name == PIPELINE_NAME]
pipeline_df.T
```
## 3. Execute the pipeline deployment CI/CD steps in Cloud Build
The CI/CD routine is defined in the [pipeline-deployment.yaml](pipeline-deployment.yaml) file, and consists of the following steps:
1. Clone the repository to the build environment.
2. Run unit tests.
3. Run a local e2e test of the pipeline.
4. Build the ML container image for pipeline steps.
5. Compile the pipeline.
6. Upload the pipeline to Cloud Storage.
### Build CI/CD container image for Cloud Build
This is the runtime environment where the steps of testing and deploying the pipeline will be executed.
```
! echo $CICD_IMAGE_URI
! gcloud builds submit --tag $CICD_IMAGE_URI build/. --timeout=15m --machine-type=e2-highcpu-8
```
### Run CI/CD from pipeline deployment using Cloud Build
```
REPO_URL = 'https://github.com/ksalama/ucaip-labs.git' # Change to your github repo.
BRANCH = 'main'
GCS_LOCATION = f'gs://{BUCKET}/{DATASET_DISPLAY_NAME}/'
TEST_GCS_LOCATION = f'gs://{BUCKET}/{DATASET_DISPLAY_NAME}/e2e_tests'
CI_TRAIN_LIMIT = 1000
CI_TEST_LIMIT = 100
CI_UPLOAD_MODEL = 0
CI_ACCURACY_THRESHOLD = 0.1
BEAM_RUNNER = 'DataflowRunner'
TRAINING_RUNNER = 'vertex'
VERSION = 'tfx-0-30'
PIPELINE_NAME = f'{MODEL_DISPLAY_NAME}-train-pipeline'
PIPELINES_STORE = os.path.join(GCS_LOCATION, 'compiled_pipelines')
TFX_IMAGE_URI = f'gcr.io/{PROJECT_ID}/{DATASET_DISPLAY_NAME}:{VERSION}'
SUBSTITUTIONS=f'''\
_REPO_URL='{REPO_URL}',\
_BRANCH={BRANCH},\
_CICD_IMAGE_URI={CICD_IMAGE_URI},\
_PROJECT_ID={PROJECT_ID},\
_REGION={REGION},\
_GCS_LOCATION={GCS_LOCATION},\
_TEST_GCS_LOCATION={TEST_GCS_LOCATION},\
_BQ_LOCATION={BQ_LOCATION},\
_BQ_DATASET_NAME={BQ_DATASET_NAME},\
_BQ_TABLE_NAME={BQ_TABLE_NAME},\
_DATASET_DISPLAY_NAME={DATASET_DISPLAY_NAME},\
_MODEL_DISPLAY_NAME={MODEL_DISPLAY_NAME},\
_CI_TRAIN_LIMIT={CI_TRAIN_LIMIT},\
_CI_TEST_LIMIT={CI_TEST_LIMIT},\
_CI_UPLOAD_MODEL={CI_UPLOAD_MODEL},\
_CI_ACCURACY_THRESHOLD={CI_ACCURACY_THRESHOLD},\
_BEAM_RUNNER={BEAM_RUNNER},\
_TRAINING_RUNNER={TRAINING_RUNNER},\
_TFX_IMAGE_URI={TFX_IMAGE_URI},\
_PIPELINE_NAME={PIPELINE_NAME},\
_PIPELINES_STORE={PIPELINES_STORE}\
'''
!echo $SUBSTITUTIONS
!gcloud builds submit --no-source --timeout=60m --config build/pipeline-deployment.yaml --substitutions {SUBSTITUTIONS} --machine-type=e2-highcpu-8
```
| github_jupyter |
```
import os
import sys
script_dir = os.getcwd()
root_dir = f"{script_dir}/../../"
sys.path.append(os.path.join(root_dir, "dpc"))
import numpy as np
import scipy.io
import imageio
import matplotlib.pyplot as plt
%matplotlib inline
import open3d
from open3d import JVisualizer
from util.system import setup_environment
from util.euler import quaternion2euler
from util.image import preprocess_input_image
from render.render_point_cloud import render_point_cloud
#!/usr/bin/env python
import pdb
import time
import torch
from models import model_pc_to as model_pc
from run.ShapeRecords import ShapeRecords
from util.app_config import config as app_config
from util.system import setup_environment
from util.fs import mkdir_if_missing
cfg = app_config
setup_environment(cfg)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
train_dir = cfg.checkpoint_dir
mkdir_if_missing(train_dir)
split_name = "test"
dataset_folder = cfg.inp_dir
dataset = ShapeRecords(dataset_folder, cfg,split_name)
dataset_loader = torch.utils.data.DataLoader(dataset,
batch_size=8, shuffle=False,
num_workers=8,drop_last=True)
log_dir = '../../dpc/run/model_run_data/'
model = model_pc.ModelPointCloud(cfg)
global_step = 100000
if global_step>0:
checkpoint_path = os.path.join(log_dir,'model.ckpt_{}.pth'.format(global_step))
print("Loading from path:",checkpoint_path)
checkpoint = torch.load(checkpoint_path, map_location=torch.device('cpu'))
global_step_val = checkpoint['global_step']
model.load_state_dict(checkpoint['model_state_dict'])
else:
global_step_val = global_step
model = model.to(device)
for i, train_data in enumerate(dataset_loader, 0):
for k in train_data.keys():
try:
train_data[k] = train_data[k].to(device)
except AttributeError:
pass
inputs = model.preprocess(train_data, cfg.step_size)
outputs = model(inputs, global_step_val, is_training=False, run_projection=True)
break
global_step=0
cfg = app_config
setup_environment(cfg)
sigma_rel = get_smooth_sigma(cfg, global_step)
_sigma_rel = sigma_rel
_gauss_sigma = sigma_rel / cfg.vox_size
_gauss_kernel = smoothing_kernel(cfg, sigma_rel)
device = 'cpu'
train_dir = cfg.checkpoint_dir
mkdir_if_missing(train_dir)
split_name = "train"
dataset_folder = cfg.inp_dir
dataset = ShapeRecords(dataset_folder, cfg, 'test')
dataset_loader = torch.utils.data.DataLoader(dataset,
batch_size=8, shuffle=False,
num_workers=8,drop_last=True)
log_dir = '../../dpc/run/model_run_data/'
model = model_pc.ModelPointCloud(cfg)
global_step = 100000
if global_step>0:
checkpoint_path = os.path.join(log_dir,'model.ckpt_{}.pth'.format(global_step))
print("Loading from path:",checkpoint_path)
checkpoint = torch.load(checkpoint_path, map_location=torch.device('cpu'))
global_step_val = checkpoint['global_step']
model.load_state_dict(checkpoint['model_state_dict'])
else:
global_step_val = global_step
model = model.to(device)
for i, train_data in enumerate(dataset_loader, 0):
for k in train_data.keys():
try:
train_data[k] = train_data[k].to(device)
except AttributeError:
pass
inputs = model.preprocess(train_data, cfg.step_size)
outputs = model(inputs, global_step_val, is_training=False, run_projection=True)
break
# select an input image from the validation set (splits defined in data/splits)
# the dataset has 5 different viewpoints for the same model
img_idx = 7
input_image_np = inputs['images'].detach().cpu().numpy()[img_idx].transpose(1,2,0)
# show input image
plt.imshow(input_image_np)
camera_pose_np = outputs['poses'].detach().cpu().numpy()[img_idx]
points_np = outputs['all_points'].detach().cpu().numpy().reshape(-1,4,8000,3)[img_idx,3]
# Interactive visualisation with Open3D
pcd = open3d.geometry.PointCloud()
pcd.points = open3d.utility.Vector3dVector(np.squeeze(points_np))
visualizer = open3d.JVisualizer()
visualizer.add_geometry(pcd)
visualizer.show()
outputs['poses'].shape
# image 1
all_points = outputs['all_points']#[img_idx_1].unsqueeze(0).repeat(128,1,1)
all_rgb = outputs['all_rgb']
camera_pose = outputs['poses']#[img_idx_1].unsqueeze(0).repeat(128,1)
predicted_translation = outputs["predicted_translation"]
proj_out = pointcloud_project_fast(cfg, all_points, camera_pose, predicted_translation,
all_rgb, _gauss_kernel,
scaling_factor=outputs['all_scaling_factors'],
focal_length=outputs['all_focal_length'])
proj = proj_out["proj"]
all_points.shape
projs = torch.squeeze(proj.reshape(32,4,64,64,1)).detach().cpu().numpy()
proj_1 = projs[img_idx_1]
proj_2 = projs[img_idx_2]
plt.imshow(torch.squeeze(inputs['masks'])[img_idx_1].cpu().numpy())
plt.imshow(proj_1[1])
plt.imshow(proj_2[1])
mixed_points = outputs['all_points'][img_idx_2*4]
def mix_points(points_1, points_2, scale_1, scale_2, center_1, center_2):
points_1 = points_1*scale_1 + center_1
points_2 = points_2*scale_2 + center_2
return torch.cat((points_1,points_2),dim=0)
points_1 = outputs['all_points'][img_idx_1*4]
points_2 = outputs['all_points'][img_idx_2*4]
center_1 = torch.from_numpy(np.array([0,0.15,0.15]).reshape(1,3))
center_2 = torch.from_numpy(np.array([0,-0.15,-0.15]).reshape(1,3))
scale_1 = 0.5
scale_2 = 0.5
mixed_points = mix_points(points_1, points_2, scale_1, scale_2, center_1, center_2)
all_points = mixed_points.unsqueeze(0).repeat(128,1,1)
all_rgb = outputs['all_rgb']
camera_pose = outputs['poses'][img_idx_1*4].unsqueeze(0).repeat(128,1)
scaling_factors = outputs['all_scaling_factors'][img_idx_1*4].unsqueeze(0).repeat(128,1)
predicted_translation = outputs["predicted_translation"]
proj_out = pointcloud_project_fast(cfg, all_points, camera_pose, predicted_translation,
all_rgb, _gauss_kernel,
scaling_factor=scaling_factors,
focal_length=outputs['all_focal_length'])
proj = proj_out["proj"]
projs = torch.squeeze(proj.reshape(32,4,64,64,1)).detach().cpu().numpy()
proj_1 = projs[img_idx_1]
proj_2 = projs[img_idx_2]
print(outputs['all_scaling_factors'].shape)
```
| github_jupyter |
#### New to Plotly?
Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).
<br>You can set up Plotly to work in [online](https://plot.ly/python/getting-started/#initialization-for-online-plotting) or [offline](https://plot.ly/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plot.ly/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!
#### Two Y Axes
```
import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Scatter(
x=[1, 2, 3],
y=[40, 50, 60],
name='yaxis data'
)
trace2 = go.Scatter(
x=[2, 3, 4],
y=[4, 5, 6],
name='yaxis2 data',
yaxis='y2'
)
data = [trace1, trace2]
layout = go.Layout(
title='Double Y Axis Example',
yaxis=dict(
title='yaxis title'
),
yaxis2=dict(
title='yaxis2 title',
titlefont=dict(
color='rgb(148, 103, 189)'
),
tickfont=dict(
color='rgb(148, 103, 189)'
),
overlaying='y',
side='right'
)
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='multiple-axes-double')
```
#### Multiple Axes
```
import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Scatter(
x=[1, 2, 3],
y=[4, 5, 6],
name='yaxis1 data'
)
trace2 = go.Scatter(
x=[2, 3, 4],
y=[40, 50, 60],
name='yaxis2 data',
yaxis='y2'
)
trace3 = go.Scatter(
x=[4, 5, 6],
y=[40000, 50000, 60000],
name='yaxis3 data',
yaxis='y3'
)
trace4 = go.Scatter(
x=[5, 6, 7],
y=[400000, 500000, 600000],
name='yaxis4 data',
yaxis='y4'
)
data = [trace1, trace2, trace3, trace4]
layout = go.Layout(
title='multiple y-axes example',
width=800,
xaxis=dict(
domain=[0.3, 0.7]
),
yaxis=dict(
title='yaxis title',
titlefont=dict(
color='#1f77b4'
),
tickfont=dict(
color='#1f77b4'
)
),
yaxis2=dict(
title='yaxis2 title',
titlefont=dict(
color='#ff7f0e'
),
tickfont=dict(
color='#ff7f0e'
),
anchor='free',
overlaying='y',
side='left',
position=0.15
),
yaxis3=dict(
title='yaxis4 title',
titlefont=dict(
color='#d62728'
),
tickfont=dict(
color='#d62728'
),
anchor='x',
overlaying='y',
side='right'
),
yaxis4=dict(
title='yaxis5 title',
titlefont=dict(
color='#9467bd'
),
tickfont=dict(
color='#9467bd'
),
anchor='free',
overlaying='y',
side='right',
position=0.85
)
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='multiple-axes-multiple')
```
#### Muliple Y-Axes Subplots
```
import plotly.plotly as py
import plotly.graph_objs as go
# Top left
trace1 = go.Scatter(
x=[1, 2, 3],
y=[2, 32, 62],
name='yaxis data',
)
trace2 = go.Scatter(
x=[1, 2, 3],
y=[40, 50, 60],
name='yaxis2 data',
yaxis='y2'
)
# Top right
trace3 = go.Scatter(
x=[1, 2, 3],
y=[2, 32, 62],
name='yaxis3 data',
xaxis='x2',
yaxis='y3'
)
trace4 = go.Scatter(
x=[1, 2, 3],
y=[40, 50, 60],
name='yaxis4 data',
xaxis='x2',
yaxis='y4'
)
# Bottom left
trace5 = go.Scatter(
x=[1, 2, 3],
y=[2, 32, 62],
name='yaxis5 data',
xaxis='x3',
yaxis='y5'
)
trace6 = go.Scatter(
x=[1, 2, 3],
y=[40, 50, 60],
name='yaxis6 data',
xaxis='x3',
yaxis='y6'
)
# Bottom right
trace7 = go.Scatter(
x=[1, 2, 3],
y=[2, 32, 62],
name='yaxis7 data',
xaxis='x4',
yaxis='y7'
)
trace8 = go.Scatter(
x=[1, 2, 3],
y=[40, 50, 60],
name='yaxis8 data',
xaxis='x4',
yaxis='y8'
)
data = [trace1, trace2, trace3, trace4, trace5, trace6, trace7, trace8]
layout = go.Layout(
title='Double Y Axis Example',
legend={'x': 1.1},
width=1000,
height=500,
# Top left
xaxis=dict(
title='xaxis title',
domain=[0, 0.4]
),
yaxis=dict(
title='yaxis title',
type='log',
domain=[0.6, 1.0],
anchor='x'
),
yaxis2=dict(
title='yaxis2 title',
overlaying='y',
side='right'
),
# Top right
xaxis2=dict(
title='xaxis2 title',
domain=[0.6, 1.0],
anchor='y3'
),
yaxis3=dict(
type='log',
title='yaxis3 title',
domain=[0.6, 1.0],
anchor='x2'
),
yaxis4=dict(
title='yaxis4 title',
domain=[0.6, 1.0],
overlaying='y3',
side='right',
anchor='x2'
),
# Bottom left
xaxis3=dict(
title='xaxis3 title',
domain=[0, 0.4],
anchor='y5'
),
yaxis5=dict(
type='log',
title='yaxis5 title',
domain=[0, 0.4],
anchor='x3'
),
yaxis6=dict(
title='yaxis6 title',
domain=[0, 0.4],
overlaying='y5',
side='right',
anchor='x3'
),
# Bottom right
xaxis4=dict(
title='xaxis4, title',
domain=[0.6, 1.0],
anchor='y7'
),
yaxis7=dict(
type='log',
title='yaxis7 title',
domain=[0, 0.4],
anchor='x4'
),
yaxis8=dict(
title='yaxis8 title',
domain=[0, 0.4],
overlaying='y7',
side='right',
anchor='x4'
)
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='multiple-y-axes-subplots')
```
### Dash Example
[Dash](https://plot.ly/products/dash/) is an Open Source Python library which can help you convert plotly figures into a reactive, web-based application. Below is a simple example of a dashboard created using Dash. Its [source code](https://github.com/plotly/simple-example-chart-apps/tree/master/dash-multipleaxesplot) can easily be deployed to a PaaS.
```
from IPython.display import IFrame
IFrame(src= "https://dash-simple-apps.plotly.host/dash-multipleaxesplot/", width="100%", height="650px", frameBorder="0")
from IPython.display import IFrame
IFrame(src= "https://dash-simple-apps.plotly.host/dash-multipleaxesplot/code", width="100%", height=500, frameBorder="0")
```
#### Reference
All of the y-axis properties are found here: https://plot.ly/python/reference/#YAxis
```
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(
'multiple-axes.ipynb', 'python/multiple-axes/', 'Multiple Axes | Plotly',
'How to make a graph with multiple axes in python.',
title = 'Python Mulitple Axes | Examples | Plotly',
name = 'Multiple Axes', has_thumbnail='true', thumbnail='thumbnail/multiple-axes.jpg',
language='python', page_type='example_index',
display_as='multiple_axes', order=1,
ipynb='~notebook_demo/270')
```
| github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn import datasets, svm, metrics
from sklearn.model_selection import train_test_split
from shapkit.shapley_values import ShapleyValues
from shapkit.inspector import inspector
from shapkit.monte_carlo_shapley import MonteCarloShapley
from shapkit.sgd_shapley import SGDshapley
%load_ext autoreload
%autoreload 2
```
# Load dataset
```
digits = datasets.load_digits()
n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))
columns = ["pixel"+str(i) for i in range(data.shape[1])]
X = pd.DataFrame(data, columns=columns)
y = digits.target
X.head(5)
# Split data into train and test subsets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, shuffle=False)
```
# Train a ML model
```
classifier = svm.SVC(gamma=0.001)
classifier.fit(X_train, y_train)
predicted = classifier.predict(X_test)
print("Classification report for classifier %s:\n%s\n" % (classifier, metrics.classification_report(y_test, predicted)))
```
# Define the game
```
d = X_train.shape[1]
n = 2**d - 2
d, n
fc = lambda x: classifier.predict(x.reshape(1,-1))[0]
r_class, x_class = 0, 0
while x_class == r_class:
idx_r, idx_x = np.random.choice(np.arange(len(X_test)), size=2, replace=False)
r = X_test.iloc[idx_r,:]
x = X_test.iloc[idx_x,:]
r_class = fc(r.values)
x_class = fc(x.values)
fc_class = lambda x: 1 if int(fc(x)) == int(x_class) else 0
plt.figure()
ax = plt.imshow(r.values.reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest')
ax.axes.set_axis_off()
plt.title("Reference r")
plt.show()
plt.figure()
ax = plt.imshow(x.values.reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest')
ax.axes.set_axis_off()
plt.title("Individual x")
plt.show()
```
# Approximation methods
## Monte Carlo
```
mc_shap = MonteCarloShapley(x=x, fc=fc_class, ref=r, n_iter=1000)
mc_shap
fig, axes = plt.subplots(1, 3, figsize=(15,7))
axes[0].imshow(r.values.reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest')
axes[0].set_title("Reference r")
axes[1].imshow(x.values.reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest')
axes[1].set_title("Individual x")
pc = axes[2].imshow(mc_shap.values.reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest')
axes[2].set_title("Pixel contributions")
cbar = fig.colorbar(pc)
plt.show()
```
## SGD
```
sgd_est = SGDshapley(d, C=y.max())
sgd_shap = sgd_est.sgd(x=x, fc=fc_class, ref=r, n_iter=10000, step=.1, step_type="sqrt")
sgd_shap
fig, axes = plt.subplots(1, 3, figsize=(15,7))
axes[0].imshow(r.values.reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest')
axes[0].set_title("Reference r")
axes[1].imshow(x.values.reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest')
axes[1].set_title("Individual x")
pc = axes[2].imshow(sgd_shap.values.reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest')
axes[2].set_title("Pixel contributions")
cbar = fig.colorbar(pc)
plt.show()
```
| github_jupyter |
## HDFS File Permissions
Let us go through file permissions in HDFS.
```
%%HTML
<iframe width="560" height="315" src="https://www.youtube.com/embed/I8ZCZYQTaVU?rel=0&controls=1&showinfo=0" frameborder="0" allowfullscreen></iframe>
```
* As we create the files, we can check the permissions on them using `-ls` command.
* Typically the owner of the user space will have **rwx**, while members of the group specified as well as others have **r-x**.
* **rwx** stands for read, write and execute while **r-x** stands for only read and execute permissions.
* We can change the permissions using `hadoop fs -chmod` or `hdfs dfs -chmod`. However one can change the permissions of their own files.
* We can specify permissions mode (e.g.: `+x` to grant execute access to owner, group as well as others) as well as octal mode (e.g.: 755 to grant rwx for owner, rx for group and others)
If you are not familiar with linux command chmod, we would highly recommend you to spend some time to get detailed understanding of it as it is very important with respect to file permissions.
```
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
* Granting write permissions on the folder to others.
```
%%sh
hdfs dfs -chmod -R o+w /user/${USER}/retail_db/orders
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
* Granting write permissions on the folder to group.
```
%%sh
hdfs dfs -chmod -R g+w /user/${USER}/retail_db/order_items
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
* We can remove write permissions for every one.
```
%%sh
hdfs dfs -chmod -R -w /user/${USER}/retail_db/orders
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
* No files can be copied to the folder or can be deleted from the folder. Below command will fail.
```
%%sh
hdfs dfs -rm /user/${USER}/retail_db/orders/part-00000
%%sh
hdfs dfs -chmod -R -w /user/${USER}/retail_db/order_items
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
* Adding write permissions only to owner. Now the owner will be able to delete the file, but others cannot.
```
%%sh
hdfs dfs -chmod -R u+w /user/${USER}/retail_db/orders
%%sh
hdfs dfs -rm /user/${USER}/retail_db/orders/part-00000
%%sh
hdfs dfs -chmod -R u+w /user/${USER}/retail_db/order_items
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
* Let us go through the details using octal format.
```
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
* Granting write permissions on the folder to others. We can set these permissions for owner, group and other.
|Binary Value|Permissions Mode|Decimal Value
|---|---|---|
|000|---|0|
|001|--x|1|
|010|-w-|2|
|011|-wx|3|
|100|r--|4|
|101|r-x|5|
|110|rw-|6|
|111|rwx|7|
* Granting write permissions on the folder to others.
```
%%sh
hdfs dfs -chmod -R 757 /user/${USER}/retail_db/orders
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
* Granting write permissions on the folder to group.
```
%%sh
hdfs dfs -chmod -R 775 /user/${USER}/retail_db/order_items
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
* We can remove write permissions for every one.
```
%%sh
hdfs dfs -chmod -R 555 /user/${USER}/retail_db/orders
%%sh
hdfs dfs -chmod -R 555 /user/${USER}/retail_db/order_items
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
* Adding write permissions only to owner.
```
%%sh
hdfs dfs -chmod -R 755 /user/${USER}/retail_db/orders
%%sh
hdfs dfs -chmod -R 755 /user/${USER}/retail_db/order_items
%%sh
hdfs dfs -ls /user/${USER}/retail_db
```
| github_jupyter |
# SqueezeNet v1.1
original repo: **https://github.com/DeepScale/SqueezeNet**
for keras: **https://github.com/rcmalli/keras-squeezenet** (pretrained imagenet weights downloaded from here)
```
$ wget -O squeezenet_v1.1.h5 https://github.com/rcmalli/keras-squeezenet/releases/download/v1.0/squeezenet_weights_tf_dim_ordering_tf_kernels.h5
```
Pre-trained imagenet weights renamed from `squeezenet_weights_tf_dim_ordering_tf_kernels.h5` to `squeezenet_v1.1.hdf5`. Weight names are converted to Keras v2 format, since Keras.js uses these names to load layer weights.
```
KERAS_MODEL_FILEPATH = '../../demos/data/squeezenet_v1.1/squeezenet_v1.1.h5'
import h5py
hdf5_file = h5py.File(KERAS_MODEL_FILEPATH, mode='r+')
f = hdf5_file
layer_names = [n.decode('utf8') for n in f.attrs['layer_names']]
offset = 0
for layer_name in layer_names:
g = f[layer_name]
weight_names = [n.decode('utf8') for n in g.attrs['weight_names']]
if weight_names:
old_weight_names = weight_names
new_weight_names = []
for weight_name in weight_names:
if '_W:' in weight_name:
new_weight_name = weight_name.replace('_W', '/kernel')
g[new_weight_name] = g[weight_name]
del g[weight_name]
elif '_b:' in weight_name:
new_weight_name = weight_name.replace('_b', '/bias')
g[new_weight_name] = g[weight_name]
del g[weight_name]
else:
new_weight_name = weight_name
new_weight_names.append(new_weight_name)
g.attrs['weight_names'] = [n.encode('utf8') for n in new_weight_names]
print(old_weight_names, '-->', new_weight_names)
hdf5_file.close()
from keras.layers import Input, Conv2D, MaxPooling2D, Activation, concatenate, Dropout, GlobalAveragePooling2D
from keras.models import Model
sq1x1 = "squeeze1x1"
exp1x1 = "expand1x1"
exp3x3 = "expand3x3"
relu = "relu_"
def fire_module(x, fire_id, squeeze=16, expand=64):
s_id = 'fire' + str(fire_id) + '/'
channel_axis = 3
x = Conv2D(squeeze, (1, 1), padding='valid', name=s_id + sq1x1)(x)
x = Activation('relu', name=s_id + relu + sq1x1)(x)
left = Conv2D(expand, (1, 1), padding='valid', name=s_id + exp1x1)(x)
left = Activation('relu', name=s_id + relu + exp1x1)(left)
right = Conv2D(expand, (3, 3), padding='same', name=s_id + exp3x3)(x)
right = Activation('relu', name=s_id + relu + exp3x3)(right)
x = concatenate([left, right], axis=channel_axis, name=s_id + 'concat')
return x
input_shape = (227, 227, 3)
classes = 1000
img_input = Input(shape=input_shape)
x = Conv2D(64, (3, 3), strides=(2, 2), padding='valid', name='conv1')(img_input)
x = Activation('relu', name='relu_conv1')(x)
x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool1')(x)
x = fire_module(x, fire_id=2, squeeze=16, expand=64)
x = fire_module(x, fire_id=3, squeeze=16, expand=64)
x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool3')(x)
x = fire_module(x, fire_id=4, squeeze=32, expand=128)
x = fire_module(x, fire_id=5, squeeze=32, expand=128)
x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool5')(x)
x = fire_module(x, fire_id=6, squeeze=48, expand=192)
x = fire_module(x, fire_id=7, squeeze=48, expand=192)
x = fire_module(x, fire_id=8, squeeze=64, expand=256)
x = fire_module(x, fire_id=9, squeeze=64, expand=256)
x = Dropout(0.5, name='drop9')(x)
x = Conv2D(classes, (1, 1), padding='valid', name='conv10')(x)
x = Activation('relu', name='relu_conv10')(x)
x = GlobalAveragePooling2D()(x)
out = Activation('softmax', name='loss')(x)
model = Model(inputs=img_input, outputs=out, name='squeezenet')
model.load_weights(KERAS_MODEL_FILEPATH)
model.compile(optimizer='adam', loss='categorical_crossentropy')
model.save(KERAS_MODEL_FILEPATH)
```
| github_jupyter |
```
import math
import pylab
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
def gen_data(N):
X = np.random.randn(N, 1)
w1 = 2.
b1 = 8.
sigma1 = 1e1 # ground truth
Y1 = X.dot(w1) + b1 + sigma1 * np.random.randn(N, 1)
w2 = 3
b2 = 3.
sigma2 = 1e0 # ground truth
Y2 = X.dot(w2) + b2 + sigma2 * np.random.randn(N, 1)
return X, Y1, Y2
class TrainData(Dataset):
def __init__(self, feature_num, X, Y1, Y2):
self.feature_num = feature_num
self.X = torch.tensor(X, dtype=torch.float32)
self.Y1 = torch.tensor(Y1, dtype=torch.float32)
self.Y2 = torch.tensor(Y2, dtype=torch.float32)
def __len__(self):
return self.feature_num
def __getitem__(self, idx):
return self.X[idx,:], self.Y1[idx,:], self.Y2[idx,:]
class MultiTaskLossWrapper(nn.Module):
def __init__(self, task_num, model):
super(MultiTaskLossWrapper, self).__init__()
self.model = model
self.task_num = task_num
self.log_vars = nn.Parameter(torch.zeros((task_num)))
def forward(self, input, targets):
outputs = self.model(input)
precision1 = torch.exp(-self.log_vars[0])
loss = torch.sum(precision1 * (targets[0] - outputs[0]) ** 2. + self.log_vars[0], -1)
precision2 = torch.exp(-self.log_vars[1])
loss += torch.sum(precision2 * (targets[1] - outputs[1]) ** 2. + self.log_vars[1], -1)
loss = torch.mean(loss)
return loss, self.log_vars.data.tolist()
class MTLModel(torch.nn.Module):
def __init__(self, n_hidden, n_output):
super(MTLModel, self).__init__()
self.net1 = nn.Sequential(nn.Linear(1, n_hidden), nn.ReLU(), nn.Linear(n_hidden, n_output))
self.net2 = nn.Sequential(nn.Linear(1, n_hidden), nn.ReLU(), nn.Linear(n_hidden, n_output))
def forward(self, x):
return [self.net1(x), self.net2(x)]
np.random.seed(0)
feature_num = 100
nb_epoch = 2000
batch_size = 20
hidden_dim = 1024
X, Y1, Y2 = gen_data(feature_num)
pylab.figure(figsize=(3, 1.5))
pylab.scatter(X[:, 0], Y1[:, 0])
pylab.scatter(X[:, 0], Y2[:, 0])
pylab.show()
train_data = TrainData(feature_num, X, Y1, Y2)
train_data_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)
model = MTLModel(hidden_dim, 1)
mtl = MultiTaskLossWrapper(2, model)
mtl
# https://github.com/keras-team/keras/blob/master/keras/optimizers.py
# k.epsilon() = keras.backend.epsilon()
optimizer = torch.optim.Adam(mtl.parameters(), lr=0.001, eps=1e-07)
loss_list = []
for t in range(nb_epoch):
cumulative_loss = 0
for X, Y1, Y2 in train_data_loader:
loss, log_vars = mtl(X, [Y1, Y2])
optimizer.zero_grad()
loss.backward()
optimizer.step()
cumulative_loss += loss.item()
loss_list.append(cumulative_loss/batch_size)
pylab.plot(loss_list)
pylab.show()
print(log_vars)
# Found standard deviations (ground truth is 10 and 1):
print([math.exp(log_var) ** 0.5 for log_var in log_vars])
```
| github_jupyter |
### Load Libraries
```
import pandas as pd
import numpy as np
import sys
import sqlite3
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KDTree
from sklearn.neighbors import NearestNeighbors
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy.util as util
from dotenv import load_dotenv
import os
```
### Load databased
```
df = pd.read_csv('data/df_prepare.csv')
print(df.shape)
df.head()
```
### Look at the 5 nearest songs of all dataset
```
"""
Make a Function to find nearest song to existing database.
"""
def find_nearest_songs(df, number_of_songs):
# use number of desired songs
songs = 5
# remove categoricals
df_numerics = df.drop(columns=['track_id', 'track_name', 'artist_name'])
# Scale Data To Cluster More Accurately, and fit clustering model
df_scaled = StandardScaler().fit_transform(df_numerics)
df_modeled = KDTree(df_scaled)
# Querying the model for the 5 Nearest Neighbors
dist, ind = df_modeled.query(df_scaled, k=(songs+1)) # can make a bigger or smaller number
# Putting the Results into a Dataframe
dist_df = pd.DataFrame(dist)
# Calculating the Distances
scores = (1 - ((dist - dist.min()) / (dist.max() - dist.min()))) * 100
# Creating A New Dataframe for the Distances
columns = ['Searched_Song', 'Nearest_Song1', 'Nearest_Song2', 'Nearest_Song3', 'Nearest_Song4',
'Nearest_Song5']
dist_score = pd.DataFrame(scores.tolist(), columns = columns)
# An Array of all indices of the nearest neighbors
ind[:(songs+1)]
# Making an array of the Track IDs
song_ids = np.array(df.track_id)
# A function that creates list of the each song with its nearest neighbors
def find_similars(song_ids, ind):
similars = []
for row in ind:
ids = [song_ids[i] for i in row]
similars.append(ids)
return similars
# using the above function
nearest_neighbors = find_similars(song_ids, ind)
# putting the results into a dataframe
nearest_neighbors_df = pd.DataFrame(nearest_neighbors, columns=columns)
return nearest_neighbors_df
# this takes a while to process
predicted = find_nearest_songs(df, 5)
predicted.head()
```
#### Save predicted dataset for later use
### save CSV
```
# save to csv
predicted.to_csv('predicted.csv', index_label=False)
```
### save JSON
```
# save to json
def save_data_frame_as_json(df=None, filename=None, orient="records"):
"""
Saves data frame to JSON format
Parameters
----------
df: Pandas DataFrame
filename: File path or name
Returns
-------
JSON file
"""
try:
if not filename.endswith('.json'):
filename += '.json'
df.to_json(filename, orient=orient)
print(f"Data Frame saved @:{filename}")
except Exception as e:
print("Data Frame couldn't be saved: ", sys.exc_info()[0])
raise
save_data_frame_as_json(predicted, 'data/predicted_df.json', orient="records")
# check the successful data record
json_df = pd.read_json('data/predicted_df.json')
json_df.head()
```
### save SQL db
```
# Prepare for the df to sql transfer
connection = sqlite3.connect('data/predicted_db.sqlite3')
curs = connection.cursor()
table_name = 'recommendations'
json_df.to_sql(table_name, con=connection, if_exists = 'replace')
# check the successful data record
curs.execute(f"SELECT count(distinct Searched_Song) as review_count FROM {table_name};")
results = curs.fetchone()
print(results, "RECORDS")
```
## Function for finding similar songs using Spotify API
```
load_dotenv()
```
### Load spotipy credentials
```
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
```
### Run the function
```
# Function for finding similar songs using Spotify API
def dj_rec(track_id, max_distance=6.5, neighbors=3):
"""
Prints the ids of relevant songs, along with their distance from the input song.
Parameters:
track_id (string): Spotify track id.
max_distance (float): maximum euclidean distance a song can be
from the input song for it to be returned.
neighbors (int): number of song recommendations returned.
"""
rel_artists = sp.artist_related_artists(sp.track(track_id=track_id)['artists'][0]['id'])['artists']
artist_log = []
for a in rel_artists:
artist_log.append(a['id'])
feat_log = []
for artist in artist_log:
for track in sp.artist_top_tracks(artist)['tracks']:
feat_log.append(sp.audio_features(track['id'])[0])
catalog = pd.DataFrame.from_dict(feat_log)
root = pd.DataFrame.from_dict(sp.audio_features(tracks=[track_id]))
merged_df = root.append(catalog, ignore_index=True)
dropped_df = merged_df.drop(columns=['uri', 'track_href', 'id', 'duration_ms', 'time_signature', 'mode', 'loudness', 'type', 'analysis_url'])
scaled_df = StandardScaler().fit_transform(dropped_df)
trans_array = scaled_df.copy()
trans_array[:,0] = [u*2.4 for u in trans_array[:,0]] # acousticness
trans_array[:,1] = [((u*u)**0.5)*u for u in trans_array[:,1]] # danceability
trans_array[:,2] = [u*1.7 for u in trans_array[:,2]] # energy
trans_array[:,3] = [u*1.4 for u in trans_array[:,3]] # instrumentalness
trans_array[:,4] = [u*0.9 for u in trans_array[:,4]] # key
trans_array[:,5] = [u*1.0 for u in trans_array[:,5]] # liveness
trans_array[:,6] = [u*1.0 for u in trans_array[:,6]] # speechiness
trans_array[:,7] = [u*1.1 for u in trans_array[:,7]] # tempo
trans_array[:,8] = [u*2.5 for u in trans_array[:,8]] # valence
knn = NearestNeighbors()
knn.fit(trans_array)
rec = knn.kneighbors(trans_array[[0]], n_neighbors=neighbors+1)
print('Seed')
print('ID: ', root.loc[0,'id'], '\n')
print('Energy: ', root.loc[0, 'energy']) # add/change/remove
print('Danceability: ', root.loc[0, 'danceability']) # ? add/change/remove
print('\nRecommendations')
for n in range(1,neighbors+1):
if rec[0][0][n] <= max_distance:
print('ID: ', merged_df.loc[rec[1][0][n],'id'])
print('Distance:', rec[0][0][n], '\n')
print('Energy:', merged_df.loc[rec[1][0][n],'energy']) # add/change/remove
print('Danceability:', merged_df.loc[rec[1][0][n],'danceability']) # add/remove/change
print('\n')
if rec[0][0][1] > max_distance:
print('No matches in catalog')
# Example
dj_rec('0Gc6TVm52BwZD07Ki6tIvf', max_distance=5.0, neighbors=3)
# Find artist name from track id
sp.track('0Gc6TVm52BwZD07Ki6tIvf')['artists']
# Find song name from track id
sp.track('0Gc6TVm52BwZD07Ki6tIvf')['name']
```
| 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.
```
# 使用 tf.data 加载文本数据
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://tensorflow.google.cn/tutorials/load_data/text"><img src="https://tensorflow.google.cn/images/tf_logo_32px.png" />在 TensorFlow.org 上查看</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/zh-cn/tutorials/load_data/text.ipynb"><img src="https://tensorflow.google.cn/images/colab_logo_32px.png" />在 Google Colab 上运行</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/zh-cn/tutorials/load_data/text.ipynb"><img src="https://tensorflow.google.cn/images/GitHub-Mark-32px.png" />查看 GitHub 上的资源</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/zh-cn/tutorials/load_data/text.ipynb"><img src="https://tensorflow.google.cn/images/download_logo_32px.png" />下载 notebook</a>
</td>
</table>
Note: 我们的 TensorFlow 社区翻译了这些文档。因为社区翻译是尽力而为, 所以无法保证它们是最准确的,并且反映了最新的
[官方英文文档](https://tensorflow.google.cn/?hl=en)。如果您有改进此翻译的建议, 请提交 pull request 到
[tensorflow/docs](https://github.com/tensorflow/docs) GitHub 仓库。要志愿地撰写或者审核译文,请加入
[docs-zh-cn@tensorflow.org Google Group](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-zh-cn)。
本教程为你提供了一个如何使用 `tf.data.TextLineDataset` 来加载文本文件的示例。`TextLineDataset` 通常被用来以文本文件构建数据集(原文件中的一行为一个样本) 。这适用于大多数的基于行的文本数据(例如,诗歌或错误日志) 。下面我们将使用相同作品(荷马的伊利亚特)三个不同版本的英文翻译,然后训练一个模型来通过单行文本确定译者。
## 环境搭建
```
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta1
import tensorflow as tf
import tensorflow_datasets as tfds
import os
```
三个版本的翻译分别来自于:
- [William Cowper](https://en.wikipedia.org/wiki/William_Cowper) — [text](https://storage.googleapis.com/download.tensorflow.org/data/illiad/cowper.txt)
- [Edward, Earl of Derby](https://en.wikipedia.org/wiki/Edward_Smith-Stanley,_14th_Earl_of_Derby) — [text](https://storage.googleapis.com/download.tensorflow.org/data/illiad/derby.txt)
- [Samuel Butler](https://en.wikipedia.org/wiki/Samuel_Butler_%28novelist%29) — [text](https://storage.googleapis.com/download.tensorflow.org/data/illiad/butler.txt)
本教程中使用的文本文件已经进行过一些典型的预处理,主要包括删除了文档页眉和页脚,行号,章节标题。请下载这些已经被局部改动过的文件。
```
DIRECTORY_URL = 'https://storage.googleapis.com/download.tensorflow.org/data/illiad/'
FILE_NAMES = ['cowper.txt', 'derby.txt', 'butler.txt']
for name in FILE_NAMES:
text_dir = tf.keras.utils.get_file(name, origin=DIRECTORY_URL+name)
parent_dir = os.path.dirname(text_dir)
parent_dir
```
## 将文本加载到数据集中
迭代整个文件,将整个文件加载到自己的数据集中。
每个样本都需要单独标记,所以请使用 `tf.data.Dataset.map` 来为每个样本设定标签。这将迭代数据集中的每一个样本并且返回( `example, label` )对。
```
def labeler(example, index):
return example, tf.cast(index, tf.int64)
labeled_data_sets = []
for i, file_name in enumerate(FILE_NAMES):
lines_dataset = tf.data.TextLineDataset(os.path.join(parent_dir, file_name))
labeled_dataset = lines_dataset.map(lambda ex: labeler(ex, i))
labeled_data_sets.append(labeled_dataset)
```
将这些标记的数据集合并到一个数据集中,然后对其进行随机化操作。
```
BUFFER_SIZE = 50000
BATCH_SIZE = 64
TAKE_SIZE = 5000
all_labeled_data = labeled_data_sets[0]
for labeled_dataset in labeled_data_sets[1:]:
all_labeled_data = all_labeled_data.concatenate(labeled_dataset)
all_labeled_data = all_labeled_data.shuffle(
BUFFER_SIZE, reshuffle_each_iteration=False)
```
你可以使用 `tf.data.Dataset.take` 与 `print` 来查看 `(example, label)` 对的外观。`numpy` 属性显示每个 Tensor 的值。
```
for ex in all_labeled_data.take(5):
print(ex)
```
## 将文本编码成数字
机器学习基于的是数字而非文本,所以字符串需要被转化成数字列表。
为了达到此目的,我们需要构建文本与整数的一一映射。
### 建立词汇表
首先,通过将文本标记为单独的单词集合来构建词汇表。在 TensorFlow 和 Python 中均有很多方法来达成这一目的。在本教程中:
1. 迭代每个样本的 `numpy` 值。
2. 使用 `tfds.features.text.Tokenizer` 来将其分割成 `token`。
3. 将这些 `token` 放入一个 Python 集合中,借此来清除重复项。
4. 获取该词汇表的大小以便于以后使用。
```
tokenizer = tfds.features.text.Tokenizer()
vocabulary_set = set()
for text_tensor, _ in all_labeled_data:
some_tokens = tokenizer.tokenize(text_tensor.numpy())
vocabulary_set.update(some_tokens)
vocab_size = len(vocabulary_set)
vocab_size
```
### 样本编码
通过传递 `vocabulary_set` 到 `tfds.features.text.TokenTextEncoder` 来构建一个编码器。编码器的 `encode` 方法传入一行文本,返回一个整数列表。
```
encoder = tfds.features.text.TokenTextEncoder(vocabulary_set)
```
你可以尝试运行这一行代码并查看输出的样式。
```
example_text = next(iter(all_labeled_data))[0].numpy()
print(example_text)
encoded_example = encoder.encode(example_text)
print(encoded_example)
```
现在,在数据集上运行编码器(通过将编码器打包到 `tf.py_function` 并且传参至数据集的 `map` 方法的方式来运行)。
```
def encode(text_tensor, label):
encoded_text = encoder.encode(text_tensor.numpy())
return encoded_text, label
def encode_map_fn(text, label):
return tf.py_function(encode, inp=[text, label], Tout=(tf.int64, tf.int64))
all_encoded_data = all_labeled_data.map(encode_map_fn)
```
## 将数据集分割为测试集和训练集且进行分支
使用 `tf.data.Dataset.take` 和 `tf.data.Dataset.skip` 来建立一个小一些的测试数据集和稍大一些的训练数据集。
在数据集被传入模型之前,数据集需要被分批。最典型的是,每个分支中的样本大小与格式需要一致。但是数据集中样本并不全是相同大小的(每行文本字数并不相同)。因此,使用 `tf.data.Dataset.padded_batch`(而不是 `batch` )将样本填充到相同的大小。
```
train_data = all_encoded_data.skip(TAKE_SIZE).shuffle(BUFFER_SIZE)
train_data = train_data.padded_batch(BATCH_SIZE, padded_shapes=([-1],[]))
test_data = all_encoded_data.take(TAKE_SIZE)
test_data = test_data.padded_batch(BATCH_SIZE, padded_shapes=([-1],[]))
```
现在,test_data 和 train_data 不是( `example, label` )对的集合,而是批次的集合。每个批次都是一对(*多样本*, *多标签* ),表示为数组。
```
sample_text, sample_labels = next(iter(test_data))
sample_text[0], sample_labels[0]
```
由于我们引入了一个新的 token 来编码(填充零),因此词汇表大小增加了一个。
```
vocab_size += 1
```
## 建立模型
```
model = tf.keras.Sequential()
```
第一层将整数表示转换为密集矢量嵌入。更多内容请查阅 [Word Embeddings](../../tutorials/sequences/word_embeddings) 教程。
```
model.add(tf.keras.layers.Embedding(vocab_size, 64))
```
下一层是 [LSTM](http://colah.github.io/posts/2015-08-Understanding-LSTMs/) 层,它允许模型利用上下文中理解单词含义。 LSTM 上的双向包装器有助于模型理解当前数据点与其之前和之后的数据点的关系。
```
model.add(tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)))
```
最后,我们将获得一个或多个紧密连接的层,其中最后一层是输出层。输出层输出样本属于各个标签的概率,最后具有最高概率的分类标签即为最终预测结果。
```
# 一个或多个紧密连接的层
# 编辑 `for` 行的列表去检测层的大小
for units in [64, 64]:
model.add(tf.keras.layers.Dense(units, activation='relu'))
# 输出层。第一个参数是标签个数。
model.add(tf.keras.layers.Dense(3, activation='softmax'))
```
最后,编译这个模型。对于一个 softmax 分类模型来说,通常使用 `sparse_categorical_crossentropy` 作为其损失函数。你可以尝试其他的优化器,但是 `adam` 是最常用的。
```
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
```
## 训练模型
利用提供的数据训练出的模型有着不错的精度(大约 83% )。
```
model.fit(train_data, epochs=3, validation_data=test_data)
eval_loss, eval_acc = model.evaluate(test_data)
print('\nEval loss: {}, Eval accuracy: {}'.format(eval_loss, eval_acc))
```
| github_jupyter |
# About this Notebook
Bayesian probabilistic matrix factorization (BPMF) is a classical model in the recommender system field. In the following, we will discuss:
- What the BPMF is?
- How to implement BPMF mainly using Python `Numpy` with high efficiency?
- How to make data imputations with real-world spatiotemporal datasets?
If you want to know more about BPMF, please read this article:
> Ruslan Salakhutdinov, Andriy Mnih, 2008. [**Bayesian probabilistic matrix factorization using Markov chain Monte Carlo**](https://www.cs.toronto.edu/~amnih/papers/bpmf.pdf). Proceedings of the 25th International Conference on Machine Learning (*ICML 2008*), Helsinki, Finland. [[Matlab code (official)](https://www.cs.toronto.edu/~rsalakhu/BPMF.html)]
## Quick Run
This notebook is publicly available for any usage at our data imputation project. Please click [**transdim**](https://github.com/xinychen/transdim).
```
import numpy as np
from numpy.random import multivariate_normal as mvnrnd
from scipy.stats import wishart
from numpy.linalg import inv as inv
```
# Part 1: Matrix Computation Concepts
## 1) Kronecker product
- **Definition**:
Given two matrices $A\in\mathbb{R}^{m_1\times n_1}$ and $B\in\mathbb{R}^{m_2\times n_2}$, then, the **Kronecker product** between these two matrices is defined as
$$A\otimes B=\left[ \begin{array}{cccc} a_{11}B & a_{12}B & \cdots & a_{1m_2}B \\ a_{21}B & a_{22}B & \cdots & a_{2m_2}B \\ \vdots & \vdots & \ddots & \vdots \\ a_{m_11}B & a_{m_12}B & \cdots & a_{m_1m_2}B \\ \end{array} \right]$$
where the symbol $\otimes$ denotes Kronecker product, and the size of resulted $A\otimes B$ is $(m_1m_2)\times (n_1n_2)$ (i.e., $m_1\times m_2$ columns and $n_1\times n_2$ rows).
- **Example**:
If $A=\left[ \begin{array}{cc} 1 & 2 \\ 3 & 4 \\ \end{array} \right]$ and $B=\left[ \begin{array}{ccc} 5 & 6 & 7\\ 8 & 9 & 10 \\ \end{array} \right]$, then, we have
$$A\otimes B=\left[ \begin{array}{cc} 1\times \left[ \begin{array}{ccc} 5 & 6 & 7\\ 8 & 9 & 10\\ \end{array} \right] & 2\times \left[ \begin{array}{ccc} 5 & 6 & 7\\ 8 & 9 & 10\\ \end{array} \right] \\ 3\times \left[ \begin{array}{ccc} 5 & 6 & 7\\ 8 & 9 & 10\\ \end{array} \right] & 4\times \left[ \begin{array}{ccc} 5 & 6 & 7\\ 8 & 9 & 10\\ \end{array} \right] \\ \end{array} \right]$$
$$=\left[ \begin{array}{cccccc} 5 & 6 & 7 & 10 & 12 & 14 \\ 8 & 9 & 10 & 16 & 18 & 20 \\ 15 & 18 & 21 & 20 & 24 & 28 \\ 24 & 27 & 30 & 32 & 36 & 40 \\ \end{array} \right]\in\mathbb{R}^{4\times 6}.$$
## 2) Khatri-Rao product (`kr_prod`)
- **Definition**:
Given two matrices $A=\left( \boldsymbol{a}_1,\boldsymbol{a}_2,...,\boldsymbol{a}_r \right)\in\mathbb{R}^{m\times r}$ and $B=\left( \boldsymbol{b}_1,\boldsymbol{b}_2,...,\boldsymbol{b}_r \right)\in\mathbb{R}^{n\times r}$ with same number of columns, then, the **Khatri-Rao product** (or **column-wise Kronecker product**) between $A$ and $B$ is given as follows,
$$A\odot B=\left( \boldsymbol{a}_1\otimes \boldsymbol{b}_1,\boldsymbol{a}_2\otimes \boldsymbol{b}_2,...,\boldsymbol{a}_r\otimes \boldsymbol{b}_r \right)\in\mathbb{R}^{(mn)\times r}$$
where the symbol $\odot$ denotes Khatri-Rao product, and $\otimes$ denotes Kronecker product.
- **Example**:
If $A=\left[ \begin{array}{cc} 1 & 2 \\ 3 & 4 \\ \end{array} \right]=\left( \boldsymbol{a}_1,\boldsymbol{a}_2 \right) $ and $B=\left[ \begin{array}{cc} 5 & 6 \\ 7 & 8 \\ 9 & 10 \\ \end{array} \right]=\left( \boldsymbol{b}_1,\boldsymbol{b}_2 \right) $, then, we have
$$A\odot B=\left( \boldsymbol{a}_1\otimes \boldsymbol{b}_1,\boldsymbol{a}_2\otimes \boldsymbol{b}_2 \right) $$
$$=\left[ \begin{array}{cc} \left[ \begin{array}{c} 1 \\ 3 \\ \end{array} \right]\otimes \left[ \begin{array}{c} 5 \\ 7 \\ 9 \\ \end{array} \right] & \left[ \begin{array}{c} 2 \\ 4 \\ \end{array} \right]\otimes \left[ \begin{array}{c} 6 \\ 8 \\ 10 \\ \end{array} \right] \\ \end{array} \right]$$
$$=\left[ \begin{array}{cc} 5 & 12 \\ 7 & 16 \\ 9 & 20 \\ 15 & 24 \\ 21 & 32 \\ 27 & 40 \\ \end{array} \right]\in\mathbb{R}^{6\times 2}.$$
```
def kr_prod(a, b):
return np.einsum('ir, jr -> ijr', a, b).reshape(a.shape[0] * b.shape[0], -1)
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8], [9, 10]])
print(kr_prod(A, B))
```
## 3) Computing Covariance Matrix (`cov_mat`)
For any matrix $X\in\mathbb{R}^{m\times n}$, `cov_mat` can return a $n\times n$ covariance matrix for special use in the following.
```
def cov_mat(mat):
dim1, dim2 = mat.shape
new_mat = np.zeros((dim2, dim2))
mat_bar = np.mean(mat, axis = 0)
for i in range(dim1):
new_mat += np.einsum('i, j -> ij', mat[i, :] - mat_bar, mat[i, :] - mat_bar)
return new_mat
```
# Part 2: Bayesian Probabilistic Matrix Factorization (BPMF)
```
def BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2):
"""Bayesian Probabilistic Matrix Factorization, BPMF."""
W = init["W"]
X = init["X"]
dim1, dim2 = sparse_mat.shape
dim = np.array([dim1, dim2])
pos = np.where((dense_mat != 0) & (sparse_mat == 0))
position = np.where(sparse_mat != 0)
binary_mat = np.zeros((dim1, dim2))
binary_mat[position] = 1
beta0 = 1
nu0 = rank
mu0 = np.zeros((rank))
W0 = np.eye(rank)
tau = 1
alpha = 1e-6
beta = 1e-6
W_plus = np.zeros((dim1, rank))
X_plus = np.zeros((dim2, rank))
mat_hat_plus = np.zeros((dim1, dim2))
for iters in range(maxiter1):
for order in range(2):
if order == 0:
mat = W.copy()
elif order == 1:
mat = X.copy()
mat_bar = np.mean(mat, axis = 0)
var_mu_hyper = (dim[order] * mat_bar + beta0 * mu0)/(dim[order] + beta0)
var_W_hyper = inv(inv(W0) + cov_mat(mat) + dim[order] * beta0/(dim[order] + beta0)
* np.outer(mat_bar - mu0, mat_bar - mu0))
var_Lambda_hyper = wishart(df = dim[order] + nu0, scale = var_W_hyper, seed = None).rvs()
var_mu_hyper = mvnrnd(var_mu_hyper, inv((dim[order] + beta0) * var_Lambda_hyper))
if order == 0:
var1 = X.T
mat0 = np.matmul(var1, sparse_mat.T)
elif order == 1:
var1 = W.T
mat0 = np.matmul(var1, sparse_mat)
var2 = kr_prod(var1, var1)
if order == 0:
mat1 = np.matmul(var2, binary_mat.T)
elif order == 1:
mat1 = np.matmul(var2, binary_mat)
var3 = tau * mat1.reshape(rank, rank, dim[order]) + np.dstack([var_Lambda_hyper] * dim[order])
var4 = tau * mat0 + np.dstack([np.matmul(var_Lambda_hyper, var_mu_hyper)] * dim[order])[0, :, :]
for i in range(dim[order]):
var_Lambda = var3[:, :, i]
inv_var_Lambda = inv((var_Lambda + var_Lambda.T)/2)
vec = mvnrnd(np.matmul(inv_var_Lambda, var4[:, i]), inv_var_Lambda)
if order == 0:
W[i, :] = vec.copy()
elif order == 1:
X[i, :] = vec.copy()
if iters + 1 > maxiter1 - maxiter2:
W_plus += W
X_plus += X
mat_hat = np.matmul(W, X.T)
if iters + 1 > maxiter1 - maxiter2:
mat_hat_plus += mat_hat
rmse = np.sqrt(np.sum((dense_mat[pos] - mat_hat[pos]) ** 2)/dense_mat[pos].shape[0])
var_alpha = alpha + 0.5 * sparse_mat[position].shape[0]
error = sparse_mat - mat_hat
var_beta = beta + 0.5 * np.sum(error[position] ** 2)
tau = np.random.gamma(var_alpha, 1/var_beta)
if (iters + 1) % 200 == 0 and iters < maxiter1 - maxiter2:
print('Iter: {}'.format(iters + 1))
print('RMSE: {:.6}'.format(rmse))
print()
W = W_plus/maxiter2
X = X_plus/maxiter2
mat_hat = mat_hat_plus/maxiter2
if maxiter1 >= 100:
final_mape = np.sum(np.abs(dense_mat[pos] - mat_hat[pos])/dense_mat[pos])/dense_mat[pos].shape[0]
final_rmse = np.sqrt(np.sum((dense_mat[pos] - mat_hat[pos]) ** 2)/dense_mat[pos].shape[0])
print('Imputation MAPE: {:.6}'.format(final_mape))
print('Imputation RMSE: {:.6}'.format(final_rmse))
print()
return mat_hat, W, X
```
# Part 3: Data Organization
## 1) Matrix Structure
We consider a dataset of $m$ discrete time series $\boldsymbol{y}_{i}\in\mathbb{R}^{f},i\in\left\{1,2,...,m\right\}$. The time series may have missing elements. We express spatio-temporal dataset as a matrix $Y\in\mathbb{R}^{m\times f}$ with $m$ rows (e.g., locations) and $f$ columns (e.g., discrete time intervals),
$$Y=\left[ \begin{array}{cccc} y_{11} & y_{12} & \cdots & y_{1f} \\ y_{21} & y_{22} & \cdots & y_{2f} \\ \vdots & \vdots & \ddots & \vdots \\ y_{m1} & y_{m2} & \cdots & y_{mf} \\ \end{array} \right]\in\mathbb{R}^{m\times f}.$$
## 2) Tensor Structure
We consider a dataset of $m$ discrete time series $\boldsymbol{y}_{i}\in\mathbb{R}^{nf},i\in\left\{1,2,...,m\right\}$. The time series may have missing elements. We partition each time series into intervals of predifined length $f$. We express each partitioned time series as a matrix $Y_{i}$ with $n$ rows (e.g., days) and $f$ columns (e.g., discrete time intervals per day),
$$Y_{i}=\left[ \begin{array}{cccc} y_{11} & y_{12} & \cdots & y_{1f} \\ y_{21} & y_{22} & \cdots & y_{2f} \\ \vdots & \vdots & \ddots & \vdots \\ y_{n1} & y_{n2} & \cdots & y_{nf} \\ \end{array} \right]\in\mathbb{R}^{n\times f},i=1,2,...,m,$$
therefore, the resulting structure is a tensor $\mathcal{Y}\in\mathbb{R}^{m\times n\times f}$.
# Part 4: Experiments on Guangzhou Data Set
```
import scipy.io
tensor = scipy.io.loadmat('./data/tensor.mat')['tensor']
#tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('./data/random_matrix.mat')['random_matrix']
#random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('./data/random_tensor.mat')['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.2
# =============================================================================
### Random missing (RM) scenario
### Set the RM scenario by:
binary_mat = (np.round(random_tensor + 0.5 - missing_rate)
.reshape([random_tensor.shape[0], random_tensor.shape[1] * random_tensor.shape[2]]))
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
tensor = scipy.io.loadmat('./data/tensor.mat')['tensor']
random_matrix = scipy.io.loadmat('./data/random_matrix.mat')['random_matrix']
random_tensor = scipy.io.loadmat('./data/random_tensor.mat')['random_tensor']
tensor.shape, random_tensor.shape
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 80
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import scipy.io
tensor = scipy.io.loadmat('../datasets/Guangzhou-data-set/tensor.mat')
tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Guangzhou-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Guangzhou-data-set/random_tensor.mat')
random_tensor = random_tensor['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.4
# =============================================================================
### Random missing (RM) scenario
### Set the RM scenario by:
binary_mat = (np.round(random_tensor + 0.5 - missing_rate)
.reshape([random_tensor.shape[0], random_tensor.shape[1] * random_tensor.shape[2]]))
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 80
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import scipy.io
tensor = scipy.io.loadmat('../datasets/Guangzhou-data-set/tensor.mat')
tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Guangzhou-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Guangzhou-data-set/random_tensor.mat')
random_tensor = random_tensor['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.2
# =============================================================================
### Non-random missing (NM) scenario
### Set the NM scenario by:
binary_tensor = np.zeros(tensor.shape)
for i1 in range(tensor.shape[0]):
for i2 in range(tensor.shape[1]):
binary_tensor[i1, i2, :] = np.round(random_matrix[i1, i2] + 0.5 - missing_rate)
binary_mat = binary_tensor.reshape([binary_tensor.shape[0], binary_tensor.shape[1] * binary_tensor.shape[2]])
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 10
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import scipy.io
tensor = scipy.io.loadmat('../datasets/Guangzhou-data-set/tensor.mat')
tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Guangzhou-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Guangzhou-data-set/random_tensor.mat')
random_tensor = random_tensor['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.4
# =============================================================================
### Non-random missing (NM) scenario
### Set the NM scenario by:
binary_tensor = np.zeros(tensor.shape)
for i1 in range(tensor.shape[0]):
for i2 in range(tensor.shape[1]):
binary_tensor[i1, i2, :] = np.round(random_matrix[i1, i2] + 0.5 - missing_rate)
binary_mat = binary_tensor.reshape([binary_tensor.shape[0], binary_tensor.shape[1] * binary_tensor.shape[2]])
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 10
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
```
**Experiment results** of missing data imputation using BPMF:
| scenario |`rank`|`maxiter1`|`maxiter2`| mape | rmse |
|:----------|-----:|---------:|---------:|-------- --:|----------:|
|**0.2, RM**| 80 | 1100 | 100 | **0.0954** | **4.0551**|
|**0.4, RM**| 80 | 1100 | 100 | **0.0981** | **4.1659**|
|**0.2, NM**| 10 | 1100 | 100 | **0.1028** | **4.2901**|
|**0.4, NM**| 10 | 1100 | 100 | **0.1040** | **4.3994**|
# Part 5: Experiments on Birmingham Data Set
```
import scipy.io
tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/tensor.mat')['tensor']
random_matrix = scipy.io.loadmat('../datasets/Birmingham-data-set/random_matrix.mat')['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/random_tensor.mat')['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.1
# =============================================================================
### Random missing (RM) scenario
### Set the RM scenario by:
binary_mat = (np.round(random_tensor + 0.5 - missing_rate)
.reshape([random_tensor.shape[0], random_tensor.shape[1] * random_tensor.shape[2]]))
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 30
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import scipy.io
tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/tensor.mat')
tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Birmingham-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/random_tensor.mat')
random_tensor = random_tensor['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.3
# =============================================================================
### Random missing (RM) scenario
### Set the RM scenario by:
binary_mat = (np.round(random_tensor + 0.5 - missing_rate)
.reshape([random_tensor.shape[0], random_tensor.shape[1] * random_tensor.shape[2]]))
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 30
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import scipy.io
tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/tensor.mat')
tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Birmingham-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/random_tensor.mat')
random_tensor = random_tensor['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.1
# =============================================================================
### Non-random missing (NM) scenario
### Set the NM scenario by:
binary_tensor = np.zeros(tensor.shape)
for i1 in range(tensor.shape[0]):
for i2 in range(tensor.shape[1]):
binary_tensor[i1, i2, :] = np.round(random_matrix[i1, i2] + 0.5 - missing_rate)
binary_mat = binary_tensor.reshape([binary_tensor.shape[0], binary_tensor.shape[1] * binary_tensor.shape[2]])
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 10
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import scipy.io
tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/tensor.mat')
tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Birmingham-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Birmingham-data-set/random_tensor.mat')
random_tensor = random_tensor['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.3
# =============================================================================
### Non-random missing (NM) scenario
### Set the NM scenario by:
binary_tensor = np.zeros(tensor.shape)
for i1 in range(tensor.shape[0]):
for i2 in range(tensor.shape[1]):
binary_tensor[i1, i2, :] = np.round(random_matrix[i1, i2] + 0.5 - missing_rate)
binary_mat = binary_tensor.reshape([binary_tensor.shape[0], binary_tensor.shape[1] * binary_tensor.shape[2]])
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 10
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
```
**Experiment results** of missing data imputation using BPMF:
| scenario |`rank`|`maxiter1`|`maxiter2`| mape | rmse |
|:----------|-----:|---------:|---------:|-----------:|-----------:|
|**10%, RM**| 30 | 1100 | 100 | **0.0787** | **81.593**|
|**30%, RM**| 30 | 1100 | 100 | **0.0995** | **83.8159**|
|**10%, NM**| 10 | 1100 | 100 | **0.1318** | **29.2774**|
|**30%, NM**| 10 | 1100 | 100 | **0.1475** | **60.2924**|
# Part 6: Experiments on Hangzhou Data Set
```
import scipy.io
tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/tensor.mat')
tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_tensor.mat')
random_tensor = random_tensor['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.2
# =============================================================================
### Random missing (RM) scenario
### Set the RM scenario by:
binary_mat = (np.round(random_tensor + 0.5 - missing_rate)
.reshape([random_tensor.shape[0], random_tensor.shape[1] * random_tensor.shape[2]]))
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 50
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import scipy.io
tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/tensor.mat')
tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_tensor.mat')
random_tensor = random_tensor['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.4
# =============================================================================
### Random missing (RM) scenario
### Set the RM scenario by:
binary_mat = (np.round(random_tensor + 0.5 - missing_rate)
.reshape([random_tensor.shape[0], random_tensor.shape[1] * random_tensor.shape[2]]))
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 50
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import scipy.io
tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/tensor.mat')
tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_tensor.mat')
random_tensor = random_tensor['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.2
# =============================================================================
### Non-random missing (NM) scenario
### Set the NM scenario by:
binary_tensor = np.zeros(tensor.shape)
for i1 in range(tensor.shape[0]):
for i2 in range(tensor.shape[1]):
binary_tensor[i1, i2, :] = np.round(random_matrix[i1, i2] + 0.5 - missing_rate)
binary_mat = binary_tensor.reshape([binary_tensor.shape[0], binary_tensor.shape[1] * binary_tensor.shape[2]])
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 10
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import scipy.io
tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/tensor.mat')
tensor = tensor['tensor']
random_matrix = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_matrix.mat')
random_matrix = random_matrix['random_matrix']
random_tensor = scipy.io.loadmat('../datasets/Hangzhou-data-set/random_tensor.mat')
random_tensor = random_tensor['random_tensor']
dense_mat = tensor.reshape([tensor.shape[0], tensor.shape[1] * tensor.shape[2]])
missing_rate = 0.4
# =============================================================================
### Non-random missing (NM) scenario
### Set the NM scenario by:
binary_tensor = np.zeros(tensor.shape)
for i1 in range(tensor.shape[0]):
for i2 in range(tensor.shape[1]):
binary_tensor[i1, i2, :] = np.round(random_matrix[i1, i2] + 0.5 - missing_rate)
binary_mat = binary_tensor.reshape([binary_tensor.shape[0], binary_tensor.shape[1] * binary_tensor.shape[2]])
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 10
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
```
**Experiment results** of missing data imputation using BPMF:
| scenario |`rank`|`maxiter1`|`maxiter2`| mape | rmse |
|:----------|-----:|---------:|---------:|-----------:|-----------:|
|**20%, RM**| 50 | 1100 | 100 | **0.2963** | **41.8653**|
|**40%, RM**| 50 | 1100 | 100 | **0.3283** | **44.4621**|
|**20%, NM**| 10 | 1100 | 100 | **0.3631** | **64.2751**|
|**40%, NM**| 10 | 1100 | 100 | **0.3643** | **59.0373**|
# Part 7: Experiments on Seattle Data Set
```
import pandas as pd
dense_mat = pd.read_csv('../datasets/Seattle-data-set/mat.csv', index_col = 0)
RM_mat = pd.read_csv('../datasets/Seattle-data-set/RM_mat.csv', index_col = 0)
dense_mat = dense_mat.values
RM_mat = RM_mat.values
missing_rate = 0.2
# =============================================================================
### Random missing (RM) scenario
### Set the RM scenario by:
binary_mat = np.round(RM_mat + 0.5 - missing_rate)
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 50
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import pandas as pd
dense_mat = pd.read_csv('../datasets/Seattle-data-set/mat.csv', index_col = 0)
RM_mat = pd.read_csv('../datasets/Seattle-data-set/RM_mat.csv', index_col = 0)
dense_mat = dense_mat.values
RM_mat = RM_mat.values
missing_rate = 0.4
# =============================================================================
### Random missing (RM) scenario
### Set the RM scenario by:
binary_mat = np.round(RM_mat + 0.5 - missing_rate)
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_mat)
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 50
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import pandas as pd
dense_mat = pd.read_csv('../datasets/Seattle-data-set/mat.csv', index_col = 0)
NM_mat = pd.read_csv('../datasets/Seattle-data-set/NM_mat.csv', index_col = 0)
dense_mat = dense_mat.values
NM_mat = NM_mat.values
missing_rate = 0.2
# =============================================================================
### Non-random missing (NM) scenario
### Set the NM scenario by:
binary_tensor = np.zeros((dense_mat.shape[0], 28, 288))
for i1 in range(binary_tensor.shape[0]):
for i2 in range(binary_tensor.shape[1]):
binary_tensor[i1, i2, :] = np.round(NM_mat[i1, i2] + 0.5 - missing_rate)
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_tensor.reshape([dense_mat.shape[0], dense_mat.shape[1]]))
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 10
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
import pandas as pd
dense_mat = pd.read_csv('../datasets/Seattle-data-set/mat.csv', index_col = 0)
NM_mat = pd.read_csv('../datasets/Seattle-data-set/NM_mat.csv', index_col = 0)
dense_mat = dense_mat.values
NM_mat = NM_mat.values
missing_rate = 0.4
# =============================================================================
### Non-random missing (NM) scenario
### Set the NM scenario by:
binary_tensor = np.zeros((dense_mat.shape[0], 28, 288))
for i1 in range(binary_tensor.shape[0]):
for i2 in range(binary_tensor.shape[1]):
binary_tensor[i1, i2, :] = np.round(NM_mat[i1, i2] + 0.5 - missing_rate)
# =============================================================================
sparse_mat = np.multiply(dense_mat, binary_tensor.reshape([dense_mat.shape[0], dense_mat.shape[1]]))
import time
start = time.time()
dim1, dim2 = sparse_mat.shape
rank = 10
init = {"W": 0.1 * np.random.rand(dim1, rank),
"X": 0.1 * np.random.rand(dim2, rank)}
maxiter1 = 1100
maxiter2 = 100
BPMF(dense_mat, sparse_mat, init, rank, maxiter1, maxiter2)
end = time.time()
print('Running time: %d seconds'%(end - start))
```
**Experiment results** of missing data imputation using BPMF:
| scenario |`rank`|`maxiter1`|`maxiter2`| mape | rmse |
|:----------|-----:|---------:|---------:|-----------:|-----------:|
|**20%, RM**| 50 | 1100 | 100 | **0.0651** | **4.0433** |
|**40%, RM**| 50 | 1100 | 100 | **0.0703** | **4.2884** |
|**20%, NM**| 10 | 1100 | 100 | **0.0912** | **5.2653** |
|**40%, NM**| 10 | 1100 | 100 | **0.0919** | **5.3047** |
| github_jupyter |
# Introduction to Logistic Regression
Logistic regression is another technique borrowed by machine learning from the field of statistics.
It is the go-to method for binary classification problems (problems with two class values).Logistic Regression (also called Logit Regression) is commonly used to estimate the probability that an instance belongs to a particular class (e.g., what is the probability that this email is spam?). If the estimated probability is greater than 50%, then the model predicts that the instance belongs to that class (called the positive class, labeled “1”), or else it predicts that it does not (i.e., it belongs to the negative class, labeled “0”). This makes it a binary classifier.
So how does it work? Just like a Linear Regression model, a Logistic Regression
model computes a weighted sum of the input features (plus a bias term), but instead
of outputting the result directly like the Linear Regression model does, it outputs the
logistic of this result.
The logistic function, also called the sigmoid function was developed by statisticians to describe
properties of population growth in ecology, rising quickly and maxing out at the carrying
capacity of the environment. It’s an S -shaped curve that can take any real-valued number and
map it into a value between 0 and 1, but never exactly at those limits.
The logistic—also called the logit, noted σ(·)—is a sigmoid function (i.e., S-shaped)
that outputs a number between 0 and 1.

Where e is the base of the natural logarithms (Euler’s number or the EXP() function in your
spreadsheet) and t is the actual numerical value that you want to transform.

Logistic regression uses an equation as the representation, very much like linear regression.
Input values (x) are combined linearly using weights or coefficient values to predict an output
value (y). A key difference from linear regression is that the output value being modeled is a
binary values (0 or 1) rather than a numeric value.

Where y is the predicted output, B0 is the bias or intercept term and B1 is the coefficient
for the single input value (x). Each column in your input data has an associated B coefficient
(a constant real value) that must be learned from your training data. The actual representation
of the model that you would store in memory or in a file are the coefficients in the equation
(the beta value or B’s).
Logistic regression models the probability of the default class.For example,
if we are modeling people’s sex as male or female from their height, then the first class could
be male and the logistic regression model could be written as the probability of male given a
person’s height, or more formally:
P (sex = male|height)
Written another way, we are modeling the probability that an input (X) belongs to the
default class (Y = 1), we can write this formally as:
P(X) = P(Y = 1|X)
Note that the probability prediction must be transformed into a binary values (0 or 1) in order
to actually make a crisp prediction.
Logistic regression is a linear method, but the predictions are transformed using the logistic
function. The impact of this is that we can no longer understand the predictions as a linear
combination of the inputs as we can with linear regression


This is useful because we can see that the calculation of the output on the right is linear again
(just like linear regression), and the input on the left is a natural logarithm of the probability of
the default class. This ratio on the left is called the odds of the default class. Odds are
calculated as a ratio of the probability of the event divided by the probability of not the event. So we could instead write:
ln(odds) = B0 + B1 × X
Because the odds are log transformed, we call this left hand side the log-odds or the probit.

Here the model is still a linear combination of the
inputs, but this linear combination relates to the log-odds of the default class.
The coefficients of the logistic regression algorithm must be estimated from your training data.
The best coefficients would result in a model that would predict a value very close to 1 (e.g.
male) for the default class and a value very close to 0 (e.g. female) for the other class.
Making predictions with a logistic regression model is as simple as plugging in numbers into the
logistic regression equation and calculating a result. Let’s make this concrete with a specific
example. Let’s say we have a model that can predict whether a person is male or female based
on their height (completely fictitious). Given a height of 150 cm is the person male or female.
We have learned the coefficients of B0 = −100 and B1 = 0.6. Using the equation above we can
calculate the probability of male given a height of 150 cm or more formally P (male|height = 150).

Or a probability of near zero that the person is a male. In practice we can use the probabilities
directly. Because this is classification and we want a crisp answer, we can snap the probabilities
to a binary class value, for example

This dataset has two input variables (X1 and
X2) and one output variable (Y ). The input variables are real-valued random numbers drawn
from a Gaussian distribution. The output variable has two values, making the problem a binary
classification problem.
```
X1 = [
2.7810836,
1.465489372,
3.396561688,
1.38807019,
3.06407232,
7.627531214,
5.332441248,
6.922596716,
8.675418651,
7.673756466]
X2 = [
2.550537003,
2.362125076,
4.400293529,
1.850220317,
3.005305973,
2.759262235,
2.088626775,
1.77106367,
-0.242068655,
3.508563011]
Y = [
0,
0,
0,
0,
0,
1,
1,
1,
1,
1]
```
The logistic regression model takes real-valued inputs and makes a prediction as to the probability
of the input belonging to the default class (class 0). If the probability is greater than 0.5 we can
take the output as a prediction for the default class (class 0), otherwise the prediction is for
the other class (class 1). For this dataset, the logistic regression has three coefficients just like
linear regression
output = B0 + B1 × X1 + B2 × X2
The job of the learning algorithm will be to discover the best values for the coefficients (B0,
B1 and B2) based on the training data. Unlike linear regression, the output is transformed into
a probability using the logistic function:

Logistic Regression model in vectorized form can be written as:

Now we know how a Logistic Regression model estimates probabilities and
makes predictions. But how is it trained? The objective of training is to set the parameter vector θ so that the model estimates high probabilities for positive instances (y =
1) and low probabilities for negative instances (y = 0). This idea is captured by the
cost function of a single training instance x

This cost function makes sense because – log(t) grows very large when t approaches
0, so the cost will be large if the model estimates a probability close to 0 for a positive instance, and it will also be very large if the model estimates a probability close to 1
for a negative instance. On the other hand, – log(t) is close to 0 when t is close to 1, so
the cost will be close to 0 if the estimated probability is close to 0 for a negative
instance or close to 1 for a positive instance, which is precisely what we want.
The cost function over the whole training set is simply the average cost over all training instances. It can be written in a single expression, called
the log loss.
Logistic Regression cost function (log loss)

This cost function is convex, so Gradient Descent (or any
other optimization algorithm) is guaranteed to find the global minimum (if the learning rate is not too large and you wait long enough). The partial derivatives of the cost
function with regards to the j th model parameter θ j is given by

It tells us how loss would change if we modified the parameters.
For each instance it computes the
prediction error and multiplies it by the j th feature value, and then it computes the
average over all training instances. Once you have the gradient vector containing all
the partial derivatives you can use it in the Batch Gradient Descent algorithm.
We can estimate the values of the coefficients using stochastic gradient descent. We can apply
stochastic gradient descent to the problem of finding the coefficients for the logistic regression
model.
Let’s start off by assigning 0.0 to each coefficient and calculating the probability of the first
training instance that belongs to class 0.
B0 = 0.0
B1 = 0.0
B2 = 0.0
The first training instance is: X1 = 2.7810836, X2 = 2.550537003, Y = 0. Using the above
equation we can plug in all of these numbers and calculate a prediction:

We can calculate the new coefficient values using a simple update equation.
b = b + alpha × (y − prediction) × prediction × (1 − prediction) × x
Where b is the coefficient we are updating and prediction is the output of making a prediction
using the model. Alpha is a parameter that you must specify at the beginning of the training
run. This is the learning rate and controls how much the coefficients (and therefore the model)
changes or learns each time it is updated.

We can repeat this process and update the model for each training instance in the dataset. A
single iteration through the training dataset is called an epoch. It is common to repeat the
stochastic gradient descent procedure for a fixed number of epochs. At the end of epoch you
can calculate error values for the model
The coefficients calculated after 10 epochs of stochastic gradient descent are:
B0 = −0.406605464
B1 = 0.852573316
B2 = −1.104746259
Now that we have trained the model, we can use it to make predictions. We can make predictions
on the training dataset, but this could just as easily be new data. Using the coefficients above
learned after 10 epochs, we can calculate output values for each training instance
Finally, we can calculate the accuracy for the model on the training dataset:

```
# Logistic Regression on Diabetes Dataset
from random import seed
from random import randrange
from csv import reader
from math import exp
# Load a CSV file
def load_csv(filename):
dataset = list()
with open(filename, 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not row:
continue
dataset.append(row)
return dataset
# Test the logistic regression algorithm on the diabetes dataset
seed(1)
# load and prepare data
filename = 'diabetes.csv'
# Convert string column to float
def str_column_to_float(dataset, column):
for row in dataset:
row[column] = float(row[column].strip())
dataset = load_csv(filename)
dataset = dataset[1:]
for i in range(len(dataset[0])):
str_column_to_float(dataset, i)
# print(dataset)
# Find the min and max values for each column
def dataset_minmax(dataset):
minmax = list()
for i in range(len(dataset[0])):
col_values = [row[i] for row in dataset]
value_min = min(col_values)
value_max = max(col_values)
minmax.append([value_min, value_max])
return minmax
# Rescale dataset columns to the range 0-1
def normalize_dataset(dataset, minmax):
for row in dataset:
for i in range(len(row)):
row[i] = (row[i] - minmax[i][0]) / (minmax[i][1] - minmax[i][0])
# normalize
minmax = dataset_minmax(dataset)
normalize_dataset(dataset, minmax)
# print(dataset)
# Split a dataset into k folds
def cross_validation_split(dataset, n_folds):
dataset_split = list()
dataset_copy = list(dataset)
fold_size = int(len(dataset) / n_folds)
for i in range(n_folds):
fold = list()
while len(fold) < fold_size:
index = randrange(len(dataset_copy))
fold.append(dataset_copy.pop(index))
dataset_split.append(fold)
return dataset_split
# Make a prediction with coefficients
def predict(row, coefficients):
yhat = coefficients[0]
for i in range(len(row)-1):
yhat += coefficients[i + 1] * row[i]
return 1.0 / (1.0 + exp(-yhat))
# Estimate logistic regression coefficients using stochastic gradient descent
def coefficients_sgd(train, l_rate, n_epoch):
coef = [0.0 for i in range(len(train[0]))]
for epoch in range(n_epoch):
for row in train:
yhat = predict(row, coef)
error = row[-1] - yhat
coef[0] = coef[0] + l_rate * error * yhat * (1.0 - yhat)
for i in range(len(row)-1):
coef[i + 1] = coef[i + 1] + l_rate * error * yhat * (1.0 - yhat) * row[i]
return coef
# Linear Regression Algorithm With Stochastic Gradient Descent
def logistic_regression(train, test, l_rate, n_epoch):
predictions = list()
coef = coefficients_sgd(train, l_rate, n_epoch)
for row in test:
yhat = predict(row, coef)
yhat = round(yhat)
predictions.append(yhat)
return(predictions)
# Calculate accuracy percentage
def accuracy_metric(actual, predicted):
correct = 0
for i in range(len(actual)):
if actual[i] == predicted[i]:
correct += 1
return correct / float(len(actual)) * 100.0
# Evaluate an algorithm using a cross validation split
def evaluate_algorithm(dataset, algorithm, n_folds, *args):
folds = cross_validation_split(dataset, n_folds)
scores = list()
for fold in folds:
train_set = list(folds)
train_set.remove(fold)
train_set = sum(train_set, [])
test_set = list()
for row in fold:
row_copy = list(row)
test_set.append(row_copy)
row_copy[-1] = None
predicted = algorithm(train_set, test_set, *args)
actual = [row[-1] for row in fold]
accuracy = accuracy_metric(actual, predicted)
scores.append(accuracy)
return scores
# evaluate algorithm
n_folds = 5
l_rate = 0.1
n_epoch = 300
scores = evaluate_algorithm(dataset, logistic_regression, n_folds, l_rate, n_epoch)
print('Scores: %s' % scores)
print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))
#imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
import sklearn
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
df = pd.read_csv('diabetes.csv')
df.head()
df.isnull().sum()
df.shape
X = df.drop(df.columns[[8]], axis=1)
y = df.drop(df.columns[[0,1,2,3,4,5,6,7]], axis=1)
#
scaler = StandardScaler()
X_new = scaler.fit_transform(X)
#
X_train, X_test, y_train, y_test = train_test_split(X_new, y, test_size=0.2, random_state=42)
clf = LogisticRegression()
clf.fit(X_train, y_train)
print (clf.intercept_, clf.coef_)
pred = clf.predict(X_test)
print ('Accuracy from sk-learn: {0}'.format(clf.score(X_test, y_test)))
```
### Problem Statement -
An expert botanist has identified species of iris as setosa, versicolor, or virginica. A new hobby botanist is interested in distinguishing the species of some
iris flowers that she has found.(Here we are assuming setosa, versicolor, or virginica are the only species our hobby botanist will encounter in the wild.) She has collected some measurements associated with
each iris: the length and width of the petals and the length and width of the sepals, all
measured in centimeters. Our goal is to build a machine learning model that can learn from the measurements
of these irises whose species is known, so that we can predict the species for a new
iris
```
#imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
df = pd.read_csv('iris-data.csv')
df.head()
df.describe()
df.info()
df.isnull().sum()
#Removing all null values row
df = df.dropna(subset=['petal_width_cm'])
df.info()
#plot
# sns.pairplot(df, hue='class', size=2.5)
df['class'].value_counts()
```
Two observations can be made from the above results
- For 5 data points 'Iris-versicolor' has been specified as 'versicolor'
- For 1 data points, 'Iris-setosa' has been specified as 'Iris-setossa'
```
df['class'].replace(["Iris-setossa","versicolor"], ["Iris-setosa","Iris-versicolor"], inplace=True)
df['class'].value_counts()
```
### Simple Logistic Regression
Consider only two class 'Iris-virginica' and 'Iris-versicolor'. Dropping all other class
```
final_df = df[df['class'] != 'Iris-setosa']
final_df.head()
final_df.shape
```
#### Outlier Check
An outlier is an observation that is unlike the other observations.
It is rare, or distinct, or does not fit in some way.
Outliers can have many causes, such as:
* Measurement or input error.
* Data corruption.
* True outlier observation
```
sns.pairplot(final_df, hue='class', size=2.5)
```
From the above plot, sepal_width and sepal_length seems to have outliers. To confirm let's plot them seperately
SEPAL LENGTH
```
final_df.hist(column = 'sepal_length_cm',bins=20, figsize=(10,5))
```
It can be observed from the plot, that for 5 data points values are below 1 and they seem to be outliers. So, these data points
are considered to be in 'm' and are converted to 'cm'.
```
final_df.loc[final_df.sepal_length_cm < 1, ['sepal_length_cm']] = final_df['sepal_length_cm']*100
final_df.hist(column = 'sepal_length_cm',bins=20, figsize=(10,5))
```
SEPAL WIDTH
```
final_df.hist(column = 'sepal_width_cm',bins=20, figsize=(10,5))
final_df.hist(column = 'petal_length_cm',bins=20, figsize=(10,5))
final_df.hist(column = 'petal_width_cm',bins=20, figsize=(10,5))
sns.pairplot(final_df, hue='class', size=2.5)
```
Successfully removed outliers!!
### Label Encoding
```
final_df['class'].replace(["Iris-virginica","Iris-versicolor"], [1,0], inplace=True)
final_df.head()
inp_df = final_df.drop(final_df.columns[[4]], axis=1)
out_df = final_df.drop(final_df.columns[[0,1,2,3]], axis=1)
#
scaler = StandardScaler()
inp_df = scaler.fit_transform(inp_df)
#
X_train, X_test, y_train, y_test = train_test_split(inp_df, out_df, test_size=0.2, random_state=42)
X_tr_arr = X_train
X_ts_arr = X_test
y_tr_arr = y_train.as_matrix()
y_ts_arr = y_test.as_matrix()
print('Input Shape', (X_tr_arr.shape))
print('Output Shape', X_test.shape)
def weightInitialization(n_features):
w = np.zeros((1,n_features))
b = 0
return w,b
def sigmoid_activation(result):
final_result = 1/(1+np.exp(-result))
return final_result
def model_optimize(w, b, X, Y):
m = X.shape[0]
# print("no of instances",m)
#Prediction
final_result = sigmoid_activation(np.dot(w,X.T)+b)
# print("sigmoid result",final_result)
Y_T = Y.T
cost = (-1/m)*(np.sum((Y_T*np.log(final_result)) + ((1-Y_T)*(np.log(1-final_result)))))
# print("cost value",cost)
#
#Gradient calculation
dw = (1/m)*(np.dot(X.T, (final_result-Y.T).T))
db = (1/m)*(np.sum(final_result-Y.T))
grads = {"dw": dw, "db": db}
return grads, cost
def model_predict(w, b, X, Y, learning_rate, no_iterations):
costs = []
for i in range(no_iterations):
#
grads, cost = model_optimize(w,b,X,Y)
#
dw = grads["dw"]
db = grads["db"]
#weight update
w = w - (learning_rate * (dw.T))
b = b - (learning_rate * db)
#
if (i % 100 == 0):
costs.append(cost)
#print("Cost after %i iteration is %f" %(i, cost))
#final parameters
coeff = {"w": w, "b": b}
gradient = {"dw": dw, "db": db}
return coeff, gradient, costs
def predict(final_pred, m):
y_pred = np.zeros((1,m))
for i in range(final_pred.shape[1]):
if final_pred[0][i] > 0.5:
y_pred[0][i] = 1
return y_pred
#Get number of features
n_features = X_tr_arr.shape[1]
print('Number of Features', n_features)
w, b = weightInitialization(n_features)
# print("weights",w)
# print("bias",b)
# #Gradient Descent
coeff, gradient, costs = model_predict(w, b, X_tr_arr, y_tr_arr, learning_rate=0.0001,no_iterations=4500)
#Final prediction
w = coeff["w"]
b = coeff["b"]
print('Optimized weights', w)
print('Optimized intercept',b)
#
final_train_pred = sigmoid_activation(np.dot(w,X_tr_arr.T)+b)
final_test_pred = sigmoid_activation(np.dot(w,X_ts_arr.T)+b)
#
m_tr = X_tr_arr.shape[0]
m_ts = X_ts_arr.shape[0]
#
y_tr_pred = predict(final_train_pred, m_tr)
print('Training Accuracy',accuracy_score(y_tr_pred.T, y_tr_arr))
#
y_ts_pred = predict(final_test_pred, m_ts)
print('Test Accuracy',accuracy_score(y_ts_pred.T, y_ts_arr))
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title('Cost reduction over time')
plt.show()
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression()
clf.fit(X_tr_arr, y_tr_arr)
print (clf.intercept_, clf.coef_)
pred = clf.predict(X_ts_arr)
print ('Accuracy from sk-learn: {0}'.format(clf.score(X_ts_arr, y_ts_arr)))
```
| github_jupyter |
## Feature Selection using Random Shuffling
```
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.metrics import roc_auc_score, mean_squared_error, r2_score
```
## Read Data
```
data = pd.read_csv('../DoHBrwTest.csv')
data.shape
data.head()
```
### Train - Test Split
```
X_train, X_test, y_train, y_test = train_test_split(
data.drop(labels=['is_intrusion'], axis=1),
data['is_intrusion'],
test_size=0.3,
random_state=0)
X_train.shape, X_test.shape
# Reset the indexes of the returned datasets
X_train.reset_index(drop=True, inplace=True)
X_test.reset_index(drop=True, inplace=True)
```
### Train ML algo with all features
```
rf = RandomForestClassifier(
n_estimators=50, max_depth=2, random_state=2909, n_jobs=4)
rf.fit(X_train, y_train)
# print roc-auc in train and testing sets
print('train auc score: ',
roc_auc_score(y_train, (rf.predict_proba(X_train.fillna(0)))[:, 1]))
print('test auc score: ',
roc_auc_score(y_test, (rf.predict_proba(X_test.fillna(0)))[:, 1]))
```
### Shuffling resources and assessing performance loss
```
# overall train roc-auc: using all the features
train_roc = roc_auc_score(y_train, (rf.predict_proba(X_train))[:, 1])
# list to capture the performance shift
performance_shift = []
# selection logic
for feature in X_train.columns:
X_train_c = X_train.copy()
# shuffle individual feature
X_train_c[feature] = X_train_c[feature].sample(
frac=1, random_state=10).reset_index(drop=True)
# make prediction with shuffled feature and calculate roc-auc
shuff_roc = roc_auc_score(y_train, rf.predict_proba(X_train_c)[:, 1])
drift = train_roc - shuff_roc
# save the drop in roc-auc
performance_shift.append(drift)
# list of performances
performance_shift
# Transform the list into a pandas Series for easy manipulation
feature_importance = pd.Series(performance_shift)
# add variable names in the index
feature_importance.index = X_train.columns
feature_importance.head()
# Sort the dataframe according to the drop in performance # caused by feature shuffling
feature_importance.sort_values(ascending=False)
# List the top 10 features that caused the major drop in the roc-auc (aka model performance)
feature_importance.sort_values(ascending=False).head(10)
# original number of features (rows in this case)
feature_importance.shape[0]
# number of features that cause a drop in performance when shuffled
feature_importance[feature_importance>0].shape[0]
```
23 out of the 41 features caused a drop in the performance of the random forests when their values were permuted. This means that we could select those features and discard the rest, and should keep the original random forest performance.
```
# print the important features
feature_importance[feature_importance>0].index
```
### Select features
```
# Building a random forests only with the selected features capture the selected features
selected_features = feature_importance[feature_importance > 0].index
# train a new random forests using only the selected features
rf = RandomForestClassifier(n_estimators=50,
max_depth=2,
random_state=2909,
n_jobs=4)
rf.fit(X_train[selected_features], y_train)
# print roc-auc in train and testing sets
print('train auc score: ', roc_auc_score(y_train, (rf.predict_proba(X_train[selected_features]))[:,1]))
print('test auc score: ', roc_auc_score(y_test, (rf.predict_proba(X_test[selected_features]))[:,1]))
```
The random forests with the selected features show a similar performance (or even slightly higher) to the random forests built using all of the features. And it provides a simpler, faster and more reliable model.
```
X_train = X_train[selected_features]
X_test = X_test[selected_features]
X_train.shape, X_test.shape
```
## Standardize Data
```
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
```
## Classifiers
```
from sklearn import linear_model
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from catboost import CatBoostClassifier
```
## Metrics Evaluation
```
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_curve, f1_score
from sklearn import metrics
from sklearn.model_selection import cross_val_score
```
### Logistic Regression
```
%%time
clf_LR = linear_model.LogisticRegression(n_jobs=-1, random_state=42, C=0.1).fit(X_train, y_train)
pred_y_test = clf_LR.predict(X_test)
print('Accuracy:', accuracy_score(y_test, pred_y_test))
f1 = f1_score(y_test, pred_y_test)
print('F1 Score:', f1)
fpr, tpr, thresholds = roc_curve(y_test, pred_y_test)
print('FPR:', fpr[1])
print('TPR:', tpr[1])
```
### Naive Bayes
```
%%time
clf_NB = GaussianNB(var_smoothing=1e-09).fit(X_train, y_train)
pred_y_testNB = clf_NB.predict(X_test)
print('Accuracy:', accuracy_score(y_test, pred_y_testNB))
f1 = f1_score(y_test, pred_y_testNB)
print('F1 Score:', f1)
fpr, tpr, thresholds = roc_curve(y_test, pred_y_testNB)
print('FPR:', fpr[1])
print('TPR:', tpr[1])
```
### Random Forest
```
%%time
clf_RF = RandomForestClassifier(random_state=0,max_depth=70,n_estimators=100).fit(X_train, y_train)
pred_y_testRF = clf_RF.predict(X_test)
print('Accuracy:', accuracy_score(y_test, pred_y_testRF))
f1 = f1_score(y_test, pred_y_testRF, average='weighted', zero_division=0)
print('F1 Score:', f1)
fpr, tpr, thresholds = roc_curve(y_test, pred_y_testRF)
print('FPR:', fpr[1])
print('TPR:', tpr[1])
```
### KNN
```
%%time
clf_KNN = KNeighborsClassifier(algorithm='brute',leaf_size=1,n_neighbors=2,weights='distance').fit(X_train, y_train)
pred_y_testKNN = clf_KNN.predict(X_test)
print('accuracy_score:', accuracy_score(y_test, pred_y_testKNN))
f1 = f1_score(y_test, pred_y_testKNN)
print('f1:', f1)
fpr, tpr, thresholds = roc_curve(y_test, pred_y_testKNN)
print('fpr:', fpr[1])
print('tpr:', tpr[1])
```
### CatBoost
```
%%time
clf_CB = CatBoostClassifier(random_state=0,depth=7,iterations=50,learning_rate=0.04).fit(X_train, y_train)
pred_y_testCB = clf_CB.predict(X_test)
print('Accuracy:', accuracy_score(y_test, pred_y_testCB))
f1 = f1_score(y_test, pred_y_testCB, average='weighted', zero_division=0)
print('F1 Score:', f1)
fpr, tpr, thresholds = roc_curve(y_test, pred_y_testCB)
print('FPR:', fpr[1])
print('TPR:', tpr[1])
```
## Model Evaluation
```
import pandas as pd, numpy as np
test_df = pd.read_csv("../KDDTest.csv")
test_df.shape
# Create feature matrix X and target vextor y
y_eval = test_df['is_intrusion']
X_eval = test_df.drop(columns=['is_intrusion'])
X_eval = X_eval[selected_features]
X_eval.shape
```
### Model Evaluation - Logistic Regression
```
modelLR = linear_model.LogisticRegression(n_jobs=-1, random_state=42, C=0.1)
modelLR.fit(X_train, y_train)
# Predict on the new unseen test data
y_evalpredLR = modelLR.predict(X_eval)
y_predLR = modelLR.predict(X_test)
train_scoreLR = modelLR.score(X_train, y_train)
test_scoreLR = modelLR.score(X_test, y_test)
print("Training accuracy is ", train_scoreLR)
print("Testing accuracy is ", test_scoreLR)
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score
print('Performance measures for test:')
print('--------')
print('Accuracy:', test_scoreLR)
print('F1 Score:',f1_score(y_test, y_predLR))
print('Precision Score:',precision_score(y_test, y_predLR))
print('Recall Score:', recall_score(y_test, y_predLR))
print('Confusion Matrix:\n', confusion_matrix(y_test, y_predLR))
```
### Cross validation - Logistic Regression
```
from sklearn.model_selection import cross_val_score
from sklearn import metrics
accuracy = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='accuracy')
print("Accuracy: %0.5f (+/- %0.5f)" % (accuracy.mean(), accuracy.std() * 2))
f = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='f1')
print("F1 Score: %0.5f (+/- %0.5f)" % (f.mean(), f.std() * 2))
precision = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='precision')
print("Precision: %0.5f (+/- %0.5f)" % (precision.mean(), precision.std() * 2))
recall = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='recall')
print("Recall: %0.5f (+/- %0.5f)" % (recall.mean(), recall.std() * 2))
```
### Model Evaluation - Naive Bayes
```
modelNB = GaussianNB(var_smoothing=1e-09)
modelNB.fit(X_train, y_train)
# Predict on the new unseen test data
y_evalpredNB = modelNB.predict(X_eval)
y_predNB = modelNB.predict(X_test)
train_scoreNB = modelNB.score(X_train, y_train)
test_scoreNB = modelNB.score(X_test, y_test)
print("Training accuracy is ", train_scoreNB)
print("Testing accuracy is ", test_scoreNB)
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score
print('Performance measures for test:')
print('--------')
print('Accuracy:', test_scoreNB)
print('F1 Score:',f1_score(y_test, y_predNB))
print('Precision Score:',precision_score(y_test, y_predNB))
print('Recall Score:', recall_score(y_test, y_predNB))
print('Confusion Matrix:\n', confusion_matrix(y_test, y_predNB))
```
### Cross validation - Naive Bayes
```
from sklearn.model_selection import cross_val_score
from sklearn import metrics
accuracy = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='accuracy')
print("Accuracy: %0.5f (+/- %0.5f)" % (accuracy.mean(), accuracy.std() * 2))
f = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='f1')
print("F1 Score: %0.5f (+/- %0.5f)" % (f.mean(), f.std() * 2))
precision = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='precision')
print("Precision: %0.5f (+/- %0.5f)" % (precision.mean(), precision.std() * 2))
recall = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='recall')
print("Recall: %0.5f (+/- %0.5f)" % (recall.mean(), recall.std() * 2))
```
### Model Evaluation - Random Forest
```
modelRF = RandomForestClassifier(random_state=0,max_depth=70,n_estimators=100)
modelRF.fit(X_train, y_train)
# Predict on the new unseen test data
y_evalpredRF = modelRF.predict(X_eval)
y_predRF = modelRF.predict(X_test)
train_scoreRF = modelRF.score(X_train, y_train)
test_scoreRF = modelRF.score(X_test, y_test)
print("Training accuracy is ", train_scoreRF)
print("Testing accuracy is ", test_scoreRF)
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score
print('Performance measures for test:')
print('--------')
print('Accuracy:', test_scoreRF)
print('F1 Score:', f1_score(y_test, y_predRF, average='weighted', zero_division=0))
print('Precision Score:', precision_score(y_test, y_predRF, average='weighted', zero_division=0))
print('Recall Score:', recall_score(y_test, y_predRF, average='weighted', zero_division=0))
print('Confusion Matrix:\n', confusion_matrix(y_test, y_predRF))
```
### Cross validation - Random Forest
```
from sklearn.model_selection import cross_val_score
from sklearn import metrics
accuracy = cross_val_score(modelRF, X_eval, y_eval, cv=10, scoring='accuracy')
print("Accuracy: %0.5f (+/- %0.5f)" % (accuracy.mean(), accuracy.std() * 2))
f = cross_val_score(modelRF, X_eval, y_eval, cv=10, scoring='f1')
print("F1 Score: %0.5f (+/- %0.5f)" % (f.mean(), f.std() * 2))
precision = cross_val_score(modelRF, X_eval, y_eval, cv=10, scoring='precision')
print("Precision: %0.5f (+/- %0.5f)" % (precision.mean(), precision.std() * 2))
recall = cross_val_score(modelRF, X_eval, y_eval, cv=10, scoring='recall')
print("Recall: %0.5f (+/- %0.5f)" % (recall.mean(), recall.std() * 2))
```
### Model Evaluation - KNN
```
modelKNN = KNeighborsClassifier(algorithm='brute',leaf_size=1,n_neighbors=2,weights='distance')
modelKNN.fit(X_train, y_train)
# Predict on the new unseen test data
y_evalpredKNN = modelKNN.predict(X_eval)
y_predKNN = modelKNN.predict(X_test)
train_scoreKNN = modelKNN.score(X_train, y_train)
test_scoreKNN = modelKNN.score(X_test, y_test)
print("Training accuracy is ", train_scoreKNN)
print("Testing accuracy is ", test_scoreKNN)
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score
print('Performance measures for test:')
print('--------')
print('Accuracy:', test_scoreKNN)
print('F1 Score:', f1_score(y_test, y_predKNN))
print('Precision Score:', precision_score(y_test, y_predKNN))
print('Recall Score:', recall_score(y_test, y_predKNN))
print('Confusion Matrix:\n', confusion_matrix(y_test, y_predKNN))
```
### Cross validation - KNN
```
from sklearn.model_selection import cross_val_score
from sklearn import metrics
accuracy = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='accuracy')
print("Accuracy: %0.5f (+/- %0.5f)" % (accuracy.mean(), accuracy.std() * 2))
f = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='f1')
print("F1 Score: %0.5f (+/- %0.5f)" % (f.mean(), f.std() * 2))
precision = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='precision')
print("Precision: %0.5f (+/- %0.5f)" % (precision.mean(), precision.std() * 2))
recall = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='recall')
print("Recall: %0.5f (+/- %0.5f)" % (recall.mean(), recall.std() * 2))
```
### Model Evaluation - CatBoost
```
modelCB = CatBoostClassifier(random_state=0,depth=7,iterations=50,learning_rate=0.04)
modelCB.fit(X_train, y_train)
# Predict on the new unseen test data
y_evalpredCB = modelCB.predict(X_eval)
y_predCB = modelCB.predict(X_test)
train_scoreCB = modelCB.score(X_train, y_train)
test_scoreCB = modelCB.score(X_test, y_test)
print("Training accuracy is ", train_scoreCB)
print("Testing accuracy is ", test_scoreCB)
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score
print('Performance measures for test:')
print('--------')
print('Accuracy:', test_scoreCB)
print('F1 Score:',f1_score(y_test, y_predCB, average='weighted', zero_division=0))
print('Precision Score:',precision_score(y_test, y_predCB, average='weighted', zero_division=0))
print('Recall Score:', recall_score(y_test, y_predCB, average='weighted', zero_division=0))
print('Confusion Matrix:\n', confusion_matrix(y_test, y_predCB))
```
### Cross validation - CatBoost
```
from sklearn.model_selection import cross_val_score
from sklearn import metrics
accuracy = cross_val_score(modelCB, X_eval, y_eval, cv=10, scoring='accuracy')
f = cross_val_score(modelCB, X_eval, y_eval, cv=10, scoring='f1')
precision = cross_val_score(modelCB, X_eval, y_eval, cv=10, scoring='precision')
recall = cross_val_score(modelCB, X_eval, y_eval, cv=10, scoring='recall')
print("Accuracy: %0.5f (+/- %0.5f)" % (accuracy.mean(), accuracy.std() * 2))
print("F1 Score: %0.5f (+/- %0.5f)" % (f.mean(), f.std() * 2))
print("Precision: %0.5f (+/- %0.5f)" % (precision.mean(), precision.std() * 2))
print("Recall: %0.5f (+/- %0.5f)" % (recall.mean(), recall.std() * 2))
```
| github_jupyter |
# Graph
Graphs can be used to represent many interesting things about our world, including systems of roads, airline flights from city to city, how the Internet is connected, or even the sequence of classes you must take to complete a major in computer science.
## Vocabulary and Definitions
- **Vertex**: A vertex (also called a “node”) is a fundamental part of a graph. It can have a name, which we will call the **“key”**. A vertex may also have additional information. We will call this additional information the “payload.”
- **Edge**: An edge (also called an “arc”) is another fundamental part of a graph. An edge connects two vertices to show that there is a relationship between them. Edges may be one-way or two-way. If the edges in a graph are all one-way, we say that the graph is a **directed graph**, or a digraph.
- **Weight**: Edges may be weighted to show that there is a cost to go from one vertex to another. For example in a graph of roads that connect one city to another, the weight on the edge might represent the distance between the two cities.
- **Path**: A path in a graph is a sequence of vertices that are connected by edges. Formally we would define a path as `w1,w2,...,wn` such that `(wi,wi+1) ∈ E` for all `1 ≤ i ≤ n−1`. The unweighted path length is the number of edges in the path, specifically n−1. The weighted path length is the sum of the weights of all the edges in the path.
- **Cycle**: A cycle in a directed graph is a path that starts and ends at the same vertex. A graph with no cycles is called an **acyclic graph**. A directed graph with no cycles is called a **directed acyclic graph(DAG)**.
A graph can be represented by `G` where `G=(V,E)`. For the graph `G`, `V` is a set of vertices and `E` is a set of edges. Each edge is a tuple `(v,w)` where `w,v ∈ V`. We can add a third component to the edge tuple to represent a weight. A subgraph s is a set of edges e and vertices v such that `e ⊂ E` and `v ⊂ V`.
## Types of Graphs
### Undirected Graph
An undirected graph is a graph in which edges have no orientation. The edge (u, v) is identical to the edge (v, u).
```{mermaid}
graph LR;
A((A))
B((B))
C((C))
D((D))
E((E))
F((F))
B---C;
B---D;
A---B;
A---C;
C---D;
C---E;
D---F;
E---F;
```
### Directed Graph (Digraph)
A directed graph or digraph is a graph in which edges have orientations. For example, the edge (u, v) is the edge from node u to node v.
```{mermaid}
graph LR;
A((A))
B((B))
C((C))
D((D))
E((E))
F((F))
A-->B;
A-->C;
B-->D;
C-->D;
D-->E;
D-->F;
E-->F;
```
### Weighted Graphs
Many graphs can have edges that contain a certain weight to represent an arbitrary value such as cost, distance, quantity, etc.
```{mermaid}
graph LR;
A((A))
B((B))
C((C))
D((D))
E((E))
F((F))
A-- 4 ---B;
A-- 2 ---C;
B-- 4 ---D;
D-- 1 --- F;
B-- 8 ---C;
C-- 3 ---D;
D-- 2 ---E;
D-- 1 ---F;
E-- 11 ---F;
```
## Special Graphs
### Trees
A tree is an undirected graph with no cycles. Equivalently, it is a connected graph with N nodes and N-1 edges.
```{mermaid}
flowchart TB;
subgraph id1 [ ]
direction TB
a1((A))
a2((B))
a3((C))
a4((D))
a1---a2
a2---a3
a3---a4
end
subgraph id2 [ ]
direction TB
b1((A))
b2((B))
b3((C))
b4((D))
b5((E))
b6((F))
b1---b2
b1---b3
b2---b4
b2---b5
b3---b6
end
subgraph id3 [ ]
direction LR
c1((A))
c2((B))
c3((C))
c4((D))
c5((E))
c6((F))
c7((G))
c8((H))
c9((I))
c1---c3
c2---c3
c3---c4
c3---c5
c3---c6
c4---c7
c5---c9
c5---c8
end
```
#### Rooted Trees
A rooted tree is a tree with a designated root node where every edge either points away from or towards the root node. When edges point away from the root the graph is called an arborescence (out-tree) and anti-arborescence (in-tree) otherwise.
```{mermaid}
flowchart TB;
subgraph ide1 [ ]
direction RL
a1((A))
a2((B))
a3((C))
a4((D))
a2-->a1
a3-->a1
a4-->a3
end
subgraph ide2 [ ]
direction TB
b1((A))
b2((B))
b3((C))
b4((D))
b5((E))
b6((F))
b7((G))
b1-->b2
b1-->b3
b2-->b4
b2-->b5
b3-->b6
b3-->b7
end
subgraph ide3 [ ]
direction RL
c0((A))
c1((B))
c2((C))
c3((D))
c4((E))
c5((F))
c6((G))
c7((H))
c8((I))
c9((J))
c1-->c0
c2-->c0
c3-->c0
c7-->c0
c4-->c1
c5-->c1
c6-->c1
c8-->c2
c9-->c2
end
style a1 fill:#FF8000
style b1 fill:#FF8000
style c0 fill:#FF8000
```
### Directed Acyclic Graphs (DAGs)
DAGs are directed graphs with no cycles. These graphs play an important role in representing structures with dependencies. Several efficient algorithms exist to operates on DAGs.
*Cool fact: All out-trees are DAGs but not all DAGs are out-trees.*
```{mermaid}
flowchart TB;
subgraph ide1 [ ]
direction LR
a1((A))
a2((B))
a3((C))
a4((D))
a5((E))
a6((F))
a7((G))
a8((H))
a9((I))
a1-->a2
a1-->a3
a2-->a4
a2-->a5
a3-->a4
a3-->a5
a4-->a6
a4-->a7
a5-->a8
a5-->a9
end
subgraph ide2 [ ]
direction TB
b1((A))
b2((B))
b3((C))
b4((D))
b5((E))
b6((F))
b7((G))
b1-->b2
b1-->b3
b2-->b4
b2-->b5
b3-->b6
b3-->b7
end
```
### Bipartite Graph
A bipartite graph is one whose vertices can be split into two independent groups U, V such that every edge connects betweens U and V.
Other definitions exist such as: The graph is two colourable or there is no odd length cycle.
```{mermaid}
flowchart LR;
a1((A))
a2((B))
a3((C))
a4((D))
b1((P))
b2((Q))
b3((R))
b4((S))
a1---b1
a1---b3
a1---b4
a2---b2
a2---b4
a3---b1
a3---b4
a4---b4
style a1 fill:#FF8000
style a2 fill:#FF8000
style a3 fill:#FF8000
style a4 fill:#FF8000
style b1 fill:#FFFFFF
style b2 fill:#FFFFFF
style b3 fill:#FFFFFF
style b4 fill:#FFFFFF
```
### Complete Graphs
A complete graph is one where there is a unique edge between every pair of nodes. A complete graph with n vertices is denoted as the graph Kn.
```{mermaid}
flowchart BT;
subgraph id1 [K1]
a1((A))
end
subgraph id2 [K2]
b1((A))
b2((B))
b1---b2
end
subgraph id3 [K3]
c1((A))
c2((B))
c3((C))
c1---c2
c2---c3
c3---c1
end
subgraph id4 [K4]
d1((A))
d2((B))
d3((C))
d4((D))
d1---d2
d2---d3
d3---d4
d4---d1
d1---d3
d2---d4
end
```
## Representing Graphs
### Adjacency Matrix
A adjacency matrix m is a very simple way to represent a graph. The idea is that the cell m[i][j] represents the edge weight of going from node i to node j.
<!--  -->
| Pros | Cons |
| :-- | :-- |
|Space efficient for representing dense graphs | Requires Θ(V²) space |
|Edge weight lookup is O(1) | Iterating over all edges takes Θ(V²) time |
|Simplest graph representation | |
### Adjacency List
An adjacency list is a way to represent a graph as a map from nodes to lists of edges.
<!--  -->
| Pros | Cons |
| :-- | :-- |
|Space efficient for representing sparse graphs | Less space efficient for denser graphs.|
|Iterating over all edges is efficient | Edge weight lookup is O(E) |
| | Slightly more complex graph representation |
### Edge List
An edge list is a way to represent a graph simply as an unordered list of edges. Assume the notation for any triplet (u,v,w) means: “the cost from node u to node v is w”
This representation is seldomly used because of its lack of structure. However, it is conceptually simple and practical in a handful of algorithms.
<!--  -->
| Pros | Cons |
| :-- | :-- |
|Space efficient for representing sparse graphs | Less space efficient for denser graphs.|
|Iterating over all edges is efficient | Edge weight lookup is O(E) |
| Very simple structure | |
## Graph Abstract Data Type
The graph abstract data type (ADT) is defined as follows:
- `Graph()` creates a new, empty graph.
- `add_vertex(vert)` adds an instance of Vertex to the graph.
- `add_edge(fromVert, toVert)` Adds a new, directed edge to the graph that connects two vertices.
- `add_edge(fromVert, toVert, weight)` Adds a new, weighted, directed edge to the graph that connects two vertices.
- `get_vertices()` returns the list of all vertices in the graph.
- `in` returns True for a statement of the form vertex in graph, if the given vertex is in the graph, False otherwise.
## Implementing a Graph in Python
An abstract data type (ADT) when given a physical implementation then we refer to the implementation as a data structure.
In any object-oriented programming language, the implementation of choice for an abstract data type such as a **Graph** is the creation of a new class. The Graph operations are implemented as methods.
Using dictionaries, it is easy to implement the adjacency list in Python. In our implementation of the Graph abstract data type we will create a classes `Graph`, which holds the master list of *vertices*, and **edges**.
```
class Graph:
def __init__(self):
self.vertices = set()
self.num_vertices = 0
self.edges = {}
self.num_edges = 0
def add_vertex(self, v):
if v not in self.vertices:
self.vertices.add(v)
self.num_vertices += 1
def add_edge(self, v, u, w=None):
self.add_vertex(v)
self.add_vertex(u)
if v not in self.edges:
self.edges[v] = {u: w}
else:
self.edges[v][u] = w
self.num_edges += 1
def get_vertices(self):
return self.vertices
def get_edges(self, v):
return self.edges[v].items()
g = Graph()
g.add_edge(0, 1, 5)
g.add_edge(0, 4, 4)
g.add_edge(4, 1, 0)
g.add_edge(4, 3, 1)
g.add_edge(1, 0, 6)
g.add_edge(1, 4, 7)
g.add_edge(1, 3, 8)
g.add_edge(1, 2, 1)
g.add_edge(2, 3, 3)
g.add_edge(3, 4, 2)
for v in g.get_vertices():
print(f"{v}")
for u, w in g.get_edges(v):
print(f" └──> {u}: {w}")
```
## Breadth First Search
Breadth first search (BFS. is one of the easiest algorithms for searching a graph. It also serves as a prototype for several other important graph algorithms.
Given a graph `G` and a starting vertex `s`, a breadth first search proceeds by exploring edges in the graph to find all the vertices in `G` for which there is a path from `s`. The remarkable thing about a breadth first search is that it finds all the vertices that are a distance `k` from s before it finds any vertices that are a distance `k+1`.
### Breadth First Search Analysis
**Breadth First Search loops** one time for each vertex in the graph `|V|`, this gives us `O(V)` for the outer loop. The inner loop, which is nested is executed at *most once for each edge in the graph*, `|E|`. The reason is that *every vertex is dequeued at most once* and we examine an edge from node u to node v only when node u is dequeued. This gives us O(E. for the for loop, combining the two loops gives us O(V+E).
### Applications of Breadth First Search
1. Shortest Path and Minimum Spanning Tree for unweighted graph In an unweighted graph, the shortest path is the path with least number of edges. With Breadth First, we always reach a vertex from given source using the minimum number of edges. Also, in case of unweighted graphs, any spanning tree is Minimum Spanning Tree.
2. Peer to Peer Networks. In Peer to Peer Networks like BitTorrent, Breadth First Search is used to find all neighbor nodes.
3. Crawlers in Search Engines.
4. Social Networking Websites: In social networks, we can find people within a given distance ‘k’ from a person using Breadth First Search till ‘k’ levels.
5. GPS Navigation systems: Breadth First Search is used to find all neighboring locations.
6. Broadcasting in Network: In networks, a broadcasted packet follows Breadth First Search to reach all nodes.
7. In Garbage Collection: Breadth First Search is used in copying garbage collection using Cheney’s algorithm. Refer this and for details. Breadth First Search is preferred over Depth First Search because of better locality of reference.
## Depth First Search
Given a graph `G` and a starting vertex `s`, a depth first search proceeds by exploring edges in the graph to create the deepest depth first tree, without any branches all the vertices in `G` for which there is a path from `s`. It is even possible that a depth first search will create more than one tree. When the depth first search algorithm creates a group of trees we call this a depth first forest.
### Depth First Search Analysis
**Depth First Search loops** one time for each vertex in the graph `|V|`, this gives us `O(V)` for the outer loop. The inner loop, which is nested is executed at *most once for each edge in the graph*, `|E|`. The reason is that *every vertex is pushed at most once* and we examine an edge from node u to node v only when node u is poped. This gives us O(E) for the for loop, combining the two loops gives us O(V+E).
### Applications of Depth First Search
1. For a weighted graph, DFS traversal of the graph produces the minimum spanning tree and all pair shortest path tree.
2. Detecting Cycle: A graph has cycle if and only if we see a back edge during DFS. So we can run DFS for the graph and check for back edges. (See this for details)
3. Path Finding: DFS algorithm can be modified to find a path between two given vertices u and z.
1. Call DFS(G, u) with u as the start vertex.
2. Use a stack S to keep track of the path between the start vertex and the current vertex.
3. As soon as destination vertex z is encountered, return the path as the contents of the stack
4. Topological Sorting: used for scheduling jobs from the given dependencies among jobs.
5. Test if a graph is bipartite
We can augment either BFS or DFS when we first discover a new vertex, color it opposited its parents, and for each other edge, check it doesn’t link two vertices of the same color. The first vertex in any connected component can be red or black! See this for details.
6. Finding Strongly Connected Components of a graph A directed graph is called strongly connected if there is a path from each vertex in the graph to every other vertex. (See this for DFS based algo for finding Strongly Connected Components)
7. Solving puzzles with only one solution, such as mazes. (DFS can be adapted to find all solutions to a maze by only including nodes on the current path in the visited set.)
## Topological Sorting
Topological sort gives the precise order in which we should do each of the steps (visit the graph nodes) in order to achieve our goal.
A topological sort takes a **directed acyclic graph (DAG)** and produces a linear ordering of all its vertices such that if the graph G contains an edge `(v, u)` then the vertex `v` comes before the vertex `u` in the ordering. Directed acyclic graphs are used in many applications to indicate the precedence of events. The topological sort is a simple but useful adaptation of a depth first search.
The algorithm for the topological sort is as follows:
1. Call dfs(g) for some graph g. The main reason we want to call depth first search is to compute the finish times for each of the vertices.
2. Store the vertices in a list in decreasing order of finish time.
3. Return the ordered list as the result of the topological sort.
## Strongly Connected Components
Strongly Connected Components (SCCs) can be thought of as self-contained cycles within a directed graph where every vertex in a given cycle can reach every other vertex in the same cycle.
Once again we will see that we can create a very powerful and efficient algorithm by making use of a depth first search. Before we tackle the main SCC algorithm we must look at one other definition. The transposition of a graph `G` is defined as the graph `GT` where all the edges in the graph have been reversed. That is, if there is a directed edge from node `A` to node `B` in the original graph then `GT` will contain and edge from node `B` to node `A`.
Algorithm to compute the strongly connected components for a graph.
1. Call dfs for the graph `G` to compute the finish times for each vertex.
2. Compute GT.
3. Call dfs for the graph `GT` but in the main loop of DFS explore each vertex in decreasing order of finish time.
4. Each tree in the forest computed in step 3 is a strongly connected component. Output the vertex ids for each vertex in each tree in the forest to identify the component.
## Shortest Path Problems
Given a weighted graph, find the shortest path of edges from node A to node B.

### Dijkstra’s Algorithm
### A* (A Star) Algorithm
## Minimum Spanning Tree (MST)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight.
| github_jupyter |
There are three different network topologies:
- Testing: AMST, AOFA, CERN, DENV, WASH, ATLA -> DENV (not SCinet)
- Calibers: AMST, AOFA, CERN, DENV, WASH, ATLA -> SCINET
- TCP: AMST, AOFA, CERN, DENV, WASH, ATLA -> SCINET
Each topology is handle by its own L2VPN VFC on each of the CORSA, by convention:
- Testing is br1
- Calibers is br2
- TCP is br2
TESTING TOPOLOGY
----------------
- Receiving DTN at DENV: 192.168.120.117 VFC= br1 ofport 11 vlan1117
- Calibers controller at ATLA: 192.168.120.119 VFC= br1 ofport 9 vlan 1119
AMST - DENV rtt= 166
- OSCARS vlan 2280 es.net-6693
- DTN 192.168.120.190 VFC= br1 ofport 23
CERN - DENV rtt= 151
- OSCARS vlan 2597 es.net-6678
- DTN: 192.168.120.194 VFC= br1 ofport 10 vlan 1194
AOFA - DENV rtt= 67
- OSCARS vlan 289 es.net-6691
- DTN: 192.168.120.191 VFC= br1 ofport 1 vlan 1191
ATLA - DENV rtt= 49.4
- OSCARS vlan 384 es.net-6690
- DTN: 192.168.120.200 VFC= br1 ofport 8 vlan 1200
WASH - DENV rtt= 62
- OSCARS vlan 1591 es.net-6692
- DTN: 192.168.120.192 VFC= br1 ofport 10 vlan 1192
DENV - DENV rtt= 0.2
- DTN: 192.168.120.201 VFC= br1 ofport 10 vlan 1201
CALIBERS TOPOLOGY
-----------------
- Receiving DTN at SCInet: 192.168.100.2 VFC= ? ofport ? vlan ???
- Calibers controller at ATLA: 192.168.120.119 VFC= br2 ofport 9 vlan 119
AMST - SCinet
- OSCARS vlan 2056 es.net-6615
- DTN 192.168.120.190 VFC= br2 ofport 23
CERN - SCinet
- OSCARS vlan 2058 es.net-6617
- DTN: 192.168.120.194 VFC= br2 ofport 10 vlan 194
AOFA - SCinet
- OSCARS vlan 2054 es.net-6624
- DTN: 192.168.120.191 VFC= br2 ofport 1 vlan 191
ATLA - SCinet
- OSCARS vlan 2050 es.net-6625
- DTN: 192.168.120.200 VFC= br2 ofport 8 vlan 200
WASH - SCinet
- OSCARS vlan 2052 es.net-6613
- DTN: 192.168.120.192 VFC= br2 ofport 10 vlan 192
DENV - SCinet
- OSCARS vlan 2060 es.net-6619
- DTN: 192.168.120.201 VFC= br2 ofport 10 vlan 201
TCP ONLY TOPOLOGY
----------------
- Receiving DTN at SCInet 192.168.200.2 VFC= ? ofport ? vlan ???
- Calibers controller at ATLA: 192.168.120.193 VFC= br3 ofport 9 vlan 193
AMST - SCinet
- OSCARS vlan 2057 es.net-6616
- DTN 192.168.120.111 VFC= br3 ofport 23
CERN - SCinet
- OSCARS vlan 2059 es.net-6618
- DTN: 192.168.120.112 VFC= br3 ofport 10 vlan 112
AOFA - SCinet
- OSCARS vlan 2055 es.net-6612
- DTN: 192.168.120.114 VFC= br3 ofport 1 vlan 114
ATLA - SCinet
- OSCARS vlan 2051 es.net-6626
- DTN: 192.168.120.113 VFC= br3 ofport 8 vlan 113
WASH - SCinet
- OSCARS vlan 2053 es.net-6614
- DTN: 192.168.120.115 VFC= br3 ofport 10 vlan 115
DENV - SCinet
- OSCARS vlan 2061 es.net-6620
- DTN: 192.168.120.116 VFC= br3 ofport 10 vlan 116
atla -> nash -> hous -> elpa -> albq -> denv
wash -> nash -> hous -> elpa -> albq -> denv
aofa -> wash -> nash -> hous -> elpa -> albq -> denv
amst -> cern-272 -> cern-513 -> lond -> aofa -> wash -> nash -> hous -> elpa -> albq -> denv
cern-272 -> cern-513 -> lond -> aofa -> wash -> nash -> hous -> elpa -> albq -> denv
star -> chic -> kans -> denv
wget https://repo.continuum.io/archive/Anaconda2-5.0.1-Linux-x86_64.sh
sh ./Anaconda2-5.0.1-Linux-x86_64.sh
as root apt-get install python-pip
pip install flask flask_restfull
jupyter notebook --no-browser
jupyter notebook --generate-config
[http://jupyter-notebook.readthedocs.io/en/stable/public_server.html]
jupyter notebook password
vi ~/.jupyter/jupyter_notebook_config.py
| github_jupyter |
# Part 2 - Refine Data
The second step for analyzing the data is to perform some additional preparations and enrichments. While the first step of storing the data into the structured zone should be mainly a technical conversion without losing any information, this next step will integrate some data and also preaggregate weather data to simplify working with it.
# 0 Prepare Python Environment
## 0.1 Spark Session
```
from pyspark.sql import SparkSession
import pyspark.sql.functions as f
if not 'spark' in locals():
spark = SparkSession.builder \
.master("local[*]") \
.config("spark.driver.memory","64G") \
.getOrCreate()
spark.version
```
## 0.2 Matplotlib
```
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
```
# 1 Read Taxi Data
Now we can read in the taxi data from the structured zone.
## 1.1 Trip Data
Let us load the NYC Taxi trip data from the Hive table `taxi.trip` and let us display the first 10 records.
```
trip_data = # YOUR CODE HERE
trip_data.limit(10).toPandas()
```
Just to be sure, let us inspect the schema. It should match exactly the specified one.
```
trip_data.printSchema()
```
## 1.2 Fare information
Now we read in the second Hive table `taxi.fare` containing the trips fare information.
```
fare_data = # YOUR CODE HERE
fare_data.limit(10).toPandas()
fare_data.printSchema()
```
## 1.3 Join datasets
We can now join both the trip information and the fare information together in order to get a complete picture. Since the trip records do not contain a technical unique key, we use the following columns as the composite primary key of each trip:
* medallion
* hack_license
* vendor_id
* pickup_datetime
Finally the result is stored into the refined zone into the Hive table `refined.taxi_trip`.
```
# Create Hive database 'refined'
# YOUR CODE HERE
# Join trip_data with fare_data using the columns "medallion", "hack_license", "vendor_id", "pickup_datetime"
taxi_trips = # YOUR CODE HERE
# Save taxi_trips into the Hive table "refined.taxi_trip" using "parquet" file format
# YOUR CODE HERE
```
### Read from Refined Zone
```
taxi_trips = spark.read.table("refined.taxi_trip")
taxi_trips.limit(10).toPandas()
```
Let us have a look at the schema of the refined table
```
taxi_trips.printSchema()
```
Let us count the number of records in the table
```
# YOUR CODE HERE
```
# 2. Weather Data
The weather data also requires some additional preprocessing, especially when we want to join against weather data. The primary problem of all measurements is, that they might happen at different time intervals and not all measurements contain all metrics. Therefore we preaggregate the weather data to hourly and daily measurements, which can directly be used for joining.
## 2.1 Weather Data
We already have weather data, but only individual measurements. We do not know how many measurements there are per hour and per day, so the raw table is not very useable for joining. Instead we'd like to have an hourly and a daily weather table containing average temperature, wind speed and precipitation. Since we are only interested in the year 2013, we also only load that specific year.
```
weather = spark.read.table("isd.weather").where(f.col("year") == 2013)
weather.limit(10).toPandas()
```
## 2.2 Calculate derived metrics and preaggregate data
In order to simplify joining against weather data, we now preaggregate weather measurements to a single record per weather station and hour or per day.
### Hourly Preaggregation
For the hourly aggregation, we want to get the following columns
* `date` - day of the measurements. The day can be extracted from the timestamp column `ts` by using the Spark function `to_date` (available in the imported module `f`)
* `hour` - hour of the measurements. The hour can be extracted using the Spark function `hour`
* Grouping should be performed on the weather station IDs `usaf` and `wban` together with both extracted time columns `date` and `hour`
* For the following metrics, we are interested in the grouped averages: `wind_speed`, `air_temperature` and `precipitation_depth`
When performing the aggregation, you should ignore invalid measurements. This can be done by using the PySpark function `f.when` to conditionally only aggregate values where the correspondign quality flag (`wind_speed_qual` and `air_temperature_qual`) is not `9`. Note that it is enough to pick up only the valid values and let the `when` function return `NULL` for invalid values, since `NULL` is ignored in aggregations.
For averaging the precipitation, you should also only pick values where `precipitation_hours` equals `1`.
The final DataFrame should have the following columns (you might need to specify explicit aliases):
* `usaf`
* `wban`
* `date`
* `hour` (0-23)
* `wind_speed`
* `temperature`
* `precipitation`
```
hourly_weather = # YOUR CODE HERE
hourly_weather.limit(10).toPandas()
```
### Daily Preaggregation
In addition to the hourly metrics, we also preaggregate the data to daily records. This can easily be performed based on the hourly aggregations with a grouping on `usaf`, `wban` and `date`. Again we want to have the metrics `temperature`, `wind_speed` and `precipitation`. For the first two metrics, we are interested in the average (as this seems to make sense), while for precipitation we are interested in the sum (total amount of rainfall per day).
```
daily_weather = # YOUR CODE HERE
daily_weather.limit(10).toPandas()
```
### Save Preaggregated Weather
Finally we save both tables (hourly and daily weather), so we can directly reuse the data in the next steps.
```
hourly_weather.write.format("parquet").saveAsTable("refined.weather_hourly")
daily_weather.write.format("parquet").saveAsTable("refined.weather_daily")
```
## 2.3 Reload Data and draw Pictures
Now let us reload the data (just to make sure everything worked out nicely) and let's draw some pictures. We use a single station (which, by pure incident, is a weather station in NYC)
```
daily_weather = spark.read.table("refined.weather_daily")
nyc_station_usaf = "725053"
nyc_station_wban = "94728"
# Filter data only of that weather station, order it by date and convert it to a Pandas DataFrame
pdf = # YOUR CODE HERE
```
### Wind Speed
The first picture will simply contain the wind speed for every day in 2013.
```
# Make a Plot
plt.figure(figsize=(16, 6), dpi=80, facecolor='w', edgecolor='k')
plt.plot(pdf["date"],pdf["wind_speed"])
```
### Air Temperature
The next picture contains the average air temperature for every day in 2013.
```
# Make a Plot
plt.figure(figsize=(16, 6), dpi=80, facecolor='w', edgecolor='k')
plt.plot(pdf["date"],pdf["temperature"])
```
### Precipitation
The last picture contains the precipitation for every day in 2013.
```
# Make a Plot
plt.figure(figsize=(16, 6), dpi=80, facecolor='w', edgecolor='k')
plt.plot(pdf["date"],pdf["precipitation"])
```
| github_jupyter |
# Pivot_Longer : One function to cover transformations from wide to long form.
```
import janitor
import numpy as np
import pandas as pd
```
Unpivoting(reshaping data from wide to long form) in Pandas is executed either through [pd.melt](https://pandas.pydata.org/docs/reference/api/pandas.melt.html), [pd.wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html), or [pd.DataFrame.stack](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html). However, there are scenarios where a few more steps are required to massage the data into the long form that we desire. Take the dataframe below, copied from [Stack Overflow](https://stackoverflow.com/questions/64061588/pandas-melt-multiple-columns-to-tabulate-a-dataset#64062002):
```
df = pd.DataFrame(
{
"id": [1, 2, 3],
"M_start_date_1": [201709, 201709, 201709],
"M_end_date_1": [201905, 201905, 201905],
"M_start_date_2": [202004, 202004, 202004],
"M_end_date_2": [202005, 202005, 202005],
"F_start_date_1": [201803, 201803, 201803],
"F_end_date_1": [201904, 201904, 201904],
"F_start_date_2": [201912, 201912, 201912],
"F_end_date_2": [202007, 202007, 202007],
}
)
df
```
Below is a [beautiful solution](https://stackoverflow.com/a/64062027/7175713), from Stack Overflow :
```
df1 = df.set_index("id")
df1.columns = df1.columns.str.split("_", expand=True)
df1 = (
df1.stack(level=[0, 2, 3])
.sort_index(level=[0, 1], ascending=[True, False])
.reset_index(level=[2, 3], drop=True)
.sort_index(axis=1, ascending=False)
.rename_axis(["id", "cod"])
.reset_index()
)
df1
```
We propose an alternative, based on [pandas melt](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html) that abstracts the reshaping mechanism, allows the user to focus on the task, can be applied to other scenarios, and is chainable :
```
result = df.pivot_longer(
index="id",
names_to=("cod", ".value"),
names_pattern="(M|F)_(start|end)_.+",
sort_by_appearance=True,
)
result
df1.equals(result)
```
[pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html#janitor.pivot_longer) is not a new idea; it is a combination of ideas from R's [tidyr](https://tidyr.tidyverse.org/reference/pivot_longer.html) and [data.table](https://rdatatable.gitlab.io/data.table/) and is built on the powerful pandas' [melt](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html) function.
[pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html#janitor.pivot_longer) can melt dataframes easily; It is just a wrapper around pandas' [melt](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html).
[Source Data](https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html#reshaping-by-melt)
```
index = pd.MultiIndex.from_tuples([("person", "A"), ("person", "B")])
df = pd.DataFrame(
{
"first": ["John", "Mary"],
"last": ["Doe", "Bo"],
"height": [5.5, 6.0],
"weight": [130, 150],
},
index=index,
)
df
df.pivot_longer(index=["first", "last"])
```
If you want the data unpivoted in order of appearance, you can set `sort_by_appearance` to `True``:
```
df.pivot_longer(index=["first", "last"], sort_by_appearance=True)
```
If you wish to reuse the original index, you can set `ignore_index` to `False``; note that the index labels will be repeated as necessary:
```
df.pivot_longer(index=["first", "last"], ignore_index=False)
```
You can also unpivot MultiIndex columns, the same way you would with pandas' [melt](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html#pandas.melt):
[Source Data](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html#pandas.melt)
```
df = pd.DataFrame(
{"A": {0: "a", 1: "b", 2: "c"}, "B": {0: 1, 1: 3, 2: 5}, "C": {0: 2, 1: 4, 2: 6}}
)
df.columns = [list("ABC"), list("DEF")]
df
df.pivot_longer(index=[("A", "D")], values_to="num")
df.pivot_longer(index=[("A", "D")], column_names=[("B", "E")])
```
And just like [melt](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html#pandas.melt), you can unpivot on a specific level, with `column_level`:
```
df.pivot_longer(index="A", column_names="B", column_level=0)
```
Note that when unpivoting MultiIndex columns, you need to pass a list of tuples to the `index` or `column_names` parameters.
Also, if `names_sep` or `names_pattern` is not None, then unpivoting on MultiIndex columns is not supported.
You can dynamically select columns, using regular expressions with the `janitor.patterns` function (inspired by R's data.table's [patterns](https://rdatatable.gitlab.io/data.table/reference/patterns.html) function, and is really just a wrapper around `re.compile`), especially if it is a lot of column names, and you are *lazy* like me 😄
```
url = "https://github.com/tidyverse/tidyr/raw/master/data-raw/billboard.csv"
df = pd.read_csv(url)
df
# unpivot all columns that start with 'wk'
df.pivot_longer(column_names=janitor.patterns("^(wk)"), names_to="week")
```
You can also use [pyjanitor's](https://pyjanitor-devs.github.io/pyjanitor/) [select_columns](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.select_columns.html#janitor.select_columns) syntax:
```
df.pivot_longer(column_names="wk*", names_to="week")
```
[pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html#janitor.pivot_longer) can also unpivot paired columns. In this regard, it is like pandas' [wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html), but with more flexibility and power. Let's look at an example from pandas' [wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html) docs :
```
df = pd.DataFrame(
{
"famid": [1, 1, 1, 2, 2, 2, 3, 3, 3],
"birth": [1, 2, 3, 1, 2, 3, 1, 2, 3],
"ht1": [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],
"ht2": [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9],
}
)
df
```
In the data above, the `height`(ht) is paired with `age`(numbers). [pd.wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html) can handle this easily:
```
pd.wide_to_long(df, stubnames="ht", i=["famid", "birth"], j="age")
```
Now let's see how [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) handles this:
```
df.pivot_longer(
index=["famid", "birth"], names_to=(".value", "age"), names_pattern=r"(ht)(\d)"
)
```
The first observable difference is that [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) is method chainable, while [pd.wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html) is not. Now, let's learn more about the `.value` variable.
When `.value` is used in `names_to`, a pairing is created between `names_to` and `names_pattern``. For the example above, we get this pairing :
{".value": ("ht"), "age": (\d)}
This tells the [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) function to keep values associated with `.value`(`ht`) as the column name, while values not associated with `.value`, in this case, the numbers, will be collated under a new column `age``. Internally, pandas `str.extract` is used to get the capturing groups before reshaping. This level of abstraction, we believe, allows the user to focus on the task, and get things done faster.
Note that if you want the data returned in order of appearance you can set `sort_by_appearance` to `True`:
```
df.pivot_longer(
index=["famid", "birth"],
names_to=(".value", "age"),
names_pattern=r"(ht)(\d)",
sort_by_appearance=True,
)
```
Note that you are likely to get more speed when `sort_by_appearance` is `False``.
Note also that the values in the `age` column are of `object` dtype. You can change the dtype, using pandas' [astype](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html) method.
We've seen already that [pd.wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html) handles this already and very well, so why bother? Let's look at another scenario where [pd.wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html) would need a few more steps. [Source Data](https://community.rstudio.com/t/pivot-longer-on-multiple-column-sets-pairs/43958):
```
df = pd.DataFrame(
{
"off_loc": ["A", "B", "C", "D", "E", "F"],
"pt_loc": ["G", "H", "I", "J", "K", "L"],
"pt_lat": [
100.07548220000001,
75.191326,
122.65134479999999,
124.13553329999999,
124.13553329999999,
124.01028909999998,
],
"off_lat": [
121.271083,
75.93845266,
135.043791,
134.51128400000002,
134.484374,
137.962195,
],
"pt_long": [
4.472089953,
-144.387785,
-40.45611048,
-46.07156181,
-46.07156181,
-46.01594293,
],
"off_long": [
-7.188632000000001,
-143.2288569,
21.242563,
40.937416999999996,
40.78472,
22.905889000000002,
],
}
)
df
```
We can unpivot with [pd.wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html) by first reorganising the columns :
```
df1 = df.copy()
df1.columns = ["_".join(col.split("_")[::-1]) for col in df1.columns]
df1
```
Now, we can unpivot :
```
pd.wide_to_long(
df1.reset_index(),
stubnames=["loc", "lat", "long"],
sep="_",
i="index",
j="set",
suffix=".+",
)
```
We can get the same transformed dataframe, with less lines, using [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html):
```
df.pivot_longer(names_to=["set", ".value"], names_pattern="(.+)_(.+)")
# Another way to see the pairings,
# to see what is linked to `.value`,
# names_to = ["set", ".value"]
# names_pattern = "(.+)_(.+)"
# column _names = off_loc
# off_lat
# off_long
```
Again, the key here is the `.value` symbol. Pairing `names_to` with `names_pattern` and its results from [pd.str.extract](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html), we get :
set--> (.+) --> [off, pt] and
.value--> (.+) --> [loc, lat, long]
All values associated with `.value`(loc, lat, long) remain as column names, while values not associated with `.value`(off, pt) are lumped into a new column `set``.
Notice that we did not have to reset the index - [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) takes care of that internally; [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) allows you to focus on what you want, so you can get it and move on.
Note that the unpivoting could also have been executed with `names_sep`:
```
df.pivot_longer(
names_to=["set", ".value"],
names_sep="_",
ignore_index=False,
sort_by_appearance=True,
)
```
Let's look at another example, from [Stack Overflow](https://stackoverflow.com/questions/45123924/convert-pandas-dataframe-from-wide-to-long/45124130) :
```
df = pd.DataFrame([{"a_1": 2, "ab_1": 3, "ac_1": 4, "a_2": 5, "ab_2": 6, "ac_2": 7}])
df
```
The data above requires extracting `a`, `ab` and `ac` from `1` and `2`. This is another example of a paired column. We could solve this using [pd.wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html); infact there is a very good solution from [Stack Overflow](https://stackoverflow.com/a/45124775/7175713)
```
df1 = df.copy()
df1["id"] = df1.index
pd.wide_to_long(df1, ["a", "ab", "ac"], i="id", j="num", sep="_")
```
Or you could simply pass the buck to [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html):
```
df.pivot_longer(names_to=(".value", "num"), names_sep="_")
```
In the solution above, we used the `names_sep` argument, as it is more convenient. A few more examples to get you familiar with the `.value` symbol.
[Source Data](https://stackoverflow.com/questions/55403008/pandas-partial-melt-or-group-melt)
```
df = pd.DataFrame(
[[1, 1, 2, 3, 4, 5, 6], [2, 7, 8, 9, 10, 11, 12]],
columns=["id", "ax", "ay", "az", "bx", "by", "bz"],
)
df
df.pivot_longer(index="id", names_to=("name", ".value"), names_pattern="(.)(.)")
```
For the code above `.value` is paired with `x`, `y`, `z`(which become the new column names), while `a`, `b` are unpivoted into the `name` column.
In the dataframe below, we need to unpivot the data, keeping only the suffix `hi`, and pulling out the number between `A` and `g`. [Source Data](https://stackoverflow.com/questions/35929985/melt-a-data-table-with-a-column-pattern)
```
df = pd.DataFrame([{"id": 1, "A1g_hi": 2, "A2g_hi": 3, "A3g_hi": 4, "A4g_hi": 5}])
df
df.pivot_longer(index="id", names_to=["time", ".value"], names_pattern="A(\d)g_(hi)")
```
Let's see an example where we have multiple values in a paired column, and we wish to split them into separate columns. [Source Data](https://stackoverflow.com/questions/64107566/how-to-pivot-longer-and-populate-with-fields-from-column-names-at-the-same-tim?noredirect=1#comment113369419_64107566) :
```
df = pd.DataFrame(
{
"Sony | TV | Model | value": {0: "A222", 1: "A234", 2: "A4345"},
"Sony | TV | Quantity | value": {0: 5, 1: 5, 2: 4},
"Sony | TV | Max-quant | value": {0: 10, 1: 9, 2: 9},
"Panasonic | TV | Model | value": {0: "T232", 1: "S3424", 2: "X3421"},
"Panasonic | TV | Quantity | value": {0: 1, 1: 5, 2: 1},
"Panasonic | TV | Max-quant | value": {0: 10, 1: 12, 2: 11},
"Sanyo | Radio | Model | value": {0: "S111", 1: "S1s1", 2: "S1s2"},
"Sanyo | Radio | Quantity | value": {0: 4, 1: 2, 2: 4},
"Sanyo | Radio | Max-quant | value": {0: 9, 1: 9, 2: 10},
}
)
df
```
The goal is to reshape the data into long format, with separate columns for `Manufacturer`(Sony,...), `Device`(TV, Radio), `Model`(S3424, ...), `maximum quantity` and `quantity``.
Below is the [accepted solution](https://stackoverflow.com/a/64107688/7175713) on Stack Overflow :
```
df1 = df.copy()
# Create a multiIndex column header
df1.columns = pd.MultiIndex.from_arrays(zip(*df1.columns.str.split("\s?\|\s?")))
# Reshape the dataframe using
# `set_index`, `droplevel`, and `stack`
(
df1.stack([0, 1])
.droplevel(1, axis=1)
.set_index("Model", append=True)
.rename_axis([None, "Manufacturer", "Device", "Model"])
.sort_index(level=[1, 2, 3])
.reset_index()
.drop("level_0", axis=1)
)
```
Or, we could use [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html), along with `.value` in `names_to` and a regular expression in `names_pattern` :
```
df.pivot_longer(
names_to=("Manufacturer", "Device", ".value"),
names_pattern=r"(.+)\|(.+)\|(.+)\|.*",
)
```
The cleanup (removal of whitespace in the column names) is left as an exercise for the reader.
What if we are interested in unpivoting only a part of the entire dataframe? [Source Data](https://stackoverflow.com/questions/63044119/converting-wide-format-data-into-long-format-with-multiple-indices-and-grouped-d)
```
df = pd.DataFrame(
{
"time": [1, 2, 3],
"factor": ["a", "a", "b"],
"variable1": [0, 0, 0],
"variable2": [0, 0, 1],
"variable3": [0, 2, 0],
"variable4": [2, 0, 1],
"variable5": [1, 0, 1],
"variable6": [0, 1, 1],
"O1V1": [0, 0.2, -0.3],
"O1V2": [0, 0.4, -0.9],
"O1V3": [0.5, 0.2, -0.6],
"O1V4": [0.5, 0.2, -0.6],
"O1V5": [0, 0.2, -0.3],
"O1V6": [0, 0.4, -0.9],
"O1V7": [0.5, 0.2, -0.6],
"O1V8": [0.5, 0.2, -0.6],
"O2V1": [0, 0.5, 0.3],
"O2V2": [0, 0.2, 0.9],
"O2V3": [0.6, 0.1, -0.3],
"O2V4": [0.5, 0.2, -0.6],
"O2V5": [0, 0.5, 0.3],
"O2V6": [0, 0.2, 0.9],
"O2V7": [0.6, 0.1, -0.3],
"O2V8": [0.5, 0.2, -0.6],
"O3V1": [0, 0.7, 0.4],
"O3V2": [0.9, 0.2, -0.3],
"O3V3": [0.5, 0.2, -0.7],
"O3V4": [0.5, 0.2, -0.6],
"O3V5": [0, 0.7, 0.4],
"O3V6": [0.9, 0.2, -0.3],
"O3V7": [0.5, 0.2, -0.7],
"O3V8": [0.5, 0.2, -0.6],
}
)
df
```
What is the task? This is copied verbatim from the source:
<blockquote>Each row of the data frame represents a time period. There are multiple 'subjects' being monitored, namely O1, O2, and O3. Each subject has 8 variables being measured. I need to convert this data into long format where each row contains the information for one subject at a given time period, but with only the first 4 subject variables, as well as the extra information about this time period in columns 2-4, but not columns 5-8.</blockquote>
Below is the accepted solution, using [wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html):
```
df1 = df.rename(
columns={x: x[2:] + x[1:2] for x in df.columns[df.columns.str.startswith("O")]}
)
df1 = pd.wide_to_long(
df1,
i=["time", "factor"] + [f"variable{i}" for i in range(1, 7)],
j="id",
stubnames=[f"V{i}" for i in range(1, 9)],
suffix=".*",
)
df1 = df1.reset_index().drop(
columns=[f"V{i}" for i in range(5, 9)] + [f"variable{i}" for i in range(3, 7)]
)
df1
```
We can abstract the details and focus on the task with [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html):
```
df.pivot_longer(
index=slice("time", "variable2"),
column_names=janitor.patterns(".+V[1-4]$"),
names_to=("id", ".value"),
names_pattern=".(.)(.+)$",
sort_by_appearance=True,
)
```
One more example on the `.value` symbol for paired columns [Source Data](https://stackoverflow.com/questions/59477686/python-pandas-melt-single-column-into-two-seperate) :
```
df = pd.DataFrame({"id": [1, 2], "A_value": [50, 33], "D_value": [60, 45]})
df
df.pivot_longer(index="id", names_to=("value_type", ".value"), names_sep="_")
```
There are scenarios where we need to unpivot the data, and group values within the column names under new columns. The values in the columns will not become new column names, so we do not need the `.value` symbol. Let's see an example below: [Source Data](https://stackoverflow.com/questions/59550804/melt-column-by-substring-of-the-columns-name-in-pandas-python)
```
df = pd.DataFrame(
{
"subject": [1, 2],
"A_target_word_gd": [1, 11],
"A_target_word_fd": [2, 12],
"B_target_word_gd": [3, 13],
"B_target_word_fd": [4, 14],
"subject_type": ["mild", "moderate"],
}
)
df
```
In the dataframe above, `A` and `B` represent conditions, while the suffixes `gd` and `fd` represent value types. We are not interested in the words in the middle (`_target_word`). We could solve it this way (this is the chosen solution, copied from [Stack Overflow](https://stackoverflow.com/a/59550967/7175713)) :
```
new_df = pd.melt(df, id_vars=["subject_type", "subject"], var_name="abc").sort_values(
by=["subject", "subject_type"]
)
new_df["cond"] = new_df["abc"].apply(lambda x: (x.split("_"))[0])
new_df["value_type"] = new_df.pop("abc").apply(lambda x: (x.split("_"))[-1])
new_df
```
Or, we could just pass the buck to [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html):
```
df.pivot_longer(
index=["subject", "subject_type"],
names_to=("cond", "value_type"),
names_pattern="([A-Z]).*(gd|fd)",
)
```
In the code above, we pass in the new names of the columns to `names_to`('cond', 'value_type'), and pass the groups to be extracted as a regular expression to `names_pattern`.
Here's another example where [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) abstracts the process and makes reshaping easy.
In the dataframe below, we would like to unpivot the data and separate the column names into individual columns(`vault` should be in an `event` column, `2012` should be in a `year` column and `f` should be in a `gender` column). [Source Data](https://dcl-wrangle.stanford.edu/pivot-advanced.html)
```
df = pd.DataFrame(
{
"country": ["United States", "Russia", "China"],
"vault_2012_f": [
48.132,
46.366,
44.266,
],
"vault_2012_m": [46.632, 46.866, 48.316],
"vault_2016_f": [
46.866,
45.733,
44.332,
],
"vault_2016_m": [45.865, 46.033, 45.0],
"floor_2012_f": [45.366, 41.599, 40.833],
"floor_2012_m": [45.266, 45.308, 45.133],
"floor_2016_f": [45.999, 42.032, 42.066],
"floor_2016_m": [43.757, 44.766, 43.799],
}
)
df
```
We could achieve this with a combination of [pd.melt](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html) and pandas string methods (or janitor's [deconcatenate_columns](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.deconcatenate_column.html#janitor.deconcatenate_column) method); or we could, again, pass the buck to [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html):
```
df.pivot_longer(
index="country",
names_to=["event", "year", "gender"],
names_sep="_",
values_to="score",
)
```
Again, if you want the data returned in order of appearance, you can turn on the `sort_by_appearance` parameter:
```
df.pivot_longer(
index="country",
names_to=["event", "year", "gender"],
names_sep="_",
values_to="score",
sort_by_appearance=True,
)
```
One more feature that [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) offers is to pass a list of regular expressions to `names_pattern`. This comes in handy when one single regex cannot encapsulate similar columns for reshaping to long form. This idea is inspired by the [melt](https://rdatatable.gitlab.io/data.table/reference/melt.data.table.html) function in R's [data.table](https://rdatatable.gitlab.io/data.table/). A couple of examples should make this clear.
[Source Data](https://stackoverflow.com/questions/61138600/tidy-dataset-with-pivot-longer-multiple-columns-into-two-columns)
```
df = pd.DataFrame(
[
{
"title": "Avatar",
"actor_1": "CCH_Pound…",
"actor_2": "Joel_Davi…",
"actor_3": "Wes_Studi",
"actor_1_FB_likes": 1000,
"actor_2_FB_likes": 936,
"actor_3_FB_likes": 855,
},
{
"title": "Pirates_of_the_Car…",
"actor_1": "Johnny_De…",
"actor_2": "Orlando_B…",
"actor_3": "Jack_Daven…",
"actor_1_FB_likes": 40000,
"actor_2_FB_likes": 5000,
"actor_3_FB_likes": 1000,
},
{
"title": "The_Dark_Knight_Ri…",
"actor_1": "Tom_Hardy",
"actor_2": "Christian…",
"actor_3": "Joseph_Gor…",
"actor_1_FB_likes": 27000,
"actor_2_FB_likes": 23000,
"actor_3_FB_likes": 23000,
},
{
"title": "John_Carter",
"actor_1": "Daryl_Sab…",
"actor_2": "Samantha_…",
"actor_3": "Polly_Walk…",
"actor_1_FB_likes": 640,
"actor_2_FB_likes": 632,
"actor_3_FB_likes": 530,
},
{
"title": "Spider-Man_3",
"actor_1": "J.K._Simm…",
"actor_2": "James_Fra…",
"actor_3": "Kirsten_Du…",
"actor_1_FB_likes": 24000,
"actor_2_FB_likes": 11000,
"actor_3_FB_likes": 4000,
},
{
"title": "Tangled",
"actor_1": "Brad_Garr…",
"actor_2": "Donna_Mur…",
"actor_3": "M.C._Gainey",
"actor_1_FB_likes": 799,
"actor_2_FB_likes": 553,
"actor_3_FB_likes": 284,
},
]
)
df
```
Above, we have a dataframe of movie titles, actors, and their facebook likes. It would be great if we could transform this into a long form, with just the title, the actor names, and the number of likes. Let's look at a possible solution :
First, we reshape the columns, so that the numbers appear at the end.
```
df1 = df.copy()
pat = r"(?P<actor>.+)_(?P<num>\d)_(?P<likes>.+)"
def repl(m):
return f"""{m.group('actor')}_{m.group('likes')}_{m.group('num')}"""
df1.columns = df1.columns.str.replace(pat, repl, regex=True)
df1
```
Now, we can reshape, using [pd.wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html) :
```
pd.wide_to_long(
df1, stubnames=["actor", "actor_FB_likes"], i="title", j="group", sep="_"
)
```
We could attempt to solve it with [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html), using the `.value` symbol :
```
df1.pivot_longer(
index="title", names_to=(".value", "group"), names_pattern="(.+)_(\d)$"
)
```
What if we could just get our data in long form without the massaging? We know our data has a pattern to it --> it either ends in a number or *likes*. Can't we take advantage of that? Yes, we can (I know, I know; it sounds like a campaign slogan 🤪)
```
df.pivot_longer(
index="title",
names_to=("actor", "num_likes"),
names_pattern=("\d$", "likes$"),
)
```
A pairing of `names_to` and `names_pattern` results in:
{"actor": '\d$', "num_likes": 'likes$'}
The first regex looks for columns that end with a number, while the other looks for columns that end with *likes*. [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) will then look for columns that end with a number and lump all the values in those columns under the `actor` column, and also look for columns that end with *like* and combine all the values in those columns into a new column -> `num_likes`. Underneath the hood, [numpy select](https://numpy.org/doc/stable/reference/generated/numpy.select.html) and [pd.Series.str.contains](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html) are used to pull apart the columns into the new columns.
Again, it is about the goal; we are not interested in the numbers (1,2,3), we only need the names of the actors, and their facebook likes. [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) aims to give as much flexibility as possible, in addition to ease of use, to allow the end user focus on the task.
Let's take a look at another example. [Source Data](https://stackoverflow.com/questions/60439749/pair-wise-melt-in-pandas-dataframe) :
```
df = pd.DataFrame(
{
"id": [0, 1],
"Name": ["ABC", "XYZ"],
"code": [1, 2],
"code1": [4, np.nan],
"code2": ["8", 5],
"type": ["S", "R"],
"type1": ["E", np.nan],
"type2": ["T", "U"],
}
)
df
```
We cannot directly use [pd.wide_to_long](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html) here without some massaging, as there is no definite suffix(the first `code` does not have a suffix), neither can we use `.value` here, again because there is no suffix. However, we can see a pattern where some columns start with `code`, and others start with `type`. Let's see how [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) solves this, using a sequence of regular expressions in the `names_pattern` argument :
```
df.pivot_longer(
index=["id", "Name"],
names_to=("code_all", "type_all"),
names_pattern=("^code", "^type"),
)
```
The key here is passing the right regular expression, and ensuring the names in `names_to` is paired with the right regex in `names_pattern`; as such, every column that starts with `code` will be included in the new `code_all` column; the same happens to the `type_all` column. Easy and flexible, right?
Let's explore another example, from [Stack Overflow](https://stackoverflow.com/questions/12466493/reshaping-multiple-sets-of-measurement-columns-wide-format-into-single-columns) :
```
df = pd.DataFrame(
[
{
"ID": 1,
"DateRange1Start": "1/1/90",
"DateRange1End": "3/1/90",
"Value1": 4.4,
"DateRange2Start": "4/5/91",
"DateRange2End": "6/7/91",
"Value2": 6.2,
"DateRange3Start": "5/5/95",
"DateRange3End": "6/6/96",
"Value3": 3.3,
}
]
)
df
```
In the dataframe above, we need to reshape the data to have a start date, end date and value. For the `DateRange` columns, the numbers are embedded within the string, while for `value` it is appended at the end. One possible solution is to reshape the columns so that the numbers are at the end :
```
df1 = df.copy()
pat = r"(?P<head>.+)(?P<num>\d)(?P<tail>.+)"
def repl(m):
return f"""{m.group('head')}{m.group('tail')}{m.group('num')}"""
df1.columns = df1.columns.str.replace(pat, repl, regex=True)
df1
```
Now, we can unpivot:
```
pd.wide_to_long(
df1, stubnames=["DateRangeStart", "DateRangeEnd", "Value"], i="ID", j="num"
)
```
Using the `.value` symbol in pivot_longer:
```
df1.pivot_longer(index="ID", names_to=[".value", "num"], names_pattern="(.+)(\d)$")
```
Or, we could allow pivot_longer worry about the massaging; simply pass to `names_pattern` a list of regular expressions that match what we are after :
```
df.pivot_longer(
index="ID",
names_to=("DateRangeStart", "DateRangeEnd", "Value"),
names_pattern=("Start$", "End$", "^Value"),
)
```
The code above looks for columns that end with *Start*(`Start$`), aggregates all the values in those columns into `DateRangeStart` column, looks for columns that end with *End*(`End$`), aggregates all the values within those columns into `DateRangeEnd` column, and finally looks for columns that start with *Value*(`^Value`), and aggregates the values in those columns into the `Value` column. Just know the patterns, and pair them accordingly. Again, the goal is a focus on the task, to make it simple for the end user.
Let's look at another example [Source Data](https://stackoverflow.com/questions/64316129/how-to-efficiently-melt-multiple-columns-using-the-module-melt-in-pandas/64316306#64316306) :
```
df = pd.DataFrame(
{
"Activity": ["P1", "P2"],
"General": ["AA", "BB"],
"m1": ["A1", "B1"],
"t1": ["TA1", "TB1"],
"m2": ["A2", "B2"],
"t2": ["TA2", "TB2"],
"m3": ["A3", "B3"],
"t3": ["TA3", "TB3"],
}
)
df
```
This is a [solution](https://stackoverflow.com/a/64316306/7175713) provided by yours truly :
```
(
pd.wide_to_long(df, i=["Activity", "General"], stubnames=["t", "m"], j="number")
.set_axis(["Task", "M"], axis="columns")
.droplevel(-1)
.reset_index()
)
```
Or, we could use [pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html), abstract the details, and focus on the task :
```
df.pivot_longer(
index=["Activity", "General"], names_pattern=["^m", "^t"], names_to=["M", "Task"]
)
```
Alright, one last example :
[Source Data](https://stackoverflow.com/questions/64159054/how-do-you-pivot-longer-columns-in-groups)
```
df = pd.DataFrame(
{
"Name": ["John", "Chris", "Alex"],
"activity1": ["Birthday", "Sleep Over", "Track Race"],
"number_activity_1": [1, 2, 4],
"attendees1": [14, 18, 100],
"activity2": ["Sleep Over", "Painting", "Birthday"],
"number_activity_2": [4, 5, 1],
"attendees2": [10, 8, 5],
}
)
df
```
The task here is to unpivot the data, and group the data under three new columns ("activity", "number_activity", and "attendees").
We can see that there is a pattern to the data; let's create a list of regular expressions that match the patterns and pass to `names_pattern``:
```
df.pivot_longer(
index="Name",
names_to=("activity", "number_activity", "attendees"),
names_pattern=("^activity", "^number_activity", "^attendees"),
)
```
Alright, let's look at one final example:
[Source Data](https://stackoverflow.com/questions/60387077/reshaping-and-melting-dataframe-whilst-picking-up-certain-regex)
```
df = pd.DataFrame(
{
"Location": ["Madrid", "Madrid", "Rome", "Rome"],
"Account": ["ABC", "XYX", "ABC", "XYX"],
"Y2019:MTD:January:Expense": [4354, 769867, 434654, 632556456],
"Y2019:MTD:January:Income": [56456, 32556456, 5214, 46724423],
"Y2019:MTD:February:Expense": [235423, 6785423, 235423, 46588],
}
)
df
df.pivot_longer(
index=["Location", "Account"],
names_to=("year", "month", ".value"),
names_pattern=r"Y(.+):MTD:(.{3}).+(Income|Expense)",
sort_by_appearance=True,
)
```
[pivot_longer](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.pivot_longer.html) does not solve all problems; no function does. Its aim is to make it easy to unpivot dataframes from wide to long form, while offering a lot of flexibility and power.
| github_jupyter |
```
import os
import ee
import json
import requests
import requests_cache
from pprint import pprint
import pandas as pd
ee.Initialize()
im = ee.Image('projects/mapbiomas-workspace/public/collection2_3/mapbiomas_collection23_integration_v1')
with open('geoms.txt') as json_data:
d = json.load(json_data)
d[0]
def getAreaByPixels(image, geom):
dict = image.reduceRegion(reducer=ee.Reducer.frequencyHistogram(),
geometry=geom, scale=30, maxPixels=1e12,bestEffort=True)
data = image.set(dict).getInfo()
total_pixels = 0
for key, value in data.get('properties').get('classification_2016').items():
total_pixels += value
tmp = []
for year in range(2000,2017):
breakdown = []
for key, value in data.get('properties').get(f'classification_{year}').items():
breakdown.append({
'classification': key,
'area_%': 100*value/total_pixels,
'area': value*30*30
})
breakdown = sorted(breakdown, key=lambda k: k.get('area'), reverse=True)
tmp.append({'classification_year': year, 'data': breakdown})
return tmp
%%time
# classification_data = []
for data in d[4894:]:
tmp = {
'iso': 'BRA',
'adm1': data.get('adm1'),
'adm2': data.get('adm2'),
# 'total_area_m2': data.get('area_m2'),
# 'geom': data.get('geom'),
'classification': getAreaByPixels(im, data.get('geom'))
}
classification_data.append(tmp)
print('done!')
len(classification_data) #5502 when complete!
with open('classification_data.txt', 'w') as file:
json.dump(classification_data, file)
print('done')
with open('classification_data.txt') as json_data:
tmp_data = json.load(json_data)
carto_export = []
carto_export.append(['iso', 'adm1', 'adm2',
'class2000', 'class2001','class2002','class2003','class2004','class2005',
'class2006','class2007','class2008','class2009','class2010','class2011',
'class2012','class2013','class2014','class2015','class2016'])
for d in tmp_data:
tmp = []
tmp.append(d.get('iso')) #iso
tmp.append(d.get('adm1')) #adm1
tmp.append(d.get('adm2')) #adm2
# tmp.append(d.get('geom')) #geom
# tmp.append(d.get('total_area_m2')) #total_area
for c in d.get('classification'):
tmp.append(c.get('data'))
carto_export.append(tmp)
print('done')
len(carto_export) #len 5502 if complete
my_df = pd.DataFrame(carto_export)
my_df.to_csv('carto_export.csv', index=False, header=False)
```
| github_jupyter |
Classification of handwritten digits
------------------------------------
*Fraida Fund*
In this notebook, we will explore the use of different techniques for
classification of handwritten digits, with a focus on:
- Classification accuracy (although we won’t do any hyperparameter
tuning. It’s possible to improve the accuracy a lot using CV for
hyperparameter tuning!)
- How long it takes to train the model
- How long it takes to make a prediction using the fitted model
- Interpretability of the model
We will use the [magic
command](https://ipython.readthedocs.io/en/stable/interactive/magics.html)
`%time` to time how long it takes to fit the model and use the fitted
model for predictions. It will tell us:
- the CPU time (amount of time for which a CPU was working on this
line of code)
- the wall time (which also includes time waiting for I/O, etc.)
(Note that a related magic command, `%timeit`, tells us how long it
takes to run multiple iterations of a line of code. This gives us a much
more accurate estimate of the average time. However, since some of the
commands we want to time will take a long time to run, we will use the
basic `%time` command instead to save time.)
```
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
from sklearn.preprocessing import MinMaxScaler
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier, AdaBoostClassifier
%matplotlib inline
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
```
### Load the digits dataset
For this demo, we will use a dataset known as
[MNIST](https://en.wikipedia.org/wiki/MNIST_database). It contains
70,000 samples of handwritten digits, size-normalized and centered in a
fixed-size image. Each sample is represented as a 28x28 pixel array, so
there are 784 features per samples.
We will start by loading the dataset using the `fetch_openml` function.
This function allows us to retrieve a dataset by name from
[OpenML](https://www.openml.org/), a public repository for machine
learning data and experiments.
```
X, y = fetch_openml('mnist_784', version=1, return_X_y=True)
```
We observe that the data has 784 features and 70,000 samples:
```
X.shape
```
The target variables is a label for each digit: 0, 1, 2, 3, 4, 5, 6, 7,
8, 9. There are between 6000 and 8000 samples for each class.
```
y.shape
print(y)
pd.Series(y).value_counts()
```
We can see a few examples, by plotting the 784 features in a 28x28 grid:
```
n_samples = 5
p = plt.figure(figsize=(n_samples*3,3));
for index, (image, label) in enumerate(zip(X[0:n_samples], y[0:n_samples])):
p = plt.subplot(1, n_samples, index + 1);
p = sns.heatmap(np.reshape(image, (28,28)), cmap=plt.cm.gray, cbar=False);
p = plt.title('Label: %s\n' % label);
```
### Prepare data
Next, we will split our data into a test and training set using
`train_test_split` from `sklearn.model_selection`.
Since the dataset is very large, it can take a long time to train a
classifier on it. We just want to use it to demonstrate some useful
concepts, so we will work with a smaller subset of the dataset. When we
split the data using the `train_test_split` function, we will specify
that we want 12,000 samples in the training set and 2,000 samples in the
test set.
```
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=9,
train_size=12000, test_size=2000)
```
We can also rescale the data:
```
sc = MinMaxScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
```
### Train a classifier using logistic regression
Now we are ready to train a classifier. We will start with `sklearn`'s
[LogisticRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html).
We will time three commands:
- The `fit` command trains the model (finds parameter estimates).
- The `predict_proba` function uses the fitted logistic regression to
get probabilities. For each sample, it returns 10 probabilities -
one for each of the ten classes.
- The `predict` function predicts a label for each sample in the test
set. This will return the class label with the highest probability.
We will use the “magic command” `%time` to time how long it takes to
execute each of these three commands. It will tell us:
- the CPU time (amount of time for which a CPU was working on this
line of code)
- the wall time (which also includes time waiting for I/O, etc.)
```
cls_log = LogisticRegression(penalty='none',
tol=0.1, solver='saga',
multi_class='multinomial')
%time cls_log.fit(X_train, y_train)
%time y_pred_log = cls_log.predict(X_test)
%time y_pred_prob_log = cls_log.predict_proba(X_test)
acc = accuracy_score(y_test, y_pred_log)
acc
```
Next, we will explore the results to see how the logistic regression
classifier offers interpretability.
```
df_results_log = pd.DataFrame(y_pred_prob_log)
df_results_log = df_results_log.assign(y_pred = y_pred_log)
df_results_log = df_results_log.assign(y_true = y_test)
df_results_log = df_results_log.assign(correct = y_test==y_pred_log)
df_mis_log = df_results_log[df_results_log['correct']==False]
df_mis_log = df_mis_log.reset_index()
confusion_matrix = pd.crosstab(df_results_log['y_true'], df_results_log['y_pred'],
rownames=['Actual'], colnames=['Predicted'], normalize='index')
p = plt.figure(figsize=(10,10));
p = sns.heatmap(confusion_matrix, annot=True, fmt=".2f", cbar=False)
scale = 1
idx_mis = df_mis_log['index']
n_samples = min(5,len(idx_mis))
n_vectors = 2
p = plt.figure(figsize=(3*n_samples,5*n_vectors));
for index in range(n_samples):
sample_index = idx_mis[index]
image = X_test[sample_index]
true_label = y_test[sample_index]
pred_label = y_pred_log[sample_index]
p = plt.subplot(1+n_vectors, n_samples, index + 1);
p = sns.heatmap(np.reshape(image, (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
p = plt.title('Predicted Label: %s\n Actual Label: %s' %
(pred_label, true_label));
p = plt.subplot(1+n_vectors, n_samples, (1)*n_samples + (index+1));
p = sns.heatmap(cls_log.coef_[int(pred_label)].reshape(28, 28),
cmap=plt.cm.RdBu, vmin=-scale, vmax=scale,
xticklabels=False, yticklabels=False, cbar=False);
p = plt.title('Predicted Class: %s' % pred_label)
p = plt.subplot(1+n_vectors, n_samples, (2)*n_samples + (index+1));
p = sns.heatmap(cls_log.coef_[int(true_label)].reshape(28, 28),
cmap=plt.cm.RdBu, vmin=-scale, vmax=scale,
xticklabels=False, yticklabels=False, cbar=False);
p = plt.title('Actual Class: %s' % true_label)
df_mis_melt = pd.melt(df_mis_log, id_vars=['y_pred','y_true','correct', 'index'],
var_name='class', value_name='probability')
df_mis_melt = df_mis_melt.sort_values(by='index')
df_mis_melt['type'] = np.select([df_mis_melt['class'].astype(float)==df_mis_melt['y_pred'].astype(float),
df_mis_melt['class'].astype(float)==df_mis_melt['y_true'].astype(float)],
['Predicted Class', 'True class'], default='Neither')
p = sns.catplot(data=df_mis_melt.head(n=n_samples*10), col="index", hue='type',
x="class", y="probability",kind="bar",
dodge=False, legend_out=False, height=3, aspect=0.8);
p.set_axis_labels("Class", "");
plt.ylim(0,1);
p.set_yticklabels();
```
### Train a classifier using K Nearest Neighbor
Next, we will use `sklearn`'s
[KNeighborsClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html).
```
cls_knn = KNeighborsClassifier(n_neighbors=3, weights='distance')
%time cls_knn.fit(X_train, y_train)
%time y_pred_knn = cls_knn.predict(X_test)
%time y_pred_prob_knn = cls_knn.predict_proba(X_test)
acc = accuracy_score(y_test, y_pred_knn)
acc
df_results_knn = pd.DataFrame(y_pred_prob_knn)
df_results_knn = df_results_knn.assign(y_pred = y_pred_knn)
df_results_knn = df_results_knn.assign(y_true = y_test)
df_results_knn = df_results_knn.assign(correct = y_test==y_pred_knn)
df_mis_knn = df_results_knn[df_results_knn['correct']==False]
df_mis_knn = df_mis_knn.reset_index()
confusion_matrix = pd.crosstab(df_results_knn['y_true'], df_results_knn['y_pred'],
rownames=['Actual'], colnames=['Predicted'], normalize='index')
p = plt.figure(figsize=(10,10));
p = sns.heatmap(confusion_matrix, annot=True, fmt=".2f", cbar=False)
distances_mis, neighbor_idx_mis = cls_knn.kneighbors(X_test[df_mis_knn['index']])
idx_mis = df_mis_knn['index']
n_samples = min(5,len(idx_mis))
n_neighbors = 3
p = plt.figure(figsize=(3*n_samples,4.25*n_neighbors));
for index in range(n_samples):
sample_index = idx_mis[index]
image = X_test[sample_index]
true_label = y_test[sample_index]
pred_label = y_pred_knn[sample_index]
p = plt.subplot(1+n_neighbors, n_samples, index + 1);
p = sns.heatmap(np.reshape(image, (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
p = plt.title('Predicted Label: %s\n Actual Label: %s' %
(pred_label, true_label));
for i in range(n_neighbors):
neighbor_index = neighbor_idx_mis[index][i]
neighbor_image = X_train[neighbor_index]
true_label = y_train[neighbor_index]
dist = distances_mis[index][i]
p = plt.subplot(1+n_neighbors, n_samples, (1+i)*n_samples + (index+1));
p = sns.heatmap(np.reshape(neighbor_image, (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
p = plt.title('Label: %s, Dist: %s' %
(true_label, "{:.2f}".format(dist)));
df_mis_melt = pd.melt(df_mis_knn, id_vars=['y_pred','y_true','correct', 'index'],
var_name='class', value_name='probability')
df_mis_melt = df_mis_melt.sort_values(by='index')
df_mis_melt['type'] = np.select([df_mis_melt['class'].astype(float)==df_mis_melt['y_pred'].astype(float),
df_mis_melt['class'].astype(float)==df_mis_melt['y_true'].astype(float)],
['Predicted Class', 'True class'], default='Neither')
p = sns.catplot(data=df_mis_melt.head(n=n_samples*10), col="index", hue='type', dodge=False,
x="class", y="probability",kind="bar", legend_out=False, height=3, aspect=0.8);
p.set_axis_labels("Class", "");
plt.ylim(0,1);
p.set_yticklabels();
```
### Train a classifier using Decision Tree
Next, we will use `sklearn`'s
[DecisionTreeClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html).
```
cls_dt = DecisionTreeClassifier()
%time cls_dt.fit(X_train, y_train)
%time y_pred_dt = cls_dt.predict(X_test)
%time y_pred_prob_dt = cls_dt.predict_proba(X_test)
acc = accuracy_score(y_test, y_pred_dt)
acc
df_results_dt = pd.DataFrame(y_pred_prob_dt)
df_results_dt = df_results_dt.assign(y_pred = y_pred_dt)
df_results_dt = df_results_dt.assign(y_true = y_test)
df_results_dt = df_results_dt.assign(correct = y_test==y_pred_dt)
df_mis_dt = df_results_dt[df_results_dt['correct']==False]
df_mis_dt = df_mis_dt.reset_index()
confusion_matrix = pd.crosstab(df_results_dt['y_true'], df_results_dt['y_pred'],
rownames=['Actual'], colnames=['Predicted'], normalize='index')
p = plt.figure(figsize=(10,10));
p = sns.heatmap(confusion_matrix, annot=True, fmt=".2f", cbar=False)
p = plt.figure(figsize=(15,15));
p = plot_tree(cls_dt, max_depth=4, filled=True, rounded=True);
```
Here's a better way to plot a large tree:
```
import graphviz
from sklearn import tree
dot_data = tree.export_graphviz(cls_dt, out_file=None,
max_depth=4,
filled=True, rounded=True)
graph = graphviz.Source(dot_data)
graph
scale_dt = 0.01
p = plt.figure(figsize=(3,3));
p = sns.heatmap(cls_dt.feature_importances_.reshape(28, 28),
cmap=plt.cm.RdBu, vmin=-scale_dt, vmax=scale_dt,
xticklabels=False, yticklabels=False, cbar=False);
p = plt.title('Feature importance')
```
### Train an ensemble of trees
Next, we will train some ensembles of trees using two different
approaches:
- **Bagging**, where we train many independent trees and average their
output. We will attempt “regular” bagging, and also a random forest,
which uses decorrelated trees.
- **Boosting**, where we iteratively train trees to focus on the
“difficult” samples that were misclassified by previous trees.
```
cls_bag = BaggingClassifier(DecisionTreeClassifier())
%time cls_bag.fit(X_train, y_train)
%time y_pred_bag = cls_bag.predict(X_test)
%time y_pred_prob_bag = cls_bag.predict_proba(X_test)
acc = accuracy_score(y_test, y_pred_bag)
acc
cls_rf = RandomForestClassifier()
%time cls_rf.fit(X_train, y_train)
%time y_pred_rf = cls_rf.predict(X_test)
%time y_pred_prob_rf = cls_rf.predict_proba(X_test)
acc = accuracy_score(y_test, y_pred_rf)
acc
cls_ab = AdaBoostClassifier()
%time cls_ab.fit(X_train, y_train)
%time y_pred_ab = cls_ab.predict(X_test)
%time y_pred_prob_ab = cls_ab.predict_proba(X_test)
acc = accuracy_score(y_test, y_pred_ab)
acc
# Faster than regular GradientBoostingClassifier
# but, still takes several minutes
cls_gradboost = HistGradientBoostingClassifier()
%time cls_gradboost.fit(X_train, y_train)
%time y_pred_gradboost = cls_gradboost.predict(X_test)
%time y_pred_prob_gradboost = cls_gradboost.predict_proba(X_test)
acc = accuracy_score(y_test, y_pred_gradboost)
acc
```
### Train a linear support vector classifier
The next classifier we’ll attempt is a support vector classifier.
```
cls_svc = SVC(kernel='linear')
%time cls_svc.fit(X_train, y_train)
%time y_pred_svc = cls_svc.predict(X_test)
# note: there is no predict_proba for SVC
acc = accuracy_score(y_test, y_pred_svc)
acc
df_results_svc = pd.DataFrame(y_pred_svc)
df_results_svc = df_results_svc.assign(y_pred = y_pred_svc)
df_results_svc = df_results_svc.assign(y_true = y_test)
df_results_svc = df_results_svc.assign(correct = y_test==y_pred_svc)
df_mis_svc = df_results_svc[df_results_svc['correct']==False]
df_mis_svc = df_mis_svc.reset_index()
confusion_matrix = pd.crosstab(df_results_svc['y_true'], df_results_svc['y_pred'],
rownames=['Actual'], colnames=['Predicted'], normalize='index')
p = plt.figure(figsize=(10,10));
p = sns.heatmap(confusion_matrix, annot=True, fmt=".2f", cbar=False)
```
The decisions of the SVC are a little bit more complicated to interpret,
but we can get some insight by looking at the support vectors.
First, we can find out the number of support vectors for each class, and
get their indices:
```
idx_support = cls_svc.support_
cls_svc.n_support_
```
Then, we can plot a random subset of support vectors for each class:
```
num_classes = len(cls_svc.classes_)
m = np.insert(np.cumsum(cls_svc.n_support_), 0, 0)
samples_per_class = 15
figure = plt.figure(figsize=(num_classes*2,(1+samples_per_class*2)));
for y, cls in enumerate(cls_svc.classes_):
idxs = np.random.choice(idx_support[m[y]:m[y+1]], samples_per_class, replace=False)
for i, idx in enumerate(idxs):
plt_idx = i * num_classes + y + 1
p = plt.subplot(samples_per_class, num_classes, plt_idx);
p = sns.heatmap(np.reshape(X_train[idx], (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
p = plt.axis('off');
```
You may notice that the support vectors include many atypical examples
of the digits they represent.
Equivalently, the support vectors include examples that are more likely
than most training samples to be confused with another class (for
example, look at the accuracy of the logistic regression on the entire
training set, and on just the support vectors!). Why?
```
cls_log.score(X_train, y_train)
cls_log.score(X_train[idx_support], y_train[idx_support])
```
It’s easier to understand the decisions of the SVC for a binary
classification problem, so to dig deeper into the interpretability, we’l
consider the the binary classification problem of distinguishing between
'5' and '6' digits.
```
X_train_bin = X_train[np.isin(y_train, ['5','6'])]
y_train_bin = y_train[np.isin(y_train, ['5','6'])]
X_test_bin = X_test[np.isin(y_test, ['5','6'])]
y_test_bin = y_test[np.isin(y_test, ['5','6'])]
```
We’l fit an SVC classifier on the 5s and 6s:
```
cls_svc_bin = SVC(kernel='linear', C=10)
cls_svc_bin.fit(X_train_bin, y_train_bin)
```
And then use it to make predictions:
```
y_pred_bin = cls_svc_bin.predict(X_test_bin)
accuracy_score(y_test_bin, y_pred_bin)
```
We will choose one test sample to explore in depth.
We’l use one that was misclassified:
```
idx_mis = np.where(y_pred_bin!=y_test_bin)[0]
idx_test = np.random.choice(idx_mis, size=1)
plt.figure(figsize=(5,5));
sns.heatmap(np.reshape(X_test_bin[idx_test], (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
plt.title("Predicted: %s\nActual: %s" % (y_pred_bin[idx_test],y_test_bin[idx_test]));
```
Now, let’s see how the SVC made its decision for this test point
$\mathbf{x_t}$, by computing
$$w_0 + \sum_{i \in S} \alpha_i y_i \sum_{j=1}^p x_{ij}, x_{tj}$$
where $S$ is the set of support vectors. (Recall that $\alpha_i = 0$ for
any point that is not a support vector.)
First, we need the list of $i \in S$.
We use `support_` to get the indices of the support vectors (in the
training set) and `n_support_` to get the number of support vectors for
each class.
```
idx_support = cls_svc_bin.support_
print(idx_support.shape)
print(cls_svc_bin.n_support_)
```
Next, for each class ($+$ and $-$), we will find:
- the support vectors for that class, $x_i$
- the values of the dual coefficients $\alpha_i$ for each support
vector for that class. Actually, the SVM model returns
$\alpha_i y_i$, but that’s fine, too.
```
n_support_c1 = cls_svc_bin.n_support_[0]
idx_support_c1 = idx_support[0:n_support_c1]
dual_coef_c1 = cls_svc_bin.dual_coef_[:,0:n_support_c1]
n_support_c2 = n_support_c1 + cls_svc_bin.n_support_[1]
idx_support_c2 = idx_support[n_support_c1:n_support_c1+n_support_c2]
dual_coef_c2 = cls_svc_bin.dual_coef_[:, n_support_c1:n_support_c1+n_support_c2]
```
Now we have the dual coefficients!
A brief digression - recall that the dual SVC problem is
$$
\begin{aligned}
\max_\alpha \quad & \sum_{i=1}^n \alpha_i - \frac{1}{2} \sum_{i,j = 1}^{n} \alpha_i \alpha_j y_i y_j
\mathbf{x}_i^T \mathbf{x}_j \\
\text{s.t.} \quad & \sum_{i=1}^n \alpha_i y_i = 0, \quad 0 \leq \alpha_i \leq C, \quad \forall i
\end{aligned}
$$
so each $\alpha_i$ will be between $0$ and $C$.
But, the values in the `dual_coef_` array returned by the `sklearn` SVM
model are not directly the $\alpha_i$. Instead, they are $\alpha_i y_i$,
so:
- the coefficients will be negative for the negative class and
positive for the positive class, but
- you should see that the magnitudes are always between $0$ and $C$.
```
dual_coef_c1
dual_coef_c2
```
Note that the constraint $\sum_{i=1}^n \alpha_i y_i = 0$ is also
satisfied:
```
np.sum(dual_coef_c1) + np.sum(dual_coef_c2)
```
Finally, we need $\mathbf{x}_i^T \mathbf{x}_{t}$ for each support vector
$i$.
This is a measure of the similarity of the test point to each support
vector, using the dot product as “similarity metric”.
We will compute this separately for the support vectors in the negative
class and then for the support vectors in the positive class.
```
from sklearn.metrics.pairwise import pairwise_kernels
similarity = pairwise_kernels(X_train_bin, X_test_bin[idx_test].reshape(1, -1))
similarity_c1 = similarity[idx_support_c1].ravel()
similarity_c2 = similarity[idx_support_c2].ravel()
```
Now that we have $\alpha_i y_i$ and $\mathbf{x}_i^T \mathbf{x}_{t}$ for
each support vector $i \in S$, we can compute
$$\sum_{i \in S} \alpha_i y_i \mathbf{x}_i^T \mathbf{x}_{t} $$
We’l do this separately for each class.
Here is the sum of
$$\sum_{i \in S^-} \alpha_i y_i \mathbf{x}_i^T \mathbf{x}_{t} $$
where $S^-$ is the set of support vectors for the negative class:
```
np.sum(similarity_c1*dual_coef_c1)
```
And here is the sum of
$$\sum_{i \in S^+} \alpha_i y_i \mathbf{x}_i^T \mathbf{x}_{t} $$
where $S^+$ is the set of support vectors for the positive class:
```
np.sum(similarity_c2*dual_coef_c2)
```
We also need the value of the intercept, $w_0$:
```
cls_svc_bin.intercept_
```
For a given test sample, the prediction depends on the sign of the
overall sum, plus the intercept $w_0$. If it is positive, the prediction
will be '6', and if it is negative, the prediction will be '5'.
```
np.sum(similarity_c1*dual_coef_c1) + \
np.sum(similarity_c2*dual_coef_c2) + \
cls_svc_bin.intercept_
```
The SVC can be interpreted as a kind of weighted nearest neighbor, where
each support vector is a “neighbor”, the dot product is the distance
metric, and we weight the contribution of each neighbor to the overall
classification using both the distance and the dual coefficient:
$$\sum_{i\in S} \alpha_i y_i \mathbf{x}_i^T \mathbf{x}_{t}$$
For the test point we chose, we can see the similarity to the five most
important support vectors in each class - the five with the greatest
magnitude of $\alpha_i$.
```
n_sv = 5
sv_c1 = np.argsort(np.abs(dual_coef_c1)).ravel()[-n_sv:]
sv_c2 = np.argsort(np.abs(dual_coef_c2)).ravel()[-n_sv:]
figure = plt.figure(figsize=(15,6));
plt.subplot(2, n_sv+1, 1);
sns.heatmap(np.reshape(X_test_bin[idx_test], (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
plt.title("Test sample\nPredicted: %s\nActual: %s" % (y_pred_bin[idx_test],y_test_bin[idx_test]));
for i, idx in enumerate(sv_c1):
plt.subplot(2, n_sv+1, i+1+1);
sns.heatmap(np.reshape(X_train_bin[idx_support_c1[idx]], (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
plt.axis('off');
plt.title("Similarity: %0.2f\nAlpha: %0.7f\nLabel: %s" % (similarity_c1[idx],
np.abs(dual_coef_c1.ravel()[idx]),
y_train_bin[idx_support_c1[idx]]));
plt.subplot(2, n_sv+1, n_sv+1+1);
sns.heatmap(np.reshape(X_test_bin[idx_test], (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
plt.title("Test sample\nPredicted: %s\nActual: %s" % (y_pred_bin[idx_test],y_test_bin[idx_test]));
for i, idx in enumerate(sv_c2):
plt.subplot(2, n_sv+1, n_sv+i+1+1+1);
sns.heatmap(np.reshape(X_train_bin[idx_support_c2[idx]], (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
plt.axis('off');
plt.title("Similarity: %0.2f\nAlpha: %0.7f\nLabel: %s" % (similarity_c2[idx],
np.abs(dual_coef_c2.ravel()[idx]),
y_train_bin[idx_support_c2[idx]]));
plt.subplots_adjust(hspace=0.35);
plt.show();
```
Can you see why these are the most “important” support vectors?
And, we can see the similarity to the five most similar support vectors
in each class.
```
n_sv = 5
sv_c1 = np.argsort(np.abs(similarity_c1)).ravel()[-n_sv:]
sv_c2 = np.argsort(np.abs(similarity_c2)).ravel()[-n_sv:]
figure = plt.figure(figsize=(15,6));
plt.subplot(2, n_sv+1, 1);
sns.heatmap(np.reshape(X_test_bin[idx_test], (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
plt.title("Test sample\nPredicted: %s\nActual: %s" % (y_pred_bin[idx_test],y_test_bin[idx_test]));
for i, idx in enumerate(sv_c1):
plt.subplot(2, n_sv+1, i+1+1);
sns.heatmap(np.reshape(X_train_bin[idx_support_c1[idx]], (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
plt.axis('off');
plt.title("Similarity: %0.2f\nAlpha: %0.7f\nLabel: %s" % (similarity_c1[idx],
np.abs(dual_coef_c1.ravel()[idx]),
y_train_bin[idx_support_c1[idx]]));
plt.subplot(2, n_sv+1, n_sv+1+1);
sns.heatmap(np.reshape(X_test_bin[idx_test], (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
plt.title("Test sample\nPredicted: %s\nActual: %s" % (y_pred_bin[idx_test],y_test_bin[idx_test]));
for i, idx in enumerate(sv_c2):
plt.subplot(2, n_sv+1, n_sv+i+1+1+1);
sns.heatmap(np.reshape(X_train_bin[idx_support_c2[idx]], (28,28)), cmap=plt.cm.gray,
xticklabels=False, yticklabels=False, cbar=False);
plt.axis('off');
plt.title("Similarity: %0.2f\nAlpha: %0.7f\nLabel: %s" % (similarity_c2[idx],
np.abs(dual_coef_c2.ravel()[idx]),
y_train_bin[idx_support_c2[idx]]));
plt.subplots_adjust(hspace=0.35);
plt.show();
```
The support vector classifier at first seems a lot like the logistic
regression, because it also learns a linear decision boundary. But, with
the correlation interpretation, you can think of it as a kind of nearest
neighbor classifier as well!
| github_jupyter |
# Reinforcement Learning
Let's describe the "taxi problem". We want to build a self-driving taxi that can pick up passengers at one of a set of fixed locations, drop them off at another location, and get there in the quickest amount of time while avoiding obstacles.
Make sure you installed gym in your computer using pip install gym.
The AI Gym lets us create this environment quickly:
```
import gym
import random
random.seed(101)
streets = gym.make("Taxi-v3").env
streets.render()
```
Let's break down what we're seeing here:
- R, G, B, and Y are pickup or dropoff locations.
- The BLUE letter indicates where we need to pick someone up from.
- The MAGENTA letter indicates where that passenger wants to go to.
- The solid lines represent walls that the taxi cannot cross.
- The filled rectangle represents the taxi itself - it's yellow when empty, and green when carrying a passenger.
Our little world here, which we've called "streets", is a 5x5 grid. The state of this world at any time can be defined by:
- Where the taxi is (one of 5x5 = 25 locations)
- What the current destination is (4 possibilities)
- Where the passenger is (5 possibilities: at one of the destinations, or inside the taxi)
So there are a total of 25 x 4 x 5 = 500 possible states that describe our world.
For each state, there are six possible actions:
- Move South, East, North, or West
- Pickup a passenger
- Drop off a passenger
Q-Learning will take place using the following rewards and penalties at each state:
- A successfull drop-off yields +20 points
- Every time step taken while driving a passenger yields a -1 point penalty
- Picking up or dropping off at an illegal location yields a -10 point penalty
Moving across a wall just isn't allowed at all.
Let's define an initial state, with the taxi at location (2, 3), the passenger at pickup location 2, and the destination at location 0:
```
initial_state = streets.encode(1, 3, 2, 0)
streets.s = initial_state
streets.render()
```
Let's examine the reward table for this initial state:
```
streets.P[initial_state]
```
Here's how to interpret this - each row corresponds to a potential action at this state: move South, North, East, or West, pickup, or dropoff. The four values in each row are the probability assigned to that action, the next state that results from that action, the reward for that action, and whether that action indicates a successful dropoff took place.
So for example, moving North from this state would put us into state number 368, incur a penalty of -1 for taking up time, and does not result in a successful dropoff.
So, let's do Q-learning! First we need to train our model. At a high level, we'll train over 10,000 simulated taxi runs. For each run, we'll step through time, with a 10% chance at each step of making a random, exploratory step instead of using the learned Q values to guide our actions.
```
import numpy as np
q_table = np.zeros([streets.observation_space.n, streets.action_space.n])
learning_rate = 0.1
discount_factor = 0.6
exploration = 0.1
epochs = 10000
for taxi_run in range(epochs):
state = streets.reset()
done = False
while not done:
random_value = random.uniform(0, 1)
if (random_value < exploration):
action = streets.action_space.sample() # Explore a random action
else:
action = np.argmax(q_table[state]) # Use the action with the highest q-value
next_state, reward, done, info = streets.step(action)
prev_q = q_table[state, action]
next_max_q = np.max(q_table[next_state])
new_q = (1 - learning_rate) * prev_q + learning_rate * (reward + discount_factor * next_max_q)
q_table[state, action] = new_q
state = next_state
```
So now we have a table of Q-values that can be quickly used to determine the optimal next step for any given state! Let's check the table for our initial state above:
```
q_table[initial_state]
```
The lowest q-value here corresponds to the action "go West", which makes sense - that's the most direct route toward our destination from that point. It seems to work! Let's see it in action!
```
from IPython.display import clear_output
from time import sleep
for tripnum in range(1, 11):
state = streets.reset()
done = False
trip_length = 0
while not done and trip_length < 25:
action = np.argmax(q_table[state])
next_state, reward, done, info = streets.step(action)
clear_output(wait=True)
print("Trip number " + str(tripnum) + " Step " + str(trip_length))
print(streets.render(mode='ansi'))
sleep(.5)
state = next_state
trip_length += 1
sleep(2)
```
## Your Challenge
Modify the block above to keep track of the total time steps, and use that as a metric as to how good our Q-learning system is. You might want to increase the number of simulated trips, and remove the sleep() calls to allow you to run over more samples.
Now, try experimenting with the hyperparameters. How low can the number of epochs go before our model starts to suffer? Can you come up with better learning rates, discount factors, or exploration factors to make the training more efficient? The exploration vs. exploitation rate in particular is interesting to experiment with.
| github_jupyter |
# MadMiner particle physics tutorial
# Appendix 2: Ensemble methods
Johann Brehmer, Felix Kling, Irina Espejo, and Kyle Cranmer 2018-2019
## (UNDER CONSTRUCTION)
Instead of using a single neural network to estimate the likelihood ratio, score, or Fisher information, we can use an ensemble of such estimators. That provides us with a more reliable mean prediction as well as a measure of the uncertainty. The class `madminer.ml.EnsembleForge` automates this process. Currently, it only supports SALLY estimators:
```
estimators = [ScoreEstimator(n_hidden=(20,)) for _ in range(5)]
ensemble = Ensemble(estimators)
```
### Training
The `EnsembleForge` object has very similar functions as `MLForge`. In particular, we can train all estimators simultaneously with `train_all()` and save the ensemble to files:
```
ensemble.train_all(
method='sally',
x='data/samples/x_train.npy',
t_xz='data/samples/t_xz_train.npy',
n_epochs=5,
)
ensemble.save('models/sally_ensemble')
```
### Evaluation
We can evaluate the ensemble similarly to the individual networks. Let's stick to the estimation of the Fisher information. There are two different ways to take the ensemble average:
- `mode='information'`: We can calculate the Fisher information for each estimator in the ensemble, and then take the mean and the covariance over the ensemble. This has the advantage that it provides a direct measure of the uncertainty of the prediction.
- `mode='score'`: We can calculate the score for each event and estimator, take the ensemble mean for the score of each event, and then calculate the Fisher information based on the mean scores. This is expected to be more precise (since the score estimates will be more precise, and the nonlinearity in the Fisher info calculation amplifies any error in the score estimation). But calculating the covariance in this approach is computationally not feasible, so there will be no error bands.
By default, MadMiner uses the 'score' mode. Here we will use the 'information' mode just to show the nice uncertainty bands we get.
```
fisher = FisherInformation('data/madminer_example_shuffled.h5')
fisher_information_mean, fisher_information_covariance = fisher.calculate_fisher_information_full_detector(
theta=[0.,0.],
model_file='models/sally_ensemble',
luminosity=3000000.,
mode='information'
)
```
The covariance can be propagated to the Fisher distance contour plot easily:
```
_ = plot_fisher_information_contours_2d(
[fisher_information_mean],
[fisher_information_covariance],
xrange=(-1,1),
yrange=(-1,1)
)
```
| github_jupyter |
# Лекция 15 "Структуры данных: деревья"
### Финансовый университет при Правительстве РФ, лектор С.В. Макрушин
Дерево - связный ациклический граф.
Представление деревьев: а – иерархическая структура, б – множества, в – линейное представление

* __Граф__ (или сеть) состоит из: вершин или узлов (vertice, node) и ребер или дуг или связей (edge, arc, link).
* __Путь__ - упорядоченный список узлов, связанных друг с другом.
* __Дочерние узлы__ (children) - все узлы имеющие входящие связи от некоторого узла, называются дочерними узлами данного узла.
* __Родитель__ (parent) - узел, исходящая связь которого соединена с данным узлом.
* __Сиблинги__ (sibling) - узлы, являющиеся дочерними узлами родителя данного узла.
* __Корень__ (root) — узел дерева, не имеющий родитетеля.
* __Лист__ (leaf node) (или терминальный узел) — узел, не имеющий дочерних узлов.
* __Внутренний узел__ — любой узел дерева, имеющий дочерние узлы, и таким образом, не являющийся листовым узлом.
* __Уровень (level) узла__ - длина пути от корня до данного узла. Уровень корня по определению равен 0.
* __Высота дерева__ (height) - максимальный уровень среди узлов дерева.
* __Поддерво__ (subtree) - множество узлов и связей включающее родителя и всех его потомков.
## Знакомство с бинарными деревьями
Двоичное (бинарное) дерево (binary tree) — иерархическая структура данных, в которой каждый узел имеет не более двух потомков (детей). Обычно, первый называется родительским узлом, а дети называются левым и правым наследниками.
Пример небольшого бинарного дерева.

Среди бинарных деревьев отдельно выделяют __полные бинарные деревья__, все вершины которых имеют по две дочерних, кроме листьев, которые расположены на одинаковой глубине:

Также полными часто называют бинарные деревья, у которых полностью заполнены _все уровни, кроме последнего_ :

```
# Представление бинарного дерева в виде списка списков:
my_tree = \
['a', #root
['b', #left subtree
['d', [], []],
['e', [], []] ],
['c', #right subtree
['f', [], []],
[] ]
]
```
Пример API (application programming interface) для работы с двоичными деревьями:
* `BinaryTree()` - создание нового экземпляра бинарного дерева.
* `get_left_child()` - возвращает бинарное дерево связанное с левым дочерним узлом рассматриваемого узла.
* `get_right_child()` - возвращает бинарное дерево связанное с правым дочерним узлом рассматриваемого узла.
* `get_root_val()` - возвращает объект, хранящийся в данном узле.
* `set_root_val(val)` - сохраняет объект, хранящийся в данном узле.
* `insert_left(val)` - создает новое бинарное дерево связанное с левым дочерним узлом рассматриваемого узла.
* `insert_right(val)` - создает новое бинарное дерево связанное с правым дочерним узлом рассматриваемого узла.
```
print(my_tree)
print('left subtree = ', my_tree[1])
print('root = ', my_tree[0])
print('right subtree = ', my_tree[2])
# Пример реализации функции insert_left для представления бинарного дерева в виде списка списков:
def insert_left(root, new_branch):
t = root.pop(1)
if len(t) > 1:
root.insert(1, [new_branch, t, []])
else:
root.insert(1, [new_branch, [], []])
return root
insert_left(my_tree[2], 'H')
```
Пример представления бинарного дерева в виде узлов и ссылок:

```
# Фрагмент реализации бинарного дерева с помощью представления в виде узлов и ссылок:
class BinaryTree:
def __init__(self, root):
self.key = root
self.left_child = None
self.right_child = None
def insert_left(self,new_node):
if self.left_child == None:
self.left_child = BinaryTree(new_node)
else:
t = BinaryTree(new_node)
t.left_child = self.left_child
self.left_child = t
def insert_right(self,new_node):
if self.right_child == None:
self.right_child = BinaryTree(new_node)
else:
t = BinaryTree(new_node)
t.right_child = self.right_child
self.right_child = t
def get_right_child(self):
return self.right_child
def get_left_child(self):
return self.left_child
def set_root_val(self,obj):
self.key = obj
def get_root_val(self):
return self.key
def __str__(self):
return '{} ({}, {})'.format(self.get_root_val(), str(self.get_left_child()), str(self.get_right_child()))
r = BinaryTree('a')
print(r)
r.insert_left('b')
print(r)
print(r.get_left_child())
print(r.get_left_child().get_root_val())
r.insert_right('c')
print(r)
print(r.get_right_child())
print(r.get_right_child().get_root_val())
print(r.get_right_child().get_root_val())
print(r)
r.insert_right('f')
print(r)
```
## Использование бинарных деревьев в прикладных задачах
Двоичные деревья можно использовать для разбора (parsing) различных выражений. Рассмотрим, например, представления математического выражения ((7 + 3) * (5 − 2)) в виде двоичного дерева.
Представление математического выражения ((7 + 3) * (5 − 2)) в виде двоичного дерева:

Представление выражения (предложения) в виде дерева позволяет удобно работать с частями выражения как с поддервеьями или родительским и дочерним узлов (пример на рис.):

Для испльзования древовидного представления выражения необходимо решить следующие задачи:
* построить древововидное представление выражения в результате разбора математического выражения.
* вычислить математиченское выражение, представленное в виде двоичного дерева.
* восстановить исходное математическое выражение из дрвеовидного представления.
Алгоритм разбора математического выражения для получения его древовидного представления:
1. Если текущий токен ‘(’, то добавляем новый узел в качестве левого дочернего узла текущего узла и спускаемся в новый узел.
2. Если текущий токен содержится в списке [‘+’,‘−’,‘/’,‘*’], то устанавливаем значение в текущем узле, соответствующее оператору, представленному в токене. Добавляем новый узел в качестве правого дочернего узла текущего узла и спускаемся в него.
3. Если текущий токен является числом, то устанавливаем значение в текущем узле соответствующее числу в токене и переходим к родительскому узлу.
4. Если текущий токен ‘)’, то переходим к родителю текущего узла.
Разбор математического выражения (3 + (4 \* 5)) или [‘(’, ‘3’, ‘+’, ‘(’, ‘4’, ‘*’, ‘5’ ,‘)’, ‘)’] и построение на его основе двоичного дерева:
<img src="m_tree_3.png" alt="Drawing" style="width: 300px;"/>
Для вычисления значения выражения имеющего древовидное представление достаточно реализовать простую рекурсивную функцию.
Представление документа (книги) как дерева:

## Обход (traversing/walk) бинарных деревьев
Прямой (preorder) порядок обхода дерева:
1. Первым просматривается корневой узел
2. Затем производится рекурсивный прямой обход левого поддерева.
3. Затем производится рекурсивный прямой обход правого поддерева.

Обратный (postorder) порядок обхода дерева:
1. Первым производится рекурсивный обратный обход левого поддерева.
2. Затем производится рекурсивный обратный обход правого поддерева.
3. Затем просматривается корневой узел

Симметричный (inorder) порядок обхода дерева:
1. Первым производится рекурсивный симметричный обход левого поддерева.
2. Затем просматривается корневой узел
3. Затем производится рекурсивный симметричный обход правого поддерева.

## Двоичное дерево поиска
Двоичное дерево поиска (binary search tree, BST) — это двоичное дерево, для которого выполняются следующие дополнительные условия (свойства дерева поиска):
1. Оба поддерева — левое и правое — являются двоичными деревьями поиска.
2. У всех узлов левого поддерева произвольного узла X значения ключей данных меньше, нежели значение ключа данных самого узла X.
3. У всех узлов правого поддерева произвольного узла X значения ключей данных больше либо равно, нежели значение ключа данных самого узла X.
Очевидно, данные в каждом узле должны обладать ключами, на которых определена операция сравнения (например, операция меньше).
Пример двоичного дерва поиска:

Основные операции в бинарном дереве поиска выполняются за время, __пропорциональное его высоте__. Для полного бинарного дерева с $n$ узлами эти операции выполняются за время $O(\ln n)$ в наихудшем
случае. Математическое ожидание высоты построенного случайным образом бинарного дерева равно $О (\ln n)$, так что все основные операции динамическим множеством в таком дереве выполняются в среднем за
время $\Theta (\ln n)$.
На практике мы не всегда можем гарантировать случайность построения бинарного дерева поиска, однако имеются версии деревьев, в
которых гарантируется хорошее время работы в наихудшем случае.
Речь идет о деревьях сбалансированных по высоте по определенным критериям, это:
* АВЛ –деревья
* 2-3, 3-4 деревья
* красно-черные деревья
высота которых определяется как $О (\ln n)$.
Алгоритм вставки нового узла в двоичное дерево поиска:
1. Начинаем просмотр с корня деерва (первый текущий узел - корень).
2. Сравниваем значение нового узла со значением в текущем узле. Если значение в новом узле меньше, то продолжаем поиск в левом поддереве (текущим узлом становется левый дочерений узел предыдущего текущего узла). Если значение в новом узле больше чем в текущем узле, то продолжаем поиск в правом поддереве.
3. Если левого или правого поддерва не существует, то мы обнаружили место для вставки нвого элемента. На это место вставляется новый узел дерева.
Пример вставки узла в двоичное дерево поиска:

```
# Приер реализации поика элемента в двоичном дереве поиска:
def get(self,key):
if self.root:
res = self._get(key, self.root)
if res:
return res.payload
else:
return None
else:
return None
def _get(self, key, current_node):
if not current_node:
return None
elif current_node.key == key:
return current_node
elif key < current_node.key:
return self._get(key, current_node.left_child)
else:
return self._get(key, current_node.right_child)
def __getitem__(self, key):
return self.get(key)
def __contains__(self, key):
if self._get(key, self.root):
return True
else:
return False
```
Наиболее сложной операцией является удаление узла из дерева:
Шаг 1. При помощи поиска по дереву найти узел который нужно удалить.
Шаг 2. После обнаружения узла существует три случая, которые требуют специфической реализации операции удаления узла.
Случай 1. Удаляемый узел не имеет потомков:

Случай 2. Удаляемый узел имеет только одного потомка:

1. Если текущий узел является левым дочерним узлом, то у его дочернего узла нужно обновить ссылку на родителя, так, чтобы она вела на родителя текущего узла. Связь родителя текущего узла с левым дочерним узлом изменится так, что он будет ссылался на дочерний узел текущего узла.
2. Если текущий узел является правым дочерним узлом, то у его дочернего узла нужно обновить ссылку на родителя, так, чтобы она вела на родителя текущего узла. Связь родителя текущего узла с правым дочерним узлом изменится так, что он будет ссылался на дочерний узел текущего узла.
3. Если у текущего узла нет родительского узла (т.е. он является корневым узлом), то его единственный потомок станет новым корневым узлом.
Случай 3. Удаляемый узел имеет двух потомков:

Если у удаляемого узла Z два дочерних узла, то мы находим следующий за ним по величине узел Y, у которого не более одного дочернего узла и убираем его из позиции, где он находился ранее, путем создания новой связи между его родителем и потомком, и заменяем им узел Z.
Поиск Y осуществляется следующим образом:
1. Переходим из Z в его правое поддерево.
2. Двигаемся вниз по левому поддерву, пока не встретим узел Y, у котрого нет левого дочернего узла (у Y может быть только один правый дочерний элемент, либо может не быть дочерних элементов вовсе). Y - искомый узел.
Пример неэффективного двоичного дерева поиска:

Алгоритм вставки в бинарное дерево, который мы только что
рассмотрели, дает хорошие результаты при использовании случайных
входных данных, но все же существует неприятная возможность того,
что при этом будет построено вырожденное дерево. Можно было бы
разработать алгоритм, поддерживающий дерево в оптимальном состоянии все время, где под оптимальностью мы в данном случае понимаем сбалансированность дерева.
Идеально сбалансированным
называется дерево, у которого для каждой вершины выполняется требование: число вершин в левом и правом поддеревьях различается не
более чем на 1.
Поддержка идеальной сбалансированности, к сожалению, очень сложная задача. Другая идея заключается в том, чтобы
ввести менее жесткие критерии сбалансированности и на их основе
предложить достаточно простые алгоритмы обеспечения этих критериев.
## Двоичные кучи и очереди с приоритетом
Двоичная куча (пирамида) (binary heap) — такое двоичное дерево, для которого выполнены три условия:
1. Значение в любой вершине не больше, чем значения её потомков.
2. Уровень всех листьев (расстояние до корня) отличается не более чем на 1.
3. Последний уровень заполняется слева направо без «дырок».
Пример двоичной кучи:

Для гарантированной логарифмической производительности мы дложны поддержвать двоичную кучу в виде сбалансированного дерева. Для этого мы будем строить двоичную кучу в виде полного бинарного дерева - дерева в котором каждый уровень кроме последнего содержит все возможные узлы, а последний уровень заполняется с лева на право без пропусков.
Пример двоичной кучи и ее представления в виде списка:

Важным свойством полного бинарного дерева является то, что такое дерево может быть представленно в виде одного списка. Левый потомок родителя (имеющего индекс p) является элеменотом списка с индексом 2p. Аналогично, правый потомок является элеменотом списка с индексом 2p + 1. Для того, чтобы найти индекс родительского узла нужно взять целую часть от индекса элемента, разделенного на 2.
Базовые операции для двоичной кучи:
* `BinaryHeap()` - создает новую пустую бинарную кучу
* `insert(k)` - добавить элемент в кучу, cложность $ O(\log {n})$
* `find_min()` - возввратить минимальный элемент в куче, сложность $ O(1)$
* `del_min()` - возввратить минимальный элемент и исключить его из кучи, cложность $ O(\log {n})$
* `is_empty()` - возвращает True если куча пуста и False в обратном случае
* `size()` - количество элементов в куче
* `build_heap(list)` - создает новую кучу на основе произвольного (не упроядоченного) массива, сложность $O(n)$
Отсортировать массив путём превращения его в кучу, а кучи в отсортированный массив. Время работы $O(n\log {n})$
```
class BinHeap:
def __init__(self):
self.heap_list = [0]
self.current_size = 0
```
Вставка нового узла и просачивание его наверх:

```
class BinHeap:
def __init__(self):
self.heap_list = [0]
self.current_size = 0
def insert(self, k):
self.heap_list.append(k)
self.current_size = self.current_size + 1
perc_up(self, self.current_size)
def perc_up(self, i):
while i // 2 > 0:
if self.heap_list[i] < self.heap_list[i // 2]:
tmp = self.heap_list[i // 2]
self.heap_list[i // 2] = self.heap_list[i]
self.heap_list[i] = tmp
else:
break
i = i // 2
```
Реализация метода `del_min`:
Свойства кучи требуют, чтобы корень дерева был наименьшим элементом в дереве. Таким образом найти наименьший элемент просто.
Сложной частью операции `del_min` является восстановление корректной структуры кучи и ее свойств после удаления корневого элемента.
1. Мы восстановим корневой элемент установив на его место элемент, изъятый из последней позиции кучи (последний элемент в представлении кучи в виде списка). Таким образом будет получена корректная структура дерева для кучи, но при этом может быть нарушено правило порядка расположения элементов в куче.
2. Восстановление порядка элементов в куче будет выполнено за счет "проталкивания" нового корневого элемента на корректную позицию. При "проталкивании" элемент при необходимости будет опускаться на место своего наименьшего потомка.
Удаление корневого элемента и просачивание нового значения вниз:

```
def perc_down(self, i):
while (i * 2) <= self.current_size:
mc = min_child(self, i)
if self.heap_list[i] > self.heap_list[mc]:
tmp = self.heap_list[i]
self.heap_list[i] = self.heap_list[mc]
self.heap_list[mc] = tmp
else:
break
i = mc
def min_child(self, i):
if i * 2 + 1 > self.current_size:
return i * 2
else:
if self.heap_list[i * 2] < self.heap_list[i * 2 + 1]:
return i * 2
else:
return i * 2 + 1
class BinHeap:
def __init__(self):
self.heap_list = [0]
self.current_size = 0
def insert(self, k):
self.heap_list.append(k)
self.current_size = self.current_size + 1
perc_up(self, self.current_size)
def del_min(self):
ret_val = self.heap_list[1]
self.heap_list[1] = self.heap_list[self.current_size]
self.current_size = self.current_size - 1
self.heap_list.pop()
perc_down(self, 1)
return ret_val
def build_heap(self, a_list):
i = len(a_list) // 2
self.current_size = len(a_list)
self.heap_list = [0] + a_list[:]
while (i > 0):
self.perc_down(i)
i = i - 1
```
| github_jupyter |
TSG068 - Show BDC HDFS status
=============================
Steps
-----
### Common functions
Define helper functions used in this notebook.
```
# Define `run` function for transient fault handling, hyperlinked suggestions, and scrolling updates on Windows
import sys
import os
import re
import json
import platform
import shlex
import shutil
import datetime
from subprocess import Popen, PIPE
from IPython.display import Markdown
retry_hints = {} # Output in stderr known to be transient, therefore automatically retry
error_hints = {} # Output in stderr where a known SOP/TSG exists which will be HINTed for further help
install_hint = {} # The SOP to help install the executable if it cannot be found
first_run = True
rules = None
debug_logging = False
def run(cmd, return_output=False, no_output=False, retry_count=0):
"""Run shell command, stream stdout, print stderr and optionally return output
NOTES:
1. Commands that need this kind of ' quoting on Windows e.g.:
kubectl get nodes -o jsonpath={.items[?(@.metadata.annotations.pv-candidate=='data-pool')].metadata.name}
Need to actually pass in as '"':
kubectl get nodes -o jsonpath={.items[?(@.metadata.annotations.pv-candidate=='"'data-pool'"')].metadata.name}
The ' quote approach, although correct when pasting into Windows cmd, will hang at the line:
`iter(p.stdout.readline, b'')`
The shlex.split call does the right thing for each platform, just use the '"' pattern for a '
"""
MAX_RETRIES = 5
output = ""
retry = False
global first_run
global rules
if first_run:
first_run = False
rules = load_rules()
# When running `azdata sql query` on Windows, replace any \n in """ strings, with " ", otherwise we see:
#
# ('HY090', '[HY090] [Microsoft][ODBC Driver Manager] Invalid string or buffer length (0) (SQLExecDirectW)')
#
if platform.system() == "Windows" and cmd.startswith("azdata sql query"):
cmd = cmd.replace("\n", " ")
# shlex.split is required on bash and for Windows paths with spaces
#
cmd_actual = shlex.split(cmd)
# Store this (i.e. kubectl, python etc.) to support binary context aware error_hints and retries
#
user_provided_exe_name = cmd_actual[0].lower()
# When running python, use the python in the ADS sandbox ({sys.executable})
#
if cmd.startswith("python "):
cmd_actual[0] = cmd_actual[0].replace("python", sys.executable)
# On Mac, when ADS is not launched from terminal, LC_ALL may not be set, which causes pip installs to fail
# with:
#
# UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 4969: ordinal not in range(128)
#
# Setting it to a default value of "en_US.UTF-8" enables pip install to complete
#
if platform.system() == "Darwin" and "LC_ALL" not in os.environ:
os.environ["LC_ALL"] = "en_US.UTF-8"
# When running `kubectl`, if AZDATA_OPENSHIFT is set, use `oc`
#
if cmd.startswith("kubectl ") and "AZDATA_OPENSHIFT" in os.environ:
cmd_actual[0] = cmd_actual[0].replace("kubectl", "oc")
# To aid supportabilty, determine which binary file will actually be executed on the machine
#
which_binary = None
# Special case for CURL on Windows. The version of CURL in Windows System32 does not work to
# get JWT tokens, it returns "(56) Failure when receiving data from the peer". If another instance
# of CURL exists on the machine use that one. (Unfortunately the curl.exe in System32 is almost
# always the first curl.exe in the path, and it can't be uninstalled from System32, so here we
# look for the 2nd installation of CURL in the path)
if platform.system() == "Windows" and cmd.startswith("curl "):
path = os.getenv('PATH')
for p in path.split(os.path.pathsep):
p = os.path.join(p, "curl.exe")
if os.path.exists(p) and os.access(p, os.X_OK):
if p.lower().find("system32") == -1:
cmd_actual[0] = p
which_binary = p
break
# Find the path based location (shutil.which) of the executable that will be run (and display it to aid supportability), this
# seems to be required for .msi installs of azdata.cmd/az.cmd. (otherwise Popen returns FileNotFound)
#
# NOTE: Bash needs cmd to be the list of the space separated values hence shlex.split.
#
if which_binary == None:
which_binary = shutil.which(cmd_actual[0])
if which_binary == None:
if user_provided_exe_name in install_hint and install_hint[user_provided_exe_name] is not None:
display(Markdown(f'HINT: Use [{install_hint[user_provided_exe_name][0]}]({install_hint[user_provided_exe_name][1]}) to resolve this issue.'))
raise FileNotFoundError(f"Executable '{cmd_actual[0]}' not found in path (where/which)")
else:
cmd_actual[0] = which_binary
start_time = datetime.datetime.now().replace(microsecond=0)
print(f"START: {cmd} @ {start_time} ({datetime.datetime.utcnow().replace(microsecond=0)} UTC)")
print(f" using: {which_binary} ({platform.system()} {platform.release()} on {platform.machine()})")
print(f" cwd: {os.getcwd()}")
# Command-line tools such as CURL and AZDATA HDFS commands output
# scrolling progress bars, which causes Jupyter to hang forever, to
# workaround this, use no_output=True
#
# Work around a infinite hang when a notebook generates a non-zero return code, break out, and do not wait
#
wait = True
try:
if no_output:
p = Popen(cmd_actual)
else:
p = Popen(cmd_actual, stdout=PIPE, stderr=PIPE, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
line = line.decode()
if return_output:
output = output + line
else:
if cmd.startswith("azdata notebook run"): # Hyperlink the .ipynb file
regex = re.compile(' "(.*)"\: "(.*)"')
match = regex.match(line)
if match:
if match.group(1).find("HTML") != -1:
display(Markdown(f' - "{match.group(1)}": "{match.group(2)}"'))
else:
display(Markdown(f' - "{match.group(1)}": "[{match.group(2)}]({match.group(2)})"'))
wait = False
break # otherwise infinite hang, have not worked out why yet.
else:
print(line, end='')
if rules is not None:
apply_expert_rules(line)
if wait:
p.wait()
except FileNotFoundError as e:
if install_hint is not None:
display(Markdown(f'HINT: Use {install_hint} to resolve this issue.'))
raise FileNotFoundError(f"Executable '{cmd_actual[0]}' not found in path (where/which)") from e
exit_code_workaround = 0 # WORKAROUND: azdata hangs on exception from notebook on p.wait()
if not no_output:
for line in iter(p.stderr.readline, b''):
try:
line_decoded = line.decode()
except UnicodeDecodeError:
# NOTE: Sometimes we get characters back that cannot be decoded(), e.g.
#
# \xa0
#
# For example see this in the response from `az group create`:
#
# ERROR: Get Token request returned http error: 400 and server
# response: {"error":"invalid_grant",# "error_description":"AADSTS700082:
# The refresh token has expired due to inactivity.\xa0The token was
# issued on 2018-10-25T23:35:11.9832872Z
#
# which generates the exception:
#
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 179: invalid start byte
#
print("WARNING: Unable to decode stderr line, printing raw bytes:")
print(line)
line_decoded = ""
pass
else:
# azdata emits a single empty line to stderr when doing an hdfs cp, don't
# print this empty "ERR:" as it confuses.
#
if line_decoded == "":
continue
print(f"STDERR: {line_decoded}", end='')
if line_decoded.startswith("An exception has occurred") or line_decoded.startswith("ERROR: An error occurred while executing the following cell"):
exit_code_workaround = 1
# inject HINTs to next TSG/SOP based on output in stderr
#
if user_provided_exe_name in error_hints:
for error_hint in error_hints[user_provided_exe_name]:
if line_decoded.find(error_hint[0]) != -1:
display(Markdown(f'HINT: Use [{error_hint[1]}]({error_hint[2]}) to resolve this issue.'))
# apply expert rules (to run follow-on notebooks), based on output
#
if rules is not None:
apply_expert_rules(line_decoded)
# Verify if a transient error, if so automatically retry (recursive)
#
if user_provided_exe_name in retry_hints:
for retry_hint in retry_hints[user_provided_exe_name]:
if line_decoded.find(retry_hint) != -1:
if retry_count < MAX_RETRIES:
print(f"RETRY: {retry_count} (due to: {retry_hint})")
retry_count = retry_count + 1
output = run(cmd, return_output=return_output, retry_count=retry_count)
if return_output:
return output
else:
return
elapsed = datetime.datetime.now().replace(microsecond=0) - start_time
# WORKAROUND: We avoid infinite hang above in the `azdata notebook run` failure case, by inferring success (from stdout output), so
# don't wait here, if success known above
#
if wait:
if p.returncode != 0:
raise SystemExit(f'Shell command:\n\n\t{cmd} ({elapsed}s elapsed)\n\nreturned non-zero exit code: {str(p.returncode)}.\n')
else:
if exit_code_workaround !=0 :
raise SystemExit(f'Shell command:\n\n\t{cmd} ({elapsed}s elapsed)\n\nreturned non-zero exit code: {str(exit_code_workaround)}.\n')
print(f'\nSUCCESS: {elapsed}s elapsed.\n')
if return_output:
return output
def load_json(filename):
"""Load a json file from disk and return the contents"""
with open(filename, encoding="utf8") as json_file:
return json.load(json_file)
def load_rules():
"""Load any 'expert rules' from the metadata of this notebook (.ipynb) that should be applied to the stderr of the running executable"""
# Load this notebook as json to get access to the expert rules in the notebook metadata.
#
try:
j = load_json("tsg068-azdata-bdc-hdfs-status.ipynb")
except:
pass # If the user has renamed the book, we can't load ourself. NOTE: Is there a way in Jupyter, to know your own filename?
else:
if "metadata" in j and \
"azdata" in j["metadata"] and \
"expert" in j["metadata"]["azdata"] and \
"expanded_rules" in j["metadata"]["azdata"]["expert"]:
rules = j["metadata"]["azdata"]["expert"]["expanded_rules"]
rules.sort() # Sort rules, so they run in priority order (the [0] element). Lowest value first.
# print (f"EXPERT: There are {len(rules)} rules to evaluate.")
return rules
def apply_expert_rules(line):
"""Determine if the stderr line passed in, matches the regular expressions for any of the 'expert rules', if so
inject a 'HINT' to the follow-on SOP/TSG to run"""
global rules
for rule in rules:
notebook = rule[1]
cell_type = rule[2]
output_type = rule[3] # i.e. stream or error
output_type_name = rule[4] # i.e. ename or name
output_type_value = rule[5] # i.e. SystemExit or stdout
details_name = rule[6] # i.e. evalue or text
expression = rule[7].replace("\\*", "*") # Something escaped *, and put a \ in front of it!
if debug_logging:
print(f"EXPERT: If rule '{expression}' satisfied', run '{notebook}'.")
if re.match(expression, line, re.DOTALL):
if debug_logging:
print("EXPERT: MATCH: name = value: '{0}' = '{1}' matched expression '{2}', therefore HINT '{4}'".format(output_type_name, output_type_value, expression, notebook))
match_found = True
display(Markdown(f'HINT: Use [{notebook}]({notebook}) to resolve this issue.'))
print('Common functions defined successfully.')
# Hints for binary (transient fault) retry, (known) error and install guide
#
retry_hints = {'azdata': ['Endpoint sql-server-master does not exist', 'Endpoint livy does not exist', 'Failed to get state for cluster', 'Endpoint webhdfs does not exist', 'Adaptive Server is unavailable or does not exist', 'Error: Address already in use']}
error_hints = {'azdata': [['azdata login', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['The token is expired', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['Reason: Unauthorized', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['Max retries exceeded with url: /api/v1/bdc/endpoints', 'SOP028 - azdata login', '../common/sop028-azdata-login.ipynb'], ['Look at the controller logs for more details', 'TSG027 - Observe cluster deployment', '../diagnose/tsg027-observe-bdc-create.ipynb'], ['provided port is already allocated', 'TSG062 - Get tail of all previous container logs for pods in BDC namespace', '../log-files/tsg062-tail-bdc-previous-container-logs.ipynb'], ['Create cluster failed since the existing namespace', 'SOP061 - Delete a big data cluster', '../install/sop061-delete-bdc.ipynb'], ['Failed to complete kube config setup', 'TSG067 - Failed to complete kube config setup', '../repair/tsg067-failed-to-complete-kube-config-setup.ipynb'], ['Error processing command: "ApiError', 'TSG110 - Azdata returns ApiError', '../repair/tsg110-azdata-returns-apierror.ipynb'], ['Error processing command: "ControllerError', 'TSG036 - Controller logs', '../log-analyzers/tsg036-get-controller-logs.ipynb'], ['ERROR: 500', 'TSG046 - Knox gateway logs', '../log-analyzers/tsg046-get-knox-logs.ipynb'], ['Data source name not found and no default driver specified', 'SOP069 - Install ODBC for SQL Server', '../install/sop069-install-odbc-driver-for-sql-server.ipynb'], ["Can't open lib 'ODBC Driver 17 for SQL Server", 'SOP069 - Install ODBC for SQL Server', '../install/sop069-install-odbc-driver-for-sql-server.ipynb'], ['Control plane upgrade failed. Failed to upgrade controller.', 'TSG108 - View the controller upgrade config map', '../diagnose/tsg108-controller-failed-to-upgrade.ipynb']]}
install_hint = {'azdata': ['SOP063 - Install azdata CLI (using package manager)', '../install/sop063-packman-install-azdata.ipynb']}
```
### Use azdata to show the Big Data Cluster HDFS status
```
run('azdata bdc hdfs status show')
print('Notebook execution complete.')
```
| github_jupyter |
```
# Importation des modules
import pandas as pd
import nltk
nltk.download('punkt')
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer(language='french')
#Affichage de toutes les colonnes
pd.set_option('display.max_columns', 500)
#Importation des données
df = pd.read_csv('data/bdd_complete2.csv', sep = ',', encoding = 'latin-1')
# Echantillon de la base
print(df.shape)
df.sample(5)
# L'objectif est de nettoyer le texte dit par les intervenants. On s'intéresse donc aux colonnes 'Réplique' et 'Didascalie'
df_texte = df[['Réplique', 'Didascalie']]
df_texte.sample(10)
# Première correction : les apostrophes sont codées par '\x92'. On les retire.
# On supprime aussi les codes '<U+0080>' qui sont avant les points d'exclamation
# On remplace les tirets par des espaces
# On met tout en minuscule
df_texte['Réplique'] = df_texte.apply(
lambda row: row.Réplique.replace('\x92', '').replace('<U+0080>', '').replace('-', ' ').lower(),
axis = 1)
df_texte['Didascalie'] = df_texte.apply(
lambda row: str(row.Didascalie).replace('\x92', '').replace('<U+0080>', '').replace('-', ' ').lower(),
axis = 1)
# Séparation des didascalies
import re
def extract_didascalie(str):
li=[]
result = re.search(r'\((.*?)\)',str)
if result !=None:
n=len(result.groups())
for i in range(1,n+1):
a=''.join(result.groups(i))
a=a.replace('(','')
a=a.replace(',','')
a=a.replace(')','')
a=a.replace("'",'')
li.append(a)
return li
def extract_replique(str):
rep=str
li=extract_didascalie(str)
for i in li:
rep=rep.replace(i,"")
rep=rep.replace("()","")
return rep
df_texte['Réplique'] = df_texte.apply(lambda row: extract_replique(row.Réplique), axis = 1)
# On tokenize les chaines de caractère
df_texte['tokenized_replique'] = df_texte.apply(lambda row: nltk.word_tokenize(row.Réplique, language='french'),
axis = 1)
df_texte['tokenized_didascalie'] = df_texte.apply(lambda row: nltk.word_tokenize(row.Didascalie, language='french'),
axis = 1)
# On obtient bien des listes de mots
df_texte.head(10)
# On remplace les nan par des listes vides
df_texte['tokenized_replique'] = df_texte.apply(lambda row: row.tokenized_replique if len(row.tokenized_replique) == 0 or row.tokenized_replique[0] != 'nan' else [], axis = 1)
df_texte['tokenized_didascalie'] = df_texte.apply(lambda row: row.tokenized_didascalie if len(row.tokenized_didascalie) == 0 or row.tokenized_didascalie[0] != 'nan' else [], axis = 1)
# On retire la ponctuation pour le moment
df_texte['tokenized_replique'] = df_texte.apply(lambda row: [word for word in row.tokenized_replique if word.isalpha()],
axis = 1)
df_texte['tokenized_didascalie'] = df_texte.apply(lambda row: [word for word in row.tokenized_didascalie if word.isalpha()],
axis = 1)
# On retire les stopwords
stop_words = set(stopwords.words('french'))
df_texte['tokenized_replique'] = df_texte.apply(lambda row: [word for word in row.tokenized_replique if not word in stop_words],
axis = 1)
df_texte['tokenized_didascalie'] = df_texte.apply(lambda row: [word for word in row.tokenized_didascalie if not word in stop_words],
axis = 1)
# Stemming
df_texte['stemmed_replique'] = df_texte.apply(lambda row: ' '.join([stemmer.stem(word) for word in row.tokenized_replique]),
axis = 1)
df_texte['stemmed_didascalie'] = df_texte.apply(lambda row: ' '.join([stemmer.stem(word) for word in row.tokenized_didascalie]),
axis = 1)
# On repasse les listes en chaines de caractère
df_texte['tokenized_replique'] = df_texte.apply(lambda row: ' '.join(row.tokenized_replique),
axis = 1)
df_texte['tokenized_didascalie'] = df_texte.apply(lambda row: ' '.join(row.tokenized_didascalie),
axis = 1)
df_cleaned = df.copy()
df_cleaned['tokenized_replique'] = df_texte['tokenized_replique']
df_cleaned['tokenized_didascalie'] = df_texte['tokenized_didascalie']
df_cleaned['stemmed_replique'] = df_texte['stemmed_replique']
df_cleaned['stemmed_didascalie'] = df_texte['stemmed_didascalie']
# df_cleaned.to_csv('data/data_cleaned.csv', sep = ',', encoding = 'latin-1')
pd.read_csv('data/data_cleaned.csv', sep = ',', encoding = 'latin-1').sample(10)
```
| github_jupyter |
# Replication of Experiments
This notebook's goal is to attempt to replicate the experiments presented in Arash *et al.* using the ISCXTor2016 dataset provided by the Canadian Institute for Cybersecurity at the University of New Brunswick (CIC-UNB). The experiments in this work are split into Scenario-A and Scenario-B. Scenario-A's goal is to classify traffic samples as Tor or NonTor, while Scenario-B attempts to classify the type of traffic (FTP, browsing, video and audio-streaming, VoIP, chat, mail, and P2P) seen in Tor samples.
Let's begin with Scenario-A.
## Scenario-A
In these experiments, the team uses three machine learning algorithms: ZeroR, C4.5, and k-Nearest Neighbors. The experiments were originally completed in Weka, however they will attempt to be replicated here using the `sklearn` python library.
The `sklearn` models used will be the following:
- ZeroR → DummyClassifier
- C4.5 → DecisionTreeClassifier
- k-Nearest Neighbor → KNeighborsClassifier
```
# DataFrame handling
import pandas as pd
# Models
from sklearn.dummy import DummyClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
# Split data with stratified cv
from sklearn.model_selection import StratifiedKFold
# Encoding of classifications
from sklearn.preprocessing import LabelEncoder
print('Imports complete.')
# Set up a few constants to keep track of
random_state=1
path='../../tor_dataset/Scenario-A/'
dep_var = 'class'
```
### Preprocessing
We have to import the dataset and modify the classification (`y`) so we can hand it to the `sklearn` models.
```
def get_Xy(filename='', verbose=False):
"""
This function takes a filename, loads the data into a dataframe, then separates the classification data
args:
filename => str, path to csv file to be loaded
returns:
list(X,y) => data, classifications
"""
df = pd.read_csv(filename)
if verbose:
print('Before encoding and splitting:')
print(df.head())
# Actual data
X = df.loc[:, df.columns != dep_var]
# Classifications
encoder = LabelEncoder()
y = encoder.fit_transform(df[dep_var])
if verbose:
print('Classification encoding:')
for i in range(len(encoder.classes_)):
print('\t{} => {}'.format(i, encoder.classes_[i]))
print('After encoding and splitting:')
print('X = ')
print(X.head())
print('\ny = ')
print(y[:5])
# X holds the data while y holds the classifications
return X, y
# Demonstration of how the function operates...
X, y = get_Xy(path + 'TimeBasedFeatures-15s-TOR-NonTOR.csv', verbose=True)
# All of the data files
files=['TimeBasedFeatures-15s-TOR-NonTOR.csv',
'TimeBasedFeatures-30s-TOR-NonTOR.csv',
'TimeBasedFeatures-60s-TOR-NonTOR.csv',
'TimeBasedFeatures-120s-TOR-NonTOR.csv']
# Lists for accuracies collected from models
list_dummy = []
list_dt = []
list_knn = []
for file in files:
print('Training for {}...'.format(file), end='')
# Load in the data
X, y = get_Xy(path + file)
# Mean accuracies for each model
mean_dummy = 0 # This is the worst kind of dummy
mean_dt = 0
mean_knn = 0
# 10-fold Stratified Cross-Validation
n_splits = 10
skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=random_state)
for train_idxs, test_idxs in skf.split(X, y):
# Define the training and testing sets
X_train, X_test = X.iloc[train_idxs], X.iloc[test_idxs]
y_train, y_test = y[train_idxs], y[test_idxs]
# Initialize the models
dummy = DummyClassifier(strategy='most_frequent')
dt = DecisionTreeClassifier(random_state=random_state)
knn = KNeighborsClassifier()
# Train the models
dummy.fit(X_train, y_train)
dt.fit(X_train, y_train)
knn.fit(X_train, y_train)
# Evaluate the models
results_dummy = dummy.score(X_test, y_test)
results_dt = dt.score(X_test, y_test)
results_knn = knn.score(X_test, y_test)
# Add the results to the running mean
mean_dummy += results_dummy / (n_splits * 1.0)
mean_dt += results_dt / (n_splits * 1.0)
mean_knn += results_knn / (n_splits * 1.0)
# Push the mean results from all of the splits to the lists
list_dummy.append(mean_dummy)
list_dt.append(mean_dt)
list_knn.append(mean_knn)
print('done')
print('All trainings complete!')
```
### Results
Below are the final results in attempting to replicate Scenario-A's experiments.
```
# Output results
print('File\t\t\t\t\tDummy\tDecision Tree\tk-Nearest Neighbor')
print('-'*82)
for i in range(len(files)):
print('{}\t{:.2f}%\t{:.2f}%\t\t{:.2f}%'.format(files[i], 100*list_dummy[i], 100*list_dt[i], 100*list_knn[i]))
```
If we compare the data we see above with the reported metrics...

...we clearly see that our results match up with the team's. Despite the fact that we are collected just the accuracy here, we can see that the recall and precision are extremely close than what we are reporting above. In the case of ZeroR, we are seeing the accuracy of our model around the middle between ZeroR's recall and precision metrics.
## Scenario-B
In these experiments, the team uses three machine learning algorithms: Random Forest, C4.5, and k-Nearest Neighbors. The experiments were originally completed in Weka, however they will attempt to be replicated here using the `sklearn` python library.
The following `sklearn` models will be used:
- Random Forest → RandomForestClassifier
- C4.5 → DecisionTreeClassifier
- k-Nearest Neighbors → KNeighborsClassifier
*Much of the process here is similar to what is done in Scenario-A. If you have any questions, please refer to Scenario-A first for any clarification*
```
# DataFrame handling
import pandas as pd
# Models
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
# Split data with stratified cv
from sklearn.model_selection import StratifiedKFold
# Encoding of classifications
from sklearn.preprocessing import LabelEncoder
print('Imports complete.')
# Set up a few constants to keep track of
random_state=1
path='../../tor_dataset/Scenario-B/'
dep_var = 'class'
# All of the data files
files=['TimeBasedFeatures-15s-Layer2.csv',
'TimeBasedFeatures-30s-Layer2.csv',
'TimeBasedFeatures-60s-Layer2.csv',
'TimeBasedFeatures-120s-Layer2.csv']
# Lists for accuracies collected from models
list_rf = []
list_dt = []
list_knn = []
for file in files:
print('Training for {}...'.format(file), end='')
# Load in the data
X, y = get_Xy(path + file)
# Mean accuracies for each model
mean_rf = 0 # This is the worst kind of dummy
mean_dt = 0
mean_knn = 0
# 10-fold Stratified Cross-Validation
n_splits = 10
skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=random_state)
for train_idxs, test_idxs in skf.split(X, y):
# Define the training and testing sets
X_train, X_test = X.iloc[train_idxs], X.iloc[test_idxs]
y_train, y_test = y[train_idxs], y[test_idxs]
# Initialize the models
rf = RandomForestClassifier(random_state=random_state)
dt = DecisionTreeClassifier(random_state=random_state)
knn = KNeighborsClassifier()
# Train the models
rf.fit(X_train, y_train)
dt.fit(X_train, y_train)
knn.fit(X_train, y_train)
# Evaluate the models
results_rf = rf.score(X_test, y_test)
results_dt = dt.score(X_test, y_test)
results_knn = knn.score(X_test, y_test)
# Add the results to the running mean
mean_rf += results_rf / (n_splits * 1.0)
mean_dt += results_dt / (n_splits * 1.0)
mean_knn += results_knn / (n_splits * 1.0)
# Push the mean results from all of the splits to the lists
list_rf.append(mean_rf)
list_dt.append(mean_dt)
list_knn.append(mean_knn)
print('done')
print('All trainings complete!')
```
### Results
Below are the final results in attempting to replicate Scenario-B's experiments.
```
# Output results
print('File\t\t\t\t\tRandomForest\tDecision Tree\tk-Nearest Neighbor')
print('-'*82)
for i in range(len(files)):
print('{}\t{:.2f}%\t\t{:.2f}%\t\t{:.2f}%'.format(files[i], 100*list_rf[i], 100*list_dt[i], 100*list_knn[i]))
```
If we compare our results with those from the Arash *et al.* paper...

...we see that our results, once again, line up pretty well with those we are seeing from the previous work. In this circumstance, our `sklearn` models appear to be marginally out-performing the `Weka` models! However, this is not the focus of the research.
Now that we've shown our ability to replicate the models presented in this work, we have the mobility to move on to the main dish, deep learning!
## References
Arash Habibi Lashkari, Gerard Draper-Gil, Mohammad Saiful Islam Mamun and Ali A. Ghorbani, "Characterization of Tor Traffic Using Time Based Features", In the proceeding of the 3rd International Conference on Information System Security and Privacy, SCITEPRESS, Porto, Portugal, 2017.
| github_jupyter |
This notebook is inspired but not limited by *Machine Learning In Action*.
All rights deserved by Diane(Qingyun Hu).
# 1. About kNN
## 1.1 Mechanism of kNN
kNN is a kind of supervised learning. It has no training process. The main idea is to classify an entry by taking the majority vote of it's closest k examples(labeled traning data).
Given a piece of unlabelled data called unknown_x, classify it's class by:
1. Calculate it's distance to all existing labeled data.
3. Find k examples that unknown_x is closest to from the existing labeled data. (For instance, sort by distance then take the first k examples).
3. Take the majority vote of the k examples' class as unknown_x's class.
## 1.2 Pros and Cons
### 1.21 Pros
1. Insensitive to anomalies.
2. High accuracy.
### 1.22 Cons
1. Computationally expensive. To classify one piece of data, it's distance to each known labeled entry has to be calculated.
2. Requires large memory. O(N*M) where N stands for the number of labeled datasets, M stands for the number of unlabeled datasets to be classified.
# 2. Build kNN Classifier Step by Step
```
# Creat demo dataset
from numpy import *
def creatData1():
X = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
y = ['A','A','B','B']
return X, y
X, y = creatData1()
# [Optional] Visualize the demo dataset
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(X[:,0],X[:,1],c=list(map(ord, y)))
list(map(plt.text,X[:,0]+0.01,X[:,1]+0.01,y))
# kNN classifier
from collections import defaultdict
def kNN_classifier(X, y, new_x, k):
# Calculate distances
diffMat = new_x - X
sqDiffMat = diffMat ** 2
distances = (sqDiffMat.sum(1)) ** 0.5
# Classification
kClasses = defaultdict(int)
sortedDistInd = distances.argsort()
for i in sortedDistInd[0:k]:
kClasses[y[i]]
return sorted(kClasses.items(), key=lambda x: x[1], reverse=True)[0][0]
# test case
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
# test case: 1
kNN_classifier(X, y, [0,0], 4)
# test case: 2
kNN_classifier(X, y, [0,0], 5)
# test case: 3
kNN_classifier(X, y, [1,4], 3)
```
# 2. Real World Test Case - Digits Recognition
```
# Data Exploration
from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape
digits.target.shape
digits.data[0] # Each Feature has the same range in this specific problem. That means normalization is not a must when dataset is large enough. Therefore, let's just skip it.
digits.target[0]
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, train_size=0.8)
# Performance Meaturement
from sklearn.metrics import accuracy_score
y_pred = array([kNN_classifier(X=X_train, y=y_train, new_x=i, k=20) for i in X_test])
print("ACC without Normalization: %f" % accuracy_score(y_true=y_test, y_pred=y_pred))
```
# 3. Misc.
## 3.1 See if Normalization make any difference
```
# See if Normalization make any difference
from sklearn.preprocessing import MinMaxScaler
y_pred = array([kNN_classifier(X=MinMaxScaler().fit_transform(X_train), y=y_train, new_x=i, k=20) for i in MinMaxScaler().fit_transform(X_test)])
print("ACC with Normalization: %f" % accuracy_score(y_true=y_test, y_pred=y_pred))
```
#### Same!!!
## 3.2 Implement with sklearn.neighbors.KNeighborsClassifier
```
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors=20)
classifier.fit(X_train, y_train)
# classifier.predict(X_test)
print("ACC with Normalization with sklearn: %f" % classifier.score(X_test,y_test))
```
| github_jupyter |
<a href="https://pymt.readthedocs.io"><img style="float: right" src="images/pymt-logo-header-text.png"></a>
# Dynamically changing a running model
In this tutorial we will learn how to:
* Use the `update_until` method
* The model grid
* Change the input values of a model while it's running
```
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
```
# Create and initialize a model
For this simulation, we'll be using the *Child* model with some non-default parameters.
```
from pymt import MODELS
child = MODELS.Child()
```
Have a look under the *Parameters* help section (you may have to scroll down - it's the section after the citations). The *Parameters* section describes optional keywords that you can pass the the `setup` method. In the previous example we just used defaults. Below we'll see how to set input file parameters programmatically through keywords.
```
config_file, config_dir = child.setup(
grid_node_spacing=750.,
grid_x_size=20000.,
grid_y_size=40000.,
run_duration=1e6,
)
child.initialize(config_file, dir=config_dir)
```
To begin with, we'll advance the model through 10 time steps.
```
for t in tqdm(range(10)):
child.update()
```
Update until some time in the future. Notice that, in this case, we update to a partial time step. Child is fine with this however some other models may not be. For models that can not update to times that are not full time steps, PyMT will advance to the next time step and interpolate values to the requested time.
```
child.update_until(201.5)
child.time
```
Child offers different output variables but we get them in the same way as before.
```
child.output_var_names
```
As before, we can get values of a variable with *get_value* (in whatever units we like).
```
child.get_value("land_surface__elevation", units="cm")
```
We can query each input and output variable. PyMT attaches a dictionary to each component called `var` that provides information about each variable. For instance we can see that `"land_surface__elevation"` has units of meters, is an input and output variable, and is defined on the nodes of grid with id 0.
```
child.var["land_surface__elevation"]
```
Notice that this variable is defined on grid with ID 0. We can get information about this grid through the `grid` attribute.
```
child.grid[0]
```
We can also get grid information through method functions of the model. For example, the number of **nodes** that define each **face** of the grid.
```
child.grid_nodes_per_face(0)
```
If we plot this variable, we can see the unsructured triangular grid that Child has decomposed its grid into.
```
child.quick_plot('land_surface__elevation', edgecolors='k', vmin=-200, vmax=200, cmap='BrBG_r')
```
Child initializes it's elevations with random noise centered around 0. We would like instead to give it elevations that have some land and some sea. First we'll get the x and y coordinates for each node along with their elevations.
```
x, y = child.grid_x(0), child.grid_y(0)
z = child.get_value('land_surface__elevation')
```
All nodes above `y=y_shore` will be land, and all nodes below `y=y_shore` will be sea.
```
y_shore = 15000.
z[y < y_shore] -= 100
z[y >= y_shore] += 100
```
We now use the model's **set_value** method to change its current elevation values.
```
child.set_value('land_surface__elevation', z)
```
Just to verify we set things up correctly, we'll create a plot.
```
child.quick_plot('land_surface__elevation', edgecolors='k', vmin=-200, vmax=200, cmap='BrBG_r')
```
To get things going, we'll run the model for 5000 years and see what things look like.
```
child.update_until(5000.)
child.quick_plot("land_surface__elevation", edgecolors="k", vmin=-200, vmax=200, cmap="BrBG_r")
```
## Exercise
We'll have some fun now by adding a simple uplift component. We'll run the component for another 5000 years but this time uplifting a corner of the grid by `dz_dt`. First, use the **get_value** method to create a new array of uplift values.
For this example, make the uplift zero everywhere except for *y>15km* and *x>10km* where it will be *0.02*.
```
# Your code here
```
## Exercise
Now with the uplift, we'll run the component for another 5000 years but this time uplifting a corner of the grid by `dz_dt` every time step.
```
# Your code here
```
We now stop the uplift and run it for an additional 5000 years.
```
for time in tqdm(np.linspace(child.time, child.time + 5000.)):
child.update_until(time)
child.quick_plot("land_surface__elevation", edgecolors="k", vmin=-200, vmax=200, cmap="BrBG_r")
```
| github_jupyter |
# Classifying Fashion-MNIST
Now it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% accuracy. Fashion-MNIST is a set of 28x28 greyscale images of clothes. It's more complex than MNIST, so it's a better representation of the actual performance of your network, and a better representation of datasets you'll use in the real world.
<img src='assets/fashion-mnist-sprite.png' width=500px>
In this notebook, you'll build your own neural network. For the most part, you could just copy and paste the code from Part 3, but you wouldn't be learning. It's important for you to write the code yourself and get it to work. Feel free to consult the previous notebooks though as you work through this.
First off, let's load the dataset through torchvision.
```
import torch
from torchvision import datasets, transforms
import helper
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# Download and load the training data
trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
# Download and load the test data
testset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)
```
Here we can see one of the images.
```
image, label = next(iter(trainloader))
helper.imshow(image[0,:]);
```
## Building the network
Here you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits or log-softmax from the forward pass. It's up to you how many layers you add and the size of those layers.
```
# TODO: Define your network architecture here
```
# Train the network
Now you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.html#loss-functions) ( something like `nn.CrossEntropyLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam`).
Then write the training code. Remember the training pass is a fairly straightforward process:
* Make a forward pass through the network to get the logits
* Use the logits to calculate the loss
* Perform a backward pass through the network with `loss.backward()` to calculate the gradients
* Take a step with the optimizer to update the weights
By adjusting the hyperparameters (hidden units, learning rate, etc), you should be able to get the training loss below 0.4.
```
# TODO: Create the network, define the criterion and optimizer
# TODO: Train the network here
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import helper
# Test out your network!
dataiter = iter(testloader)
images, labels = dataiter.next()
img = images[0]
# Convert 2D image to 1D vector
img = img.resize_(1, 784)
# TODO: Calculate the class probabilities (softmax) for img
ps =
# Plot the image and probabilities
helper.view_classify(img.resize_(1, 28, 28), ps, version='Fashion')
```
| github_jupyter |
# Temperature-dependent solvation free energy and vapor-liquid equilibrium calculations
This ipython notebook calculates temperature-dependent solvation free energy and vapor-liquid equilibrium ratio for a dilue binary mixture at the saturation pressure of the solvent. Read documentation on solvation thermochemistry for detailed method (http://reactionmechanismgenerator.github.io/RMG-Py/users/rmg/liquids.html). Please cite our work in your publication:
Chung, Y. & Gillis R. & Green W. H. (2020). Temperature‐dependent vapor–liquid equilibria and solvation free
energy estimation from minimal data. AIChE J. 2020; 66:e16976
Code written by Yunsie Chung.
```
import os.path
import math
import numpy as np
import matplotlib.pyplot as plt
from CoolProp.CoolProp import PropsSI
from rmgpy import settings
from rmgpy.rmg.main import Species
from rmgpy.data.solvation import SolvationDatabase
%matplotlib inline
solvationDatabase = SolvationDatabase()
solvationDatabase.load(os.path.join(settings['database.directory'], 'solvation'))
```
# Initial setup to get the available solvent list and valid tempertaure range
```
print("Available solvents and their valid temperature ranges for T-dependent solvation calculation are:\n")
for index, entry in solvationDatabase.libraries['solvent'].entries.items():
if entry.data.s_h is not None and entry.data.name_in_coolprop is not None:
Tc = "%.2f" % entry.data.get_solvent_critical_temperature()
print(' - ' + index + ': 280 K - {0} K'.format(Tc))
```
# User Input: Solute SMILES, Solvent Name, and Temperature
```
################# Change these as needed ##########################
solute_smiles = 'CC(C)O' # most of solutes that contain only H, C, N, O, S are available
solvent_name = 'water' # this should one of the solvent name from the list above
temprature = [300, 400, 500, 600] # give temperature(s) in K. This should be within the valid range shown above
###################################################################
# Note: if you have your own Abraham parameters for the solute, add it to
# RMG-database/input/solvation/libraries/solute.py as a new entry, and re-run this ipython notebook.
```
# Run solvation calculations
```
solute = Species().from_smiles(solute_smiles)
solute.generate_resonance_structures()
solute_data = solvationDatabase.get_solute_data(solute)
solvent_data = solvationDatabase.get_solvent_data(solvent_name)
print('Results are given in K-factor (VLE solute mole fraction ratio, y2/x2) and solvation free energy:\n')
for T in temprature:
Kfactor = solvationDatabase.get_Kfactor(solute_data, solvent_data, T)
dGsolv = solvationDatabase.get_T_dep_solvation_energy(solute_data, solvent_data, T) / 1000 # in kJ/mol
print(' At {0} K, K-factor = {1:.3f}, solvation free energy = {2:.2f} kJ/mol'.format(T, Kfactor, dGsolv))
```
# Make useful plots from 280 K up to the critical point of the solvent
```
Tc = solvent_data.get_solvent_critical_temperature() # critical temperature of the solvent in K
temp_list = np.linspace(280, Tc-0.01, 100)
log_Kfactor_list = []
log_KfactorPsat_list = []
dGsolv_list = []
for T in temp_list:
Kfactor = solvationDatabase.get_Kfactor(solute_data, solvent_data, T)
dGsolv = solvationDatabase.get_T_dep_solvation_energy(solute_data, solvent_data, T) / 1000 # in kJ/mol
Psat = PropsSI('P', 'T', T, 'Q', 0, solvent_data.name_in_coolprop) # saturation pressure of the solvent, in Pa
log_Kfactor_list.append(math.log(Kfactor))
log_KfactorPsat_list.append(math.log(Kfactor*Psat*1e-6)) # in ln(1/MPa)
dGsolv_list.append(dGsolv)
fig = plt.figure(figsize=(15, 15))
ax = fig.add_subplot(2, 2, 1)
plt.plot(temp_list, log_Kfactor_list)
plt.title('ln(K-factor)', fontsize=20)
ax.set_xlabel('Temperature (K)', fontsize = 16)
ax.set_ylabel('ln($K_{2,1}^{\infty}$)', fontsize = 16)
ax = fig.add_subplot(2, 2, 2)
plt.plot(temp_list, log_KfactorPsat_list)
plt.title('ln(K-factor * $P^{sat}$)\n$P^{sat}$ = saturation pressure of the solvent', fontsize=20)
ax.set_xlabel('Temperature (K)', fontsize = 16)
ax.set_ylabel('ln($K_{2,1}^{\infty}P^{sat}$/1 MPa)', fontsize = 16)
ax = fig.add_subplot(2, 2, 3)
plt.plot(temp_list, dGsolv_list)
plt.title('Solvation Gibbs Free Energy', fontsize=20)
ax.set_xlabel('Temperature (K)', fontsize = 16)
ax.set_ylabel('Solvation Energy (kJ/mol)', fontsize = 16)
```
| github_jupyter |
```
%load_ext autoreload
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import pymc3 as pm
import numpy as np
import theano.tensor as tt
import theano
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
from pymc3.backends import HDF5, text
%autoreload 2
theano.__version__
```
# Introduction
I'd like to try doing multiclass classification with a deep neural network. The network architecture is a feed-forward network with one hidden layer in between the input and output; `n_hidden` units is a hyperparameter.
# Model Specification
Because neural networks are the highlight here, I will first do the model specification up-front.
```
def make_nn(ann_input, ann_output, n_hidden):
"""
Makes a feed forward neural network with n_hidden layers for doing multi-
class classification.
Feed-forward networks are easy to define, so I have not relied on any
other Deep Learning frameworks to define the neural network here.
"""
init_1 = np.random.randn(ann_input.shape[1], n_hidden)
init_2 = np.random.randn(n_hidden, n_hidden)
init_out = np.random.randn(n_hidden, ann_output.shape[1])
with pm.Model() as nn_model:
# Define weights
weights_1 = pm.Normal(
"w_1", mu=0, sd=1, shape=(ann_input.shape[1], n_hidden), testval=init_1
)
weights_2 = pm.Normal(
"w_2", mu=0, sd=1, shape=(n_hidden, n_hidden), testval=init_2
)
weights_out = pm.Normal(
"w_out", mu=0, sd=1, shape=(n_hidden, ann_output.shape[1]), testval=init_out
)
# Define activations
acts_1 = pm.Deterministic(
"activations_1", tt.tanh(tt.dot(ann_input, weights_1))
)
acts_2 = pm.Deterministic("activations_2", tt.tanh(tt.dot(acts_1, weights_2)))
acts_out = pm.Deterministic(
"activations_out", tt.nnet.softmax(tt.dot(acts_2, weights_out))
) # noqa
# Define likelihood
out = pm.Multinomial("likelihood", n=1, p=acts_out, observed=ann_output)
return nn_model
```
# Preprocess Data
## Basic Cleaning
Now, let's read in the dataset. There's a bunch of preprocessing that has to happen. I happened to have this code written for the IACS 2017 data science bootcamp, and copied it over from there. It's commented out because it takes some time to execute, and if executed once, it needn't be executed again.
```
# df = pd.read_csv('datasets/covtype.data', header=None)
# columns = [
# 'Elevation',
# 'Aspect',
# 'Slope',
# 'Horizontal_Distance_To_Hydrology',
# 'Vertical_Distance_To_Hydrology',
# 'Horizontal_Distance_To_Roadways',
# 'Hillshade_9am',
# 'Hillshade_Noon',
# 'Hillshade_3pm',
# 'Horizontal_Distance_To_Fire_Points'
# ]
# # Add in wilderness area data (binary)
# for i in range(1, 5):
# columns.append('Wilderness_Area_{0}'.format(i))
# # Add in soil type data (binary)
# for i in range(1, 41):
# columns.append('Soil_Type_{0}'.format(i))
# # Add in soil cover type
# columns.append('Cover_Type')
# df.columns = columns
# # Add in soil codes. These were downloaded from the UCI repository.
# soil_codes = pd.read_csv('datasets/climatic_geologic_zone.csv')
# soil_dict = soil_codes.set_index('soil_type').to_dict()
# # Add geologic and climatic zone code to soil type
# for i in range(1, 41):
# df.loc[df['Soil_Type_{i}'.format(i=i)] == 1, 'Climatic_Zone'] = soil_dict['climatic_zone'][i]
# df.loc[df['Soil_Type_{i}'.format(i=i)] == 1, 'Geologic_Zone'] = soil_dict['geologic_zone'][i]
# # Encode one-of-K for the geologic zone, climatic zone, and cover_type encodings.
# # This is important because the geologic and climatic zones aren't ordinal - they are strictly categorical.
# enc = OneHotEncoder()
# clm_zone_enc = enc.fit_transform(df['Climatic_Zone'].values.reshape(-1, 1)).toarray()
# geo_zone_enc = enc.fit_transform(df['Geologic_Zone'].values.reshape(-1, 1)).toarray()
# cov_type_enc = enc.fit_transform(df['Cover_Type'].values.reshape(-1, 1)).toarray()
# for i in range(clm_zone_enc.shape[1]):
# df['Climatic_Zone_{i}'.format(i=i)] = clm_zone_enc[:, i]
# for i in range(geo_zone_enc.shape[1]):
# df['Geologic_Zone_{i}'.format(i=i)] = geo_zone_enc[:, i]
# del df['Climatic_Zone']
# del df['Geologic_Zone']
# df.to_csv('datasets/covtype_preprocess.csv')
df = pd.read_csv("../datasets/covtype_preprocess.csv", index_col=0)
df.shape
```
Let's now make the X and Y matrices. We use patsy to give us a quick and fast way to turn categorical variables into one-of-K columns.
```
df["Cover_Type"] = df["Cover_Type"].apply(lambda x: str(x))
output_col = "Cover_Type"
input_cols = [c for c in df.columns if c != output_col]
input_formula = "".join(c + " + " for c in input_cols)
input_formula = input_formula + "-1"
import patsy
from sklearn.preprocessing import scale, normalize
X = patsy.dmatrix(formula_like=input_formula, data=df, return_type="dataframe")
# X = normalize(X)
Y = patsy.dmatrix(formula_like="Cover_Type -1", data=df, return_type="dataframe")
print(X.shape, Y.shape)
Y.head()
```
## Balance Classes
We will balance out the classes to make them evenly distributed.
```
from sklearn.preprocessing import MinMaxScaler
downsampled_targets = []
for i in range(1, 7 + 1):
# print(f'target[{i}]')
target = Y[Y["Cover_Type[{i}]".format(i=i)] == 1]
# print(len(target))
downsampled_targets.append(target.sample(2747))
mms = MinMaxScaler()
X_tfm = pm.floatX(mms.fit_transform(X[input_cols]))
Y_downsampled = pd.concat(downsampled_targets)
Y_downsamp = pm.floatX(Y_downsampled)
X_downsampled = X_tfm[Y_downsampled.index]
X_downsamp = pm.floatX(X_downsampled)
X_downsamp.shape
from models.feedforward import ForestCoverModel
fcm = ForestCoverModel(n_hidden=20,)
fcm.fit(X_downsamp, Y_downsamp)
X_downsampled.shape
X_downsamp.dtype
n_hidden = 20 # define the number of hidden units
```
# Model Execution
We now make the model with {{n_hidden}} hidden units.
```
model = make_nn(X_downsamp, Y_downsamp, n_hidden=n_hidden)
with model:
# s = theano.shared(pm.floatX(1.1))
# inference = pm.ADVI(cost_part_grad_scale=s)
approx = pm.fit(
500000, callbacks=[pm.callbacks.CheckParametersConvergence(tolerance=1e-1)]
)
plt.plot(approx.hist)
plt.yscale("log")
with model:
trace = approx.sample(1000)
# pm.traceplot(trace, varnames=['w_1'])
# pm.traceplot(trace, varnames=['w_2'])
# pm.traceplot(trace, varnames=['w_out'])
with model:
samp_ppc = pm.sample_ppc(trace, samples=1000)
```
# Results
```
preds_proba = samp_ppc["likelihood"].mean(axis=0)
preds = (preds_proba == np.max(preds_proba, axis=1, keepdims=True)) * 1
plt.pcolor(preds)
plt.savefig("figures/class_predictions.png", dpi=600)
plt.pcolor(preds_proba)
plt.savefig("figures/class_probabilities.png", dpi=600)
plt.pcolor(samp_ppc["likelihood"].std(axis=0))
plt.savefig("figures/class_uncertainties.png", dpi=600)
from sklearn.metrics import classification_report
print(classification_report(Y_downsamp, preds))
```
Compared to the logistic regression notebook, we have higher performance!
# Fit `sklearn`-like estimator
| github_jupyter |
# Intro to Pandas
Pandas is a Python package for data analysis and exposes two new
data structures: Dataframes and Series.
- [Dataframes](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html) store tabular data consisting of rows and columns.
- [Series](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html) are similar to Python's built-in list or set data types.
In this notebook, we will explore the data structures that Pandas
provides, and learn how to interact with them.
### 1. Importing Pandas
To import an external Python library such as Pandas, use Python's
import function. To save yourself some typing later on, you can
give the library you import an alias. Here, we are importing Pandas
and giving it an alias of `pd`.
```
import pandas as pd
```
### 2. Creating A Dataframe and Basic Exploration
We will load a CSV file as a dataframe using Panda's `read_csv`
method. This will allow us to use Pandas' dataframe functions to
explore the data in the CSV.
```
# If one is downloading via repository, a zip file is
# downloaded instead of a csv.
try:
df = pd.read_csv("../data/loans_full_africa.zip")
except:
df = pd.read_csv("../data/loans_full_africa.csv")
```
Once we have loaded the CSV as a dataframe, we can start to explore
the data. Here are a few useful methods:
- .head(): returns first 5 rows of the DataFrame
- .tail(): returns last 5 rows of the DataFrame
- .shape: returns tuple with first element indicating the number of rows and the second element indicating the number of columns
- .columns: returns list of all columns in DataFrame
- .index: returns DataFrame indices
- .dtypes: returns Series explaining the datatype of each column
```
df.shape
```
This function allow you to see the shape of your dataset
```
df.dtypes
```
To get some basic stats of the columns you can either use .describe() for discrete data or .value_counts for categroical data
```
df.describe()
df.isnull().sum().value_counts()
```
This function allow you to see the sum of missing value in your dataset.
Alternatively, if you want just the count or min / max of one column, you can use Pandas built in functions:
```
print(len(df['borrower_count']))
print(max(df['funded_amount']))
print(df['loan_amount'].mean())
df.head()
df['activity'].value_counts()
```
### 3. Selecting Data
To examine a specfic column of the DataFrame:
```
df['activity'].head()
df[['activity','basket_amount']].tail()
```
To examine specific rows and columns of a Dataframe, Pandas provides
the `iloc` and `loc` methods to do so. `iloc` is used when you want to specify a list or range of indices, and `.loc` is used when you want to specify a list or range of labels.
For both of these methods you need to specify two elements, with the first element indicating the rows that you want to select and the second element indicating the columns that you want to select.
```
# Get rows 1 through 3 and columns 0 through 5.
df.iloc[1:3,:5]
# Get rows with index values of 2-4 and the columns basket_amount and activity
df.loc[2:4, ["basket_amount", "activity"]]
```
What do you notice about the way the indices work for `iloc` versus `loc`?
```
# To see all the rows and columns:
# Note: [remove the .head() to see it all]
df.iloc[:,:].head()
# You can also store a slice of the dataframe as a new dataframe!
titles_df = df.iloc[:,2]
titles_df.head()
```
### 4. Select subets of the DataFrame
A powerful feature of DataFrames is that you can view a subset of the DataFrame based on the values of the columns or rows. For example, lets say you only wanted to view loans with a status of "expired"
```
df[df['status']=='expired'].head()
```
To view all loans with a status of "expired" `or` "fundraising":
```
df[(df['status']=='expired')|(df['status']=='fundraising')]
```
Select loans that have expired and with loan amounts greater than 1000
```
df[(df['status']=='expired')&(df['loan_amount']>1000)]
```
### 5. Merging and grouping data
You can group data by a column that has duplicates, like activity for the sector group.
```
df.groupby(['activity'])['loan_amount'].sum().reset_index()
```
You can also use SQL functions like inner join, outer join, left / right join using pd.merge(). Find documentation on this concept here: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html
## Great Resources for further information:
- [10 minute introduction to pandas](http://pandas.pydata.org/pandas-docs/stable/10min.html)
- [Pandas in ipython notebooks](http://nbviewer.jupyter.org/github/jvns/pandas-cookbook/blob/master/cookbook/A%20quick%20tour%20of%20IPython%20Notebook.ipynb)
- [Read CSV, ZIP, JSON, or more from Pandas Library](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html)
```
!ls
!pip install "name of the library missing"
```
| github_jupyter |
**Aims**:
- Explore best ways to present the data
- Prepare the publication-quality figure for the manuscript
```
%run notebook_setup.ipynb
%vault from pubmed_derived_data import literature
duplicated_doi = literature.doi.dropna()[literature.doi.dropna().duplicated()]
with_duplicated_doi = literature[literature.doi.isin(duplicated_doi)]
with_duplicated_doi
# all duplicates are identical:
assert all(with_duplicated_doi.groupby('doi').agg(set).apply(len) == 1)
```
Remove all but the first occurrence of duplicates:
```
uids_of_all_but_first = with_duplicated_doi.reset_index().groupby('doi').agg(list).uid.apply(lambda x: x[1:]).sum()
uids_of_all_but_first
literature = literature[~literature.index.isin(uids_of_all_but_first)].copy()
from pandas import Series, to_datetime
from search_terms import primary_terms, secondary_terms, descriptive_terms
terms = [*primary_terms, *secondary_terms, *descriptive_terms]
literature = literature.replace({float('nan'): None}).infer_objects()
literature.date = to_datetime(literature.date, utc=True)
%R -i literature -i terms
%%R
library(ComplexUpset)
source('helpers/plots.R')
source('helpers/colors.R')
```
# Publication figures
```
%vault from pubmed_derived_data import predicted_article_types, reliable_article_types
%vault from pubmed_derived_data import code_repositories
from pandas import concat
combined_article_types = concat([
predicted_article_types,
reliable_article_types
]).loc[literature.index]
%vault from pubmed_derived_data import omics_features
from helpers.text_processing import prefix_remover
omics_columns = omics_features.columns
omes_or_omics = (
omics_features[omics_columns[omics_columns.str.startswith('ome_or_omic_')]]
.rename(columns=prefix_remover('ome_or_omic_'))
)
literature['omic_terms_detected'] = omes_or_omics.sum(axis=1)
%vault from pubmed_derived_data import domain_features
data = (
literature
.drop(columns=['full_text', 'abstract'])
.join(combined_article_types)
.join(code_repositories)
.join(omics_features)
.join(
domain_features
[domain_features.columns[domain_features.columns.str.startswith('mentiones_')]]
)
)
data['is_type_predicted'] = data.index.isin(predicted_article_types.index)
type_names = {
'is_review': 'Review',
'is_method': 'Computational method',
'is_other_research_article': 'Other research article',
'is_other': 'Other'
}
def get_type(t):
if len(t) > 1:
return 'multiple'
if len(t):
return type_names[list(t)[0]]
return 'unknown'
data['chosen_type'] = combined_article_types.apply(lambda x: get_type(set(x[x != False].index)), axis=1)
data['chosen_type'].value_counts()
from pandas import DataFrame
from statistics import mean
from helpers.stats import bootstrap
oo = []
for predicted in [True, False]:
for type in combined_article_types.columns:
d = data[(data[type] != False) & (data['is_type_predicted'] == predicted)].dropna(subset=['omic_terms_detected'])
boot = bootstrap(list(d['omic_terms_detected']), stat=mean)
oo.append({
'is_type_predicted': predicted,
'type': type_names[type],
'mean_omics_detected': d['omic_terms_detected'].mean(),
'mean_omics_detected_ci_lower': boot['lower'],
'mean_omics_detected_ci_upper': boot['upper']
})
oo = DataFrame(oo)
%%R -i oo -r 110
(
ggplot(oo, aes(x=type, y=mean_omics_detected, fill=is_type_predicted))
+ geom_col(position='dodge')
+ geom_errorbar(
aes(ymin=mean_omics_detected_ci_lower, ymax=mean_omics_detected_ci_upper),
width=.2,
position=position_dodge(width = 0.9)
)
+ theme_bw()
+ scale_fill_manual(values=c('FALSE'='darkgreen', 'TRUE'='green'), name='Article type predicted?')
+ xlab('Article type')
+ ylab('Mean number of omics detected')
+ theme(legend.position = 'bottom')
)
%%R -i oo -r 110 -h 160
plot_counts_summary =function(...) {(
ggplot(oo[oo$is_type_predicted == FALSE, ], aes(x=type, y=mean_omics_detected))
+ geom_col(
position='dodge', fill='darkorange',
...
)
+ geom_errorbar(
aes(ymin=mean_omics_detected_ci_lower, ymax=mean_omics_detected_ci_upper),
width=.3,
position=position_dodge(width=0.9),
size=0.3
)
+ theme_bw()
+ ylab('Mean number of omics detected (95% CI)')
+ theme(legend.position='bottom', axis.title.y=element_blank())
+ coord_flip()
)}
plot_counts_summary(width=0.5)
integ = 'integrated omics*'
multix = 'multi-view omics**'
other = 'other terms***'
data['term_group'] = data.term.replace({
'integrated omics': integ,
'integrative omics': integ,
'integromics': integ,
'multi-block omics': multix,
'multi-modal omics': multix,
'multi-source omics': multix,
'multi-view omics': multix,
'cross-omics': other,
'pan-omics': other,
'poly-omics': other,
'trans-omics': other,
'multiple': 'multiple terms'
})
%R -i data
%%R -w 700 -h 400 -r 100
(
ggplot(data, aes(x=year, fill=term))
+ geom_bar()
+ scale_fill_manual(values=terms_colors)
+ theme_bw()
)
literature[literature[list(terms)].sum(axis=1) > 2][['title', 'doi', 'abstract_clean']]
%%R -w 700 -h 400 -r 100 -i integ -i multix
terms_group_colors = c(
terms_colors,
c(
'multi-omics'='#59A14F',
'multi-view omics**'='#EDC948',
'integrated omics*'='#4D79D7',
'multiple terms'='#b3b7b8',
'other terms***'='#c85200'
)
)
term_counts = (
ggplot(data, aes(x=year, fill=term_group))
+ geom_bar()
+ scale_fill_manual(values=terms_group_colors, name='')
+ theme(legend.position = 'bottom')
+ theme_bw()
)
term_counts
%%R -w 800 -h 400 -r 110
term_counts = (
ggplot(data, aes(x=year, fill=term_group))
+ geom_area(stat='count')
+ scale_fill_manual(values=terms_group_colors, name='')
+ theme(legend.position = 'bottom')
+ theme_bw()
)
term_counts
%vault from pubmed_derived_data import all_articles_by_journal_and_year
total_articles_in_popular_multi_omics_journals = all_articles_by_journal_and_year.groupby('year')['count'].sum()
total_articles_in_popular_multi_omics_journals.head(2)
term_groups_summary = data.assign(one=1).groupby(['year', 'term_group']).one.sum().rename('count').reset_index()
total_by_year = term_groups_summary.groupby('year')['count'].sum()
present = list(term_groups_summary[['term_group', 'year']].apply(tuple, axis=1))
for term in set(term_groups_summary.term_group):
for year in set(term_groups_summary.year):
if (term, year) not in present:
term_groups_summary = term_groups_summary.append({
'term_group': term,
'year': year,
'count': 0
}, ignore_index=True)
term_groups_summary['count_adjusted'] = term_groups_summary['count'] / term_groups_summary.year.map(total_articles_in_popular_multi_omics_journals)
total_by_year.head(8)
start_with_year = total_by_year[total_by_year <= 3].idxmax() + 1
term_groups_summary = term_groups_summary[term_groups_summary.year >= start_with_year].copy()
start_with_year
term_groups_summary['yearly_fraction'] = term_groups_summary['count'] / term_groups_summary.year.map(term_groups_summary.groupby('year')['count'].sum())
from datetime import date
SEARCH_DATE = date(year=2020, month=7, day=25)
term_groups_summary['complete_year'] = (term_groups_summary.year + 1).replace({2021: SEARCH_DATE.year + SEARCH_DATE.timetuple().tm_yday / 365})
%%R -w 800 -h 400 -r 110 -i term_groups_summary
(
ggplot(term_groups_summary, aes(x=complete_year, fill=term_group, y=count_adjusted))
+ geom_area(stat='identity')
+ scale_fill_manual(values=terms_group_colors, name='')
+ theme(legend.position = 'bottom')
+ theme_bw()
)
%%R -w 800 -h 400 -r 110 -i term_groups_summary
term_popularity = (
ggplot(term_groups_summary, aes(x=complete_year, fill=term_group, y=yearly_fraction))
+ geom_area(stat='identity')
+ scale_fill_manual(values=terms_group_colors, name='')
+ theme(legend.position = 'bottom')
+ theme_bw()
)
term_popularity
%%R -w 800 -h 400 -r 110 -i term_groups_summary
term_counts = ggplot(term_groups_summary, aes(x=complete_year, fill=term_group, y=count)) +
geom_area(stat='identity') +
scale_fill_manual(values=terms_group_colors, name='') +
theme(legend.position = 'bottom') +
theme_bw() +
ylab('Articles in PubMed')
term_counts
from repository_detection import (
source_code_platforms, mixed_publication_platforms, data_only_platforms,
all_platforms as platforms
)
mostly_code_platforms = list(source_code_platforms) + ['bioconductor']
mostly_data_platforms = list(set(mixed_publication_platforms) - {'bioconductor'}) + list(data_only_platforms)
platform_id_to_name = {
'.git': 'Other git',
'bioconductor': 'Bioconductor',
'bitbucket': 'Bitbucket',
'cran': 'CRAN',
'dryad': 'Dryad',
'github': 'GitHub',
'gitlab': 'GitLab',
'osf': 'OSF',
'pypi': 'PyPI',
'sourceforge': 'SourceForge',
'zenodo': 'Zenodo'
}
from pandas import Categorical
platforms_counts = code_repositories[[f'mentions_{platform}' for platform in platforms]].sum().to_frame('count').sort_values('count')
platforms_counts['platform_id'] = platforms_counts.index.str[len('mentions_'):]
platforms_counts['platform_type'] = platforms_counts.platform_id.apply(lambda p: 'code' if p in mostly_code_platforms else 'data')
platforms_counts.loc['mentions_zenodo', 'platform_type'] = 'both'
platforms_counts['platform_type'] = Categorical(platforms_counts['platform_type'], ordered=True, categories=['code', 'data', 'both'])
platforms_counts['platform_name'] = platforms_counts.platform_id.map(platform_id_to_name)
platforms_counts['platform_name'] = Categorical(platforms_counts['platform_name'], ordered=True, categories=reversed(platforms_counts['platform_name']))
platforms_counts['nudge_y'] = 0
platforms_counts.loc['mentions_gitlab', 'nudge_y'] = -0.5
platforms_counts.loc['mentions_osf', 'nudge_y'] = 0.5
platforms_counts['label_top'] = 0
for i, platform in enumerate(platforms_counts[platforms_counts['nudge_y'] == 0].index):
platforms_counts.loc[platform, 'label_top'] = (((i % 2) - 0.5) * 2) * -1
platforms_counts
%%R -i platforms_counts -r 110 -w 800 -h 190
code_and_data_platforms = function(text_size=3, point_size=3, scale_name='Used for') {
(
ggplot(platforms_counts, aes(y=nudge_y, x=count))
+ geom_text(
data=platforms_counts[platforms_counts$label_top == 0, ],
aes(
label=platform_name,
x=count - 0.5
),
hjust=1,
size=text_size
)
+ ggrepel::geom_text_repel(
data=platforms_counts[platforms_counts$label_top != 0, ],
aes(
label=platform_name,
nudge_y=label_top * 1.3
),
min.segment.length=0,
segment.curvature=-1e-20,
segment.color='grey40',
point.padding=2.5,
size=text_size
)
+ geom_point(
aes(group=platform_name, fill=platform_type, shape=platform_type),
color='black',
size=point_size
)
+ scale_fill_manual(
values=c(
'code'='#d62726',
'data'='#1f77b4',
'both'='#9467bd'
),
name=scale_name
)
+ scale_shape_manual(
values=c(
'code'='circle filled',
'data'='square filled',
'both'='diamond filled'
),
name=scale_name
)
+ theme_bw()
+ scale_x_log10(
sec.axis = dup_axis(breaks=platforms_counts$count, name=element_blank()),
name='Detected use of code and data versioning/distribution platforms'
)
#+ annotation_logticks(sides='b')
+ scale_y_continuous(expand=c(1, 0.5, 1, 0.5)) # bottom mult, bottom add, top mult, top add
+ theme(
legend.position='right',
axis.title.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank(),
panel.grid.major.y=element_blank(),
panel.grid.minor.y=element_blank(),
)
)
}
code_and_data_platforms()
20 / len(data) * 100
from helpers.features import number_of_articles_mentioning_feature, eval_features_frame
domain_features_py = eval_features_frame(domain_features)
from pandas import concat
top_n = 10
features_counts = concat([
number_of_articles_mentioning_feature(
domain_features_py,
Series(['diseases', 'clinical_findings']),
exclude=['disease']
).head(top_n),
number_of_articles_mentioning_feature(
domain_features_py,
Series(['species'])
).head(top_n)
]).reset_index()
features_counts.head(2)
%%R -i features_counts -r 110
plot_features = function(names_padding=0.05, counts_padding=0.05, expand=expansion(mult=0, add=0)) {
(
ggplot(features_counts, aes(x=kind, y=rank))
+ geom_tile(fill='white')
+ geom_text(aes(label=strtrim(term, 25)), hjust=0, position=position_nudge(x=-(0.5-names_padding)), size=3)
+ geom_text(
aes(label=count, color=proportion_of_articles),
hjust=1, position=position_nudge(x=0.5-counts_padding), size=3.4
)
+ theme_bw()
+ scale_y_reverse()
+ scale_x_discrete(
position="top",
labels=c(
'diseases,clinical_findings'='disease/clinical finding',
'species'='species'
),
name='Top diseases and species mentioned in the abstracts',
expand=expand
)
+ theme(
legend.position='bottom',
axis.title.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank(),
)
)}
plot_features(names_padding=0.05, counts_padding=0.05)
from omics import omics_by_entity, omics_by_entity_group
omic_entities_columns = Series(list(omics_by_entity.keys()))
omic_entities_group_columns = Series(list(omics_by_entity_group.keys()))
omic_entities = data.rename(columns=prefix_remover('entity_', enforce=False))
omic_entities_groups = data.rename(columns=prefix_remover('entity_group_', enforce=False))
%R -i omic_entities
%R -i omic_entities_groups
%%R -w 800 -r 100 -i omic_entities_columns
omics_upset = function(...) {
upset(
omic_entities,
omic_entities_columns,
min_size=50,
width_ratio=0.2,
min_degree=3,
base_annotations=list(
'Intersection size'=intersection_size(
counts=FALSE,
mapping=aes(fill=term_group)
)
),
themes=upset_modify_themes(
list(
'overall_sizes'=theme(axis.text.x=element_text(angle=90))
)
),
labeller=function(x) {
c(
'endogenous molecules'='metabolites²',
'genes'='genes',
'transcripts'='transcripts',
'proteins & peptides'='proteins¹',
'epigenetic modifications'='epigenetic³'
)[x]
},
set_sizes=FALSE,
...
) + theme(axis.title.x=element_blank()) & scale_fill_manual(values=terms_group_colors, name='')
}
omics_upset()
%%R -r 110 -w 800 -h 800
upset_plot = wrap_elements(
omics_upset(matrix=intersection_matrix(geom=geom_point(size=1.75)))
& theme(
legend.position='none',
plot.margin=unit(c(0, 0, -0.3, 0), "cm"),
panel.background=element_rect(fill='transparent', colour=NA),
plot.background=element_rect(fill='transparent', colour=NA)
)
+ theme(panel.border=element_rect(color='grey20', fill=NA))
)
TITLE_SIZE = 10
common_theme = theme(
axis.title.x=element_blank(),
plot.title=element_text(size=TITLE_SIZE)
)
%%R -r 110 -w 800 -h 800
figure = (
(
(
(
(
upset_plot
+ labs(
title='A. Frequently discussed omics combinations'
)
+ common_theme
)
|
(
term_counts
+ common_theme
+ labs(
title='B. Multi-omics articles indexed by PubMed'
)
)
)
& theme(legend.position='bottom')
& plot_layout(guides='collect')
)
/
(
(
plot_counts_summary(width=0.8)
+ scale_y_continuous(
expand=c(0, 0.02, 0, 0.1),
position='right',
)
+ shadowtext::geom_shadowtext(
aes(label=type, y=0.1), hjust=0, size=3,
bg.r=0.05, color='black', bg.color='orange'
)
+ theme(
legend.position='right',
axis.title.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank(),
axis.title.x=element_blank(),
plot.title.position='plot'
)
+ common_theme
+ labs(title='C. Mean number of omics detected (95% CI)')
)
|
(
plot_features(names_padding=0.035, counts_padding=0.035, expand=expansion(add=0.0))
+ guides(
color=guide_colorbar(
barheight=0.5,
label.position='top',
title.vjust=0.5,
title.theme=element_text(size=9),
order=0,
#label.vjust=-5,
label.hjust=0
)
)
+ common_theme
+ scale_color_gradient(
low='grey40',
high='red',
name='D) Proportion of publications',
breaks=c(0.0, 0.1, 0.2),
limits=function(automatic_limits) {
automatic_limits[[1]] = 0
automatic_limits
},
labels=scales::percent
)
+ labs(
title='D. Top diseases & species mentioned in the abstracts'
)
) & theme(legend.position='bottom')
)
/
(
code_and_data_platforms(scale_name='E) Platform used for')
+ common_theme
+ labs(
title='E. Detected use of code and data versioning/distribution platforms'
)
+ guides(
fill=guide_legend(
keywidth=0.1,
title.theme=element_text(size=9),
)
)
) & theme(
legend.position='bottom',
legend.box='horizontal',
legend.direction='horizontal',
legend.margin=unit(-15, 'cm'),
)
)
+ plot_layout(
heights=c(3, 2, 0.9),
guides='collect'
) + plot_annotation(title='Multi-omics literature overview')
)
figure
%R ggsave(filename='figures/overview.pdf', plot=figure, scale=1.1)
%R ggsave(filename='figures/overview.tiff', plot=figure, scale=1.1, dpi=300)
%R ggsave(filename='figures/overview.png', plot=figure, scale=1.1, device='png', dpi=105)
```
Compress the PNG if trimage is available:
```
from shutil import which
from contextlib import redirect_stdout
from io import StringIO
if which('trimage'):
f = StringIO()
with redirect_stdout(f):
!trimage -f figures/overview.png
```
### Details for captions
Proportion full-text articles among all articles:
```
(data.has_full_text==True).mean()
```
Proportion full-text articles among PMC articles (this is because non-PMC are NA, and are not accounted for when calculating the mean below!):
```
data.has_full_text.mean()
```
### Alternative UpSet plots
```
%%R -w 800 -r 100 -i omic_entities_group_columns
upset(omic_entities_groups, omic_entities_group_columns, min_size=50, width_ratio=0.1, min_degree=3)
%%R -w 800 -r 100 -i omic_entities_columns
upset(
omic_entities,
omic_entities_columns,
min_size=50,
width_ratio=0.2,
min_degree=3,
base_annotations=list(
'Intersection size'=intersection_size(
counts=FALSE,
aes=aes(fill=chosen_type)
)
),
themes=upset_modify_themes(
list(
'overall_sizes'=theme(axis.text.x=element_text(angle=90))
)
),
set_sizes=FALSE
)
```
| github_jupyter |
```
from google.colab import drive
drive.mount('/content/gdrive')
import json
with open('/content/gdrive/My Drive/Colab Notebooks/jigsaw-unintended-bias-in-toxicity-classification/comments_videos_pewdiepie_4000.json') as json_data:
data = json.load(json_data)
!pip install pytorch-pretrained-bert
# Converting the lines to BERT format
# Thanks to https://www.kaggle.com/httpwwwfszyc/bert-in-keras-taming
from tqdm import tqdm, tqdm_notebook
import numpy as np
def convert_lines(example, max_seq_length,tokenizer):
max_seq_length -=2
all_tokens = []
longer = 0
for text in tqdm_notebook(example):
tokens_a = tokenizer.tokenize(text)
if len(tokens_a)>max_seq_length:
tokens_a = tokens_a[:max_seq_length]
longer += 1
one_token = tokenizer.convert_tokens_to_ids(["[CLS]"]+tokens_a+["[SEP]"])+[0] * (max_seq_length - len(tokens_a))
all_tokens.append(one_token)
print(longer)
return np.array(all_tokens)
import torch.utils.data
def get_video_predictions(X_pew):
for param in model.parameters():
param.requires_grad=False
model.eval()
valid_preds_pews = np.zeros((len(X_pew)))
valid_pews = torch.utils.data.TensorDataset(torch.tensor(X_pew,dtype=torch.long))
valid_loader_pews = torch.utils.data.DataLoader(valid_pews, batch_size=32, shuffle=False)
tk0 = tqdm_notebook(valid_loader_pews)
for i,(x_batch,) in enumerate(tk0):
pred_pews = model(x_batch.to(device), attention_mask=(x_batch>0).to(device), labels=None)
valid_preds_pews[i*32:(i+1)*32]=pred_pews[:,0].detach().cpu().squeeze().numpy()
test_df_pews=torch.sigmoid(torch.tensor(valid_preds_pews)).numpy()
return test_df_pews
import torch
from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification
path = "/content/gdrive/My Drive/Colab Notebooks/bert_pytorch.bin"
y_columns=['target']
device=torch.device('cuda')
model = BertForSequenceClassification.from_pretrained('bert-base-uncased',num_labels=len(y_columns))
model.load_state_dict(torch.load(path))
model.to(device)
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
videos_results = []
MAX_SEQUENCE_LENGTH = 128
#BertAdam doesn't compensate for bias as in the regular Adam optimizer.
for video in tqdm_notebook(data):
comments = video["comments"]
X_pew = convert_lines(comments,MAX_SEQUENCE_LENGTH,tokenizer)
predictions = get_video_predictions(X_pew)
mean_prediction = np.mean(predictions)
toxic_amount = len([tox for tox in predictions if tox > 0.5])
vid_results = {
"video_id":video["videoId"],
"total_comments": len(predictions),
"mean_toxicity":mean_prediction,
"toxic_amount":toxic_amount ,
"comments":comments,
"predictions":predictions
}
videos_results.append(vid_results)
import json
with open('/content/gdrive/My Drive/Colab Notebooks/comments_toxicity_analysed_pewdiepie_4000.json', 'w') as outfile:
json.dump(videos_results, outfile, indent=4)
(videos_results[0])
```
| github_jupyter |
```
import numpy
import toyplot
numpy.random.seed(1234)
# Generate 8 sets of samples, each with different counts and distributions
datasets = []
for i in numpy.arange(8):
mean = numpy.random.uniform()
scale = numpy.random.uniform()
size = numpy.random.randint(100, 2000)
datasets.append(numpy.random.normal(mean, scale, size=size))
```
If we wanted to look at the distribution of the first dataset, we could use a simple one-liner histogram plot:
```
dataset = datasets[0]
toyplot.bars(numpy.histogram(dataset, 25), width=600, height=300);
```
However, unlike a visualization with multiple line plots, multiple histograms don't work very well:
```
canvas = toyplot.Canvas(width=600, height=300)
axes = canvas.cartesian()
for dataset in datasets:
axes.bars(numpy.histogram(dataset, 25))
```
Instead, let's plot the histograms separately, but in a single canvas:
```
canvas = toyplot.Canvas(width=400, height=1000)
for index, dataset in enumerate(datasets):
axes = canvas.cartesian(grid=(len(datasets), 1, index))
axes.bars(numpy.histogram(dataset, 25))
```
This plot is too tall to be useful, so let's turn it on its side by orienting each plot along the Y axis:
```
canvas = toyplot.Canvas(width=1000, height=400)
for index, dataset in enumerate(datasets):
axes = canvas.cartesian(grid=(1, len(datasets), index))
axes.bars(numpy.histogram(dataset, 25), along="y")
```
The X axes for each plot are too short to be useful, and our goal is to make purely qualitative comparisons of the shapes of the distributions anyway, so let's hide the axes and replace them with human-readable labels, including a single Y axis label along the left side of the graph:
```
canvas = toyplot.Canvas(width=1000, height=400)
for index, dataset in enumerate(datasets):
axes = canvas.cartesian(grid=(1, len(datasets), index))
axes.x.spine.show = False
axes.x.ticks.labels.show = False
axes.x.label.text = "Series {}".format(index)
if index == 0:
axes.y.show = True
axes.y.label.text = "Range"
axes.bars(numpy.histogram(dataset, 25), along="y")
```
Notice that the Y axis values vary from plot-to-plot, since the domain of each dataset differs. To make meaningful comparisons between distributions, we need to have consistency along the axes, so let's force each Y axis to display a range of values that incorporates all of the datasets:
```
canvas = toyplot.Canvas(width=1000, height=400)
for index, dataset in enumerate(datasets):
axes = canvas.cartesian(grid=(1, len(datasets), index))
axes.x.spine.show = False
axes.x.ticks.labels.show = False
axes.x.label.text = "Series {}".format(index)
if index == 0:
axes.y.show = True
axes.y.label.text = "Range"
axes.y.domain.min = numpy.min(numpy.concatenate(datasets))
axes.y.domain.max = numpy.max(numpy.concatenate(datasets))
axes.bars(numpy.histogram(dataset, 25), along="y")
```
Note that, now that the Y axis domains are properly aligned with one another, the bar widths vary, which can be an unwanted distration. To eliminate this, we will replace the bar plots with fill plots:
```
canvas = toyplot.Canvas(width=1000, height=400)
for index, dataset in enumerate(datasets):
axes = canvas.cartesian(grid=(1, len(datasets), index))
axes.x.spine.show = False
axes.x.ticks.labels.show = False
axes.x.label.text = "Series {}".format(index)
if index == 0:
axes.y.show = True
axes.y.label.text = "Range"
axes.y.domain.min = numpy.min(numpy.concatenate(datasets))
axes.y.domain.max = numpy.max(numpy.concatenate(datasets))
counts, bins = numpy.histogram(dataset, 25)
centers = (bins[:-1] + bins[1:]) / 2
axes.fill(centers, counts, along="y")
```
Finally, we mirror each fill plot around the Y axis to emphasize its shape, producing a classic violin plot:
```
canvas = toyplot.Canvas(width=1000, height=400)
for index, dataset in enumerate(datasets):
axes = canvas.cartesian(grid=(1, len(datasets), index))
axes.x.spine.show = False
axes.x.ticks.labels.show = False
axes.x.label.text = "Series {}".format(index)
if index == 0:
axes.y.show = True
axes.y.label.text = "Range"
axes.y.domain.min = numpy.min(numpy.concatenate(datasets))
axes.y.domain.max = numpy.max(numpy.concatenate(datasets))
counts, bins = numpy.histogram(dataset, 25)
centers = (bins[:-1] + bins[1:]) / 2
axes.fill(centers, counts * 2, baseline=-counts, along="y")
```
The final visualization makes it easy to compare the shapes and domains of the distributions.
As always, don't forget to render out an identical high-quality figure for publication:
```
import toyplot.pdf
toyplot.pdf.render(canvas, "violin-plot.pdf")
```
| github_jupyter |
# 6장 입력과 출력
## 6.1 화면 출력
### 기본 출력
**[6장: 95페이지]**
```
print("Hello Python!!")
```
**[6장: 96페이지]**
```
print("Best", "python", "book") # 공백이 삽입됨
```
**[6장: 96페이지]**
```
print("Best", "python", "book", sep = '!!!') # 연결문자를 !!!로 지정
print("Best", "python", "book", sep = '\n') # 연결문자를 \n으로 지정
```
**[6장: 96페이지]**
```
print("abcd" + "efg") # + 연산자는 공백 없이 연결시킴
```
**[6장: 96페이지]**
```
print("Best", "python", "book" + ":", "This book") # + 문자로 연결하면 공백 없이 연결됨
```
**[6장: 96페이지]**
```
x = 10
print(x)
```
**[6장: 97페이지]**
```
name = "James"
ID_num = 789
print("Name:", name + ",", "ID Number:", ID_num )
```
**[6장: 97페이지]**
```
print("James is my friend.\nHe is Korean.") #줄바꿈
```
**[6장: 97페이지]**
```
print("James is my friend.\n\nHe is Korean.") ##두줄바꿈
```
**[6장: 97페이지]**
```
print("Welcome to ")
print("python!")
```
**[6장: 98페이지]**
```
print("Welcome to ", end="") #줄바꿈없이 다음 명령어 실행
print("python!")
```
### 형식 지정 출력
#### 나머지 연산자(%)를 이용한 형식 및 위치 지정
**[6장: 99페이지]**
```
name = "광재"
print("%s는 나의 친구입니다." % name) # %s 는 문자열데이터
```
**[6장: 99페이지]**
```
r = 3 # 변수 r에 정수 데이터 할당
PI = 3.14159265358979 # 변수 PI에 실수 데이터 할당
print("반지름: %d, 원주율: %f" % (r, PI)) # 지정된 위치에 데이터 출력, %d는 정수데이터 %f는 실수데이터
# 데이터가 두개 이상일 경우 ()괄호로 묶여주어야 함
```
#### 형식 지정 문자열에서 출력 위치 지정
**[6장: 100페이지]**
```
animal_0 = "cat"
animal_1 = "dog"
animal_2 = "fox"
print("Animal: {0}".format(animal_0))
print("Animal: {0},{1},{2}".format(animal_0, animal_1, animal_2))
```
**[6장: 100페이지]**
```
print("Animal: {1},{2},{0}".format(animal_0, animal_1, animal_2)) # 입력 데이터의 순서를 지정할 수 있음
```
**[6장: 100페이지]**
```
print("Animal: {0},{2}".format(animal_0, animal_1, animal_2)) # 안넣어 줄 수도 있음
```
**[6장: 101페이지]**
```
print("Animal: {}, {}, {}".format(animal_0, animal_1, animal_2)) # 숫자를 안적으면 앞에서부터 순서대로
```
**[6장: 101페이지]**
```
name = "Tomas"
age = 10
a = 0.1234567890123456789
fmt_string = "String: {0}. Integer Number: {1}. Floating Number: {2}"
print(fmt_string.format(name, age, a)) # 변수로 지정하여 출력할 수도 있음
```
#### 형식 지정 문자열에서 숫자 출력 형식 지정
**[6장: 101페이지]**
```
a = 0.1234567890123456789
print("{0:.2f}, {0:.5f}".format(a)) # 소수점 두번째, 다섯번째까지 출력
```
## 6.1 키보드 입력
**[6장: 103페이지]**
```
yourName = input("Wie ist Ihr Name? ") # 입력창과 함께 출력할 메세지를 입력할 수 있음
print("Okay, Sie heißen {}. Danke sehr!".format(yourName)) # 입력값을 입력한 즉시 다음 코드가 실행됨
```
**[6장: 103페이지]**
```
num = input("숫자를 입력하세요: ") # 입력창과 함께 메세지를 보여주고, 입력받은 데이터를 변수에 저장
print("당신이 입력한 숫자는 {}입니다.".format(num))
print(type(num))
```
**[6장: 103페이지]**
```
a = input("정사각형 한 변의 길이는?: ")
area = int(a) ** 2 # 입력받은 문자데이터를 숫자데이터로 바꿔줌
print("정사각형의 넓이: {}".format(area))
```
**[6장: 103페이지]**
```
b = input("정사각형 한 변의 길이는?:")
area = float(b) ** 2 #정수인지, 실수인지 모를 경우 float()함수로 바꿔주어야 오류가 발생하지 않음
print("정사각형의 넓이: {}".format(area))
```
**[6장: 104페이지]**
```
c = float(input("정사각형 한 변의 길이는?: "))
area = c ** 2
print("정사각형의 넓이: {}".format(area))
```
## 6.3 파일 읽고 쓰기
### 파일 열기
### 파일 쓰기
**[6장: 106페이지]**
```
cd C:\myPyCode
```
**[6장: 106페이지]**
```
f = open('myFile.txt', 'w') # (1)'myFile.txt' 파일 쓰기 모드로 열어서 f로 지정
f.write('This is my first file. 이것은 내 파일입니다.') # (2) 연 파일에 문자열 쓰기
f.close() # (3) 파일 닫기
```
**[6장: 106페이지]**
```
!type myFile.txt
```
### 파일 읽기
**[6장: 107페이지]**
```
f = open('myFile.txt', 'r') # (1)'myFile.txt' 파일 읽기 모드로 열기
file_text = f.read() # (2) 파일 내용 읽은 후에 변수에 저장
f.close() # (3) 파일 닫기
print(file_text) # 변수에 저장된 내용 출력
```
## 6.4 반복문을 이용해 파일 읽고 쓰기
### 파일에 문자열 한 줄씩 쓰기
**[6장: 107페이지]**
```
f = open('two_times_table.txt','w') # (1)파일을 쓰기 모드로 열기
for num in range(1,6): # (2) for문: num이 1~5까지 반복
format_string = "2 x {0} = {1}\n".format(num,2*num) # 저장할 문자열 생성
f.write(format_string) # (3) 파일에 문자열 저장
f.close() # (4) 파일 닫기
for num in range(1,6): # (2) for문: num이 1~5까지 반복
format_string = "2 x {0} = {1}\n".format(num,2*num) # 저장할 문자열 생성
print(format_string)
```
**[6장: 108페이지]**
```
!type two_times_table.txt
```
### 파일에서 문자열 한 줄씩 읽기
#### readline()
**[6장: 109페이지]**
```
f = open("two_times_table.txt") # 파일을 읽기 모드로 열기
line1 = f.readline() # 한 줄씩 문자열을 읽기
line2 = f.readline()
f.close() # 파일 닫기
print(line1, end="") # 한 줄씩 문자열 출력(줄 바꿈 안 함)
print(line2, end="")
```
**[6장: 109페이지]**
```
f = open("two_times_table.txt") # 파일을 읽기 모드로 열기
line = f.readline() # 문자열 한 줄 읽기
while line: # line이 공백인지 검사해서 반복 여부 결정
print(line, end = "") # 문자열 한 줄 출력(줄 바꿈 안 함)
line = f.readline() # 문자열 한 줄 읽기
f.close() # 파일 닫기
```
#### readlines()
**[6장: 110페이지]**
```
f = open("two_times_table.txt") # (1) 파일을 읽기 모드로 열기
lines = f.readlines() # (2) 파일 전체 읽기(리스트로 반환)
f.close() # (3) 파일 닫기
print(lines) # 리스트 변수 내용 출력
```
**[6장: 110페이지]**
```
f = open("two_times_table.txt") # 파일을 읽기 모드로 열기
lines = f.readlines() # 파일 전체 읽기(리스트로 반환)
f.close() # 파일 닫기
for line in lines: # 리스트를 <반복 범위>로 지정
print(line, end="") # 리스트 항목을 출력(줄 바꿈 안 함)
```
**[6장: 111페이지]**
```
f = open("two_times_table.txt") # 파일을 읽기 모드로 열기
for line in f.readlines(): # 파일 전체를 읽고, 리스트 항목을 line에 할당
print(line, end="") # 리스트 항목을 출력(줄 바꿈 안 함)
f.close()
```
**[6장: 111페이지]**
```
f = open("two_times_table.txt") # 파일을 읽기 모드로 열기
for line in f: # 파일 전체를 읽고, 리스트 항목을 line에 할당
print(line, end="") # line의 내용 출력(줄 바꿈 안 함)
f.close() # 파일 닫기
```
## 6.5 with 문을 활용해 파일 읽고 쓰기
### with 문의 구조
**[6장: 112페이지]**
```
f = open('myTextFile.txt', 'w') # (1) 파일 열기
f.write('File write/read test.') # (2) 파일 쓰기
f.close() # (3) 파일 닫기
```
**[6장: 112페이지]**
```
f = open('myTextFile.txt', 'r') # (1) 파일 열기
test = f.read() # (2) 파일 읽기
f.close() # (3) 파일 닫기
print(test)
```
### with문의 활용
**[6장: 113페이지]**
```
with open('C:/myPyCode/myTextFile2.txt', 'w') as f: # (1) 파일 열기
f.write('File read/write test2: line1\n') # (2) 파일 쓰기
f.write('File read/write test2: line2\n')
f.write('File read/write test2: line3\n')
!type myTextFile2.txt
```
**[6장: 113페이지]**
```
with open('C:/myPyCode/myTextFile2.txt') as f: # (1) 파일 열기
file_string = f.read() # (2) 파일 읽기
print(file_string)
```
**[6장: 113페이지]**
```
with open('C:/myPyCode/myTextFile3.txt', 'w') as f: # 파일을 쓰기 모드로 열기
for num in range(1,6): # for문에서 num이 1~5까지 반복
format_string = "3 x {0} = {1}\n".format(num,3*num) # 문자열 생성
f.write(format_string) # 파일에 문자열 쓰기
```
**[6장: 114페이지]**
```
with open('C:/myPyCode/myTextFile3.txt', 'r') as f: # 파일을 읽기 모드로 열기
for line in f: # 파일 전체를 읽고 리스트 항목을 line에 할당
print(line, end="") # line에 할당된 문자열 출력(줄 바꿈 안 함)
```
# 6.6 정리
| github_jupyter |
Lambda School Data Science
*Unit 2, Sprint 2, Module 4*
---
# Classification Metrics
## Assignment
- [ ] If you haven't yet, [review requirements for your portfolio project](https://lambdaschool.github.io/ds/unit2), then submit your dataset.
- [ ] Plot a confusion matrix for your Tanzania Waterpumps model.
- [ ] Continue to participate in our Kaggle challenge. Every student should have made at least one submission that scores at least 70% accuracy (well above the majority class baseline).
- [ ] Submit your final predictions to our Kaggle competition. Optionally, go to **My Submissions**, and _"you may select up to 1 submission to be used to count towards your final leaderboard score."_
- [ ] Commit your notebook to your fork of the GitHub repo.
- [ ] Read [Maximizing Scarce Maintenance Resources with Data: Applying predictive modeling, precision at k, and clustering to optimize impact](https://towardsdatascience.com/maximizing-scarce-maintenance-resources-with-data-8f3491133050), by Lambda DS3 student Michael Brady. His blog post extends the Tanzania Waterpumps scenario, far beyond what's in the lecture notebook.
## Stretch Goals
### Reading
- [Attacking discrimination with smarter machine learning](https://research.google.com/bigpicture/attacking-discrimination-in-ml/), by Google Research, with interactive visualizations. _"A threshold classifier essentially makes a yes/no decision, putting things in one category or another. We look at how these classifiers work, ways they can potentially be unfair, and how you might turn an unfair classifier into a fairer one. As an illustrative example, we focus on loan granting scenarios where a bank may grant or deny a loan based on a single, automatically computed number such as a credit score."_
- [Notebook about how to calculate expected value from a confusion matrix by treating it as a cost-benefit matrix](https://github.com/podopie/DAT18NYC/blob/master/classes/13-expected_value_cost_benefit_analysis.ipynb)
- [Simple guide to confusion matrix terminology](https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/) by Kevin Markham, with video
- [Visualizing Machine Learning Thresholds to Make Better Business Decisions](https://blog.insightdatascience.com/visualizing-machine-learning-thresholds-to-make-better-business-decisions-4ab07f823415)
### Doing
- [ ] Share visualizations in our Slack channel!
- [ ] RandomizedSearchCV / GridSearchCV, for model selection. (See module 3 assignment notebook)
- [ ] More Categorical Encoding. (See module 2 assignment notebook)
- [ ] Stacking Ensemble. (See below)
### Stacking Ensemble
Here's some code you can use to "stack" multiple submissions, which is another form of ensembling:
```python
import pandas as pd
# Filenames of your submissions you want to ensemble
files = ['submission-01.csv', 'submission-02.csv', 'submission-03.csv']
target = 'status_group'
submissions = (pd.read_csv(file)[[target]] for file in files)
ensemble = pd.concat(submissions, axis='columns')
majority_vote = ensemble.mode(axis='columns')[0]
sample_submission = pd.read_csv('sample_submission.csv')
submission = sample_submission.copy()
submission[target] = majority_vote
submission.to_csv('my-ultimate-ensemble-submission.csv', index=False)
```
```
import numpy as np
import pandas as pd
import category_encoders as ce
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import RandomizedSearchCV
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set_style('darkgrid')
%%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge/master/data/'
!pip install category_encoders==2.*
# If you're working locally:
else:
DATA_PATH = '../data/'
import pandas as pd
# Merge train_features.csv & train_labels.csv
train = pd.merge(pd.read_csv(DATA_PATH+'waterpumps/train_features.csv'),
pd.read_csv(DATA_PATH+'waterpumps/train_labels.csv'))
# Read test_features.csv & sample_submission.csv
test = pd.read_csv(DATA_PATH+'waterpumps/test_features.csv')
sample_submission = pd.read_csv(DATA_PATH+'waterpumps/sample_submission.csv')
features = ['basin', 'public_meeting', 'scheme_management', 'permit', 'extraction_type',
'management', 'payment', 'water_quality', 'quantity', 'source', 'waterpoint_type']
target = 'status_group'
X_train, X_valid, y_train, y_valid = train_test_split(train[features], train[target])
X_test = test[features]
encoder = ce.OrdinalEncoder()
X_train = encoder.fit_transform(X_train)
X_valid = encoder.transform(X_valid)
X_test = encoder.transform(X_test)
model = RandomForestClassifier(n_estimators = 256, n_jobs = -1) #max_depth = 64,
k = 4
scores = cross_val_score(model, X_train, y_train, cv=k, scoring = 'accuracy')
print(f'Accuracy for {k} folds:', scores)
model.fit(X_train, y_train)
yv_pred = model.predict(X_valid)
yt_pred = model.predict(X_test)
accuracy_score(yv_pred, y_valid)
print(confusion_matrix(y_valid, yv_pred))
sns.heatmap(pd.DataFrame(confusion_matrix(y_valid, yv_pred)), annot=True, cmap = 'coolwarm')
plt.show()
```
| github_jupyter |
# Transformer model for predicting modalities in scRNA-seq
**Authors**<br>Vedu Mallela: GiwoTech, vedu.mallela@gmail.com<br>Simon Lee: UC Santa Cruz, siaulee@ucsc.edu
# Goal of the code
**TODO: explain algorithm**
# Libraries
Import all files and modules for this competition<br>
*below will provide documentation of the following libraries*<br>
<br>
**scanpy** (**s**ingle **c**ell **an**alysis in **Py**thon) - https://scanpy.readthedocs.io/en/stable/ <br>
**anndata** (**ann**otated **data**) - https://anndata.readthedocs.io/en/latest/ <br>
**matplotlib** - https://matplotlib.org/ <br>
**numpy** - https://numpy.org/doc/stable/ <br>
**pandas** - https://pandas.pydata.org/ <br>
**logging** - https://docs.python.org/3/howto/logging.html <br>
**sklearn** - https://scikit-learn.org/stable/ <br>
<br>
*code begins here*
```
import scanpy as sc
import anndata as ad
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import logging
from sklearn.decomposition import TruncatedSVD
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
```
# LOAD DATA
```
path = '/tmp/public/multiome/'
outpath ='../out/'
adata_gex = ad.read_h5ad(path + "multiome_gex_processed_training.h5ad")
adata_atac = ad.read_h5ad(path + "multiome_atac_processed_training.h5ad")
```
After successfully loading in the data, we can try to begin plotting the batch for the **Assay for Transposase-Accessible Chromatin using sequencing** (ATAC-seq) and **Gene Expression** (GEX) data on the umap interface. These umap projections will be saved to GEX.pdf and ATAC.pdf
```
#sc.tl.pca(adata_gex)
#sc.pl.umap(adata_gex, color=['batch'],save='_GEX', title='GEX umap Display')
#sc.tl.pca(adata_atac)
#sc.pl.umap(adata_atac, color=['batch'], layer='counts', save='_ATAC', title='ATAC umap Display')
```
Next we are going to check out all the indivdual cell types occuring in both the ATAC and GEX data. This way we can see all the types of cells from this dataset provided.
```
#sc.tl.pca(adata_gex)
#sc.pl.umap(adata_gex, color='cell_type',save='_GEX_ct', title='GEX Cell Type umap')
#sc.tl.pca(adata_atac)
#sc.pl.umap(adata_atac, color='cell_type',save='_ATAC_ct', title='ATAC Cell Type umap')
```
# Filter out our Data <1%
```
# filter out the data
# Convert anndata objects to dataframes and filter.
# Genes that show up in < 1% cells are dropped.
# Atac seq data that shows up in < 1% cells are dropped
gex_df = adata_gex.to_df()
atac_df = adata_atac.to_df()
mask = gex_df>0
total_cells = gex_df.shape[0]
maskdf = mask.sum(axis=0)/total_cells*100 <=1
gex_feature_drop = list(maskdf.loc[maskdf==True].index.values)
mask = atac_df>0
maskdf = mask.sum(axis=0)/total_cells <=0.01
atac_feature_drop = list(maskdf.loc[maskdf==True].index.values)
gex_ = gex_df.drop(columns=gex_feature_drop)
atac_ = atac_df.drop(columns=atac_feature_drop)
print('Filtered data set')
print('GEX data: Total cells=' + str(gex_.shape[0]) + ', Number features=' + str(gex_.shape[1]))
print('ATAC data: Total cells=' + str(atac_.shape[0]) + ', Number Features=' + str(atac_.shape[1]))
```
# Filtered out Gene Expression and ATAC data
```
gex_
atac_
```
# import Transformer libraries
```
from transformers import AutoTokenizer, AutoModelWithLMHead, T5ForConditionalGeneration
from pathlib import Path
from sklearn.model_selection import train_test_split
import torch
```
# This is unorganizaed but we are working starting here. I commented what needs to be done!!!!!!
```
import numpy as np
import sklearn
#convert anndata to numpy array
gex_numpy_matrix = np.array(gex_)
atac_numpy_matrix = np.array(atac_)
print(type(atac_numpy_array))
print(gex_numpy_matrix.shape)
#binarize the gex data
genex_ = sklearn.preprocessing.binarize(gex_numpy_matrix, threshold=2.0, copy=False)
# if gex or atac data is present or 1 in binary obtain the name and replace binary value with name
print(gex_numpy_matrix[0,10])
#store the atac seq and gex of s1d1 for example in a .txt file
#ex. {'TAGGTA': 'chr1-633515-634474 chr1-633525-634474 ', 'en': 'That is good.'}
#call wrapper function
#class TextLineTask(FunctionTask): found in text-to-text-transfer-transformer/t5/data/dataset_providers.py
#call t5 small model
genex_
#looks like the numpy array works
# read the sequence and split it into chunks
def read_seq_split(split_dir):
split_dir = (split_dir)
texts = []
labels = []
for label_dir in ["gex", "atac"]: # for each label
for text_file in (split_dir/label_dir).iterdir():
texts.append(text_file.read_text())
return texts, labels
from transformers import AutoTokenizer, AutoModelWithLMHead, T5ForConditionalGeneration, T5Tokenizer
from pathlib import Path
from sklearn.model_selection import train_test_split
import torch
#gex_df = adata_gex.to_df()
#X = gex_df.drop(['target'],axis=1).values # independant features
#y = gex_df['target'].values # dependant variable
#train_texts, val_texts, train_labels, val_labels = train_test_split(x, y, train_texts, train_labels, test_size=.2)
#train_text, train_labels = read_seq_split(gex_df)
#train_text =
tokenizer = T5Tokenizer.from_pretrained("t5-small")
train_encodings = tokenizer(adata_gex, truncation=True, padding=True)
#val_encodings = tokenizer(val_texts, truncation=True, padding=True)
#test_encodings = tokenizer(test_texts, truncation=True, padding=True)
#train_texts, train_labels = read_seq_split(adata_gex)
#test_texts, test_labels = read_seq_split('figures/test')
adata_atac.obs
```
We are now going to print out the number of observations and features of our GEX and ATAC-seq data.
Few things to note before we proceed:
```
print(f"The GEX data has {adata_gex.n_obs} observations and {adata_gex.n_vars} features.")
print(f"The ATAC data has {adata_atac.n_obs} observations and {adata_atac.n_vars} features.")
```
# TRANSFORMER
The Transformer T-5 small model will take in a custom dataset. This model relies solely on training therefore it is important that we have the proper pretraining before turning in this method for single cell sequencing analysis.
```
# read the sequence and split it into chunks
def read_seq_split(split_dir):
split_dir = Path(split_dir)
texts = []
labels = []
for label_dir in ["", ""]: # for each label
for text_file in (split_dir/label_dir).iterdir():
texts.append(text_file.read_text())
return texts, labels
```
Loading up the data so the sequences can be read
Train our transformer using this the train_test_split() function. This wraps input validation and application to input data into a single call
```
# wraps input validation and application to input data into a single call
train_texts, val_texts, train_labels, val_labels = train_test_split(train_texts, train_labels, test_size=.2)
train_encodings = tokenizer(train_texts, truncation=True, padding=True)
val_encodings = tokenizer(val_texts, truncation=True, padding=True)
test_encodings = tokenizer(test_texts, truncation=True, padding=True)
class MIADataset(torch.utils.data.Dataset): # create a custom dataset for neurips mia model
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
item['labels'] = torch.tensor(self.labels[idx])
return item
def __len__(self):
return len(self.labels)
```
Using Pytorch trainer, we want to train our model. t-5 small and transformers all around rely solely on this training data so this is definatley the most important aspect of the code. Doing so will play a massive role in how we analyze this single cell data.
```
# assuming we want to use trainer in leiu of custom pytorch trainer
# need to change training args based on raz input on the model
training_args = TrainingArguments(
output_dir='./results', # output directory
num_train_epochs=3, # total number of training epochs
per_device_train_batch_size=16, # batch size per device during training
per_device_eval_batch_size=64, # batch size for evaluation
warmup_steps=500, # number of warmup steps for learning rate scheduler
weight_decay=0.01, # strength of weight decay
logging_dir='./logs', # directory for storing logs
logging_steps=10,
)
model = AutoModelWithLMHead.from_pretrained("t5-small")
trainer = Trainer(
model=model, # the instantiated 🤗 Transformers model to be trained
args=training_args, # training arguments, defined above
train_dataset=train_dataset, # training dataset
eval_dataset=val_dataset # evaluation dataset
)
trainer.train()
```
# Baseline Models given by NeurIPS
a few statistical metrics given to us in the NeurIPS competition that shows how are algorithm performs. <br>
The tests include:<br>
**rmse** - **r**oot **m**ean **s**quare **e**rror<br>
**baseline_linear** - linear regressor test<br>
**baseline_mean** - mean test
```
def calculate_rmse(true_test_mod2, pred_test_mod2):
if pred_test_mod2.var["feature_types"][0] == "GEX":
return mean_squared_error(true_test_mod2.layers["log_norm"].toarray(), pred_test_mod2.X, squared=False)
else:
raise NotImplementedError("Only set up to calculate RMSE for GEX data")
def baseline_linear(input_train_mod1, input_train_mod2, input_test_mod1):
'''Baseline method training a linear regressor on the input data'''
input_mod1 = ad.concat(
{"train": input_train_mod1, "test": input_test_mod1},
axis=0,
join="outer",
label="group",
fill_value=0,
index_unique="-",
)
# Binarize ATAC
if input_train_mod1.var["feature_types"][0] == "ATAC":
input_mod1.X[input_mod1.X > 1] = 1
elif input_train_mod2.var["feature_types"][0] == "ATAC":
input_train_mod2.X[input_mod1.X > 1] = 1
# Do PCA on the input data
logging.info('Performing dimensionality reduction on modality 1 values...')
embedder_mod1 = TruncatedSVD(n_components=50)
mod1_pca = embedder_mod1.fit_transform(input_mod1.X)
logging.info('Performing dimensionality reduction on modality 2 values...')
embedder_mod2 = TruncatedSVD(n_components=50)
mod2_pca = embedder_mod2.fit_transform(input_train_mod2.layers["log_norm"])
# split dimred mod 1 back up for training
X_train = mod1_pca[input_mod1.obs['group'] == 'train']
X_test = mod1_pca[input_mod1.obs['group'] == 'test']
y_train = mod2_pca
assert len(X_train) + len(X_test) == len(mod1_pca)
logging.info('Running Linear regression...')
reg = LinearRegression()
# Train the model on the PCA reduced modality 1 and 2 data
reg.fit(X_train, y_train)
y_pred = reg.predict(X_test)
# Project the predictions back to the modality 2 feature space
y_pred = y_pred @ embedder_mod2.components_
pred_test_mod2 = ad.AnnData(
X = y_pred,
obs = input_test_mod1.obs,
var = input_train_mod2.var,
)
# Add the name of the method to the result
pred_test_mod2.uns["method"] = "linear"
return pred_test_mod2
def baseline_mean(input_train_mod1, input_train_mod2, input_test_mod1):
'''Dummy method that predicts mean(input_train_mod2) for all cells'''
logging.info('Calculate mean of the training data modality 2...')
y_pred = np.repeat(input_train_mod2.layers["log_norm"].mean(axis=0).reshape(-1,1).T, input_test_mod1.shape[0], axis=0)
# Prepare the ouput data object
pred_test_mod2 = ad.AnnData(
X=y_pred,
obs=input_test_mod1.obs,
var=input_train_mod2.var,
)
pred_test_mod2.uns["method"] = "mean"
return pred_test_mod2
```
| github_jupyter |
# A Conceptual, Practical Introduction to Trax Layers
This notebook introduces the core concepts of the Trax library through a series of code samples and explanations. The topics covered in following sections are:
1. **Layers**: the basic building blocks and how to combine them into networks
1. **Data Streams**: how individual layers manage inputs and outputs
1. **Data Stack**: how the Trax runtime manages data streams for the layers
1. **Defining New Layer Classes**: how to define and test your own layer classes
1. **Models**: how to train, evaluate, and run predictions with Trax models
## General Setup
Execute the following few cells (once) before running any of the code samples in this notebook.
```
# Copyright 2018 Google LLC.
# 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.
import numpy as np
# Import Trax
! pip install -q -U trax
! pip install -q tensorflow
from trax import math
from trax import layers as tl
from trax import shapes
from trax.math import numpy as jnp # For use in defining new layer types.
from trax.shapes import ShapeDtype
from trax.shapes import signature
# Settings and utilities for handling inputs, outputs, and object properties.
np.set_printoptions(precision=3) # Reduce visual noise from extra digits.
def show_layer_properties(layer_obj, layer_name):
template = ('{}.n_in: {}\n'
'{}.n_out: {}\n'
'{}.sublayers: {}\n'
'{}.weights: {}\n')
print(template.format(layer_name, layer_obj.n_in,
layer_name, layer_obj.n_out,
layer_name, layer_obj.sublayers,
layer_name, layer_obj.weights))
```
# 1. Layers
The Layer class represents Trax's basic building blocks:
```
class Layer(object):
"""Base class for composable layers in a deep learning network.
Layers are the basic building blocks for deep learning models. A Trax layer
computes a function from zero or more inputs to zero or more outputs,
optionally using trainable weights (common) and non-parameter state (not
common). Authors of new layer subclasses typically override at most two
methods of the base `Layer` class:
forward(inputs):
Computes this layer's output as part of a forward pass through the model.
init_weights_and_state(self, input_signature):
Initializes weights and state for inputs with the given signature.
...
```
## Layers compute functions.
A layer computes a function from zero or more inputs to zero or more outputs.
The inputs and outputs are NumPy arrays or JAX objects behaving as NumPy arrays.
The simplest layers, those with no weights or sublayers, can be used without
initialization. You can think of them as (pure) mathematical functions that can
be plugged into neural networks.
For ease of testing and interactive exploration, layer objects implement the
`__call__ ` method, so you can call them directly on input data:
```
y = my_layer(x)
```
Layers are also objects, so you can inspect their properties. For example:
```
print(f'Number of inputs expected by this layer: {my_layer.n_in}')
```
### Example 1. tl.Relu $[n_{in} = 1, n_{out} = 1]$
```
relu = tl.Relu()
x = np.array([[-2, -1, 0, 1, 2],
[-20, -10, 0, 10, 20]])
y = relu(x)
# Show input, output, and two layer properties.
print(f'x:\n{x}\n\n'
f'relu(x):\n{y}\n\n'
f'Number of inputs expected by this layer: {relu.n_in}\n'
f'Number of outputs promised by this layer: {relu.n_out}')
```
### Example 2. tl.Concatenate $[n_{in} = 2, n_{out} = 1]$
```
concat = tl.Concatenate()
x0 = np.array([[1, 2, 3],
[4, 5, 6]])
x1 = np.array([[10, 20, 30],
[40, 50, 60]])
y = concat([x0, x1])
print(f'x0:\n{x0}\n\n'
f'x1:\n{x1}\n\n'
f'concat([x1, x2]):\n{y}\n\n'
f'Number of inputs expected by this layer: {concat.n_in}\n'
f'Number of outputs promised by this layer: {concat.n_out}')
```
## Layers are configurable.
Many layer types have creation-time parameters for flexibility. The
`Concatenate` layer type, for instance, has two optional parameters:
* `axis`: index of axis along which to concatenate the tensors; default value of -1 means to use the last axis.
* `n_items`: number of tensors to join into one by concatenation; default value is 2.
The following example shows `Concatenate` configured for **3** input tensors,
and concatenation along the initial $(0^{th})$ axis.
### Example 3. tl.Concatenate(n_items=3, axis=0)
```
concat3 = tl.Concatenate(n_items=3, axis=0)
x0 = np.array([[1, 2, 3],
[4, 5, 6]])
x1 = np.array([[10, 20, 30],
[40, 50, 60]])
x2 = np.array([[100, 200, 300],
[400, 500, 600]])
y = concat3([x0, x1, x2])
print(f'x0:\n{x0}\n\n'
f'x1:\n{x1}\n\n'
f'x2:\n{x2}\n\n'
f'concat3([x0, x1, x2]):\n{y}')
```
## Layers are trainable.
Many layer types include weights that affect the computation of outputs from
inputs, and they use back-progagated gradients to update those weights.
🚧🚧 *A very small subset of layer types, such as `BatchNorm`, also include
weights (called `state`) that are updated based on forward-pass
inputs/computation rather than back-propagated gradients.*
### Initialization
Trainable layers must be initialized before use. Trax can take care of this
as part of the overall training process. In other settings (e.g., in tests or
interactively in a Colab notebook), you need to initialize the
*outermost/topmost* layer explicitly. For this, use `init`:
```
def init(self, input_signature, rng=None):
"""Initializes this layer and its sublayers recursively.
This method is designed to initialize each layer instance once, even if the
same layer instance occurs in multiple places in the network. This enables
weight sharing to be implemented as layer sharing.
Args:
input_signature: A `ShapeDtype` instance (if this layer takes one input)
or a list/tuple of `ShapeDtype` instances.
rng: A single-use random number generator (JAX PRNG key). If none is
provided, a default rng based on the integer seed 0 will be used.
Returns:
A (weights, state) tuple, in which weights contains newly created weights
on the first call and `EMPTY_WEIGHTS` on all subsequent calls.
"""
```
Input signatures can be built from scratch using `ShapeDType` objects, or can
be derived from data via the `signature` function (in module `shapes`):
```
def signature(obj):
"""Returns a `ShapeDtype` signature for the given `obj`.
A signature is either a `ShapeDtype` instance or a tuple of `ShapeDtype`
instances. Note that this function is permissive with respect to its inputs
(accepts lists or tuples, and underlying objects can be any type as long as
they have shape and dtype attributes), but strict with respect to its outputs
(only `ShapeDtype`, and only tuples).
Args:
obj: An object that has `shape` and `dtype` attributes, or a list/tuple
of such objects.
"""
```
### Example 4. tl.LayerNorm $[n_{in} = 1, n_{out} = 1]$
```
layer_norm = tl.LayerNorm()
x = np.array([[-2, -1, 0, 1, 2],
[1, 2, 3, 4, 5],
[10, 20, 30, 40, 50]]).astype(np.float32)
layer_norm.init(signature(x))
y = layer_norm(x)
print(f'x:\n{x}\n\n'
f'layer_norm(x):\n{y}\n')
print(f'layer_norm.weights:\n{layer_norm.weights}')
```
## Layers combine into layers.
The Trax library authors encourage users to build new layers as combinations of
existing layers. Hence, the library provides a small set of _combinator_
layers: layer objects that make a list of layers behave as a single layer.
The new layer, like other layers, can:
* compute outputs from inputs,
* update parameters from gradients, and
* combine with yet more layers.
### Combine with `Serial`
The most common way to combine layers is with the `Serial` class:
```
class Serial(base.Layer):
"""Combinator that applies layers serially (by function composition).
A Serial combinator uses stack semantics to manage data for its sublayers.
Each sublayer sees only the inputs it needs and returns only the outputs it
has generated. The sublayers interact via the data stack. For instance, a
sublayer k, following sublayer j, gets called with the data stack in the
state left after layer j has applied. The Serial combinator then:
- takes n_in items off the top of the stack (n_in = k.n_in) and calls
layer k, passing those items as arguments; and
- takes layer k's n_out return values (n_out = k.n_out) and pushes
them onto the data stack.
...
```
If one layer has the same number of outputs as the next layer has inputs (which
is the usual case), the successive layers behave like function composition:
```
# h(.) = g(f(.))
layer_h = Serial(
layer_f,
layer_g,
)
```
Note how, inside `Serial`, function composition is expressed naturally as a
succession of operations, so that no nested parentheses are needed.
### Example 5. y = layer_norm(relu(x)) $[n_{in} = 1, n_{out} = 1]$
```
layer_block = tl.Serial(
tl.Relu(),
tl.LayerNorm(),
)
x = np.array([[-2, -1, 0, 1, 2],
[-20, -10, 0, 10, 20]]).astype(np.float32)
layer_block.init(signature(x))
y = layer_block(x)
print(f'x:\n{x}\n\n'
f'layer_block(x):\n{y}')
```
And we can inspect the block as a whole, as if it were just another layer:
### Example 5'. Inspecting a Serial layer.
```
print(f'layer_block: {layer_block}\n\n'
f'layer_block.weights: {layer_block.weights}')
```
### Combine with `Branch`
The `Branch` combinator arranges layers into parallel computational channels:
```
def Branch(*layers):
"""Combinator that applies a list of layers in parallel to copies of inputs.
Each layer in the input list is applied to as many inputs from the stack
as it needs, and their outputs are successively combined on stack.
For example, suppose one has three layers:
- F: 1 input, 1 output
- G: 3 inputs, 1 output
- H: 2 inputs, 2 outputs (h1, h2)
Then Branch(F, G, H) will take 3 inputs and give 4 outputs:
- inputs: a, b, c
- outputs: F(a), G(a, b, c), h1, h2 where h1, h2 = H(a, b)
```
Residual blocks, for example, are implemented using `Branch`:
```
def Residual(*layers, **kwargs):
"""Wraps a series of layers with a residual connection.
Args:
*layers: One or more layers, to be applied in series.
**kwargs: If empty (the usual case), the Residual layer computes the
element-wise sum of the stack-top input with the output of the layer
series. If non-empty, the only key should be 'shortcut', whose value is
a layer that applies to a copy of the inputs and (elementwise) adds its
output to the output from the main layer series.
Returns:
A layer representing a residual connection paired with a layer series.
"""
shortcut = kwargs.get('shortcut') # default None signals no-op (copy inputs)
layers = _ensure_flat(layers)
layer = layers[0] if len(layers) == 1 else Serial(layers)
return Serial(
Branch(shortcut, layer),
Add(), # pylint: disable=no-value-for-parameter
)
```
Here's a simple code example to highlight the mechanics.
### Example 6. Branch
```
relu = tl.Relu()
times_100 = tl.Fn("Times100", lambda x: x * 100.0)
branch_relu_t100 = tl.Branch(relu, times_100)
x = np.array([[-2, -1, 0, 1, 2],
[-20, -10, 0, 10, 20]])
branch_relu_t100.init(signature(x))
y0, y1 = branch_relu_t100(x)
print(f'x:\n{x}\n\n'
f'y0:\n{y0}\n\n'
f'y1:\n{y1}')
```
# 2. Data Streams
The Trax runtime supports the concept of multiple data streams, which gives
individual layers flexibility to:
- process a single data stream ($n_{in} = n_{out} = 1$),
- process multiple parallel data streams ($n_{in} = n_{out} = 2, 3, ... $),
- split or inject data streams ($n_{in} < n_{out}$), or
- merge or remove data streams ($n_{in} > n_{out}$).
We saw in section 1 the example of `Residual`, which involves both a split and a merge:
```
...
return Serial(
Branch(shortcut, layer),
Add(),
)
```
In other words, layer by layer:
- `Branch(shortcut, layers)`: makes two copies of the single incoming data stream, passes one copy via the shortcut (typically a no-op), and processes the other copy via the given layers, applied in series. [$n_{in} = 1$, $n_{out} = 2$]
- `Add()`: combines the two streams back into one by adding elementwise. [$n_{in} = 2$, $n_{out} = 1$]
# 3. Data Stack
# 4. Defining New Layer Classes
## Simpler layers, with the `Fn` layer-creating function.
Many layer types needed in deep learning compute pure functions from inputs to
outputs, using neither weights nor randomness. You can use Trax's `Fn` function
to define your own pure layer types:
```
"""Returns a layer with no weights that applies the function f.
`f` can take and return any number of arguments, and takes only positional
arguments -- no default or keyword arguments. It often uses JAX-numpy (jnp).
The following, for example, would create a layer that takes two inputs and
returns two outputs -- element-wise sums and maxima:
Fn('SumAndMax', lambda x0, x1: (x0 + x1, jnp.maximum(x0, x1)), n_out=2)
The layer's number of inputs (`n_in`) is automatically set to number of
positional arguments in `f`, but you must set the number of outputs (`n_out`)
explicitly whenever it's not the default value 1.
Args:
name: Class-like name for the resulting layer; for use in debugging.
f: Pure function from input tensors to output tensors, where each input
tensor is a separate positional arg, e.g.:
f(x0, x1) --> x0 + x1
Output tensors must be packaged as specified for `Layer.forward`.
n_out: Number of outputs promised by the layer; default value 1.
Returns:
Layer executing the function f.
"""
```
### Example 7. Use `Fn` to define a new layer type:
```
# Define new layer type.
def Gcd():
"""Returns a layer to compute the greatest common divisor, elementwise."""
return tl.Fn('Gcd', lambda x0, x1: jnp.gcd(x0, x1))
# Use it.
gcd = Gcd()
x0 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
x1 = np.array([11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
y = gcd((x0, x1))
print(f'x0:\n{x0}\n\n'
f'x1:\n{x1}\n\n'
f'gcd((x0, x1)):\n{y}')
```
### Example 8. `Fn` with multiple outputs:
```
# Define new layer type.
def SumAndMax():
"""Returns a layer to compute sums and maxima of two input tensors."""
return tl.Fn('SumAndMax',
lambda x0, x1: (x0 + x1, jnp.maximum(x0, x1)),
n_out=2)
# Use it.
sum_and_max = SumAndMax()
x0 = np.array([1, 2, 3, 4, 5])
x1 = np.array([10, 20, 30, 40, 50])
y0, y1 = sum_and_max([x0, x1])
print(f'x0:\n{x0}\n\n'
f'x1:\n{x1}\n\n'
f'y0:\n{y0}\n\n'
f'y1:\n{y1}')
```
### Example 9. Use `Fn` to define a configurable layer:
```
# Function defined in trax/layers/core.py:
def Flatten(n_axes_to_keep=1):
layer_name = f'Flatten_keep{n_axes_to_keep}'
def f(x): # pylint: disable=invalid-name
in_rank = len(x.shape)
if in_rank <= n_axes_to_keep:
raise ValueError(f'Input rank ({in_rank}) must exceed the number of '
f'axes to keep ({n_axes_to_keep}) after flattening.')
return jnp.reshape(x, (x.shape[:n_axes_to_keep] + (-1,)))
return tl.Fn(layer_name, f)
flatten_keep_1_axis = Flatten(n_axes_to_keep=1)
flatten_keep_2_axes = Flatten(n_axes_to_keep=2)
x = np.array([[[1, 2, 3],
[10, 20, 30],
[100, 200, 300]],
[[4, 5, 6],
[40, 50, 60],
[400, 500, 600]]])
y1 = flatten_keep_1_axis(x)
y2 = flatten_keep_2_axes(x)
print(f'x:\n{x}\n\n'
f'flatten_keep_1_axis(x):\n{y1}\n\n'
f'flatten_keep_2_axes(x):\n{y2}')
```
## Full subclass definitions, where necessary
# 5. Models
| github_jupyter |
# Table of Contents
<p><div class="lev2 toc-item"><a href="#group-by-function;-reducer-generator" data-toc-modified-id="group-by-function;-reducer-generator-01"><span class="toc-item-num">0.1 </span>group by function; reducer generator</a></div>
```
sql="""
SELECT cc, sum(iso_num) AS x, sum(cc) AS xm, sum(avg_vis) AS x,'ddd' as d, avg_vis
FROM 'NOAA/DMSP-OLS/NIGHTTIME_LIGHTS'
WHERE ST_INTERSECTS(ST_SetSRID(ST_GeomFromGeoJSON('{\"type\":\"Polygon\",\"coordinates\":[[[-5.273512601852417,42.81137220349083],[-5.273512601852417,42.811803118457306],[-5.272732079029083,42.811803118457306],[-5.272732079029083,42.81137220349083],[-5.273512601852417,42.81137220349083]]]}'), 4326), the_geom)
and iso_num > 2
and iso_num < 10
or iso_num = 2
order by y asc
GROUP BY x
LIMIT 1
"""
url='https://api.resourcewatch.org/v1/convert/sql2SQL'
payload={
'sql':sql
}
r=requests.get(url, params=payload).json()
r
import ee
import json
from cached_property import cached_property
ee.Initialize()
#le pasariamos data.attributes.jsonSql.where nos deberia de devolver null si no lo encuentra o el geojson. type:function, value:ST_GeomFromGeoJSON arguments[0] value <-- json.parse
def filterGen(data, parents=[]):
# print(data)
# print('-')
# print(parents)
# print('****')
_filters = {
'<': ee.Filter.lt,
'<=': ee.Filter.lte,
'>': ee.Filter.gt,
'>=': ee.Filter.gte,
'<>': ee.Filter.neq,
'=': ee.Filter.eq,
'!=': ee.Filter.neq,
'bedate': ee.Filter.date,
'between': ee.Filter.rangeContains,
'like': ee.Filter.eq,
'%like%': ee.Filter.stringContains,
'%like': ee.Filter.stringEndsWith,
'like%': ee.Filter.stringStartsWith
}
_comparisons = {
'and': ee.Filter.And,
'or': ee.Filter.Or
}
left = None
right = None
result =[]
dparents=list(parents)
if 'type' in [*data] and data['type']=='conditional': ########---------------------------- Leaf with groups:
left = data['left']
right = data['right']
dparents=[data['value']]
elif 'type' in [*data] and data['type']=='operator': ########------------------------------------------- Latests leaf we will want to return
return data['value']
if left and right: ########-------------------------------------- leaf group iteration
#for l in left:
partialL=filterGen(left, dparents)
#for r in right:
partialR=filterGen(right, dparents)
if not partialL:
result=partialR
elif not partialR:
result=partialL
else:
result={dparents[0]:[partialR, partialL]}
return result ########----------------------------------- Return result in:[[ee.Filter.eq('month','historical'),ee.Filter.eq('model','historical'),...],...]
geometry=None
x=filterGen(r['data']['attributes']['jsonSql']['where'])
print(x)
def notDupe(list):
r = [i for n, i in enumerate(list) if i not in list[n + 1:]]
return len(list) == len(r)
def _colGen(selectArray):
columns={'columns': {'cc': 'String',
'iso_alpha2': 'String',
'iso_alpha3': 'String',
'iso_num': 'Float',
'name': 'String',
'region': 'String',
'system:index': 'String',
'tld': 'String'}}
bands={'bands':[{'id': 'avg_vis', 'data_type': {'type': 'PixelType', 'precision': 'int', 'min': 0, 'max': 255}, 'dimensions': [43201, 16801], 'crs': 'EPSG:4326', 'crs_transform': [0.0083333333, 0.0, -180.00416666665, 0.0, -0.0083333333, 75.00416666665]},
{'id': 'stable_lights', 'data_type': {'type': 'PixelType', 'precision': 'int', 'min': 0, 'max': 255}, 'dimensions': [43201, 16801], 'crs': 'EPSG:4326', 'crs_transform': [0.0083333333, 0.0, -180.00416666665, 0.0, -0.0083333333, 75.00416666665]},
{'id': 'cf_cvg', 'data_type': {'type': 'PixelType', 'precision': 'int', 'min': 0, 'max': 255}, 'dimensions': [43201, 16801], 'crs': 'EPSG:4326', 'crs_transform': [0.0083333333, 0.0, -180.00416666665, 0.0, -0.0083333333, 75.00416666665]},
{'id': 'avg_lights_x_pct', 'data_type': {'type': 'PixelType', 'precision': 'float'}, 'dimensions': [43201, 16801], 'crs': 'EPSG:4326', 'crs_transform': [0.0083333333, 0.0, -180.00416666665, 0.0, -0.0083333333, 75.00416666665]}]}
c=[]
b=[]
if columns:
_init_cols=columns['columns'].keys()
if bands:
_init_bands=[v['id'] for v in bands['bands']]
response={
'columns':[],
'_columns':[],
'bands':[],
'_bands':[],
'functions':[],
'others':[]
}
for a in selectArray:
if a['type']=='literal':
# This will retrieve the columns and bands for our dataset
if a['value'] in _init_cols:
response['columns'].append(a)
elif a['value'] in _init_bands:
response['bands'].append(a)
else:
raise NameError('column/band name not valid: {0}'.format(a['value']))
elif a['type']=='function':
# This will retrieve the columns and bands for our dataset and extend the cols/bands to select if they already hasn't being selected
response['functions'].append(a)
c.extend([args['value'] for args in a['arguments'] if args['type']=='literal' and args['value'] in _init_cols])
b.extend([args['value'] for args in a['arguments'] if args['type']=='literal'and args['value'] in _init_bands])
f=[args['value'] for args in a['arguments'] if args['type']=='literal'and args['value'] not in _init_bands and args['value'] not in _init_cols]
if f:
raise NameError('column/band name not valid in function {0}: {1}'.format(a['value'],f))
elif a['type']=='wildcard':
d = [{'type':'literal','alias': None, 'value':f} for f in _init_cols]
response['columns'].extend(d)
else:
response['others'].append(a)
assert notDupe(response['columns']), 'we cannot have 2 columns with the same alias'
assert notDupe(response['bands']), 'we cannot have 2 bands with the same alias'
response['_columns'] =list(set([a['value'] for a in response['columns']]).union(c))
response['_bands']=list(set([a['value'] for a in response['bands']]).union(b))
return response
x=_colGen(r['data']['attributes']['jsonSql']['select'])
print(x)
```
For management pourposes we will need to get the list of bands; columns functions and others selected on the query, compare it with the available columns/bands and decide what to do next.
For feature collection we will only have columns: so function will be applied to column values and we will need to reduceColumn.
For image collections we will have columns and bands we migh need to reduce by column or reduceImage with reduceRegion.
For images we will only have bands. reducers (functions inside ReduceRegion) will be applied only to bands.
## group by function; reducer generator
```
#Load a collection of US counties with census data properties.
counties = ee.FeatureCollection('ft:1S4EB6319wWW2sWQDPhDvmSBIVrD3iEmCLYB7nMM');
#Compute sums of the specified properties, grouped by state name.
sums = counties.filter(ee.Filter.And(ee.Filter.neq('Census 2000 Population', None), ee.Filter.neq('Census 2000 Housing Units', None))).reduceColumns(**{
'selectors': ['Census 2000 Population', 'Census 2000 Housing Units', 'StateName'],
'reducer': ee.Reducer.sum().repeat(2).group(**{
'groupField': 2,
'groupName': 'state'
})
});
#Print the resultant Dictionary.
print(sums);
```
input:
* `x`
* `r['data']['attributes']['jsonSql']['group']`
output:
```
ee.Reducer.sum().repeat(3).group(**{
'groupField': 2,
'groupName': 'x',
}),
```
```
print('x: ',x['functions'])
print('group by: ',r['data']['attributes']['jsonSql']['group'])
def reduceGen(selectFunctions, groupBy):
#input: group by and above x result
#output: reducer well compose
_agFunctions = {
'mean': ee.Reducer.mean,
'max': ee.Reducer.max,
'min': ee.Reducer.min,
'count': ee.Reducer.count,
'sum': ee.Reducer.sum
}
reducers={'reduceRegion':{},
'reduceColumns':{},
'reduceImage':{}
}
reducers = []
result = []
if any(function['value'] == 'sum' for function in selectFunctions):
sum_quantity = sum(function['value'] == 'sum' for function in selectFunctions)
reducer = _agFunctions['sum']().repeat(sum_quantity)
reducers.append(reducer)
# For each reducer in result, apply each group by
# .group(**{'groupField': 0,'groupName':groupBy[0]['value']}
for reducer in reducers:
for group in groupBy:
reducer = reducer.group(**{'groupField': 1,'groupName':group['value']})
if group == groupBy[-1]:
result.append(reducer)
return result
result = reduceGen(x['functions'], r['data']['attributes']['jsonSql']['group'])
print(result[0].getInfo())
class SQL2GEE(object):
"""
Takes an SQL2JSON like object and relates it to Google's Earth Engine syntax (specifically the Python 3.5 GEE API).
Designed to perform operations on three types of geo-objects, Tables (Feature Collections), Rasters (Images) or
Raster Collections (Image Collections).
For single rasters there are only a specific number of valid operations (retrieve metadata, histogram data, or get
summary statistics). We use postgis-like functions as the syntax to do this, and check to see if this is given in
the sql string to detect the user intention.
If geojson data is provided, we will assume that a user intends for us to subset an image, by these data.
"""
def __init__(self, sql, geojson=None, flags=None):
self._raw = sql
self._asset_id = sql['data']['attributes']['jsonSql']['from'].strip("'")
self.metadata = self._metadata()
self.type = self.metadata['type']
self._asset =self._getAsset()
self._parsed = sql['data']['attributes']['jsonSql']
self.geojson = self._geojson_to_featurecollection(geojson)
self.flags = flags # <-- Will be used in a later version of the code
self._filters = {
'<': ee.Filter.lt,
'<=': ee.Filter.lte,
'>': ee.Filter.gt,
'>=': ee.Filter.gte,
'<>': ee.Filter.neq,
'=': ee.Filter.eq,
'!=': ee.Filter.neq,
'bedate': ee.Filter.date,
'between': ee.Filter.rangeContains,
'like': ee.Filter.eq,
'%like%': ee.Filter.stringContains,
'%like': ee.Filter.stringEndsWith,
'like%': ee.Filter.stringStartsWith
}
self._comparisons = {
'and': ee.Filter.And,
'or': ee.Filter.Or
}
self._agFunctions = {
'mean': ee.Reducer.mean,
'max': ee.Reducer.max,
'min': ee.Reducer.min,
'count': ee.Reducer.count,
}
self._agTFunctions = {
'mean': ee.Reducer.mean,
'max': ee.Reducer.max,
'min': ee.Reducer.min,
'min': ee.Reducer.min,
}
def _metadata(self):
"""Property that holds the Metadata dictionary returned from Earth Engine."""
if 'ft:' in self._asset_id:
meta = ee.FeatureCollection(self._asset_id).limit(0).getInfo()
assert meta != None, 'please enter a valid fusion table'
info={'type': meta['type'],
'columns':meta['columns'],
'id':self._asset_id,
'version':'',
'properties':meta['properties']}
return info
else:
info=ee.data.getInfo(self._asset_id)
assert info!=None, "data type not expected"
if ('bands' in info) and (not info['bands']):
meta=ee.ImageCollection(self._asset_id).limit(1).getInfo()['features'][0] ### this is a bit ...
info['bands']=meta['bands']
info['columns']={k: type(v).__name__ for k,v in meta['properties'].items()}
return info
def _geo_extraction(self, json_input):
lookup_key='type'
lookup_value='function'
Sqlfunction='ST_GeomFromGeoJSON'
if isinstance(json_input, dict):
for k, v in json_input.items():
if k == lookup_key and v==lookup_value and json_input['value']==Sqlfunction:
yield json_input['arguments'][0]['value'].strip("'")
else:
for child_val in self._geo_extraction(v):
yield child_val
elif isinstance(json_input, list):
for item in json_input:
for item_val in self._geo_extraction(item):
yield item_val
def _geojson_to_featurecollection(self, geojson):
"""If Geojson kwarg is recieved or ST_GEOMFROMGEOJSON sql argument is used,
(containing geojson data) convert it into a useable E.E. object."""
geometries=[json.loads(x) for x in self._geo_extraction(self._parsed)]
if geometries:
geojson = {u'features': geometries,
u'type': u'FeatureCollection'}
if isinstance(geojson, dict):
assert geojson.get('features') != None, "Expected key not found in item passed to geojoson"
return ee.FeatureCollection(geojson.get('features'))
else:
return None
def _getAsset(self):
_data={
'Image':ee.Image(self._asset_id),
'FeatureCollection':ee.FeatureCollection(self._asset_id),
'ImageCollection':ee.ImageCollection(self._asset_id)
}
return _data[self.type]
def _filterGen(self, data, parents=[]):
left = None
right = None
result =[]
dparents=list(parents)
if 'type' in [*data] and data['type']=='conditional': ########---------------------------- Leaf with groups:
left = data['left']
right = data['right']
dparents=[data['value']]
elif 'type' in [*data] and data['type']=='operator': ########------------------------------------------- Latests leaf we will want to return
return self._filters[data['value']](data['left']['value'], data['right']['value'])
#return {data['value']:[data['left']['value'], data['right']['value']]}
if left and right: ########-------------------------------------- leaf group iteration
#for l in left:
partialL=self._filterGen(left, dparents)
#for r in right:
partialR=self._filterGen(right, dparents)
if not partialL:
result=partialR
elif not partialR:
result=partialL
else:
result=self._comparisons[dparents[0]](partialR, partialL)
#result={dparents[0] : [*partialR, *partialL]}
return result ########----------------------------------- Return result in:[[ee.Filter.eq('month','historical'),ee.Filter.eq('model','historical'),...],...]
def _select(self,cols):
# It returns the asset with only the *selected* columns/bands.
if self['type']:
return self.asset.select(cols)
else:
return self.asset
def _where(self):
# It gets *where* conditions and converts them in the proper filters.
# self.asset.filter(ee.Filter([ee.Filter.eq('scenario','historical'), ee.Filter.date('1996-01-01','1997-01-01')])).filterBounds(geometry)
_filters=self._filterGen(self._parsed['where'])
if self.geojson:
return self._asset.filter(_filters).filterBounds(self.geojson)
else:
return self._asset.filter(_filters)
return 0
def _fGroupBy(self):
return 0
def _orderBy(self):
return 0
def _limit(self):
return 0
def _genSql(self):
# it will depends on the asset type, but it will give back this:
# imageCollection.<filters>.<functions>.<sorts>.<imageReducers>.<reduceRegion>.limit(n).getInfo()
# featureCollection.<filters>.<functions>.<sorts>.<columnReducers>.limit(n).getInfo()
# image.<filters>.<functions>.<sorts>.<reduceRegion>.limit(n).getInfo()
return 0
import requests
f=SQL2GEE(r)
print(f.metadata)
#print(f.geojson)
#
print(f._filterGen(r['data']['attributes']['jsonSql']['where']))
print(f._filterGen(r['data']['attributes']['jsonSql']['where']).getInfo())
f._where().getInfo()
```
| github_jupyter |
## Summary
**Parameters**
- `SEQUENCE_GENERATION_METHOD`
- `STRUCTURE_ID`
- `SLURM_ARRAY_TASK_ID`
**Notes:**
- `astar` method should be given >= 64G memory in order to generate 200k sequences.
- `astar` cannot be ran in parallel.
**SLURM scripts**
```bash
export STRUCTURE_ID="4beuA02"
SEQUENCE_GENERATION_METHOD="astar" sbatch --mem 64G --time 72:00:00 ./scripts/run_notebook_gpu.sh $(realpath notebooks/10_generate_protein_sequences.ipynb)
SEQUENCE_GENERATION_METHOD="expectimax" sbatch --mem 32G --time 24:00:00 --array=1-3 ./scripts/run_notebook_gpu.sh $(realpath notebooks/10_generate_protein_sequences.ipynb)
SEQUENCE_GENERATION_METHOD="randexpectimax" sbatch --mem 32G --time 24:00:00 --array=1-3 ./scripts/run_notebook_gpu.sh $(realpath notebooks/10_generate_protein_sequences.ipynb)
```
----
## Imports
```
import gzip
import heapq
import io
import json
import os
import shutil
import time
from pathlib import Path
import kmtools.sci_tools
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import proteinsolver
import pyarrow as pa
import pyarrow.parquet as pq
import torch
import torch_geometric
from IPython.display import HTML, display
from kmbio import PDB
from torch_geometric.data import Batch
from tqdm.notebook import tqdm
```
## Properties
```
NOTEBOOK_NAME = "generate_protein_sequences"
NOTEBOOK_PATH = Path(NOTEBOOK_NAME).resolve()
NOTEBOOK_PATH.mkdir(exist_ok=True)
NOTEBOOK_PATH
UNIQUE_ID = "191f05de"
BEST_STATE_FILES = {
#
"191f05de": "protein_train/191f05de/e53-s1952148-d93703104.state"
}
# STRUCTURE_ID = os.getenv("STRUCTURE_ID", "5vli02")
# STRUCTURE_ID = os.getenv("STRUCTURE_ID", "1n5uA03")
STRUCTURE_ID = os.getenv("STRUCTURE_ID", "4z8jA00")
# STRUCTURE_ID = os.getenv("STRUCTURE_ID", "4unuA00")
# STRUCTURE_ID = os.getenv("STRUCTURE_ID", "4beuA02")
STRUCTURE_ID
STRUCTURE_FILE = Path(
os.getenv(
"STRUCTURE_FILE",
NOTEBOOK_PATH.parent.parent / "proteinsolver" / "data" / "inputs" / f"{STRUCTURE_ID}.pdb",
)
).resolve()
STRUCTURE_FILE
min_expected_proba_preset = {
#
"1n5uA03": 0.20,
"4z8jA00": 0.29,
"4unuA00": 0.25,
"4beuA02": 0.25,
}
MIN_EXPECTED_PROBA = min_expected_proba_preset.get(STRUCTURE_ID, 0.15)
MIN_EXPECTED_PROBA
SEQUENCE_GENERATION_METHOD = os.getenv("SEQUENCE_GENERATION_METHOD", "expectimax")
assert SEQUENCE_GENERATION_METHOD in ("astar", "expectimax", "randexpectimax", "root2expectimax", "root10expectimax")
SEQUENCE_GENERATION_METHOD
START_FILE_INDEX = int(os.getenv("SLURM_ARRAY_TASK_ID", 0)) * 1000
START_FILE_INDEX
os.environ["CUDA_VISIBLE_DEVICES"]
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device
```
## Helper functions
```
@torch.no_grad()
def design_sequence(net, data, random_position=False, value_selection_strategy="map", num_categories=None):
assert value_selection_strategy in ("map", "multinomial", "ref")
if num_categories is None:
num_categories = data.x.max().item()
if hasattr(data, "batch"):
batch_size = data.batch.max().item() + 1
else:
print("Defaulting to batch size of one.")
batch_size = 1
if value_selection_strategy == "ref":
x_ref = data.y if hasattr(data, "y") and data.y is not None else data.x
x = torch.ones_like(data.x) * num_categories
x_proba = torch.zeros_like(x).to(torch.float)
index_array_ref = torch.arange(x.size(0))
mask_ref = x == num_categories
while mask_ref.any():
output = net(x, data.edge_index, data.edge_attr)
output_proba_ref = torch.softmax(output, dim=1)
output_proba_max_ref, _ = output_proba_ref.max(dim=1)
for i in range(batch_size):
mask = mask_ref
if batch_size > 1:
mask = mask & (data.batch == i)
index_array = index_array_ref[mask]
max_probas = output_proba_max_ref[mask]
if random_position:
selected_residue_subindex = torch.randint(0, max_probas.size(0), (1,)).item()
max_proba_index = index_array[selected_residue_subindex]
else:
selected_residue_subindex = max_probas.argmax().item()
max_proba_index = index_array[selected_residue_subindex]
assert x[max_proba_index] == num_categories
assert x_proba[max_proba_index] == 0
category_probas = output_proba_ref[max_proba_index]
if value_selection_strategy == "map":
chosen_category_proba, chosen_category = category_probas.max(dim=0)
elif value_selection_strategy == "multinomial":
chosen_category = torch.multinomial(category_probas, 1).item()
chosen_category_proba = category_probas[chosen_category]
else:
assert value_selection_strategy == "ref"
chosen_category = x_ref[max_proba_index]
chosen_category_proba = category_probas[chosen_category]
assert chosen_category != num_categories
x[max_proba_index] = chosen_category
x_proba[max_proba_index] = chosen_category_proba
mask_ref = x == num_categories
del output, output_proba_ref, output_proba_max_ref
return x.cpu(), x_proba.cpu()
from dataclasses import dataclass
from dataclasses import field
from typing import Any
def load_heap_dump(heap_file):
try:
pfile = pq.ParquetFile(heap_file)
heap = []
for row_group in pfile.num_row_groups:
df = pfile.read_row_group(row_group).to_parquet()
heap = heap + [
proteinsolver.utils.PrioritizedItem(
tup.p, torch.tensor(tup.x, dtype=torch.int8), tup.total_proba, tup.total_logproba
)
for tup in df.itertuples()
]
except Exception as e:
print(f"Encountered error loading heap file '{heap_file}': '{e}'.")
heap_file_bak = heap_file.with_suffix(".parquet.bak")
try:
pfile = pq.ParquetFile(heap_file)
heap = []
for row_group in pfile.num_row_groups:
df = pfile.read_row_group(row_group).to_parquet()
heap = heap + [
proteinsolver.utils.PrioritizedItem(
tup.p, torch.tensor(tup.x, dtype=torch.int8), tup.total_proba, tup.total_logproba
)
for tup in df.itertuples()
]
except Exception as e:
print(f"Encountered error loading heap file '{heap_file_bak}': '{e}'.")
def update_heap_dump(heap_file, heap):
try:
shutil.copy2(heap_file, heap_file.with_suffix(".parquet.bak"))
except FileNotFoundError:
pass
df = pd.DataFrame(
[
{"p": pi.p, "x": pi.x.data.tolist(), "total_proba": pi.total_proba, "total_logproba": pi.total_logproba}
for pi in heap
]
)
chunk_size = 100_000
writer = None
for start in range(0, len(df), chunk_size):
df_chunk = df[start : start + chunk_size]
table = pa.Table.from_pandas(df_chunk, preserve_index=False)
if writer is None:
writer = pq.ParquetWriter(heap_file, table.schema)
writer.write_table(table)
writer.close()
def get_descendents(net, x, total_proba, total_logproba, edge_index, edge_attr, cutoff):
index_array = torch.arange(x.size(0))
mask = x == 20
with torch.no_grad():
output = net(x, edge_index, edge_attr).cpu()
output = torch.softmax(output, dim=1)
output = output[mask]
index_array = index_array[mask]
max_proba, max_index = output.max(dim=1)[0].max(dim=0)
row_with_max_proba = output[max_index]
assert total_logproba <= 0, total_logproba
children = []
for i, p in enumerate(row_with_max_proba):
x_clone = x.clone()
assert x_clone[index_array[max_index]] == 20
x_clone[index_array[max_index]] = i
total_proba_clone = total_proba - cutoff + p.item()
total_logproba_clone = total_logproba - np.log(cutoff) + np.log(p.item())
children.append((x_clone, total_proba_clone, total_logproba_clone))
return children
def design_sequence_astar(
net, data, cutoff, num_categories=20, max_results=5_000, max_heap_size=100_000_000, heap=None
):
# TODO: keep only total probabilities and log-probabilities instead of the entire array
assert num_categories < 128 # So that we can store x as int8
total_proba = cutoff * data.x.size(0)
total_logproba = np.log(cutoff) * data.x.size(0)
if heap is None:
heap = [
proteinsolver.utils.PrioritizedItem(
-total_logproba, data.x.cpu().to(torch.int8), total_proba, total_logproba
)
]
results = []
pbar = tqdm(total=max_results)
while len(results) < max_results:
try:
item = heapq.heappop(heap)
except IndexError:
break
if not (item.x == num_categories).any():
assert item.x.dtype == torch.int8
results.append((item.x.data, item.total_proba, item.total_logproba))
pbar.update(1)
else:
children = get_descendents(
net,
item.x.to(torch.long).to(device),
item.total_proba,
item.total_logproba,
data.edge_index,
data.edge_attr,
cutoff,
)
for x, total_proba, total_logproba in children:
heapq.heappush(
heap,
proteinsolver.utils.PrioritizedItem(
-total_logproba, x.cpu().to(torch.int8), total_proba, total_logproba
),
)
if len(heap) > max_heap_size:
heap = heap[: len(heap) // 2]
heapq.heapify(heap)
return results, heap
```
## Load structure
```
structure_all = PDB.load(STRUCTURE_FILE)
if STRUCTURE_ID in ["5vli02"]:
chain_id = "C"
else:
chain_id = "A"
structure = PDB.Structure(STRUCTURE_FILE.name + chain_id, structure_all[0].extract(chain_id))
assert len(list(structure.chains)) == 1
view = PDB.view_structure(structure)
view
```
## Load model
```
%run protein_train/{UNIQUE_ID}/model.py
batch_size = 1
num_features = 20
adj_input_size = 2
hidden_size = 128
frac_present = 0.5
frac_present_valid = frac_present
info_size= 1024
state_file = BEST_STATE_FILES[UNIQUE_ID]
state_file
net = Net(
x_input_size=num_features + 1, adj_input_size=adj_input_size, hidden_size=hidden_size, output_size=num_features
)
net.load_state_dict(torch.load(state_file, map_location=device))
net.eval()
net = net.to(device)
```
## Design pipeline
### Load protein sequence and geometry
```
pdata = proteinsolver.utils.extract_seq_and_adj(structure, chain_id)
# print(pdata)
sequence_ref = pdata.sequence
print(len(sequence_ref), sequence_ref)
```
### Convert data to suitable format
```
data = proteinsolver.datasets.protein.row_to_data(pdata)
data = proteinsolver.datasets.protein.transform_edge_attr(data)
```
### Basic model statistics
```
model_stats = {}
residues, residue_probas = design_sequence(
net, data.to(device), random_position=False, value_selection_strategy="map", num_categories=20
)
model_stats.update(
{
"map_sequence_identity": sum(
proteinsolver.utils.AMINO_ACIDS[r] == sequence_ref[i] for (i, r) in enumerate(residues)
)
/ len(sequence_ref),
"map_proba": residue_probas.mean().item(),
"map_logproba": residue_probas.log().mean().item(),
}
)
residues, residue_probas = design_sequence(
net, data.to(device), random_position=False, value_selection_strategy="ref", num_categories=20
)
model_stats.update(
{
"ref_sequence_identity": sum(
proteinsolver.utils.AMINO_ACIDS[r] == sequence_ref[i] for (i, r) in enumerate(residues)
)
/ len(sequence_ref),
"ref_proba": residue_probas.mean().item(),
"ref_logproba": residue_probas.log().mean().item(),
}
)
model_stats
model_stats_file = NOTEBOOK_PATH.joinpath(f"stats-{UNIQUE_ID}-{STRUCTURE_FILE.stem}.json")
with model_stats_file.open("wt") as fout:
json.dump(model_stats, fout)
model_stats_file
```
### Run protein design using expectimax search
```
amino_acids = proteinsolver.utils.AMINO_ACIDS
def get_output_file(file_index):
return NOTEBOOK_PATH.joinpath(f"designs-{UNIQUE_ID}-{SEQUENCE_GENERATION_METHOD}-{STRUCTURE_FILE.stem}-{file_index}.parquet")
file_index = START_FILE_INDEX
while get_output_file(file_index).is_file():
file_index += 1
file_index
start_time = time.perf_counter()
random_position = SEQUENCE_GENERATION_METHOD.startswith("rand")
print(f"random_position: {random_position}")
batch_size = int(
512
* (3586 / (data.x.size(0) + data.edge_attr.size(0)))
* (torch.cuda.get_device_properties(device).total_memory / 12_650_217_472)
)
print(f"batch_size: {batch_size}")
batch_size = 1
data_batch = Batch.from_data_list([data.clone() for _ in range(batch_size)]).to(device)
data_batch.x = torch.ones_like(data_batch.x) * 20
batch_values, batch_probas = design_sequence(
net, data_batch, random_position=random_position, value_selection_strategy="multinomial"
)
for i in range(batch_size):
values = batch_values[data_batch.batch == i]
probas = batch_probas[data_batch.batch == i]
sequence = "".join(amino_acids[i] for i in values)
probas_sum = probas.sum().item()
probas_log_sum = probas.log().sum().item()
print(f"Elapsed time: {time.perf_counter() - start_time}.")
timing_stats = {
"5vli02": np.mean(
[
0.13965036603622139,
0.1378761320374906,
0.14166183699853718,
0.1354912610258907,
0.1416573489550501,
]
),
"1n5uA03": np.mean(
[
0.2606568201445043,
0.273853771854192,
0.274543966865167,
0.25143068190664053,
0.2526147000025958,
]
),
"4z8jA00": np.mean(
[
0.2858221740461886,
0.2860491331666708,
0.28511124989017844,
0.2742918790318072,
0.2711744031403214,
]
),
"4unuA00": np.mean(
[
0.36467301612719893,
0.34314795304089785,
0.33564279321581125,
0.37832364114001393,
0.3413601068314165,
]
),
"4beuA02": np.mean(
[
1.2793075828813016,
1.2771926030982286,
1.2803262548986822,
1.276441911002621,
1.2801529061980546,
]
),
}
print(timing_stats)
print(np.mean(list(timing_stats.values())))
```
| github_jupyter |
```
!pip install pandas
!pip install xlrd
!pip install sklearn
!pip install imblearn
import xlrd
book = xlrd.open_workbook("Datasheets info.xlsx")
sheetMQ2 = book.sheet_by_name("MQ2 - Pololulu")
sheetMQ3 = book.sheet_by_name("MQ3 - Sparkfun")
sheetMQ4 = book.sheet_by_name("MQ4 - Sparkfun")
sheetMQ5 = book.sheet_by_name("MQ5 - Sparkfun")
sheetMQ6 = book.sheet_by_name("MQ6 - Sparkfun")
sheetMQ7 = book.sheet_by_name("MQ7 - Sparkfun")
sheetMQ8 = book.sheet_by_name("MQ8 - Sparkfun")
sheetMQ9 = book.sheet_by_name("MQ9 - Haoyuelectronics")
sheetMQ131 = book.sheet_by_name("MQ131- Sensorsportal")
sheetMQ135 = book.sheet_by_name("MQ135 - HANWEI")
sheetMQ303A = book.sheet_by_name("MQ303A - HANWEI")
sheetMQ309A = book.sheet_by_name("MQ309A - HANWEI")
for row_index in range(1,20): #reading first columns
RsR0, LPG, CO, CH4 = sheetMQ9.row_values(row_index, start_colx=0, end_colx=4)
print(RsR0, " ", LPG, " ", CO, " ", CH4)
x_MQ9 = sheetMQ9.col_values(0)[2:]
MQ9_LPG = sheetMQ9.col_values(1)[2:]
MQ9_CO = sheetMQ9.col_values(2)[2:]
MQ9_CH4 = sheetMQ9.col_values(3)[2:]
def zero_to_nan(values):
"""Replace every 0 with 'nan' and return a copy."""
return [float('nan') if x==0 else x for x in values]
MQ9_LPG =zero_to_nan(MQ9_LPG)
MQ9_CH4 =zero_to_nan(MQ9_CH4)
MQ9_CO =zero_to_nan(MQ9_CO)
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
#from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn import datasets
from sklearn import linear_model
dataLPG = {'RsRo': x_MQ9, 'LPG': MQ9_LPG}
dataCH4 = {'RsRo': x_MQ9, 'CH4': MQ9_CH4}
dataCO = {'RsRo': x_MQ9, 'CO': MQ9_CO}
dfMQ9_LPG = pd.DataFrame(dataLPG)
dfMQ9_CH4 = pd.DataFrame(dataCH4)
dfMQ9_CO = pd.DataFrame(dataCO)
dfMQ9_LPG['LPG'] = pd.to_numeric(dfMQ9_LPG['LPG'])
dfMQ9_CH4['CH4'] = pd.to_numeric(dfMQ9_CH4['CH4'])
dfMQ9_CO['CO'] = pd.to_numeric(dfMQ9_CO['CO'])
dfMQ9_LPG['LPG'] = dfMQ9_LPG['LPG'].replace('',None, regex=True)
dfMQ9_CH4['CH4'] = dfMQ9_CH4['CH4'].replace('',None, regex=True)
dfMQ9_CO['CO'] = dfMQ9_CO['CO'].replace('',None, regex=True)
#Global X_Predict variable
X_Predict = dfMQ9_LPG.RsRo.apply(lambda x: [x]).tolist()
#Model and train LPG
dataset2TrainLPG = dfMQ9_LPG.copy()
dataset2TrainLPG.dropna(inplace=True)
X_trainLPG = dataset2TrainLPG.RsRo.apply(lambda x: [x]).tolist()
y_trainLPG = dataset2TrainLPG['LPG'].tolist()
model = linear_model.Lasso(alpha=0.1)
model.fit(X_trainLPG, y_trainLPG)
#Predict
LPG_Predicted = model.predict(X_Predict)
#save into MQ2
MQ9_LPG = LPG_Predicted
#Model and train CH4
dataset2TrainCH4 = dfMQ9_CH4.copy()
dataset2TrainCH4.dropna(inplace=True)
X_trainCH4 = dataset2TrainCH4.RsRo.apply(lambda x: [x]).tolist()
y_trainCH4 = dataset2TrainCH4['CH4'].tolist()
model = linear_model.Lasso(alpha=0.1)
model.fit(X_trainCH4, y_trainCH4)
#Predict
CH4_Predicted = model.predict(X_Predict)
#save into MQ2
MQ9_CH4 = CH4_Predicted
#Model and train CO
dataset2TrainCO = dfMQ9_CO.copy()
dataset2TrainCO.dropna(inplace=True)
X_trainCO = dataset2TrainCO.RsRo.apply(lambda x: [x]).tolist()
y_trainCO = dataset2TrainCO['CO'].tolist()
model = linear_model.Lasso(alpha=0.1)
model.fit(X_trainCO, y_trainCO)
#Predict
CO_Predicted = model.predict(X_Predict)
#save into MQ2
MQ9_CO = CO_Predicted
%config InlineBackend.figure_formats = ['svg']
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.transforms as mtransforms
fig, ax = plt.subplots()
fig.set_size_inches(9, 5.5, forward=True)
fig.set_dpi(200)
# only these two lines are calibration curves
plt.plot(MQ9_LPG, x_MQ9, marker='o', linewidth=1, label='LPG')
plt.plot(MQ9_CH4, x_MQ9, marker='o', linewidth=1, label='CH4')
plt.plot(MQ9_CO, x_MQ9, marker='o', linewidth=1, label='CO')
# reference line, legends, and axis labels
#line = mlines.Line2D([0, 1], [0, 1], color='black')
#transform = ax.transAxes
#line.set_transform(transform)
#ax.add_line(line)
plt.yscale('log')
plt.xscale('log')
plt.legend()
plt.grid(b=True, which='minor', color='lightgrey', linestyle='--')
fig.suptitle('Calibration plot for MQ-9 data')
ax.set_xlabel('PPM Concentration')
ax.set_ylabel('Rs/Ro')
#Save image
plt.savefig('MQ9.svg', format = 'svg', dpi = 1200)
plt.savefig('MQ9.png')
plt.savefig('MQ9.eps', format = 'eps', dpi = 1200)
```
| github_jupyter |
<center> <h1>Realismo local y realismo no local</h1>
<h2> Desigualdades de Bell </h2></center>
Para ejemplificar esto, asumamos que se generan parejas de fotones que están máximamente entrelazados en el cristal del centro con frecuencias $\nu_A$ y $\nu_B$ en direcciones opuestas. Éstos, serán detectados por un par de fotodectores frente a los polarizadores mostrados en la figura, los cuales puede discernir entre estados ortogonales. Los analizadores sólo dejan pasar fotones que se alinean con el eje de polarización mostrado en la figura a cada detector.
<center>
<img src="Images/measure.png" alt="drawing" style="width:350px;">
</center>
El estado que se produce en el cristal se puede describir en la base de polarización como sigue
$$
|\Phi_+^{AB}\rangle =\frac{1}{\sqrt{2}} \left(|x,x\rangle + |y,y\rangle \right).
$$
El proceso de detección se puede describir con los operadores
$$
E^A (\alpha) = |x^A\rangle \langle x^A| - |y^A \rangle \langle y^A|,\\
E^B (\beta) = |x^B\rangle \langle x^B| - |y^B \rangle \langle y^B|.
$$
$P_{+-}$ es la probabilidad que la polarización $x^A$ se observe en $A$ y $y^B$ en $B$, que corresponde con haber obtenido +1 y -1 y un producto -1.
Para cualquier ángulo de los polarizadores mostrado en la figura, es posible escribir las polarizaciones rotadas en la siguiente forma:
$$
|x^A\rangle = cos\alpha |x \rangle + \sin \alpha |y\rangle, \quad
|y^A\rangle = -sin \alpha |x \rangle + \cos \alpha |y\rangle.
$$
Con lo anterior se pueden obtener las diferentes probabilidades $P_{ij}$, $ij = {=,-}$, por ejemplo $P_{++}= \langle \Phi_+^{AB} |x^A,x^B \rangle \langle x^A,x^B| \Phi_+^{AB}= \frac{1}{2}\cos^2(\beta-\alpha)$.
Ejercicio: calcule las probabilidades restantes.
Asimismo, calcule el coeficiente de correlación $\epsilon ^{AB}(\alpha,\beta):=\langle \Phi_+^{AB}|E^A(\alpha)\otimes E^B(\beta) | \Phi_+{AB}\langle$
Deberá obtener los resultados siguientes:
$$
P_{--}=P_{++}\\
P_{+-} = P_{-+} = \frac{1}{2}\sin^2 (\beta-\alpha)
$$
$$
\epsilon ^{AB}(\alpha,\beta)=P_{++}+P_{--}-P_{+-}-P_{-+}=\cos 2(\beta-\alpha)
$$
<center><h2> Variables ocultas </h2></center>
Un conjunto de variables ocultas se sumarizan en $\lambda$.
* $\lambda \in \Re$.
* Las propiedades de un objeto se pueden describir por cierto conjunto de valores de $\lambda$.
* Se producen partículas con un conjunto de valores $\lambda$ por alguna fuente con una densidad de probabilidad dada por $\rho (\lambda)$, se cumple
* $\begin{equation}\int \rho (\lambda) d\lambda =1,\tag{1}\end{equation}$
* $\rho (\lambda)$ es positiva y semidefinida.
<p class="fragment fade-up">
Objeto clásico: Un objeto clásico en $A$, caracterizado por $\lambda$ y con un ángulo de rotación $\delta_1$ del analizador en $A$ tiene predeterminado cual polarización será observada ($x^A$ o $y^A$). Por lo tanto existe una función no ambigua $S_A^\lambda (\delta_1)$ con valores +1 o -1.
$$
S_A^\lambda (\delta_1) = \left \{ \begin{matrix} +1
\\ -1 \end{matrix}\right\}, S_B^\lambda (\delta_2) = \left \{ \begin{matrix} +1
\\ -1 \end{matrix}\right\}.
$$
</p>
<p class="fragment fade-up">
Con la correlación clásica
$$\begin{equation} \epsilon^{cl}(\delta_1,\delta_2) = \int \rho (\lambda) S_A^\lambda (\delta_1) S_B^\lambda (\delta_2) d\lambda.
\label{eq2}
\tag{2}
\end{equation}
$$
</p>
<p class="fragment fade-up">
Esto corresponde con una teoría para variables ocultas $\lambda$.
</p>
</section>
<center><h2> Desigualdades de Bell </h2></center>
En el caso de analizadores con orientación paralela deberá cumplirse la correlación completa
$$ \epsilon^{cl}(\delta_1,\delta_2) = \int \rho (\lambda) S_A^\lambda (\delta_1) S_B^\lambda (\delta_2) d\lambda =1
$$
utilizando (1) y (2), es posible notar que $S_A^\lambda (\delta) = S_B^\lambda (\delta)$
### CASO GENERAL
Se realizarán mediciones utilizando tres orientaciones $\delta_1, \delta_2, \delta_3$. En el orden siguiente $(\delta_1, \delta_2), (\delta_2, \delta_3), (\delta_1, \delta_3)$.
Esto es porque $$ -S^\lambda (\delta_1)S^\lambda (\delta_3) = -S^\lambda (\delta_1)S^\lambda (\delta_2)S^\lambda (\delta_2)S^\lambda (\delta_3)$$.
<p class="fragment fade-up">
Ahora agregamos un término nulo al lado izquierdo dado por $S^\lambda (\delta_1)S^\lambda (\delta_2)-S^\lambda (\delta_1)S^\lambda (\delta_2)$
</p>
<p class="fragment fade-up"> con lo que se pueden arreglar de la sigueinte manera
$$ S^\lambda (\delta_1)S^\lambda (\delta_2) - S^\lambda (\delta_2)S^\lambda (\delta_3) = S^\lambda (\delta_1)S^\lambda (\delta_2) [1-S^\lambda (\delta_2)S^\lambda (\delta_3)]$$
</p>
La integración de la expresión anterior conduce a
$$ \begin{align}
& \left|\int d\lambda \rho (\lambda) [S^\lambda(\delta_1)S^\lambda(\delta_2) - S^\lambda(\delta_1)S^\lambda(\delta_3)]\right| \\
= &\left| \int \rho(\lambda) d\lambda S^\lambda (\delta_1)S^\lambda (\delta_2) [1-S^\lambda (\delta_2)S^\lambda (\delta_3)] \right|\\
\leq & 1 - \int d\lambda \rho(\lambda) S^\lambda (\delta_2)S^\lambda (\delta_3)]
\end{align}
$$
<p class="fragment fade-up"> Tras lo anterior, podemos escribir la relación para la correlación clásica simplemente como
$$ \left| \epsilon^{cl} (\delta_1,\delta_2) - \epsilon^{cl} (\delta_2,\delta_3) \right| \leq 1- \epsilon^{cl} (\delta_2,\delta_3) $$
</p>
<section>
<span class="fragment fade-in">
<span class="fragment highlight-red">La cual es la expresión que aparece en el artículo de Bell de 1964
J.S. Bell, On the Einstein-Podolsky-Rosen paradox, Physics 1, 195-200 (1964)</span>
</span>
</section>
<center><h2> Desigualdad de Clauser, Horne, Shimony and Holt (CHSH) </h2></center>
<p class="fragment fade-up">
Aquí se requieren 2 orientaciones de los analizadores para $A$ y para $B$.
</p>
<p class="fragment fade-up">
Se medirán $\alpha_1$ y $\alpha_2$ en $A$ y $\beta_1$ y $\beta_2$ en $B$.
Recordar que $S^\lambda_{A,B} = \pm 1$. Con esto se construye la siguiente expresión
</p>
<p class="fragment fade-up">
$$S_A^\lambda (\alpha_2) [ S_B^\lambda (\beta_1) +S_B^\lambda (\beta_2)]+S_A^\lambda (\alpha_1) [ S_B^\lambda (\beta_1) -S_B^\lambda (\beta_2)]:=\{ \cdots \}
$$</p>
<p class="fragment fade-up">
Al expresarla en términos de la variable oculta $\lambda$
$$\left|\int \rho (\lambda) d\lambda \{ \cdots \} \right| \leq 2 \int \rho (\lambda) d\lambda =2 $$
</p>
<p class="fragment fade-up">
Con esto escribimos la expresión en términos de los coeficientes de correlación
$$
S^{cl} = \left| \epsilon^{cl} (\alpha_2,\beta_1) + \epsilon^{cl} (\alpha_2,\beta_2) \epsilon^{cl} (\alpha_1,\beta_1) -\epsilon^{cl} (\alpha_1,\beta_2) \right| \leq 2
$$
Clauser, J.F., Horne, M.A., Shimonu, A., and Holt, R.A., Proposed experimento to test local hidden-variable theories, Phys. Rev. Lett., 23, 880-884 (1969).
</p>
Ejemplo de implementación de las desigualdades de Bell con strawberry fields.
<center>
<img src="Images/jgpo1.png" alt="drawing" style="width:600px;">
</center>
Se basan en el estado
$$ | \psi \rangle = \frac{1}{\sqrt{2}} \left( |2\rangle |0\rangle + |0\rangle |2\rangle\right)$$
### Descripción del método híbrido
Pueden medir ya sea N fotones o la cuadratura X, y los resultados análogos a $S^\lambda(\delta)$ se explican como sigue: Alice y Bob pueden obtener los resultados $a,b = \{+1,-1\}$ bajo las siguientes condiciones:
(Se dan para Alice, pero son equivalentes para Bob)
$$
N: \left \{ \begin{matrix} a = +1, & N>0
\\ a = -1, & N=0 \end{matrix} \right. \quad X: \left \{ \begin{matrix} a = +1, & x \in \mathcal{A}^+, \mathcal{A}^+\in \Re, \mathcal{A}^+ =[-z,z]
\\ a = -1, & x \in \mathcal{A}^- = \Re \text{\ } \mathcal{A}^+ \end{matrix} \right.
$$
<p class="fragment fade-up">
Se utiliza la desigualdad CHSH
$S= E_{XX}+ E_{XN} +E_{NX} - E_{NN} \leq 2$,
en donde $E_{jk} = P(a=b|jk) - P(a\neq b | jk)$
</p>
<p class="fragment fade-up">
Si Alice y Bob seleccionan medir en N, entonces $E_{NN} = -1$, esto se puede resumir en $P(a,b|NN) = (1-ab)/4$.
</p>
<p class="fragment fade-up">
¿Cómo hacer esta simulación en strawberry fields?
</p>
<p class="fragment fade-up">
https://peterwittek.com/verifying-cv-bell-correlations.html
</p>
```
import numpy as np
import strawberryfields as sf
from numpy import pi as π
from strawberryfields.ops import Fock, BSgate, MeasureFock, MeasureX
from tqdm import tqdm
np.set_printoptions(suppress=True, precision=3)
def prepare_and_measure(Alice, Bob, q):
Fock(1) | q[0]
Fock(1) | q[1]
BSgate(π/4, π) | (q[0], q[1])
Alice | q[0]
Bob | q[1]
def postprocess(in_, out, z):
if in_ == 0:
if out > 0:
return 1
else:
return 0
else:
if out < -z or out > z:
return 0
else:
return 1
def preprocess(in_):
if in_ == 0:
return MeasureFock()
else:
return MeasureX
def do_experiment(x, y, z=40.83):
Alice = preprocess(x)
Bob = preprocess(y)
eng, q = sf.Engine(2)
with eng:
prepare_and_measure(Alice, Bob, q)
eng.run('fock', cutoff_dim=3)
a = postprocess(x, q[0].val, z)
b = postprocess(y, q[1].val, z)
return a, b
n_rounds = 400
N = np.zeros((2, 2, 2, 2))
for _ in tqdm(range(n_rounds)):
x = np.random.randint(2)
y = np.random.randint(2)
a, b = do_experiment(x, y)
N[a, b, x, y] += 1
def calculate_expectation(N, x, y):
n = sum(N[a, b, x, y] for a in range(2) for b in range(2))
return (sum(N[a, b, x, y] for a, b in zip(range(2), range(2))) -
sum(N[a, b, x, y] for a, b in zip(range(2), range(1, -1,-1))))/n
E_NN = calculate_expectation(N, 0, 0)
E_XN = calculate_expectation(N, 1, 0)
E_NX = calculate_expectation(N, 0, 1)
E_XX = calculate_expectation(N, 1, 1)
print(E_XX + E_XN + E_NX - E_NN)
```
## Ejercicio
* Discute la posibilidad de utilizar las desigualdades de Bell para el mismo problema
* Realiza una adaptación del método de Cavalcanti para estados entrelazados en polarización e impleméntala con el simulador. ¿Qué puedes concluir de tus resultados?
| github_jupyter |
# Visualizing Time Series Data
```
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
%matplotlib inline
df_apple = pd.read_csv('data/apple_stock.csv',index_col='Date',parse_dates=True)
df_apple.head()
# Adj.Close 와 Adj.Volume 의 variance 문제로 보기 불편함.
df_apple[['Volume','Adj Close']].plot()
# Adj.Close 와 Adj.Volume 의 축을 함께 그리기
df_apple[['Volume','Adj Close']].plot(secondary_y=['Volume'])
# figsize 조정, ylabel, xlabel, title 추가
df_apple['Adj Close'].plot(figsize=(12,8))
plt.ylabel('Close Price')
plt.xlabel('Overwrite Date Index')
plt.title('Apple')
```
# Plot Formatting
## X Limits
```
df_apple['Adj Close'].plot(xlim=['2015-01-01','2018-01-01'])
```
## Y Limits
```
df_apple['Adj Close'].plot(xlim=['2015-01-01','2018-01-01'],ylim=[80,180])
```
## Color and Style
```
df_apple['Adj Close'].plot(xlim=['2015-01-01','2018-01-01'],ylim=[80,180],
ls='--',c='r')
```
## Basic matplotlib plot
```
idx = df_apple.loc['2015-01-01':'2018-01-01'].index
stock = df_apple.loc['2015-01-01':'2018-01-01']['Adj Close']
fig, ax = plt.subplots()
ax.plot_date(idx, stock,'-')
plt.tight_layout()
plt.show()
```
## Fix the overlap!
```
fig, ax = plt.subplots()
ax.plot_date(idx, stock,'-')
fig.autofmt_xdate() # Auto fixes the overlap!
plt.tight_layout()
plt.show()
```
## Customize grid
```
fig, ax = plt.subplots()
ax.plot_date(idx, stock,'-')
ax.yaxis.grid(True)
ax.xaxis.grid(True)
fig.autofmt_xdate() # Auto fixes the overlap!
plt.tight_layout()
plt.show()
```
## Format dates on Major Axis
```
idx = df_apple.loc['2018-01-01':].index
stock = df_apple.loc['2018-01-01':]['Adj Close']
fig, ax = plt.subplots(figsize=(15,7))
ax.plot_date(idx, stock,'-')
# Grids
ax.yaxis.grid(True)
ax.xaxis.grid(True)
# Major Axis
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('%b\n%Y'))
fig.autofmt_xdate() # Auto fixes the overlap!
plt.tight_layout()
plt.show()
fig, ax = plt.subplots(figsize=(15,7))
ax.plot_date(idx, stock,'-')
# Grids
ax.yaxis.grid(True)
ax.xaxis.grid(True)
# Major Axis
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n\n%Y--%B'))
fig.autofmt_xdate() # Auto fixes the overlap!
plt.tight_layout()
plt.show()
```
## Minor Axis
```
fig, ax = plt.subplots(figsize=(15,7))
ax.plot_date(idx, stock,'-')
# Major Axis
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n%Y--%B'))
# Minor Axis
ax.xaxis.set_minor_locator(dates.WeekdayLocator())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d'))
# Grids
ax.yaxis.grid(True)
ax.xaxis.grid(True)
fig.autofmt_xdate() # Auto fixes the overlap!
plt.tight_layout()
plt.show()
fig, ax = plt.subplots(figsize=(15,8))
ax.plot_date(idx, stock,'-')
# Major Axis
ax.xaxis.set_major_locator(dates.WeekdayLocator(byweekday=1))
ax.xaxis.set_major_formatter(dates.DateFormatter('%B-%d-%a'))
# Grids
ax.yaxis.grid(True)
ax.xaxis.grid(True)
fig.autofmt_xdate() # Auto fixes the overlap!
plt.tight_layout()
plt.show()
```
| github_jupyter |
[](http://rpi.analyticsdojo.com)
<center><h1>Basic Text Feature Creation in Python</h1></center>
<center><h3><a href = 'http://rpi.analyticsdojo.com'>rpi.analyticsdojo.com</a></h3></center>
```
!wget https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/train.csv
!wget https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/test.csv
import numpy as np
import pandas as pd
import pandas as pd
train= pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
#Print to standard output, and see the results in the "log" section below after running your script
train.head()
#Print to standard output, and see the results in the "log" section below after running your script
train.describe()
train.dtypes
#Let's look at the age field. We can see "NaN" (which indicates missing values).s
train["Age"]
#Now let's recode.
medianAge=train["Age"].median()
print ("The Median age is:", medianAge, " years old.")
train["Age"] = train["Age"].fillna(medianAge)
#Option 2 all in one shot!
train["Age"] = train["Age"].fillna(train["Age"].median())
train["Age"]
#For Recoding Data, we can use what we know of selecting rows and columns
train["Embarked"] = train["Embarked"].fillna("S")
train.loc[train["Embarked"] == "S", "EmbarkedRecode"] = 0
train.loc[train["Embarked"] == "C", "EmbarkedRecode"] = 1
train.loc[train["Embarked"] == "Q", "EmbarkedRecode"] = 2
# We can also use something called a lambda function
# You can read more about the lambda function here.
#http://www.python-course.eu/lambda.php
gender_fn = lambda x: 0 if x == 'male' else 1
train['Gender'] = train['Sex'].map(gender_fn)
#or we can do in one shot
train['NameLength'] = train['Name'].map(lambda x: len(x))
train['Age2'] = train['Age'].map(lambda x: x*x)
train
#We can start to create little small functions that will find a string.
def has_title(name):
for s in ['Mr.', 'Mrs.', 'Miss.', 'Dr.', 'Sir.']:
if name.find(s) >= 0:
return True
return False
#Now we are using that separate function in another function.
title_fn = lambda x: 1 if has_title(x) else 0
#Finally, we call the function for name
train['Title'] = train['Name'].map(title_fn)
test['Title']= train['Name'].map(title_fn)
test
#Writing to File
submission=pd.DataFrame(test.loc[:,['PassengerId','Survived']])
#Any files you save will be available in the output tab below
submission.to_csv('submission.csv', index=False)
```
| github_jupyter |
# [Chapter 2] 머신러닝 프로젝트 처음부터 끝까지
**✔︎ 예제 프로젝트 주요 단계**
1. 큰 그림을 본다.
2. 데이터를 구한다.
3. 데이터를 탐색하고 시각화한다.
4. 데이터를 준비한다.
5. 모델을 선택하고 훈련시킨다.
6. 모델을 상세하게 조정한다.
7. 솔루션을 제시한다.
8. 시스템을 론칭하고 모니터링하고 유지 보수한다.
## 1. 실제 데이터로 작업하기
**✔︎ 유명한 공개 데이터 저장소**
- [UC Irvine 머신러닝 저장소](http://archive.ics.uci.edu/ml/)
- [Kaggle Datasets](http://www.kaggle.com/datasets)
- [Amazon AWS Datasets](http://aws.amazon.com/ko/datasets)
## 2. 큰 그림 보기
### 1) 문제 정의
- 파이프라인 : 데이터처리 컴포넌트들이 연속되어 있는것 (각 컴포넌트는 독립적)
- 부동산 가격 예측 : 지도학습(각 샘플이 레이블됨) + 다변량 회귀(특성이 여러개) + 배치학습(데이터가 연속적X)
### 2) 성능 측정 지표 선택
- 평균 제곱근 오차(RMSE=Root Mean Square Error) : (예측값 - 실제값) ** 2의 합계를 m으로 나눈 후 √ ➜ 회귀문제에서 제일 많이 쓰임
- 평균 절대 오차(MAE=Mean Absolute Error) : |(예측값 - 실제값)|의 합계를 m으로 나눔 ➜ 이상치로 보이는 구역이 많을때
### 3) 가정 검사
- 지금까지 만든 가정을 나열하고 검사해보기 (ex. 가격이 아니라 저렴/보통/고가 같은 카테고리로 나누게되면 회귀가 아니라 분류작업이 됨)
## 3. 데이터 가져오기
### 1) 작업환경 만들기
- Python, Jupyter, NumPy, Pandas, Matplotlib, Scikit-learn 설치
### 2) 데이터 다운로드
```
import os
import tarfile
from six.moves import urllib
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml/master/"
HOUSING_PATH = os.path.join("datasets", "housing")
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"
def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
if not os.path.isdir(housing_path):
os.makedirs(housing_path)
tgz_path = os.path.join(housing_path, "housing.tgz")
urllib.request.urlretrieve(housing_url, tgz_path)
housing_tgz = tarfile.open(tgz_path)
housing_tgz.extractall(path=housing_path)
housing_tgz.close()
fetch_housing_data()
import pandas as pd
def load_housing_data(housing_path=HOUSING_PATH):
csv_path = os.path.join(housing_path, "housing.csv")
return pd.read_csv(csv_path)
```
### 3) 데이터 구조 훑어보기
```
housing = load_housing_data()
housing.head() # 첫 5행 출력
housing.info() # 데이터의 간략설명
```
**✔︎ 위 info데이터로 알 수 있는 것**
- 총 데이터 20,640개 / total_bedrooms만 20,433개 ➜ 207개는 이 특성이 없음
- ocean_proximity : 아마도 text + categorical (이거빼고는 모두 float 숫자형)
```
# 어떤 카테고리 있는지, 각 카테고리마다 얼마나 많은 구역 있는지 확인
housing["ocean_proximity"].value_counts()
housing.describe() # 숫자형 특성의 요약정보
# %matplotlib inline : Matplotlib이 Jupyter의 백엔드사용(그래프가 노트북안에 그려짐)
%matplotlib inline
import matplotlib.pyplot as plt
housing.hist(bins=50, figsize=(20,15))
plt.show()
```
**✔︎ 히스토그램에서 확인할 수 있는 사항**
- median_income : US달러로 표현X/ 상한 15, 하한 0.5로 스케일 조정된 데이터
- housing_median_age, median_house_value
- 오른쪽에서 그래프가 심하게 높아지면서 끝남 ➜ max, min이 설정됨
- median_house_value값은 target으로 사용하기 때문에 상의해서 max값을 없애고 정확한 레이블 구하거나 or test set에서 제거
- 특성들의 스케일이 서로 많이 다름 ➜ 스케일링 필요
- 히스토그램 꼬리가 두꺼움 = 가운데에서 오른쪽으로 더 멀리 뻗어있음 ➜ 종 모양 되도록 변형필요
### 4) 테스트 세트 만들기
- data snooping 편향 : 테스트세트로 일반화오차 추정하면 매우 낙관적 ➜ 론칭후 기대성능 안나옴 ➜ 무작위로 데이터셋의 20%정도 떼어내어 테스트셋 생성
- 랜덤추출의 문제점 : 프로그램 실행할때마다 다른 테스트셋이 생성되어 결국 전체 데이터셋을 보게됨 ➜ 처음 실행에서 테스트셋 저장후 다음 실행에서 이를 불러들여야함
**✔︎ 일반적인 해결책**
- 샘플의 식별자 사용해 테스트셋으로 보낼지 말지 결정
```
# 각 샘플 식별자의 해시값 마지막바이트 <= 51일 때만 테스트셋으로 보냄
from zlib import crc32
import numpy as np
def test_set_check(identifier, test_ratio):
return crc32(np.int64(identifier)) & 0xffffffff < test_ratio * 2**32
def split_train_test_by_id(data, test_ratio, id_column):
ids = data[id_column]
in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio))
return data.loc[~in_test_set], data.loc[in_test_set]
# 주택 데이터셋에는 식별자컬럼X ➜ 행의 인덱스를 ID로 사용
housing_with_id = housing.reset_index() # 'index'열 추가된 dataframe
train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "index")
test_set.head()
# scikit-learn 이용 (제일 많이사용)
from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)
test_set.head()
```
**✔︎ median_income이 median_house_value 예측하는데 매우 중요하다는 정보 얻음**
- 계층별로 데이터셋에 충분한 샘플 수 있어야함 = 너무 많은 계층X + 각 계층이 충분히 커야함
```
housing["median_income"].hist()
# 소득 카테고리 개수를 제한하기 위해 1.5로 나눔
housing["income_cat"] = np.ceil(housing["median_income"] / 1.5)
# 5 이상은 5로 합침
housing["income_cat"].where(housing["income_cat"] < 5, 5.0, inplace=True)
housing["income_cat"].hist()
# 소득카테고리 기반으로 계층샘플링
from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(housing, housing["income_cat"]):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
# 전체 주택 데이터셋에서 소득 카테고리의 비율
housing["income_cat"].value_counts() / len(housing)
```
**✔︎ 전체 데이터셋과 계층 샘플링으로 만든 테스트셋에서 소득 카테고리 비율 비교**
- 계층 샘플링 사용해 만든 테스트셋(Stratified)이 Overall과 거의 같음
- Random 샘플링은 비율이 많이 다름
```
def income_cat_proportions(data):
return data["income_cat"].value_counts() / len(data)
train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)
compare_props = pd.DataFrame({
"Overall": income_cat_proportions(housing),
"Stratified": income_cat_proportions(strat_test_set),
"Random": income_cat_proportions(test_set),
}).sort_index()
compare_props["Rand. %error"] = 100 * compare_props["Random"] / compare_props["Overall"] - 100
compare_props["Strat. %error"] = 100 * compare_props["Stratified"] / compare_props["Overall"] - 100
compare_props
```
## 4. 데이터 이해를 위한 탐색과 시각화
```
# 훈련셋을 손상시키지 않기 위해 복사본 사용
housing = strat_train_set.copy()
```
### 1) 지리적 데이터 시각화
```
housing.plot(kind="scatter", x="longitude", y="latitude")
# alpha 추가해 데이터포인트가 밀집된 영역 보여주기
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.1)
# s=인구=원의 반지름 / c=가격=색깔
# cmap="jet" : 파란색-빨간색으로 나타내는 컬러맵
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4,
s=housing["population"]/100, label="population", figsize=(10,7),
c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True,
sharex=False)
plt.legend()
```
### 2) 상관관계 조사
- 상관계수 : 선형적인 상관관계만 측정, 기울기와 관계X
```
corr_matrix = housing.corr()
corr_matrix["median_house_value"].sort_values(ascending=False)
from pandas.plotting import scatter_matrix
attributes = ["median_house_value", "median_income", "total_rooms",
"housing_median_age"]
scatter_matrix(housing[attributes], figsize=(12, 8))
# 중간주택가격 예측에 가장 유용해보이는 중간소득과의 상관관계
housing.plot(kind="scatter", x="median_income", y="median_house_value", alpha=0.1)
plt.axis([0, 16, 0, 550000])
```
✔︎ **이 그래프로 알 수 있는 것**
- 상관관계가 매우 강함 (위쪽으로 향함 + 포인트들이 너무 널리 퍼져있지X)
- 가격제한값이 \$500,000와 \$450,000, \$350,000 등등 몇 군데에서 직선에 가까움 ➜ 이런 이상한 형태를 학습하지 않도록 해당 구역 제거
### 3) 특성 조합으로 실험
```
housing["rooms_per_household"] = housing["total_rooms"]/housing["households"]
housing["bedrooms_per_room"] = housing["total_bedrooms"]/housing["total_rooms"]
housing["population_per_household"]=housing["population"]/housing["households"]
corr_matrix = housing.corr()
corr_matrix["median_house_value"].sort_values(ascending=False)
```
- bedrooms_per_room : total_rooms, total_bedrooms보다 상관관계 높음 ➜ 침대/방의 비율이 낮음 = 더 비싼 경향
- rooms_per_household : total_rooms보다 상관관계 높음 ➜ 더 큰집이 더 비쌈
## 5. 머신러닝 알고리즘을 위한 데이터 준비
- 함수를 만들어 데이터준비를 자동화시키기
```
# 훈련셋을 위해 레이블 삭제
housing = strat_train_set.drop("median_house_value", axis=1)
# 데이터 복사본 만들어 원본에 영향X
housing_labels = strat_train_set["median_house_value"].copy()
```
### 1) 데이터 정제
```
# Missing data가 있는 rows
sample_incomplete_rows = housing[housing.isnull().any(axis=1)].head()
sample_incomplete_rows
# 1. 해당 데이터 전부 제거
sample_incomplete_rows.dropna(subset=["total_bedrooms"])
# 2. 특성 column 삭제
sample_incomplete_rows.drop("total_bedrooms", axis=1)
# 3. 특정값으로 채우기 (ex. 0,평균,중간값 등)
# 훈련셋의 중간값을 median에 저장해놓고 테스트셋의 누락값에 채우기
median = housing["total_bedrooms"].median()
sample_incomplete_rows["total_bedrooms"].fillna(median, inplace=True)
sample_incomplete_rows
from sklearn.preprocessing import Imputer
imputer = Imputer(strategy="median")
# 중간값이 수치형 특성에서만 계산되니까 텍스트특성은 제외
housing_num = housing.drop('ocean_proximity', axis=1)
# imputer : 중간값 계산해 객체의 statistics_ 속성에 저장
imputer.fit(housing_num)
imputer.statistics_
# 수동으로 계산한 값과 같은지 확인
housing_num.median().values
# 훈련셋에서 누락된 값을 학습한 중간값으로 바꾸기
X = imputer.transform(housing_num)
# NumPy 배열을 Pandas dataframe으로 바꾸기
housing_tr = pd.DataFrame(X, columns=housing_num.columns,
index = list(housing.index.values))
```
### 2) 텍스트와 범주형 특성 다루기
```
housing_cat = housing['ocean_proximity']
housing_cat.head(10)
# factorize : 문자열 범주형을 숫자형으로 변환
housing_cat_encoded, housing_categories = housing_cat.factorize()
housing_cat_encoded[:10]
housing_categories
```
**✔︎ One-hot encoding : 한 특성만 1이고(핫) 나머지는 0**
```
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder()
housing_cat_1hot = encoder.fit_transform(housing_cat_encoded.reshape(-1,1))
housing_cat_1hot
# OneHotEncoder는 희소행렬(Sparse matrix) 반환 ➜ 밀집된 NumPy 배열로 바꾸기
housing_cat_1hot.toarray()
```
### 3) 나만의 변환기
- 데이터 준비단계를 자동화해 많은 하이퍼파라미터 조합을 시도 후 최상의 조합 찾기
```
from sklearn.base import BaseEstimator, TransformerMixin
# 컬럼 인덱스
rooms_ix, bedrooms_ix, population_ix, household_ix = 3, 4, 5, 6
class CombinedAttributesAdder(BaseEstimator, TransformerMixin):
def __init__(self, add_bedrooms_per_room = True): # no *args or **kargs
self.add_bedrooms_per_room = add_bedrooms_per_room
def fit(self, X, y=None):
return self # nothing else to do
def transform(self, X, y=None):
rooms_per_household = X[:, rooms_ix] / X[:, household_ix]
population_per_household = X[:, population_ix] / X[:, household_ix]
if self.add_bedrooms_per_room:
bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix]
return np.c_[X, rooms_per_household, population_per_household,
bedrooms_per_room]
else:
return np.c_[X, rooms_per_household, population_per_household]
attr_adder = CombinedAttributesAdder(add_bedrooms_per_room=False)
housing_extra_attribs = attr_adder.transform(housing.values)
```
### 4) 특성 스케일링
- 모든 특성의 범위를 같도록 만들기
- 훈련셋에만 fit()한 후 ➜ 훈련셋, 테스트셋에는 transform()
✔︎ **min-max 스케일링 (=정규화(normalization))**
- MinMaxScaler : 0~1 범위에 들도록 값 이동후 스케일 조정
✔︎ **표준화(standardization)**
- StandardScaler : 분산 1, 평균 0으로 조정
### 5) 변환 파이프라인
```
# Pipeline 클래스 : 연속된 변환을 순서대로 처리
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
num_pipeline = Pipeline([
('imputer', SimpleImputer(strategy="median")),
('attribs_adder', CombinedAttributesAdder()),
('std_scaler', StandardScaler())
])
housing_num_tr = num_pipeline.fit_transform(housing_num)
from sklearn.compose import ColumnTransformer
num_attribs = list(housing_num)
cat_attribs = ["ocean_proximity"]
full_pipeline = ColumnTransformer([
("num", num_pipeline, num_attribs),
("cat", OneHotEncoder(categories='auto'), cat_attribs),
])
housing_prepared = full_pipeline.fit_transform(housing)
housing_prepared
```
## 6. 모델 선택과 훈련
### 1) 훈련 세트에서 훈련하고 평가하기
```
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(housing_prepared, housing_labels)
# 훈련 샘플 몇 개를 사용해 전체 파이프라인을 적용
some_data = housing.iloc[:5]
some_labels = housing_labels.iloc[:5]
some_data_prepared = full_pipeline.transform(some_data)
print("Prediction:", lin_reg.predict(some_data_prepared))
print("Label:", list(some_labels))
from sklearn.metrics import mean_squared_error
housing_predictions = lin_reg.predict(housing_prepared)
lin_mse = mean_squared_error(housing_labels, housing_predictions)
lin_rmse = np.sqrt(lin_mse)
lin_rmse
```
✔︎ **DecisionTreeRegressor 훈련**
```
from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor()
tree_reg.fit(housing_prepared, housing_labels)
housing_predictions = tree_reg.predict(housing_prepared)
tree_mse = mean_squared_error(housing_labels, housing_predictions)
tree_rmse = np.sqrt(tree_mse)
tree_rmse
```
### 2) 교차 검증을 사용한 평가
✔︎ **K-fold cross-validation**
- 훈련셋을 fold라 불리는 10개의 서브셋으로 무작위로 분할
- ➜ 모델을 10번 훈련하고 평가
- ➜ 매번 다른 폴드를 선택해 평가에 사용하고 나머지 9개 폴드는 훈련에 사용
- ➜ 10개의 평가점수가 담긴 배열이 아웃풋됨
```
from sklearn.model_selection import cross_val_score
# scoring : 클수록 좋은 효용함수 필요. MSE값을 neg로 입력해야함
scores = cross_val_score(tree_reg, housing_prepared, housing_labels,
scoring="neg_mean_squared_error", cv=10)
tree_rmse_scores = np.sqrt(-scores)
def display_scores(scores):
print("Scores:", scores)
print("Mean:", scores.mean())
print("Standard deviation:", scores.std())
display_scores(tree_rmse_scores)
lin_scores = cross_val_score(lin_reg, housing_prepared, housing_labels,
scoring="neg_mean_squared_error", cv=10)
lin_rmse_scores = np.sqrt(-lin_scores)
display_scores(lin_rmse_scores)
```
## 7. 모델 세부 튜닝
### 1) 그리드 탐색
- 탐색하고자 하는 하이퍼파라미터와 시도해볼값을 지정 ➜ 가능한 모든 하이퍼파라미터 조합에 대해 교차검증 사용해 평가
### 2) 랜덤 탐색
- 각 반복마다 하이퍼파라미터에 임의의 수를 대입해 지정한 횟수만큼 각기 다른 값을 평가
### 3) 앙상블 방법
- 최상의 모델을 연결
### 4) 최상의 모델과 오차 분석
- 최상의 모델을 분석하면 문제에 대한 좋은 통찰 얻음
- 시스템이 특정한 오차를 만들었다면 왜 그런 문제가 생겼는지 이해하고 문제해결방법 찾기
### 5) 테스트 세트로 시스템 평가하기
## 8. 론칭, 모니터링, 그리고 시스템 유지 보수
| github_jupyter |
# ElasticNet with StandardScaler
This Code template is for the regression analysis using a ElasticNet Regression and the feature rescaling technique StandardScaler in a pipeline
### Required Packages
```
import warnings as wr
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import ElasticNet
from sklearn.metrics import mean_squared_error, r2_score,mean_absolute_error
wr.filterwarnings('ignore')
```
### Initialization
Filepath of CSV file
```
#filepath
file_path= ""
```
List of features which are required for model training .
```
#x_values
features=[]
```
Target feature for prediction.
```
#y_value
target=''
```
### Data Fetching
Pandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.
We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.
```
df=pd.read_csv(file_path) #reading file
df.head()#displaying initial entries
print('Number of rows are :',df.shape[0], ',and number of columns are :',df.shape[1])
df.columns.tolist()
```
### Data Preprocessing
Since the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes.
```
def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_dummies(df)
```
#### Correlation Map
In order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns.
```
plt.figure(figsize = (15, 10))
corr = df.corr()
mask = np.triu(np.ones_like(corr, dtype = bool))
sns.heatmap(corr, mask = mask, linewidths = 1, annot = True, fmt = ".2f")
plt.show()
correlation = df[df.columns[1:]].corr()[target][:]
correlation
```
### Feature Selections
It is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.
We will assign all the required input features to X and target/outcome to Y.
```
#spliting data into X(features) and Y(Target)
X=df[features]
Y=df[target]
```
Calling preprocessing functions on the feature and target set.
```
x=X.columns.to_list()
for i in x:
X[i]=NullClearner(X[i])
X=EncodeX(X)
Y=NullClearner(Y)
X.head()
```
### Data Splitting
The train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data.
```
#we can choose randomstate and test_size as over requerment
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 1) #performing datasplitting
```
## Model
### Data Scaling
**Used StandardScaler**
* Standardize features by removing the mean and scaling to unit variance The standard score of a sample x is calculated as:
z = (x - u) / s
* Where u is the mean of the training samples or zero if with_mean=False, and s is the standard deviation of the training samples or one if with_std=False.
### ElasticNet
Elastic Net first emerged as a result of critique on Lasso, whose variable selection can be too dependent on data and thus unstable. The solution is to combine the penalties of Ridge regression and Lasso to get the best of both worlds.
**Features of ElasticNet Regression-**
* It combines the L1 and L2 approaches.
* It performs a more efficient regularization process.
* It has two parameters to be set, λ and α.
#### Model Tuning Parameters
1. alpha : float, default=1.0
> Constant that multiplies the penalty terms. Defaults to 1.0. See the notes for the exact mathematical meaning of this parameter. alpha = 0 is equivalent to an ordinary least square, solved by the LinearRegression object. For numerical reasons, using alpha = 0 with the Lasso object is not advised. Given this, you should use the LinearRegression object.
2. l1_ratio : float, default=0.5
> The ElasticNet mixing parameter, with 0 <= l1_ratio <= 1. For l1_ratio = 0 the penalty is an L2 penalty. For l1_ratio = 1 it is an L1 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
3. normalize : bool, default=False
>This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
4. max_iter : int, default=1000
>The maximum number of iterations.
5. tol : float, default=1e-4
>The tolerance for the optimization: if the updates are smaller than tol, the optimization code checks the dual gap for optimality and continues until it is smaller than tol.
6. selection : {‘cyclic’, ‘random’}, default=’cyclic’
>If set to ‘random’, a random coefficient is updated every iteration rather than looping over features sequentially by default. This (setting to ‘random’) often leads to significantly faster convergence especially when tol is higher than 1e-4.
```
#training the ElasticNet
Input=[("standard",StandardScaler()),("model",ElasticNet())]
model = Pipeline(Input)
model.fit(X_train,y_train)
```
#### Model Accuracy
score() method return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
```
print("Accuracy score {:.2f} %\n".format(model.score(X_test,y_test)*100))
#prediction on testing set
prediction=model.predict(X_test)
```
### Model evolution
**r2_score:** The r2_score function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions.
**MAE:** The mean abosolute error function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our model.
**MSE:** The mean squared error function squares the error(penalizes the model for large errors) by our model.
```
print('Mean Absolute Error:', mean_absolute_error(y_test, prediction))
print('Mean Squared Error:', mean_squared_error(y_test, prediction))
print('Root Mean Squared Error:', np.sqrt(mean_squared_error(y_test, prediction)))
print("R-squared score : ",r2_score(y_test,prediction))
#ploting actual and predicted
red = plt.scatter(np.arange(0,80,5),prediction[0:80:5],color = "red")
green = plt.scatter(np.arange(0,80,5),y_test[0:80:5],color = "green")
plt.title("Comparison of Regression Algorithms")
plt.xlabel("Index of Candidate")
plt.ylabel("target")
plt.legend((red,green),('ElasticNet', 'REAL'))
plt.show()
```
### Prediction Plot¶
First, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis. For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis.
```
plt.figure(figsize=(10,6))
plt.plot(range(20),y_test[0:20], color = "green")
plt.plot(range(20),model.predict(X_test[0:20]), color = "red")
plt.legend(["Actual","prediction"])
plt.title("Predicted vs True Value")
plt.xlabel("Record number")
plt.ylabel(target)
plt.show()
```
#### Creator: Vipin Kumar , Github: [Profile](https://github.com/devVipin01)
| github_jupyter |
Most similar topics for all DUC2006 + DUC2007 topics
===
Disclaimer. I use python 2.7, so take care if you use something else...
```
import numpy as np
import os
from os import path
from gensim.models import KeyedVectors
import codecs
from scipy.spatial.distance import cosine
import scipy
import json
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
from sklearn import decomposition
from sklearn import datasets
def load_w2v_by_name(embeddings_path = path.abspath(path.normpath(path.join(path.expanduser("~"), ".ukpsummarizer","embeddings"))), variant="google.neg.300d"):
binary = True
embeddings={}
if variant == "google.neg.300d":
embeddPath = path.normpath(path.join(embeddings_path, "english/GoogleNews-vectors-negative300.bin.gz"))
embeddData = path.normpath(path.join(embeddings_path, "english/data/"))
vocab_size = 3000000
embedding_size = 300
elif variant == "glove.6B.300d":
embeddPath = path.normpath(path.join(embeddings_path, "english/glove/glove.6B.300d.txt.w2v"))
embeddData = path.normpath(path.join(embeddings_path, "english/glove/glove.6B.300d/"))
vocab_size = 400000
embedding_size = 300
binary=False
elif variant == "tudarmstadt_german":
embeddPath = path.normpath(path.join(embeddings_path, "german/2014_tudarmstadt_german_50mincount.vec"))
embeddData = path.normpath(path.join(embeddings_path, "german/data/"))
vocab_size = 648460
embedding_size = 100
else:
raise ValueError("Embeddings variant unknown. was %s" % (variant))
if not path.exists(embeddData):
os.makedirs(embeddData)
embeddings = LoadEmbeddings(filepath=embeddPath, data_path=embeddData, vocab_size=vocab_size,
embedding_size=embedding_size, binary_val=binary)
return embeddings
class LoadEmbeddings():
def __init__(self, filepath, data_path, vocab_size, embedding_size=300, binary_val=True):
self.vocab_dict = {}
self.embedding_size = embedding_size
_, self.embedding_variant = os.path.split(data_path)
self.loadEmbeddings(filepath, data_path, vocab_size, binary_val)
def convertToNumpy(self, vector):
return np.array([float(x) for x in vector])
def loadEmbeddings(self, filepath, data_path, vocab_size, binary_val):
embed_short = os.path.normpath("%s/embed.dat" % data_path)
if not path.exists(embed_short):
print("Caching word embeddings in memmapped format...")
print(binary_val, filepath)
wv = KeyedVectors.load_word2vec_format("%s" % (filepath), binary=binary_val)
fp = np.memmap(embed_short, dtype=np.double, mode='w+', shape=wv.syn0.shape)
fp[:] = wv.syn0[:]
with open(os.path.normpath("%s/embed.vocab" % data_path), "w") as fp:
for _, w in sorted((voc.index, word) for word, voc in wv.vocab.items()):
fp.write("%s\n"%(w.encode("utf8")))
del fp, wv
self.W = np.memmap(os.path.normpath("%s/embed.dat" % data_path), dtype=np.double, mode="r", shape=(vocab_size, self.embedding_size))
with codecs.open(os.path.normpath("%s/embed.vocab" % data_path), 'r', 'utf-8') as f:
vocab_list = [x.strip() for x in f.readlines()]
self.vocab_dict = {w: k for k, w in enumerate(vocab_list)}
def word2embedd(self, word):
word = word.lower()
if word in self.vocab_dict:
return self.W[self.vocab_dict[word]]
else:
return self.W[self.vocab_dict["unknown"]]
def isKnown(self, word):
word = word.lower()
return word in self.vocab_dict
class ConceptEmbedder():
def __init__(self, word_embeddings):
self.word_embeddings = word_embeddings
self.cache = {}
self.errorcount = 0
def __call__(self, words):
"""
:param concept: str representing the concept
:return: vectorial representation of the concept
@type concept: list[str]
"""
key = " ".join(sorted(words))
w2v = self.word_embeddings
vector = np.zeros(w2v.embedding_size)
if not self.cache.has_key(key):
for word in words:
if w2v.isKnown(word):
lookup = w2v.word2embedd(word.lower())
vector += lookup
else:
# print("unknown word:", word)
self.errorcount += 1
vector = vector / len(words)
self.cache[key] = vector
return self.cache[key]
# if the embeddings are stored somewhere else than in the dedicated directory,
# load_w2v does also provide another parameter that can be used to modify the behaviour
embeddings = load_w2v_by_name(variant="glove.6B.300d")
ce = ConceptEmbedder(embeddings)
```
Now lets do some basics on texts
===
```
"The quick brown fox jumped over the lazy dog".split(" ")
sorted("The quick brown fox jumped over the lazy dog".split(" "))
# linear algebra on "concepts"
ce("The quick brown fox jumped over the lazy dog".split(" ")) - ce(["The fox jumped over the dog"])
cosine(ce("The quick brown fox jumped over the lazy dog".split(" ")), ce("The brown fox jumped over the lazy dog".split(" ")))
cosine(ce("The quick brown fox jumped over the lazy dog".split(" ")), ce("The brown fox jumped over the dog".split(" ")))
cosine(ce("The quick brown fox jumped over the lazy dog".split(" ")), ce("The fox jumped over the dog".split(" ")))
cosine(ce("The quick brown fox jumped".split(" ")), ce("jumped over the lazy dog".split(" ")))
```
Example creation of distance matrix from strings
===
```
titles = ["incremental self improvement for life time multi agent reinforcement learning",
"incremental self improvement for life time multi agent active learning",
"incremental self improvement",
"an intrinsic neuromodulation model for realizing anticipatory behavior in reaching movement under unexperienced force fields"]
vectors = [ce(title) for title in titles]
# calculate the condensed distance matrix. Beware, it really is the DISTANCE, not the similarity.
cdm = scipy.spatial.distance.pdist(vectors, "cosine")
# to have a "nice" distance matrix, we need to convert the condensed DM into squarified form
sdm = scipy.spatial.distance.squareform(cdm)
sdm
m = round(np.min(cdm), 3)+0.001
res = np.where(sdm<=m)
res
```
Because of the fact that the diagonal is zero, those are also included in the result. So the only values of interest in the `res` object are those where the value at the same index in both array differ.
```
titles[0]
titles[1]
```
Distance matrix for all DUC2006 + DUC2007 topics
===
```
p = path.abspath(path.normpath(path.join(".","cosine-on-titles", "duc2006+2007-titles.json")))
df = pd.read_json(p)
df.head()
titles = df["narrative"]
vectors = [ce(title) for title in titles]
len(vectors)
cdm = scipy.spatial.distance.pdist(vectors, "cosine")
cdm
sdm = scipy.spatial.distance.squareform(cdm)
np.fill_diagonal(sdm, np.inf) # fill diagonal with +inf to prevent those cells as minimae
m = round(np.min(cdm), 3)+0.003
res = np.where(sdm<=m)
np.min(cdm)
np.max(cdm)
np.where(cdm<0.01)
np.min(sdm)
np.max(sdm)
sdm.argmin(axis=0)
np.transpose(np.where(sdm<0.003))
for u in np.transpose(np.where(sdm<0.003)):
print df.iloc[[ u[0], u[1]]]["topic"]
df.iloc[np.where(sdm<0.003)[0],np.where(sdm<0.003)[1]]
np.where(sdm<0.0)[0]
df.iloc[[0,13,73]]
df.iloc[[53,64]]
df.iloc[[62,64]]
```
Project the distance matrix in lower dimensions
===
```
dmf = pd.DataFrame(sdm)
pcasdm = np.fill_diagonal(sdm, 0.0)
pca = decomposition.PCA(n_components=2)
pca.fit(sdm)
x = pca.transform(sdm)
pcadf = pd.DataFrame(x, columns=["x","y"])
pcadf.plot.scatter(x="x",y="y")
plt.show()
```
Weather and climate cluster
===
```
df.loc[df["topic"] == "D0641E"]
df.loc[df["topic"] == "D0643G"]
sdm[85][87]
```
| github_jupyter |
<center>
<img src="https://gitlab.com/ibm/skills-network/courses/placeholder101/-/raw/master/labs/module%201/images/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" />
</center>
# **Survey Dataset Exploration Lab**
Estimated time needed: **30** minutes
## Objectives
After completing this lab you will be able to:
* Load the dataset that will used thru the capstone project.
* Explore the dataset.
* Get familier with the data types.
## Load the dataset
Import the required libraries.
```
import pandas as pd
```
The dataset is available on the IBM Cloud at the below url.
```
dataset_url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DA0321EN-SkillsNetwork/LargeData/m1_survey_data.csv"
```
Load the data available at dataset_url into a dataframe.
```
# your code goes here
df = pd.read_csv(dataset_url)
```
## Explore the data set
It is a good idea to print the top 5 rows of the dataset to get a feel of how the dataset will look.
Display the top 5 rows and columns from your dataset.
```
# your code goes here
df.head()
```
## Find out the number of rows and columns
Start by exploring the numbers of rows and columns of data in the dataset.
Print the number of rows in the dataset.
```
# your code goes here
# df[df.columns[0]].count()
len(df)
```
Print the number of columns in the dataset.
```
# your code goes here
len(df.columns)
```
## Identify the data types of each column
Explore the dataset and identify the data types of each column.
Print the datatype of all columns.
```
# your code goes here
df.dtypes
```
Print the mean age of the survey participants.
```
# your code goes here
# df.columns
df['Age'].mean()
```
The dataset is the result of a world wide survey. Print how many unique countries are there in the Country column.
```
# your code goes here
df['Country'].unique()
```
## Authors
Ramesh Sannareddy
### Other Contributors
Rav Ahuja
## Change Log
| Date (YYYY-MM-DD) | Version | Changed By | Change Description |
| ----------------- | ------- | ----------------- | ---------------------------------- |
| 2020-10-17 | 0.1 | Ramesh Sannareddy | Created initial version of the lab |
Copyright © 2020 IBM Corporation. This notebook and its source code are released under the terms of the [MIT License](https://cognitiveclass.ai/mit-license?utm_medium=Exinfluencer\&utm_source=Exinfluencer\&utm_content=000026UJ\&utm_term=10006555\&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDA0321ENSkillsNetwork21426264-2021-01-01\&cm_mmc=Email_Newsletter-\_-Developer_Ed%2BTech-\_-WW_WW-\_-SkillsNetwork-Courses-IBM-DA0321EN-SkillsNetwork-21426264\&cm_mmca1=000026UJ\&cm_mmca2=10006555\&cm_mmca3=M12345678\&cvosrc=email.Newsletter.M12345678\&cvo_campaign=000026UJ).
| github_jupyter |
## 1. Breath alcohol tests in Ames, Iowa, USA
<p>Ames, Iowa, USA is the home of Iowa State University, a land grant university with over 36,000 students. By comparison, the city of Ames, Iowa, itself only has about 65,000 residents. As with any other college town, Ames has had its fair share of alcohol-related incidents. (For example, Google 'VEISHEA riots 2014'.) We will take a look at some breath alcohol test data from Ames that is published by the State of Iowa.</p>
<p><img style="width:500px" src="https://s3.amazonaws.com/assets.datacamp.com/production/project_208/img/usa.jpg"> </p>
<p>The data file 'breath_alcohol_ames.csv' contains 1,556 readings from breath alcohol tests administered by the Ames and Iowa State University Police Departments from January 2013 to December 2017. The columns in this data set are year, month, day, hour, location, gender, Res1, Res2.</p>
```
# import pandas
# ... YOUR CODE FOR TASK 1 ...
import pandas as pd
# read the data into your workspace
ba_data = pd.read_csv("datasets/breath_alcohol_ames.csv")
# quickly inspect the data
print(ba_data.head())
# obtain counts for each year
ba_year = ba_data['year'].value_counts()
ba_year
```
## 2. What is the busiest police department in Ames?
<p>There are two police departments in the data set: the Iowa State University Police Department and the Ames Police Department. Which one administers more breathalyzer tests? </p>
```
# use value_counts to tally up the totals for each department
pds = ba_data['location'].value_counts()
pds
```
## 3. Nothing Good Happens after 2am
<p><img src="https://s3.amazonaws.com/assets.datacamp.com/production/project_208/img/himym02.jpg" style="float: left;margin:5px 20px 5px 1px;width:300px"></p>
<p>We all know that "nothing good happens after 2am." Thus, there are inevitably some times of the day when breath alcohol tests, especially in a college town like Ames, are most and least common. Which hours of the day have the most and least breathalyzer tests? </p>
```
%matplotlib inline
# print(ba_data["hour"].value_counts())
# count by hour
hourly = ba_data.groupby(['hour']).size()
# print(hourly)
# create a vertical bar graph of the arrest count by hour
hourly.plot.bar()
```
## 4. Breathalyzer tests by month
<p>Now that we have discovered which time of day is most common for breath alcohol tests, we will determine which time of the year has the most breathalyzer tests. Which month will have the most recorded tests?</p>
```
# count by month and arrange by descending frequency
monthly = ba_data.groupby(['month']).size()
# use plot.bar to make the appropriate bar chart
monthly.plot.bar()
```
## 5. COLLEGE
<p><img src="https://s3.amazonaws.com/assets.datacamp.com/production/project_208/img/PF2081John-Belushi-College-Posters.jpg" style="float: left;margin:5px 20px 5px 1px"> </p>
<p>When we think of (binge) drinking in college towns in America, we usually think of something like this image at the left. And so, one might suspect that breath alcohol tests are given to men more often than women and that men drink more than women. </p>
```
# count by gender
counts_gender = ba_data["gender"].value_counts()
# print(counts_gender)
# create a dataset with no NAs in gender
gen = ba_data.dropna(subset=["gender"])
# print(gen)
# create a mean test result variable
mean_bas = gen.assign(meanRes=(gen["Res1"] + gen["Res2"])/2)
# # create side-by-side boxplots to compare the mean blood alcohol levels of men and women
mean_bas.boxplot(['meanRes'], by = "gender")
## 6. Above the legal limit
<p>In the USA, it is illegal to drive with a blood alcohol concentration (BAC) above 0.08%. This is the case for <a href="https://www.dmv.org/automotive-law/dui.php">all 50 states</a>. Assuming everyone tested in our data was driving (though we have no way of knowing this from the data), if either of the results (<code>Res1</code>, <code>Res2</code>) are above 0.08, the person would be charged with DUI (driving under the influence). </p>
# Filter the data
duis = ba_data[(ba_data["Res1"] > 0.08) | (ba_data["Res2"] > 0.08)]
# print(duis)
# proportion of tests that would have resulted in a DUI
# print(duis.shape)
p_dui = duis.shape[0] / ba_data.shape[0]
p_dui
```
## 7. Breathalyzer tests: is there a pattern over time?
<p>We previously saw that 2am is the most common time of day for breathalyzer tests to be administered, and August is the most common month of the year for breathalyzer tests. Now, we look at the weeks in the year over time. </p>
```
# Create date variable
ba_data['date'] = pd.to_datetime(ba_data[['year', 'month', 'day']])
# Create a week variable
ba_data['week'] = ba_data['date'].dt.week
# Check your work
ba_data.head()
```
## 8. Looking at timelines
<p>How do the weeks differ over time? One of the most common data visualizations is the time series, a line tracking the changes in a variable over time. We will use the new <code>week</code> variable to look at test frequency over time. We end with a time series plot showing the frequency of breathalyzer tests by week in year, with one line for each year. </p>
```
# choose and count the variables of interest
timeline = ba_data.___(['___','___']).___()['Res1']
# unstack and plot
timeline.___().___(title='VEISHEA DUIs', legend=True)
```
## 9. The end of VEISHEA
<p>From <a href="https://en.wikipedia.org/wiki/VEISHEA">Wikipedia</a>:
"VEISHEA was an annual week-long celebration held each spring on the campus of Iowa State University in Ames, Iowa. The celebration featured an annual parade and many open-house demonstrations of the university facilities and departments. Campus organizations exhibited products, technologies, and held fundraisers for various charity groups. In addition, VEISHEA brought speakers, lecturers, and entertainers to Iowa State. [...] VEISHEA was the largest student-run festival in the nation, bringing in tens of thousands of visitors to the campus each year."</p>
<p>This over 90-year tradition in Ames was <a href="https://www.news.iastate.edu/news/2014/08/07/veisheaend">terminated permanently</a> after <a href="https://www.desmoinesregister.com/story/news/crime-and-courts/2014/04/09/veishea-ames-car-tipping/7495935/">riots in 2014</a>, where drunk celebrators flipped over multiple vehicles and tore light poles down. This was not the first incidence of violence and severe property damage in VEISHEA's history. Did former President Leath make the right decision by canceling VEISHEA?</p>
```
## Was it right to permanently cancel VEISHEA? TRUE or FALSE?
canceling_VEISHEA_was_right = ___
```
| github_jupyter |
```
import os
import random as rnd
import numpy as np
import pandas as pd
import peakutils
import cv2 as cv
from matplotlib import pyplot as plt
%matplotlib notebook
def add_images(dirname, offset=np.array([0, 0]), macrostep=np.array([0, 0]), step=np.array([0, 0]),\
infield_shifts=np.array([np.array([0, 0]), np.array([0, 0])]), annotation=None,\
multifields=True):
full_df = pd.DataFrame()
for i in os.listdir(dirname):
path = os.path.join(dirname, i)
if os.path.isfile(path):
parts = i.split('.')
if parts[-1] not in image_formats:
continue
name = ".".join(parts[0:-1]).split('_')
if len(name) >= 3 and not multifields:
if name[-3][:-1] != "f" and name[-3][:-1] != "F" and name[-3][:-1] != "field":
print("Supposedly auxillary image", i, "was not inserted")
continue
field = int(name[-3][-1])
shift = macrostep * np.array([(field - 1) % 2, (field - 1) // 2])
infield_shift = infield_shift[0]
elif len(name) >= 4 and multifields:
if name[-4][:-1] != "f" and name[-4][:-1] != "F" and name[-4][:-1] != "field":
print("Supposedly auxillary image", i, "was not inserted")
continue
field = int(name[-4][-1])
infield = name[-3]
shift = macrostep * np.array([(field-1) % 2, (field-1) // 2])
if infield == 'r':
infield_shift = infield_shifts[1]
elif infield == 'l':
infield_shift = infield_shifts[0]
else:
print("Wrong filename. Image", i, "was not inserted")
continue
else:
print("Wrong filename. Image", i, "was not inserted")
continue
p0 = offset + shift + infield_shift + np.array([int(name[-2])-1, int(name[-1])-1]) * step
sup_path = os.path.join(dirname, '_'.join(name) + '_sup.' + parts[-1])
if not os.path.isfile(sup_path):
sup_path = None
df = addpic(path, sup_path, p0, step, annotation)
if df is None:
print("Cannot find 4 crosses in", i)
continue
full_df = full_df.append(df)
full_df.to_csv(os.path.join(dirname, "info.csv"), header=None, index=False)
return full_df
def add_images_QDEV(dirname, macrooffset=np.array([360, 360]), offset=np.array([10, 12]),\
macrostep=np.array([600, 600]), step=np.array([120, 120]),\
ministep=np.array([25, 16]), annotation=None, threshold='Adaptive'):
full_df = pd.DataFrame()
for i in os.listdir(dirname):
path = os.path.join(dirname, i)
if os.path.isfile(path):
parts = i.split('.')
if parts[-1] not in image_formats:
continue
name = ".".join(parts[0:-1]).split('_')
if len(name) >= 6:
if name[-5][0] != "f" and name[-5][0] != "F" and name[-5][:-1] != "field":
print("Supposedly auxillary image", i, "was not inserted")
continue
field = int(name[-5][1:])
shift = macrooffset + macrostep*np.array([(field-1) % 4, (field-1) // 4])
shift += step*np.array([int(name[-4])-1, int(name[-3])-1])
p0 = shift + offset + ministep*np.array([int(name[-2])-1, int(name[-1])-1])
else:
print("Wrong filename. Image", i, "was not inserted")
continue
sup_path = os.path.join(dirname, '_'.join(name) + '_sup.' + parts[-1])
if not os.path.isfile(sup_path):
sup_path = None
df = addpic(path, sup_path, p0, ministep, annotation, threshold)
if df is None:
print("Cannot find 4 crosses in", i)
continue
full_df = full_df.append(df)
full_df.to_csv(os.path.join(dirname, "info.csv"), header=None, index=False)
return full_df
image_formats = set(["png", "jpg", "tif", "tiff"])
def get_coords(cnt):
x, y = cnt.T[0][0], cnt.T[1][0]
histx, binsx = np.histogram(x, bins=min(200, max(x)-min(x)));
indsx = peakutils.indexes(histx, min_dist=3, thres=0.3)
if len(indsx) > 2:
new = sorted(indsx, key=lambda i: histx[i])
indsx = np.array(new[-2:])
histy, binsy = np.histogram(y, bins=min(200, max(y)-min(y)));
indsy = peakutils.indexes(histy, min_dist=3, thres=0.3)
if len(indsy) > 2:
new = sorted(indsy, key=lambda i: histy[i])
indsy = np.array(new[-2:])
if len(indsx) < 2 or len(indsy) < 2:
return None
return np.array([binsx[indsx[1]] + binsx[indsx[0]], binsy[indsy[1]] + binsy[indsy[0]]], dtype='int64') // 2
def addpic(path, sup_path, p0, step, annotation, threshold='Adaptive'):
'''
p0 - coords of left bottom cross on image (in um)
step - step in um from bottom left cross to the top right
supposed that crosses are vertexes of a rectangle
'''
# coordinates in microns - new points
i = np.array([1, 0])
j = np.array([0, 1])
new_pts = np.array([p0, p0 + step*i, p0 + step*j, p0 + step])
# coordinats in pixels - old points
old_pts = []
orig_img = cv.imread(path)
size_thres = min(orig_img.shape[:1]) * 0.06
img = orig_img
if sup_path is not None:
img = cv.imread(sup_path)
size_thres /= 2
if annotation is not None:
img = img[:int(img.shape[0] * (1-annotation))]
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
equ = cv.equalizeHist(gray)
if threshold == 'Adaptive':
thresh = cv.adaptiveThreshold(equ, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 61, 0)
else:
_, thresh = cv.threshold(equ, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
kernel = np.ones((2, 2), np.uint8)
# Iteration over opening 'iterations' -- increasing contrast and
# checking if it is possible to distinguish 4 differenet crosses
itera = 1
while len(old_pts) != 4 and itera < 5:
old_pts = []
plot_contours = []
opening = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel, iterations=itera)
contours, hierarchy = cv.findContours(opening, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
for cnt in contours:
x, y, w, h = cv.boundingRect(cnt)
if w > size_thres and h > size_thres:
M = cv.moments(cnt)
centroid = np.array([int(M['m10'] / M['m00']), int(M['m01'] / M['m00'])])
bbox_center = np.array([x + w / 2, y + h / 2])
center = get_coords(cnt)
if center is not None:
# print(w / h < 1.33, w / h > 0.75,np.linalg.norm(centroid - center) < 0.2 * max(w,h),\
# np.linalg.norm(centroid - bbox_center) < 0.2 * max(w,h))
if w / h < 1.33 and w / h > 0.75 and np.linalg.norm(centroid - center) < 0.2 * max(w,h) and\
np.linalg.norm(centroid - bbox_center) < 0.2 * max(w,h) or sup_path is not None:
plot_contours.append(cnt)
old_pts.append([center[0] - orig_img.shape[1]/2, -center[1] + orig_img.shape[0]/2 + 1])
itera += 1
plot_img = orig_img
for cnt in plot_contours:
x, y, w, h = cv.boundingRect(cnt)
center = get_coords(cnt)
cv.rectangle(plot_img, (x, y), (x + w, y + h), (0, 255, 0), img.shape[0] // 400)
color = (rnd.randint(0, 256), rnd.randint(0, 256), rnd.randint(0, 256))
cv.drawContours(plot_img, [cnt], 0, color, img.shape[0] // 400, cv.LINE_8, hierarchy, 0)
cv.circle(plot_img, tuple(center), img.shape[0] // 200, (0, 0, 255), -1)
old_pts = np.array(sorted(old_pts, key=lambda p: 2*np.sign(p[1]) + np.sign(p[0])))
df = pd.DataFrame([[path] + list(old_pts.flatten()) + list(new_pts.flatten())])
fig, ax = plt.subplots(figsize=(7, 7 * orig_img.shape[0]/orig_img.shape[1]))
fig.tight_layout()
ax.imshow(plot_img, interpolation='none', cmap='gray');
if len(old_pts) != 4:
return None
return df
dirname = "/home"
# Old designs with multifields
# df = add_images(dirname, offset=np.array([456, 576]), macrostep=np.array([1800, 1800]),\
# infield_shifts = np.array([[0, 0], [240, 0]]), step=np.array([16, 12]))
df = add_images_QDEV(dirname, threshold='Binary')
df = add_images_QDEV(dirname, annotation=0.0625, threshold='Adaptive')
```
| github_jupyter |
```
%matplotlib inline
```
# Testing DuBE with different number of classes (3-15)
In this example, we compare the :class:`duplebalance.DupleBalanceClassifier`
and other ensemble-based class-imbalanced learning methods on multi-class
tasks (with number of classes varying from 3 to 15).
```
print(__doc__)
RANDOM_STATE = 42
```
## Preparation
Import necessary packages.
```
from duplebalance import DupleBalanceClassifier
from duplebalance.base import sort_dict_by_key
import numpy as np
import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
```
## Train All Ensemble Classifier
Train all ensemble-based IL classifier (including DuBE) on multi-class datasets.
```
from imbalanced_ensemble.ensemble import *
ensemble_init_kwargs = {
'base_estimator': DecisionTreeClassifier(),
'n_estimators': 10,
'random_state': RANDOM_STATE,
}
dube_fit_kwargs = {
'resampling_target': 'hybrid',
'resampling_strategy': 'shem',
'perturb_alpha': .5,
}
eval_kwargs = {'average': 'macro', 'multi_class': 'ovo'}
ensemble_clfs = {
'DuBE': DupleBalanceClassifier,
'RusBoost': RUSBoostClassifier,
'OverBoost': OverBoostClassifier,
'SmoteBoost': SMOTEBoostClassifier,
'RusBoost': RUSBoostClassifier,
'UnderBagging': UnderBaggingClassifier,
'OverBagging': OverBaggingClassifier,
'SmoteBagging': SMOTEBaggingClassifier,
'Cascade': BalanceCascadeClassifier,
'SelfPacedEns': SelfPacedEnsembleClassifier,
}
# Initialize results list
all_results = []
for n_class in range(3, 16):
# Assign long-tail class weights
weights = np.array([np.power(.8, i) for i in range(n_class)])
weights /= weights.sum()
info = "#Classes: {}\nImbalance Ratio: ".format(n_class)
for weight in weights:
info += '{:.2f}/'.format(weight/weights.min())
print (info.rstrip('/'))
# Generate synthetic multi-class imbalanced dataset
X, y = make_classification(n_classes=n_class, class_sep=1,
weights=weights, n_informative=4, n_redundant=1, flip_y=0,
n_features=20, n_clusters_per_class=1, n_samples=5000, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42)
for ens_name, clf_class in ensemble_clfs.items():
# Train all ensemble classifiers
clf = clf_class(
**ensemble_init_kwargs
)
if ens_name == 'DuBE':
clf.fit(X_train, y_train, **dube_fit_kwargs)
else: clf.fit(X_train, y_train)
y_pred_proba = clf.predict_proba(X_test)
score = roc_auc_score(y_test, y_pred_proba, **eval_kwargs)
all_results.append([ens_name, score, n_class])
print ("{:<15s} | Balanced AUROC: {:.3f}".format(ens_name, score))
```
## Results Visualization
```
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('talk')
all_results_columns = ['Method', 'AUROC (macro)', '#Classes']
data_vis = pd.DataFrame(all_results, columns=all_results_columns)
def plot_results_comp(data_vis, x, y, title, figsize=(8,6)):
fig = plt.figure(figsize=figsize)
ax = sns.lineplot(
data=data_vis, x=x, y=y, hue='Method', style='Method',
markers=True, err_style='bars', linewidth=4, markersize=20, alpha=0.9
)
for position, spine in ax.spines.items():
spine.set_color('black')
spine.set_linewidth(2)
ax.grid(color = 'black', linestyle='-.', alpha=0.3)
ax.set_ylabel('AUROC (macro)')
ax.set_title(title)
ax.legend(
title='',
borderpad=0.25,
columnspacing=0.05,
borderaxespad=0.15,
handletextpad=0.05,
labelspacing=0.05,
handlelength=1.2,
)
return ax
plot_results_comp(data_vis, x='#Classes', y='AUROC (macro)',
title='DuBE versus Ensemble Baselines (#Classes 3-15)')
```
| github_jupyter |
# Cake Eating
```
# Cake Eating
# max sum β^t * u(c(t))
# s.t. c(t) + x(t+1) <= x(t)(1+r), x(0) given
import numpy as np
x0 = 1
β = 0.95
γ = 0.9
r = 0.05
u = lambda c: c**(1-γ)/(1-γ)
# V(x) = max u(x(1+r)-x')) + β*V_old(x')
# s.t. 0 < x'< x
N = 100
X = np.linspace(1e-6, x0, N) # State space
V_ = u(X) # initial guess for value function
V = np.zeros(N)
P = np.zeros(N)
# VFI
for i in range(100):
for ix, x in enumerate(X):
V[ix] = np.max(u(x*(1+r) - X[X <= x*(1+r)]) + β*V_[X <= x*(1+r)])
P[ix] = X[np.argmax(u(x*(1+r) - X[X <= x*(1+r)]) + β*V_[X <= x*(1+r)])]
V_ = V.copy()
import matplotlib.pyplot as plt
plt.plot(X, V)
plt.title('Value Function V(x)')
plt.show()
plt.plot(X, P)
plt.title('Decision Rule x\'(x)')
plt.show()
plt.plot(X, X*(1+r)-P)
plt.title('Decision Rule c(x)')
plt.show()
```
# Cake Eating with Taste Shocks
```
# Cake eating with taste shocks
# max sum βt * u(c(t), e(t))
# s.t. c(t) + x(t+1) <= x(t)(1+r), x(0) given
# T(i,j) = P(e(t+1) = i| e(t) = j)
import numpy as np
x0 = 1
β = 0.95
γ = 0.5
r = 0.05
u = lambda c, e: c**(1-γ)/(1-γ) * np.exp(e**0.5)
# V(x, e) = max u(x*(1+r) - x', e) + β*E[V(x', e')|e], x0 given
N_X = 500
N_E = 3
X = np.linspace(1e-6, x0, N_X) # State Space
E = np.arange(1, N_E+1, 1) # Shock Space
V_ = np.zeros((N_X, N_E))
V = np.zeros((N_X, N_E))
P = np.zeros((N_X, N_E))
T = np.ones((N_E, N_E))/N_E
T = np.array([[0.9, 0.9, 0.9],
[0.05, 0.5, 0.05],
[0.05, 0.05, 0.05]]) # high taste shocks are less likely
# V(x, e) = max u(x*(1+r)-x', e) + β*E[V(x', e')|e], x0 given
for i in range(10):
for ix, x in enumerate(X):
for ie, e in enumerate(E):
V[ix, ie] = np.max(u(x*(1+r) - X[X <= x*(1+r)], e) + β*np.dot(V_[X <= x*(1+r), :], T[:, ie]))
P[ix, ie] = X[np.argmax(u(x*(1+r) - X[X <= x*(1+r)], e) + β*np.dot(V_[X <= x*(1+r), :], T[:, ie]))]
V_ = V.copy()
import matplotlib.pyplot as plt
for i, j in enumerate(E):
plt.plot(X, V[:, i], label = f'e={j}')
plt.legend()
plt.title('Value Function V(x)')
plt.show()
for i, j in enumerate(E):
plt.plot(X, P[:, i], label = f'e={j}')
plt.legend()
plt.title('Decision Rule x\'(x)')
plt.show()
for i, j in enumerate(E):
plt.plot(X, X*(1+r) - P[:, i], label = f'e={j}')
plt.legend()
plt.title('Decision Rule c(x)')
plt.show()
Xdata
# Function Approximation with NNs
Xdata = np.ones((N_X*N_E, 2))
Xdata[:, 0] = np.r_[X, X, X]
Xdata[:, 1] = np.r_[np.ones(N_X), 2*np.ones(N_X), 3*np.ones(N_X)]
Ydata = np.r_[P[:, 0], P[:, 1], P[:, 2]]
#Ydata = P.reshape(N_E * N_X)
import pandas as pd
df = pd.DataFrame(np.c_[Ydata, Xdata], columns = ['Policy', 'Cake', 'Shock'])
import plotly.express as px
fig = px.scatter_3d(df, x='Cake', y='Shock', z='Policy')
fig.show()
# Function Approximation with NNs
Xdata = np.ones((N_X*N_E, 2))
Xdata[:, 0] = np.r_[X, X, X]
Xdata[:, 1] = np.r_[np.ones(N_X), 2*np.ones(N_X), 3*np.ones(N_X)]
Ydata = np.r_[P[:, 0], P[:, 1], P[:, 2]]
#Ydata = P.reshape(N_E * N_X)
# Function Approximation with NNs
Xdata = np.ones((N_X*N_E, 2))
Xdata[:, 0] = np.r_[X, X, X]
Xdata[:, 1] = np.r_[np.ones(N_X), 2*np.ones(N_X), 3*np.ones(N_X)]
Ydata = np.r_[P[:, 0], P[:, 1], P[:, 2]]
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
model = tf.keras.Sequential([layers.Dense(units=10, activation="relu"), layers.Dense(units=1)])
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.01),loss='mean_squared_error')
history = model.fit(Xdata,Ydata,epochs=500,verbose=0,validation_split = 0.2)
plt.plot(model.predict(Xdata))
plt.plot(Ydata)
import pandas as pd
df = pd.DataFrame(np.c_[Ydata, Xdata], columns = ['Policy', 'Cake', 'Shock'])
import plotly.express as px
fig = px.scatter_3d(df, x='Cake', y='Shock', z='Policy')
fig.show()
```
# Cake Eating as Discrete Choice with Taste Shock
```
# Cake eating as Discrete Choice with taste shocks
# max sum βt * u(c(t), e(t))
# s.t. c(t) + x(t+1) <= x(t)(1+r), x(0) given
# T(i,j) = P(e(t+1) = i| e(t) = j)
import numpy as np
x0 = 1
β = 0.95
γ = 0.5
r = 0.05
u = lambda c, e: c**(1-γ)/(1-γ) * np.exp(e**0.5)
# V(x, e) = max u(x*(1+r) - x', e) + β*E[V(x', e')|e], x0 given
N_X = 500
N_E = 2
X = np.linspace(1e-6, x0, N_X) # Cake Space
E = np.arange(1, N_E+1, 1) # Shock Space
V_ = np.zeros((N_X, N_E))
V = np.zeros((N_X, N_E))
P = np.zeros((N_X, N_E))
T = np.array([[0.9, 0.9],
[0.1, 0.1]]) # high taste shocks are less likely
#T = np.ones((N_E, N_E)) / N_E
# V(x, e) = max {u(x*(1+r)-x', e), β*E[V(x', e')|e]}
for i in range(100):
for ix, x in enumerate(X):
for ie, e in enumerate(E):
V[ix, ie] = np.maximum(u(x*(1+r), e), np.max(β*np.dot(V_[X <= x*(1+r), :], T[:, ie])))
P[ix, ie] = np.where(u(x*(1+r), e)>= np.max(β*np.dot(V_[X <= x*(1+r), :], T[:, ie])), 1, 0)
V_ = V.copy()
import matplotlib.pyplot as plt
for i, j in enumerate(E):
plt.plot(X, V[:, i], label = f'e={j}')
plt.legend()
plt.title('Value Function V(x)')
import matplotlib.pyplot as plt
for ie, e in enumerate(E):
plt.plot(X, u(X*(1+r), e), label = f'Threshold e={e}', )
plt.legend()
plt.title('Value Function V(x)')
plt.show()
for i, j in enumerate(E):
plt.plot(X, P[:, i], label = f'e={j}')
plt.legend()
plt.title('Decision Rule x\'(x)')
plt.show()
```
# Cake Eating with Income Shock
```
# Simple cake eating with income shocks
# max E sum beta^t * u(c(t))
# s.t. c(t) + x(t+1) <= x(t) + e(t), x(0) given
# E in {0.1, 0.2, ... }
# T(i,j) = P(e(t+1) = i| e(t) = j) = 1/|E|
import numpy as np
x0 = 1
beta = 0.95
u = lambda c: c**0.5
N_X = 1000
N_E = 10
X = np.linspace(1e-6, x0, N_X) # Cake Space
E = np.arange(1, N_E+1, 1)*0.01 # Shock Space
V_ = np.zeros((N_X, N_E))
V = np.zeros((N_X, N_E))
P = np.zeros((N_X, N_E))
T = np.ones((N_E, N_E)) / N_E
# V(x, e) = max u(x+e-x') + beta*E[V(x', y')|y], x0 given
for i in range(50):
for ix, x in enumerate(X):
for ie, e in enumerate(E):
V[ix, ie] = np.max(u(x+e - X[X <= x+e]) + beta*np.dot(V_[X <= x+e, :], T[:, ie]))
P[ix, ie] = X[np.argmax(u(x+e - X[X <= x+e]) + beta*np.dot(V_[X <= x+e, :], T[:, ie]))]
V_ = V.copy()
import matplotlib.pyplot as plt
for i, j in enumerate(E):
plt.plot(X, V[:, i], label = f'e={j}')
plt.legend()
plt.title('Value Function V(x)')
plt.show()
for i, j in enumerate(E):
plt.plot(X, P[:, i], label = f'e={j}')
plt.legend()
plt.title('Decision Rule x\'(x)')
plt.show()
for i, j in enumerate(E):
plt.plot(X, X - P[:, i], label = f'e={j}')
plt.legend()
plt.title('Decision Rule c(x)')
plt.show()
```
# Cake eating with Taste and Income shocks
```
# Simple cake eating with taste and income shocks
# max E sum beta^t * u(c(t), e(t))
# s.t. c(t) + x(t+1) <= x(t) + y(t), x(0) given
# E in {0.1, 0.2, ... }
# T(i,j) = P(e(t+1) = i| e(t) = j) = 1/|E|
# R(i,j) = P(y(t+1) = i| y(t) = j) = 1/|J|
import numpy as np
x0 = 1
beta = 0.95
u = lambda c, e: c**0.5 * np.exp(e**0.5)
N_X = 1000
N_E = 2
N_Y = 2
X = np.linspace(1e-6, x0, N_X) # State Space
E = np.arange(1, N_E+1, 1)*0.05 # Taste Shock Space
Y = np.arange(1, N_E+1, 1)*0.05 # Income Shock Space
V_ = np.zeros((N_X, N_E, N_Y)) # Old Value
V = np.zeros((N_X, N_E, N_Y))
P = np.zeros((N_X, N_E, N_Y))
T = np.ones((N_E, N_E))/ N_E # Taste Transition
R = np.ones((N_Y, N_Y))/ N_Y # Income Transition
# V(x, y, e) = max u(x+y-x',e) + beta*E[V(x', y', e')|y, e]
for i in range(50):
for ix, x in enumerate(X):
for ie, e in enumerate(E):
for iy, y in enumerate(Y):
V[ix, ie, iy] = np.max(u(x+y - X[X <= x+y], e) + beta*np.dot(np.dot(V_[X <= x+y, :, :], T[:, ie]), R[:, iy]))
P[ix, ie, iy] = X[np.argmax(u(x+y - X[X <= x+y], e) + beta*np.dot(np.dot(V_[X <= x+y, :, :], T[:, ie]), R[:, iy]))]
V_ = V.copy()
import matplotlib.pyplot as plt
for ie, e in enumerate(E):
for iy, y in enumerate(Y):
plt.plot(X, V[:, ie, iy], label = f'e={E[ie]}, y={Y[iy]}')
plt.legend()
plt.title('Value Function V(x)')
plt.show()
import matplotlib.pyplot as plt
for ie, e in enumerate(E):
for iy, y in enumerate(Y):
plt.plot(X, P[:, ie, iy], label = f'e={E[ie]}, y={Y[iy]}')
plt.legend()
plt.title('Policy Function x\'(x)')
plt.show()
import matplotlib.pyplot as plt
for ie, e in enumerate(E):
for iy, y in enumerate(Y):
plt.plot(X, X-P[:, ie, iy], label = f'e={E[ie]}, y={Y[iy]}')
plt.legend()
plt.title('Policy Function c(x)')
plt.show()
```
# Cake eating with Habit Formation
```
# Cake Eating with habit formation
# max sum β^t * u(c(t), c(t-1))
# s.t. c(t) + x(t+1) <= x(t)(1+r), x(0) given
import numpy as np
x0 = 1
β = 0.95
γ = 0.9
r = 0.05
u = lambda c, c_: c**(1-γ)/(1-γ) + c_**(1-γ)/(1-γ) * 0.1
# # V(x, c) = max u(c', c)) + β*V_old(x', c')
# V(x, c) = max u(x(1+r)-x', c)) + β*V_old(x', x(1+r)-x')
# s.t. 0 < x'< x
N = 100
X = np.linspace(1e-6, x0, N) # State space
V_ = u(X) # initial guess for value function
V = np.zeros(N)
P = np.zeros(N)
# VFI
for i in range(100):
for ix, x in enumerate(X):
V[ix] = np.max(u(x*(1+r) - X[X <= x*(1+r)]) + β*V_[X <= x*(1+r)])
P[ix] = X[np.argmax(u(x*(1+r) - X[X <= x*(1+r)]) + β*V_[X <= x*(1+r)])]
V_ = V.copy()
import matplotlib.pyplot as plt
plt.plot(X, V)
plt.title('Value Function V(x)')
plt.show()
plt.plot(X, P)
plt.title('Decision Rule x\'(x)')
plt.show()
plt.plot(X, X*(1+r)-P)
plt.title('Decision Rule c(x)')
plt.show()
```
# Cake Eating with Time Iteration
```
Cake eating with time iteration
```
# Cake Eating as Estimation Problem
```
```
| github_jupyter |
# Machine Learning with H2O - Tutorial 4b: Classification Models (Ensembles)
<hr>
**Objective**:
- This tutorial explains how to create stacked ensembles of classification models for better out-of-bag performance.
<hr>
**Titanic Dataset:**
- Source: https://www.kaggle.com/c/titanic/data
<hr>
**Steps**:
1. Build GBM models using random grid search and extract the best one.
2. Build DRF models using random grid search and extract the best one.
3. Use model stacking to combining different models.
<hr>
**Full Technical Reference:**
- http://docs.h2o.ai/h2o/latest-stable/h2o-py/docs/modeling.html
- http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/stacked-ensembles.html
<br>
```
# Import all required modules
import h2o
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.random_forest import H2ORandomForestEstimator
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from h2o.estimators.stackedensemble import H2OStackedEnsembleEstimator
from h2o.grid.grid_search import H2OGridSearch
# Start and connect to a local H2O cluster
h2o.init(nthreads = -1)
```
<br>
```
# Import Titanic data (local CSV)
titanic = h2o.import_file("kaggle_titanic.csv")
titanic.head(5)
# Convert 'Survived' and 'Pclass' to categorical values
titanic['Survived'] = titanic['Survived'].asfactor()
titanic['Pclass'] = titanic['Pclass'].asfactor()
# Define features (or predictors) manually
features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']
# Split the H2O data frame into training/test sets
# so we can evaluate out-of-bag performance
titanic_split = titanic.split_frame(ratios = [0.8], seed = 1234)
titanic_train = titanic_split[0] # using 80% for training
titanic_test = titanic_split[1] # using the rest 20% for out-of-bag evaluation
titanic_train.shape
titanic_test.shape
```
<br>
## Define Search Criteria for Random Grid Search
```
# define the criteria for random grid search
search_criteria = {'strategy': "RandomDiscrete",
'max_models': 9,
'seed': 1234}
```
<br>
## Step 1: Build GBM Models using Random Grid Search and Extract the Best Model
```
# define the range of hyper-parameters for GBM grid search
# 27 combinations in total
hyper_params = {'sample_rate': [0.7, 0.8, 0.9],
'col_sample_rate': [0.7, 0.8, 0.9],
'max_depth': [3, 5, 7]}
# Set up GBM grid search
# Add a seed for reproducibility
gbm_rand_grid = H2OGridSearch(
H2OGradientBoostingEstimator(
model_id = 'gbm_rand_grid',
seed = 1234,
ntrees = 10000,
nfolds = 5,
fold_assignment = "Modulo", # needed for stacked ensembles
keep_cross_validation_predictions = True, # needed for stacked ensembles
stopping_metric = 'mse',
stopping_rounds = 15,
score_tree_interval = 1),
search_criteria = search_criteria, # full grid search
hyper_params = hyper_params)
# Use .train() to start the grid search
gbm_rand_grid.train(x = features,
y = 'Survived',
training_frame = titanic_train)
# Sort and show the grid search results
gbm_rand_grid_sorted = gbm_rand_grid.get_grid(sort_by='auc', decreasing=True)
print(gbm_rand_grid_sorted)
# Extract the best model from random grid search
best_gbm_model_id = gbm_rand_grid_sorted.model_ids[0]
best_gbm_from_rand_grid = h2o.get_model(best_gbm_model_id)
best_gbm_from_rand_grid.summary()
```
<br>
## Step 2: Build DRF Models using Random Grid Search and Extract the Best Model
```
# define the range of hyper-parameters for DRF grid search
# 27 combinations in total
hyper_params = {'sample_rate': [0.5, 0.6, 0.7],
'col_sample_rate_per_tree': [0.7, 0.8, 0.9],
'max_depth': [3, 5, 7]}
# Set up DRF grid search
# Add a seed for reproducibility
drf_rand_grid = H2OGridSearch(
H2ORandomForestEstimator(
model_id = 'drf_rand_grid',
seed = 1234,
ntrees = 200,
nfolds = 5,
fold_assignment = "Modulo", # needed for stacked ensembles
keep_cross_validation_predictions = True), # needed for stacked ensembles
search_criteria = search_criteria, # full grid search
hyper_params = hyper_params)
# Use .train() to start the grid search
drf_rand_grid.train(x = features,
y = 'Survived',
training_frame = titanic_train)
# Sort and show the grid search results
drf_rand_grid_sorted = drf_rand_grid.get_grid(sort_by='auc', decreasing=True)
print(drf_rand_grid_sorted)
# Extract the best model from random grid search
best_drf_model_id = drf_rand_grid_sorted.model_ids[0]
best_drf_from_rand_grid = h2o.get_model(best_drf_model_id)
best_drf_from_rand_grid.summary()
```
<br>
## Model Stacking
```
# Define a list of models to be stacked
# i.e. best model from each grid
all_ids = [best_gbm_model_id, best_drf_model_id]
# Set up Stacked Ensemble
ensemble = H2OStackedEnsembleEstimator(model_id = "my_ensemble",
base_models = all_ids)
# use .train to start model stacking
# GLM as the default metalearner
ensemble.train(x = features,
y = 'Survived',
training_frame = titanic_train)
```
<br>
## Comparison of Model Performance on Test Data
```
print('Best GBM model from Grid (AUC) : ', best_gbm_from_rand_grid.model_performance(titanic_test).auc())
print('Best DRF model from Grid (AUC) : ', best_drf_from_rand_grid.model_performance(titanic_test).auc())
print('Stacked Ensembles (AUC) : ', ensemble.model_performance(titanic_test).auc())
```
<br>
<br>
| github_jupyter |
# Sustainable energy transitions data model
```
import pandas as pd, numpy as np, json, copy, zipfile, random
```
## Country and region name converters
```
#country name converters
#EIA->pop
clist1={'North America':'Northern America',
'United States':'United States of America',
'Central & South America':'Latin America and the Caribbean',
'Bahamas, The':'Bahamas',
'Saint Vincent/Grenadines':'Saint Vincent and the Grenadines',
'Venezuela':'Venezuela (Bolivarian Republic of)',
'Macedonia':'The former Yugoslav Republic of Macedonia',
'Moldova':'Republic of Moldova',
'Russia':'Russian Federation',
'Iran':'Iran (Islamic Republic of)',
'Palestinian Territories':'State of Palestine',
'Syria':'Syrian Arab Republic',
'Yemen':'Yemen ',
'Congo (Brazzaville)':'Congo',
'Congo (Kinshasa)':'Democratic Republic of the Congo',
'Cote dIvoire (IvoryCoast)':"C\xc3\xb4te d'Ivoire",
'Gambia, The':'Gambia',
'Libya':'Libyan Arab Jamahiriya',
'Reunion':'R\xc3\xa9union',
'Somalia':'Somalia ',
'Sudan and South Sudan':'Sudan',
'Tanzania':'United Republic of Tanzania',
'Brunei':'Brunei Darussalam',
'Burma (Myanmar)':'Myanmar',
'Hong Kong':'China, Hong Kong Special Administrative Region',
'Korea, North':"Democratic People's Republic of Korea",
'Korea, South':'Republic of Korea',
'Laos':"Lao People's Democratic Republic",
'Macau':'China, Macao Special Administrative Region',
'Timor-Leste (East Timor)':'Timor-Leste',
'Virgin Islands, U.S.':'United States Virgin Islands',
'Vietnam':'Viet Nam'}
#BP->pop
clist2={u' European Union #':u'Europe',
u'Rep. of Congo (Brazzaville)':u'Congo (Brazzaville)',
'Republic of Ireland':'Ireland',
'China Hong Kong SAR':'China, Hong Kong Special Administrative Region',
u'Total Africa':u'Africa',
u'Total North America':u'Northern America',
u'Total S. & Cent. America':'Latin America and the Caribbean',
u'Total World':u'World',
u'Total World ':u'World',
'South Korea':'Republic of Korea',
u'Trinidad & Tobago':u'Trinidad and Tobago',
u'US':u'United States of America'}
#WD->pop
clist3={u"Cote d'Ivoire":"C\xc3\xb4te d'Ivoire",
u'Congo, Rep.':u'Congo (Brazzaville)',
u'Caribbean small states':'Carribean',
u'East Asia & Pacific (all income levels)':'Eastern Asia',
u'Egypt, Arab Rep.':'Egypt',
u'European Union':u'Europe',
u'Hong Kong SAR, China':u'China, Hong Kong Special Administrative Region',
u'Iran, Islamic Rep.':u'Iran (Islamic Republic of)',
u'Kyrgyz Republic':u'Kyrgyzstan',
u'Korea, Rep.':u'Republic of Korea',
u'Latin America & Caribbean (all income levels)':'Latin America and the Caribbean',
u'Macedonia, FYR':u'The former Yugoslav Republic of Macedonia',
u'Korea, Dem. Rep.':u"Democratic People's Republic of Korea",
u'South Asia':u'Southern Asia',
u'Sub-Saharan Africa (all income levels)':u'Sub-Saharan Africa',
u'Slovak Republic':u'Slovakia',
u'Venezuela, RB':u'Venezuela (Bolivarian Republic of)',
u'Yemen, Rep.':u'Yemen ',
u'Congo, Dem. Rep.':u'Democratic Republic of the Congo'}
#COMTRADE->pop
clist4={u"Bosnia Herzegovina":"Bosnia and Herzegovina",
u'Central African Rep.':u'Central African Republic',
u'China, Hong Kong SAR':u'China, Hong Kong Special Administrative Region',
u'China, Macao SAR':u'China, Macao Special Administrative Region',
u'Czech Rep.':u'Czech Republic',
u"Dem. People's Rep. of Korea":"Democratic People's Republic of Korea",
u'Dem. Rep. of the Congo':"Democratic Republic of the Congo",
u'Dominican Rep.':u'Dominican Republic',
u'Fmr Arab Rep. of Yemen':u'Yemen ',
u'Fmr Ethiopia':u'Ethiopia',
u'Fmr Fed. Rep. of Germany':u'Germany',
u'Fmr Panama, excl.Canal Zone':u'Panama',
u'Fmr Rep. of Vietnam':u'Viet Nam',
u"Lao People's Dem. Rep.":u"Lao People's Democratic Republic",
u'Occ. Palestinian Terr.':u'State of Palestine',
u'Rep. of Korea':u'Republic of Korea',
u'Rep. of Moldova':u'Republic of Moldova',
u'Serbia and Montenegro':u'Serbia',
u'US Virgin Isds':u'United States Virgin Islands',
u'Solomon Isds':u'Solomon Islands',
u'United Rep. of Tanzania':u'United Republic of Tanzania',
u'TFYR of Macedonia':u'The former Yugoslav Republic of Macedonia',
u'USA':u'United States of America',
u'USA (before 1981)':u'United States of America',
}
#Jacobson->pop
clist5={u"Korea, Democratic People's Republic of":"Democratic People's Republic of Korea",
u'All countries':u'World',
u"Cote d'Ivoire":"C\xc3\xb4te d'Ivoire",
u'Iran, Islamic Republic of':u'Iran (Islamic Republic of)',
u'Macedonia, Former Yugoslav Republic of':u'The former Yugoslav Republic of Macedonia',
u'Congo, Democratic Republic of':u"Democratic Republic of the Congo",
u'Korea, Republic of':u'Republic of Korea',
u'Tanzania, United Republic of':u'United Republic of Tanzania',
u'Moldova, Republic of':u'Republic of Moldova',
u'Hong Kong, China':u'China, Hong Kong Special Administrative Region'
}
#NREL solar->pop
clist6={u"Antigua & Barbuda":u'Antigua and Barbuda',
u"Bosnia & Herzegovina":u"Bosnia and Herzegovina",
u"Brunei":u'Brunei Darussalam',
u"Cote d'Ivoire":"C\xc3\xb4te d'Ivoire",
u"Iran":u'Iran (Islamic Republic of)',
u"Laos":u"Lao People's Democratic Republic",
u"Libya":'Libyan Arab Jamahiriya',
u"Moldova":u'Republic of Moldova',
u"North Korea":"Democratic People's Republic of Korea",
u"Reunion":'R\xc3\xa9union',
u'Sao Tome & Principe':u'Sao Tome and Principe',
u'Solomon Is.':u'Solomon Islands',
u'St. Lucia':u'Saint Lucia',
u'St. Vincent & the Grenadines':u'Saint Vincent and the Grenadines',
u'The Bahamas':u'Bahamas',
u'The Gambia':u'Gambia',
u'Virgin Is.':u'United States Virgin Islands',
u'West Bank':u'State of Palestine'
}
#NREL wind->pop
clist7={u"Antigua & Barbuda":u'Antigua and Barbuda',
u"Bosnia & Herzegovina":u"Bosnia and Herzegovina",
u'Occupied Palestinian Territory':u'State of Palestine',
u'China Macao SAR':u'China, Macao Special Administrative Region',
#"C\xc3\xb4te d'Ivoire":"C\xc3\xb4te d'Ivoire",
u'East Timor':u'Timor-Leste',
u'TFYR Macedonia':u'The former Yugoslav Republic of Macedonia',
u'IAM-country Total':u'World'
}
#country entroids->pop
clist8={u'Burma':'Myanmar',
u"Cote d'Ivoire":"C\xc3\xb4te d'Ivoire",
u'Republic of the Congo':u'Congo (Brazzaville)',
u'Reunion':'R\xc3\xa9union'
}
def cnc(country):
if country in clist1: return clist1[country]
elif country in clist2: return clist2[country]
elif country in clist3: return clist3[country]
elif country in clist4: return clist4[country]
elif country in clist5: return clist5[country]
elif country in clist6: return clist6[country]
elif country in clist7: return clist7[country]
elif country in clist8: return clist8[country]
else: return country
```
# Population
Consult the notebook entitled *pop.ipynb* for the details of mining the data from the UN statistics division online database.
Due to being the reference database for country names cell, the cell below needs to be run first, before any other databases.
```
#pop_path='https://dl.dropboxusercontent.com/u/531697/datarepo/Set/db/
pop_path='E:/Dropbox/Public/datarepo/Set/db/'
#suppres warnings
import warnings
warnings.simplefilter(action = "ignore")
cc=pd.read_excel(pop_path+'Country Code and Name ISO2 ISO3.xls')
#http://unstats.un.org/unsd/tradekb/Attachment321.aspx?AttachmentType=1
ccs=cc['Country Code'].values
```
## Country neighbor list
```
neighbors=pd.read_csv(pop_path+'contry-geotime.csv')
#https://raw.githubusercontent.com/ppKrauss/country-geotime/master/data/contry-geotime.csv
#country name converter from iso to comtrade and back
iso2c={}
isoc2={}
for i in cc.T.iteritems():
iso2c[i[1][0]]=i[1][1]
isoc2[i[1][1]]=i[1][0]
#country name converter from pop to iso
pop2iso={}
for i in cc.T.iteritems():
pop2iso[cnc(i[1][1])]=int(i[1][0])
#country name converter from alpha 2 to iso
c2iso={}
for i in neighbors.T.iteritems():
c2iso[str(i[1][0])]=i[1][1]
c2iso['NA']=c2iso['nan'] #adjust for namibia
c2iso.pop('nan');
#create country neighbor adjacency list based on iso country number codes
c2neighbors={}
for i in neighbors.T.iteritems():
z=str(i[1][4]).split(' ')
if (str(i[1][1])!='nan'): c2neighbors[int(i[1][1])]=[c2iso[k] for k in z if k!='nan']
#extend iso codes not yet encountered
iso2c[729]="Sudan"
iso2c[531]="Curacao"
iso2c[535]="Bonaire, Sint Eustatius and Saba"
iso2c[728]="South Sudan"
iso2c[534]="Sint Maarten (Dutch part)"
iso2c[652]="Saint Barthélemy"
def save3(sd):
#if True:
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile.ZIP_STORED
popsave={}
countries=[]
isocountries={}
c=sorted(data.keys())
for country in c:
popdummy={}
tosave=[]
for year in data[country]:
popdummy[year]=data[country][year]['population']
for fuel in data[country][year]['energy']:
#for fuel in allfuels:
if fuel not in {'nrg','nrg_sum'}:
tosave.append({"t":year,"u":fuel,"g":"f","q1":"pp","q2":999,
"s":round(0 if (('navg3' in data[country][year]['energy'][fuel]['prod']) \
and (np.isnan(data[country][year]['energy'][fuel]['prod']['navg3']))) else \
data[country][year]['energy'][fuel]['prod']['navg3'] if \
'navg3' in data[country][year]['energy'][fuel]['prod'] else 0,3)
})
tosave.append({"t":year,"u":fuel,"g":"m","q1":"cc","q2":999,
"s":round(0 if (('navg3' in data[country][year]['energy'][fuel]['cons']) \
and (np.isnan(data[country][year]['energy'][fuel]['cons']['navg3']))) else \
data[country][year]['energy'][fuel]['cons']['navg3'] if \
'navg3' in data[country][year]['energy'][fuel]['cons'] else 0,3)
})
#save balances - only for dev
#if (year > min(balance.keys())):
# if year in balance:
# if country in balance[year]:
# tosave.append({"t":year,"u":"balance","g":"m","q1":"cc","q2":999,
# "s":balance[year][country]})
#no import export flows on global
if country not in {"World"}:
flowg={"Import":"f","Export":"m","Re-Export":"m","Re-Import":"f"}
if country in tradealpha:
for year in tradealpha[country]:
for fuel in tradealpha[country][year]:
for flow in tradealpha[country][year][fuel]:
for partner in tradealpha[country][year][fuel][flow]:
if partner not in isocountries:
isocountries[partner]=cnc(iso2c[int(float(partner))])
tosave.append({"t":int(float(year)),"u":fuel,"g":flowg[flow],"q1":flow,"q2":partner,
"s":round(tradealpha[country][year][fuel][flow][partner],3)
})
popsave[country]=popdummy
countries.append(country)
file('E:/Dropbox/Public/datarepo/Set/ajson/'+str(sd)+'/data.json','w').write(json.dumps(tosave))
zf = zipfile.ZipFile('E:/Dropbox/Public/datarepo/Set/json/'+str(sd)+'/'+str(country.encode('utf-8').replace('/','&&'))+'.zip', mode='w')
zf.write('E:/Dropbox/Public/datarepo/Set/json/'+str(sd)+'/data.json','data.json',compress_type=compression)
zf.close()
#save all countries list
file('E:/Dropbox/Public/datarepo/Set/json/'+str(sd)+'/countries.json','w').write(json.dumps(countries))
#save countries populations
#file('E:/Dropbox/Public/datarepo/Set/json/pop.json','w').write(json.dumps(popsave))
#save all trade countries dictionary
file('E:/Dropbox/Public/datarepo/Set/json/'+str(sd)+'/isocountries.json','w').write(json.dumps(isocountries))
#https://www.researchgate.net/publication/299824220_First_Insights_on_the_Role_of_solar_PV_in_a_100_Renewable_Energy_Environment_based_on_hourly_Modeling_for_all_Regions_globally
cost=pd.read_excel(pop_path+'/maps/storage.xlsx')
#load tradealpha d
predata=json.loads(file(pop_path+'/trade/traded.json','r').read())
tradealpha={}
for c in predata:
tradealpha[c]={}
for year in predata[c]:
tradealpha[c][int(year)]=predata[c][year]
predata={}
#existing electricity trade grid (and other fuels)
grid={}
allgrid={}
gridz={}
allgridsize={}
zgrid={}
zzsize={}
for fuel in {"oil","coal","gas","electricity"}:
if fuel not in grid:grid[fuel]={}
if fuel not in zgrid:zgrid[fuel]={}
if fuel not in zzsize:zzsize[fuel]={}
gridpartners={}
gridsize={}
for c in tradealpha:
if c not in gridpartners:gridpartners[c]=[]
if c not in allgrid:allgrid[c]=[]
if c not in gridsize:gridsize[c]=0
if c not in allgridsize:allgridsize[c]=0
for y in tradealpha[c]:
if y not in zgrid[fuel]:zgrid[fuel][y]={}
if y not in zzsize[fuel]:zzsize[fuel][y]={}
if fuel in tradealpha[c][y]:
for f in tradealpha[c][y][fuel]:
for i in tradealpha[c][y][fuel][f]:
if i not in {"World","Northern America","Africa",'Latin America and the Caribbean','Europe'}:
if int(float(i)) in iso2c:
if not np.isnan(tradealpha[c][y][fuel][f][i]):
if tradealpha[c][y][fuel][f][i]!=0:
p=cnc(iso2c[int(float(i))])
gridsize[c]+=tradealpha[c][y][fuel][f][i]
if p not in gridpartners[c]:
gridpartners[c].append(p)
allgridsize[c]+=tradealpha[c][y][fuel][f][i]
if p not in allgrid[c]:
allgrid[c].append(p)
if c not in zzsize[fuel][y]:zzsize[fuel][y][c]=0
zzsize[fuel][y][c]+=tradealpha[c][y][fuel][f][i]
if c not in zgrid[fuel][y]:zgrid[fuel][y][c]={}
if p not in zgrid[fuel][y][c]:
zgrid[fuel][y][c][p]=tradealpha[c][y][fuel][f][i]
grid[fuel]=gridpartners
gridz[fuel]=gridsize
#existing electricity trade grid (and other fuels) last 5 years
grid5={}
gridz5={}
allgrid5={}
allgridsize5={}
for fuel in {"oil","coal","gas","electricity"}:
if fuel not in grid:grid[fuel]={}
gridpartners={}
gridsize={}
for c in tradealpha:
if c not in gridpartners:gridpartners[c]=[]
if c not in allgrid5:allgrid5[c]=[]
if c not in gridsize:gridsize[c]=0
if c not in allgridsize5:allgridsize5[c]=0
for y in tradealpha[c]:
if y>2010:
if fuel in tradealpha[c][y]:
for f in tradealpha[c][y][fuel]:
for i in tradealpha[c][y][fuel][f]:
if i not in {"World","Northern America","Africa",'Latin America and the Caribbean','Europe'}:
if int(float(i)) in iso2c:
if not np.isnan(tradealpha[c][y][fuel][f][i]):
if tradealpha[c][y][fuel][f][i]!=0:
p=cnc(iso2c[int(float(i))])
if p not in gridpartners[c]:
gridpartners[c].append(p)
allgridsize[c]+=tradealpha[c][y][fuel][f][i]
if p not in allgrid[c]:
allgrid[c].append(p)
grid5[fuel]=gridpartners
gridz5[fuel]=gridsize
```
world country centroids for network visualizations
```
import requests, StringIO
r = requests.get('http://gothos.info/resource_files/country_centroids.zip') #define URL path of zip file to read
z = zipfile.ZipFile(StringIO.StringIO(r.content))
coord=pd.read_csv(z.open('country_centroids_all.csv'),sep='\t').drop(['DMS_LAT','DMS_LONG','MGRS','JOG','DSG','FULL_NAME','ISO3136','AFFIL','FIPS10','MOD_DATE'],axis=1)
coord.columns=['LAT','LONG','Country']
coord=coord.set_index('Country',drop=True)
coord.head(2)
#create normalized distance matrix of countries
names=[]
for i in coord.index:
names.append(cnc(i))
coord['NAME']=names
coord=coord.set_index('NAME',drop=True)
from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
def distance(i,j):
if i in coord.index and j in coord.index:
return haversine(coord.loc[i]['LONG'],coord.loc[i]['LAT'],
coord.loc[j]['LONG'],coord.loc[j]['LAT'])
else: return 5000
predata=json.loads(file(pop_path+'savedata5.json','r').read())
data={}
for c in predata:
data[c]={}
for year in predata[c]:
data[c][int(year)]=predata[c][year]
predata={}
goodcountries=list(set(data.keys()).intersection(set(tradealpha.keys())))
limit=20 #dev
#goodcountries=goodcountries[:limit]
rgc={} #reverse goodcountries coder
for i in range(len(goodcountries)):
rgc[goodcountries[i]]=i
matrix=[[0 for i in goodcountries] for j in goodcountries]
#long, run once
dists=[]
for i in range(len(goodcountries)):
for j in range(i):
dists.append(distance(goodcountries[i],goodcountries[j]))
distancenorm=np.mean(dists)
def normdistance(i,j):
if i in coord.index and j in coord.index:
return haversine(coord.loc[i]['LONG'],coord.loc[i]['LAT'],
coord.loc[j]['LONG'],coord.loc[j]['LAT'])/distancenorm
else: return 5000.0/distancenorm
```
## ALLOCATION
Create Hungarian cost matrix. this will be a normalized, per unit EROEI * willingness to do trade. this is the cumulative, directed trade history.
Calculate trade influence matrix. Trade influence is proportional to the total histrocial value of energy trade. If there is no energy trade, some trade is still better than no trade. We will two pairs of import-export flows for each pair, once in each entry's data. For deciding the impor cost influence, we will use 2/3 historical imports and 1/3 historcial exports, caluclated separately for sender and receiver flows, then averged. E.g. a good import partner of country A, let's call it country B, exports a large percentage of its exports to country A and country A receives a large share of its exports from B. The reverse flows are also factored in with a weight of 1/3. The partner-parnter weights are factored in with weights 2/3 (meaning that it is a directed flow but any country who depends on imports or exports signifcantly on another, will push hard politically to keep this trade flowing). We have no weighting to differentiate between energy products, all treated the same. We consider the direct flows more reliable information, hence we give them a weight of 2/3, while the reverse flows get 1/3.
## Impex updating
```
tradecutoff=0.01
#direct flow matrices
importmatrix=[[0 for i in goodcountries] for j in goodcountries]
exportmatrix=[[0 for i in goodcountries] for j in goodcountries]
#reverse flow matrices
rimportmatrix=[[0 for i in goodcountries] for j in goodcountries]
rexportmatrix=[[0 for i in goodcountries] for j in goodcountries]
cid={}
for i in range(len(goodcountries)):
cid[goodcountries[i]]=i
#fill import-export matrix for year x with flow f of value v
def impex(reporter,partner,flow,value):
global importmatrix
global exportmatrix
global rimportmatrix
global rexportmatrix
i=cid[reporter]
j=cid[partner]
if flow in {"Export","Re-Export"}:
exportmatrix[i][j]+=value
rimportmatrix[j][i]+=value
if flow in {"Import","Re-Import"}:
importmatrix[i][j]+=value
rexportmatrix[j][i]+=value
return
#fill up existing values
def reloadimpex(): #runright after after resetting tradealpha
for i in range(len(goodcountries)):
reporter=goodcountries[i]
for year in tradealpha[reporter]:
for fuel in tradealpha[reporter][year]:
for flow in tradealpha[reporter][year][fuel]:
for p in tradealpha[reporter][year][fuel][flow]:
pp=int(float(str(p)))
if pp in iso2c:
if cnc(iso2c[pp]) in goodcountries:
#self trade allowed
partner=cnc(iso2c[pp])
value=tradealpha[reporter][year][fuel][flow][p]
if value>tradecutoff:
impex(reporter,partner,flow,value)
#create influence matrix (from normilzed trade matrices)
#norm direct flow matrices
nimportmatrix=[[0 for i in goodcountries] for j in goodcountries]
nexportmatrix=[[0 for i in goodcountries] for j in goodcountries]
#norm reverse flow matrices
nrimportmatrix=[[0 for i in goodcountries] for j in goodcountries]
nrexportmatrix=[[0 for i in goodcountries] for j in goodcountries]
def normalizeimpex():
global nimportmatrix
global nexportmatrix
global nrimportmatrix
global nrexportmatrix
#initialize normalized matrices
for i in range(len(goodcountries)):
for j in range(len(goodcountries)):
if np.nanmean(importmatrix[i])>0:nimportmatrix[i][j]=importmatrix[i][j]/np.nanmean(importmatrix[i])
if np.nanmean(exportmatrix[i])>0:nexportmatrix[i][j]=exportmatrix[i][j]/np.nanmean(exportmatrix[i])
if np.nanmean(rimportmatrix[i])>0:nrimportmatrix[i][j]=rimportmatrix[i][j]/np.nanmean(rimportmatrix[i])
if np.nanmean(rexportmatrix[i])>0:nrexportmatrix[i][j]=rexportmatrix[i][j]/np.nanmean(rexportmatrix[i])
def impex(reporter,partner,flow,value):
global importmatrix
global exportmatrix
global rimportmatrix
global rexportmatrix
i=cid[reporter]
j=cid[partner]
if flow in {"Export","Re-Export"}:
exportmatrix[i][j]+=value
rimportmatrix[j][i]+=value
if flow in {"Import","Re-Import"}:
importmatrix[i][j]+=value
rexportmatrix[j][i]+=value
return
def updatenormimpex(reporter,partner,flow,value,weight=0.1):
global mimportmatrix
global mexportmatrix
global mrimportmatrix
global mrexportmatrix
i=cid[reporter]
j=cid[partner]
if flow in {"Export","Re-Export"}:
nexportmatrix[i][j]=((nexportmatrix[i][j]*(1-weight))+(value*weight))/2.0
nrimportmatrix[j][i]=((nrimportmatrix[j][i]*(1-weight))+(value*weight))/2.0
if flow in {"Import","Re-Import"}:
nimportmatrix[i][j]+=((nrimportmatrix[i][j]*(1-weight))+(value*weight))/2.0
nrexportmatrix[j][i]+=((nrexportmatrix[j][i]*(1-weight))+(value*weight))/2.0
return
def influence(reporter,partner,selfinfluence=100,nonlinearitypower=0.5):
i=cid[reporter]
j=cid[partner]
if i==j: v=selfinfluence
else: v=12.0/36*nimportmatrix[i][j]\
+6.0/36*nexportmatrix[j][i]\
+4.0/36*nrimportmatrix[i][j]\
+2.0/36*nrexportmatrix[j][i]\
+6.0/36*nexportmatrix[i][j]\
+3.0/36*nimportmatrix[j][i]\
+2.0/36*nrexportmatrix[i][j]\
+1.0/36*nrimportmatrix[j][i]
#trade is naturally exponentially distributed, so we need to account for this
return v**nonlinearitypower
```
Create energy cost by filling the matrix with the cost of row importing 1TWh from column. neglecting transport energy costs for now, this will be the extraction energy cost. Let us consider only solar for now. Try optimization with all three source, choose one with best objective value. 1TWh tier changes based on granurality.
```
#weighted resource class calculator
def re(dic,total):
if dic!={}:
i=max(dic.keys())
mi=min(dic.keys())
run=True
keys=[]
weights=[]
counter=0
while run:
counter+=1 #safety break
if counter>1000: run=False
if i in dic:
if total<dic[i]:
keys.append(i)
weights.append(total)
run=False
else:
total-=dic[i]
keys.append(i)
weights.append(dic[i])
i-=1
if i<mi: run=False
if sum(weights)==0: return 0
else: return np.average(keys,weights=weights)
else: return 0
```
Allocation algorithm:
1. Step year
1. Create list of countries with negative balances
1. Pick a country at random from the list who have negative balances
1. Tier the country's needs into k(=5) tiers
1. Query cost matrix for all countries for the amount on the tier k for all energy sources
1. Choose partner and energy source based on an indicator composed of:
1. Lowest cost
1. Country influence - partners are ranked from 0 to 1. Self has a weight of 2.
1. Does not exceed diversification limits within the same year (providing max z%(=20) of the year's demand)
1. Choose form of trade:
1. Calculate costs for trade for:
1. On existing grid or grid expansion
1. PTL
1. Calculate costs of storage based on:
1. Global storage need in gird share and its distributions by type (from Breyer)
1. Implement trade:
1. Update receiver balance
1. Reduce provider reserves
1. Add provider investment costs: building the capacity
1. Distribute equally on provider energy mix
1. Add receiver investment costs: storage, transport, grid expansion, grid rent
1. Distribute equally on receiver energy mix
- Record total cost of the trade
1. Pick another ocuntry at random and repeat until all countries are finished
1. Calculate total cost of year
1. Try to minimize total cost through simulated annealing repeated within year:
1. Start with random processing order for countries
1. Complete the year with that order
1. Swap two countries in the order at ranom
1. Repeat the year and see if the total costs decreased
1. If yes, keep the swap, then swap another one
1. If no, revert the swap and swap another one
1. Calculate total cost of transition for year, then step year
1. After all years finished, record total cost of transition
```
#average resource quality calculator for the globe
def update_aroei():
global aroei
aroei={}
groei={}
for c in res:
for r in res[c]:
if r not in groei: groei[r]={}
for cl in res[c][r]['res']:
if cl not in groei[r]: groei[r][cl]=0
groei[r][cl]+=res[c][r]['res'][cl]
for r in groei:
x=[]
y=[]
for i in range(len(sorted(groei[r].keys()))):
x.append(float(sorted(groei[r].keys())[i]))
y.append(float(groei[r][sorted(groei[r].keys())[i]]))
aroei[r]=np.average(x,weights=y)
#1Bdi - grid
def gridtestimator(country,partner):
def electricitytrade(country,partner):
scaler=1
gridpartners=grid5['electricity']
#existing trade partners
if ((partner in gridpartners[country]) or (country in gridpartners[partner])):
scaler+=cost.loc[region.loc[country]]['egrid'].values[0]/2.0
#neighbors, but need to build
elif pop2iso[country] in c2neighbors:
if (pop2iso[partner] in c2neighbors[pop2iso[country]]):
scaler+=cost.loc[region.loc[country]]['grid'].values[0]/2.0*normdistance(country,partner)
#not neighbors or partners but in the same region, need to build
elif (region.loc[country][0]==region.loc[partner][0]):
scaler+=cost.loc[region.loc[country]]['grid'].values[0]*3.0/2.0*normdistance(country,partner)
#need to build supergrid, superlative costs
else: scaler+=cost.loc[region.loc[country]]['grid'].values[0]*10.0/2.0*normdistance(country,partner)
return scaler
def ptltrade(country,partner):
#ptg costs scale with distance
scaler=1+cost.loc[11]['ptg']*normdistance(country,partner)
return scaler
if ptltrade(country,partner)<electricitytrade(country,partner):
return {"scaler":ptltrade(country,partner),"tradeway":"ptl"}
else: return {"scaler":electricitytrade(country,partner),"tradeway":"grid"}
#1Bdii - storage &curtailment
def storagestimator(country,partner):
return cost.loc[region.loc[country]]['min'].values[0]
#curtoversizer
def curtestimator(country,partner):
return cost.loc[region.loc[country]]['curt'].values[0]
#global eroei, due to state of technology
#http://www.sciencedirect.com/science/article/pii/S0301421513003856
eroei={
'oil':13,
'coal':27,
'gas':14,
'nuclear':10,
'biofuels':1.5,
'hydro':84,
'geo_other':22,
'pv':16,
'csp':3,
'wind':24 #was 24
}
#esoei
#http://pubs.rsc.org/en/content/articlepdf/2013/ee/c3ee41973h
#various, but especially CSP from https://en.wikipedia.org/wiki/EROEI
#http://link.springer.com/chapter/10.1007/978-3-319-02940-5_5#Sec18
#charlie hall says number are 5-7 for csp, but without additional costs of the supporting infrastructure
```
# ALLINONE
```
sd=5
region=pd.read_excel(pop_path+'regions.xlsx').set_index('Country')
#import resources
###################################
###################################
#load resources
predata=json.loads(file(pop_path+'maps/res.json','r').read())
res={}
for c in predata:
res[c]={}
for f in predata[c]:
res[c][f]={}
for r in predata[c][f]:
res[c][f][r]={}
for year in predata[c][f][r]:
res[c][f][r][int(year)]=predata[c][f][r][year]
predata={}
print 'scenario',sd,'loaded resources',
###################################
###################################
#load balance
predata=json.loads(file(pop_path+'balance.json','r').read())
balance={}
for year in predata:
balance[int(year)]=predata[year]
predata={}
print 'balance',
###################################
###################################
#load tradealpha d
predata=json.loads(file(pop_path+'/trade/traded.json','r').read())
tradealpha={}
for c in predata:
tradealpha[c]={}
for year in predata[c]:
tradealpha[c][int(year)]=predata[c][year]
predata={}
print 'tradedata',
###################################
###################################
#reload impex and normalize
predata=json.loads(file(pop_path+'trade/nimpex.json','r').read())
nexportmatrix=predata["nexport"]
nimportmatrix=predata["nimport"]
nrexportmatrix=predata["nrexport"]
nrimportmatrix=predata["nrimport"]
predata={}
print 'impex',
###################################
###################################
#load latest savedata
''' #we dont change the data for now, everything is handled through trade
predata=json.loads(file(pop_path+'savedata5.json','r').read())
data={}
for c in predata:
data[c]={}
for year in predata[c]:
data[c][int(year)]=predata[c][year]
predata={}
print 'data'
'''
###################################
###################################
###################################
###################################
###################################
###################################
for year in range(2015,2100):
print year,
#SET PARAMETERS
#------------------------------------------------
#0-reset reserves
'''
predata=json.loads(file(pop_path+'maps/res.json','r').read())
res={}
for c in predata:
res[c]={}
for f in predata[c]:
res[c][f]={}
for r in predata[c][f]:
res[c][f][r]={}
for y in predata[c][f][r]:
res[c][f][r][int(y)]=predata[c][f][r][y]
predata={}
'''
#1A
needers=sorted([c for c in balance[year] if balance[year][c]<0])
#1B
#import random
random.seed(sd)
#shuffle order of parsing countries
random.shuffle(needers)
#------------------------------------------------
#1Ba
#country for parsing the needers list
for counter in range(len(needers)):
country=needers[counter]
#print country,
need=-balance[year][country] #as a convention switch to positive, defined as 'need'
mintier=1 #in TWh
midtier=10 #mid tier TWh
if need>midtier: tiernumber=5
elif need>mintier: tiernumber=3
else: tiernumber=1
for tier in range(tiernumber):
tierneed=need*1.0/tiernumber
#------------------------------------------------
#1Bb
costvector={}
update_aroei() #update sate of the resources globally to be able to rank between technologies
for partner in goodcountries:
if partner in res:
for fuel in {'csp','pv','wind'}:
if res[partner][fuel]['res']!={}:
#rq (resource query) returns the average resource class at which this tierneed can be provided
rq=re(res[partner][fuel]['res'],tierneed)
#the costvector takes the resource class and converts it to eroei by comparing it
#the average resource class at a known point with a know eroei (at start in 2015)
#we are looking figh highvalues, as a marginal quality of resource
costvector[fuel+'_'+partner]=(rq/aroei[fuel]*eroei[fuel]) #normalized resource quality over eroei
#1Bbi - norlmalize costvector to be able to compare with trade influence
normcostvector=copy.deepcopy(costvector)
for i in normcostvector:
costvector[i]/=np.nanmean(costvector.values())
#1Bbii - create costfactor, weights are tweakable
costfactor={}
for key in costvector:
partner=key[key.find('_')+1:]
costfactor[key]=((costvector[key]**2)*(influence(country,partner)**2))**(1/4.0)
#The geometric mean is more appropriate than the arithmetic mean for describing proportional growth,
#both exponential growth (constant proportional growth) and varying growth; i
#n business the geometric mean of growth rates is known as the compound annual growth rate (CAGR).
#The geometric mean of growth over periods yields the equivalent constant growth rate that would
#yield the same final amount.
#1Bc - choose partner
best=max(costfactor, key=costfactor.get)
tradepartner=best[best.find('_')+1:]
tradefuel=best[:best.find('_')]
#------------------------------------------------
#1Be - IMPLEMENT TRADE
#1Beii - Reduce provider reserves within year
levels=res[tradepartner][tradefuel]['res'].keys()
level=max(levels)
tomeet=tierneed*1.0
while level>min(levels): #give them back after 25 yrs
if level not in res[tradepartner][tradefuel]['res']: level-=1
elif res[tradepartner][tradefuel]['res'][level]<tomeet:
tomeet-=res[tradepartner][tradefuel]['res'][level]
res[tradepartner][tradefuel]['res'].pop(level)
level-=1
else:
res[tradepartner][tradefuel]['res'][level]-=tomeet
level=0
#1Bei - update receiver balance
for l in range(year,year+25):
balance[l][country]-=tierneed
#------------------------------------------------
#1Be-implement country trade
key=gridtestimator(country,partner)['tradeway']+'_'+tradefuel
#add import flow
if key not in tradealpha[country][l]:tradealpha[country][l][key]={}
if 'Import' not in tradealpha[country][l][key]:tradealpha[country][l][key]["Import"]={}
if str(pop2iso[tradepartner]) not in tradealpha[country][l][key]["Import"]:
tradealpha[country][l][key]["Import"][str(pop2iso[tradepartner])]=0
tradealpha[country][l][key]["Import"][str(pop2iso[tradepartner])]+=tierneed
#add export flow
if key not in tradealpha[tradepartner][l]:tradealpha[tradepartner][l][key]={}
if 'Export' not in tradealpha[tradepartner][l][key]:tradealpha[tradepartner][l][key]["Export"]={}
if str(pop2iso[country]) not in tradealpha[tradepartner][l][key]["Export"]:
tradealpha[tradepartner][l][key]["Export"][str(pop2iso[country])]=0
tradealpha[tradepartner][l][key]["Export"][str(pop2iso[country])]+=tierneed
#record trade to influence - counld be weighted, deaful is 10%
updatenormimpex(country,tradepartner,'Import',tierneed/need)
updatenormimpex(tradepartner,country,'Export',tierneed/need)
save3(sd)
```
| github_jupyter |
```
import numpy as np
import pandas as pd
from sklearn import *
import matplotlib.pyplot as plt
%matplotlib inline
sample_size = 5000
data1,target1 = datasets.make_circles(n_samples=sample_size, factor=.1, noise=0.2)
target1 = (3*data1[:,0])-(16*data1[:,1]) + (0.5*data1[:,0]*data1[:,1]) + np.random.normal(0,2,size=sample_size)
data2,target2 = datasets.make_circles(n_samples=sample_size, factor=.5, noise=0.2)
target2 = np.power(data2[:,0],2) + 10*np.power(data2[:,1],3) + (50*data2[:,0]*np.power(data2[:,1],2)) + np.random.normal(0,2,size=sample_size)
data3,target3 = datasets.make_moons(n_samples=sample_size,noise=0.2)
data3[:,0] = (2 * (data3[:, 0]-(-1))/(3))-1
data3[:,1] = (2 * (data3[:, 1]-(-1))/(2))-1
target3 = (50*data3[:,0]*np.sin(data3[:,1])) + (50*data3[:,1]*np.cos(data3[:,0]))
data4,target4 = datasets.make_moons(n_samples=sample_size,noise=0.2)
temp = np.copy(data4[:, 0])
data4[:, 0] = data4[:, 1]
data4[:, 1] = temp
data4[:,0] = (2 * (data4[:, 0]-(-1))/(2))-1
data4[:,1] = (2 * (data4[:, 1]-(-1))/(3))-1
target4 = (30*data1[:,0])-(16*data1[:,1]) - (1.5*data1[:,0]*data1[:,1]) + np.random.normal(0,1,size=sample_size)
data = np.concatenate((data1, data2, data3, data4), axis=0)
target = np.concatenate((target1,target2,target3,target4),axis=0)
alpha = np.concatenate((np.zeros(sample_size),np.ones(sample_size),np.zeros(sample_size),np.ones(sample_size)), axis=0)
beta = np.concatenate((np.zeros(sample_size),np.zeros(sample_size),np.ones(sample_size),np.ones(sample_size)), axis=0)
data_frame = pd.DataFrame(data = data,columns=["x","y"])
data_frame["alpha"] = pd.Series(alpha).map(lambda v: 'ax01' if v==0 else 'ax02')
data_frame["beta"] = pd.Series(beta).map(lambda v: 'bx01' if v==0 else 'bx02')
data_frame["target"] = target
data_frame.describe()
distribution = ([0] * sample_size) + ([1] * sample_size) + ([2] * sample_size) + ([3] * sample_size)
splitter = model_selection.StratifiedShuffleSplit(n_splits=1, test_size=0.25, random_state=0)
splits = list(splitter.split(X=data_frame.iloc[:,[0,1,2,3]],y=distribution))
learn_index = splits[0][0]
test_index = splits[0][1]
learn_df = data_frame.iloc[learn_index,:]
size2 = int(len(learn_df)/4)
distribution2 = ([0] * size2) + ([1] * size2) + ([2] * size2) + ([3] * size2)
splitter = model_selection.StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
splits = list(splitter.split(X=learn_df.iloc[:,[0,1,2,3]],y=distribution2))
train_index = splits[0][0]
valid_index = splits[0][1]
train_df = learn_df.iloc[train_index,:]
print(len(train_df))
valid_df = learn_df.iloc[valid_index,:]
print(len(valid_df))
test_df = data_frame.iloc[test_index,:]
print(len(test_df))
train_df.to_csv(path_or_buf="data/train-data.csv", header=False, index=True)
valid_df.to_csv(path_or_buf="data/valid-data.csv", header=False, index=True)
test_df.to_csv(path_or_buf="data/test-data.csv", header=False, index=True)
```
| github_jupyter |
# Comparisons using the BatchStudy class
In this notebook, we will be going through the `BatchStudy` class and will be discussing how different models, experiments, chemistries, etc. can be compared with each other using the same.
## Comparing models
We start by creating a simple script to compare `SPM`, `SPMe` and `DFN` model with the default parameters.
```
%pip install pybamm -q # install PyBaMM if it is not installed
import pybamm
# loading up 3 models to compare
dfn = pybamm.lithium_ion.DFN()
spm = pybamm.lithium_ion.SPM()
spme = pybamm.lithium_ion.SPMe()
```
The `BatchStudy` class requires a dictionary of models, and all the default values for a given model are used if no additional parameter is passed in.
```
models = {
"dfn": dfn,
"spm": spm,
"spme": spme,
}
# creating a BatchStudy object
batch_study = pybamm.BatchStudy(models=models)
# solving and plotting the comparison
batch_study.solve(t_eval=[0, 3600])
batch_study.plot()
```
`BatchStudy` by default requires equal number of items in all the dictionaries passed, which can be changed by setting the value of `permutations` to `True`. When set `True`, a cartesian product of all the available items is taken.
For example, here we pass 3 models but only 1 parameter value, hence it is necessary to set `permutations` to `True`. Here, the given parameter value is used for all the provided models.
```
# passing parameter_values as a dictionary
parameter_values = {"Chen2020": pybamm.ParameterValues("Chen2020")}
# creating a BatchStudy object and solving the simulation
batch_study = pybamm.BatchStudy(models=models, parameter_values=parameter_values, permutations=True)
batch_study.solve(t_eval=[0, 3600])
batch_study.plot()
```
## Comparing parameters
`BatchStudy` can also be used to compare different things (like affect of changing a parameter's value) on a single model.
In the following cell, we compare different values of `"Curent function [A]"` using the `Single Paritcle Model with electrolyte`.
```
model = {"spme": spme}
# populating a dictionary with 3 same parameter values
parameter_values = {
"Chen2020_1": pybamm.ParameterValues("Chen2020"),
"Chen2020_2": pybamm.ParameterValues("Chen2020"),
"Chen2020_3": pybamm.ParameterValues("Chen2020"),
}
# different values for "Current function [A]"
current_values = [4.5, 4.75, 5]
# changing the value of "Current function [A]" in all the parameter values present in the
# parameter_values dictionary
for k, v, current_value in zip(parameter_values.keys(), parameter_values.values(), current_values):
v["Current function [A]"] = current_value
# creating a BatchStudy object with permutations set to True to create a cartesian product
batch_study = pybamm.BatchStudy(models=model, parameter_values=parameter_values, permutations=True)
batch_study.solve(t_eval=[0, 3600])
# generating the required labels and plotting
labels = [f"Current function [A]: {current}" for current in current_values]
batch_study.plot(labels=labels)
```
`BatchStudy` also includes a `create_gif` method which can be used to create a GIF of the simulation.
```
# using less number of images in the example
# for a smoother GIF use more images
batch_study.create_gif(number_of_images=5, duration=0.2)
```
Displaying the GIF using markdown-

## Using experiments
Experiments can also be specified for comparisons, and they are also passed as a dictionary (a dictionary of `pybamm.Experiment`) in the `BatchStudy` class.
In the next cell, we compare a single experiment, with a single model, but with a varied parameter value.
```
pybamm.set_logging_level("NOTICE")
# using the cccv experiment with 10 cycles
cccv = pybamm.Experiment(
[
("Discharge at C/10 for 10 hours or until 3.3 V",
"Rest for 1 hour",
"Charge at 1 A until 4.1 V",
"Hold at 4.1 V until 50 mA",
"Rest for 1 hour")
]
* 10,
)
# creating the experiment dict
experiment = {
"cccv": cccv
}
# populating a dictionary with 3 same parameter values (Mohtat2020 chemistry)
parameter_values = {
"Mohtat2020_1": pybamm.ParameterValues("Mohtat2020"),
"Mohtat2020_2": pybamm.ParameterValues("Mohtat2020"),
"Mohtat2020_3": pybamm.ParameterValues("Mohtat2020"),
}
# different values for the parameter "Inner SEI open-circuit potential [V]"
inner_sei_oc_v_values = [2.0e-4, 2.7e-4, 3.4e-4]
# updating the value of "Inner SEI open-circuit potential [V]" in all the dictionary items
for k, v, inner_sei_oc_v in zip(parameter_values.keys(), parameter_values.values(), inner_sei_oc_v_values):
v.update(
{
"Inner SEI open-circuit potential [V]": inner_sei_oc_v
},
)
# creating a Single Particle Model with "electron-mitigation limited" SEI
model = {"spm": pybamm.lithium_ion.SPM({"SEI": "electron-migration limited"})}
# creating a BatchStudy object with the given experimen, model and parameter_values
batch_study = pybamm.BatchStudy(models=model, experiments=experiment, parameter_values=parameter_values, permutations=True)
#solving and plotting the result
batch_study.solve(initial_soc=1)
labels = [f"Inner SEI open-circuit potential [V]: {inner_sei_oc_v}" for inner_sei_oc_v in inner_sei_oc_v_values]
batch_study.plot(labels=labels)
```
The difference in the individual plots is not very well visible in the above slider plot, but we can access all the simulations created by `BatchStudy` (`batch_study.sims`) and pass it to `pybamm.plot_summary_variables` to plot the summary variables (more details on "summary variables" are available in the [`simulationg-long-experiments`](https://github.com/pybamm-team/PyBaMM/blob/develop/examples/notebooks/simulating-long-experiments.ipynb) notebook).
## Comparing summary variables
```
pybamm.plot_summary_variables([sim.solution for sim in batch_study.sims])
```
Other than the above examples, the `BatchStudy` class can be used to compare a lot of different configurations, like models with different SEIs or a model with reversible and irreversible lithium plating, etc.
## References
The relevant papers for this notebook are:
```
pybamm.print_citations()
```
| github_jupyter |
## Learning Objectives
The goal of this notebook is for describing data and to see and practice:
- Load raw data
- View the loaded data
- Formulate an explorative data description question
- Describe the raw data tables
- See and practice data science research tools and practices
### 1 Practical Data Science Research
Can we find good online learning strategies?
We need to define:
- "good", what is good in context of learning?
- "learning", what is learning, and how do you measure it?
- "strategy", what is a strategy for learning and how would you observe it?
Then we need to ask:
- Is it possible to observe any learning in the data?
- Are there any observable strategies?
**Note:** Without a clear goal you can get lost in the data, however there is also a need to explore.
So how do you balance broad exploration for knowledge and in-depth exploitation knowledge.
#### Data used
```
Kuzilek J., Hlosta M., Zdrahal Z. Open University Learning Analytics dataset Sci. Data 4:170171 doi: 10.1038/sdata.2017.171 (2017).
```
See [https://analyse.kmi.open.ac.uk/open_dataset#about](https://analyse.kmi.open.ac.uk/open_dataset#about)
#### What do the tables in the data look like?
**Note:** If you are getting ahead explore the other tables as well
### 2 Import software libraries
There are data science libraries in `Python` for data structures, analysis and plotting
**Note:**
- Using the correct path to the library is important.
- Do not ask me how many times I have had import errors. I usually have a "standard"
layout for projects to avoid spending too much time on configuration of software.
- Using an appropriate data structure is important for usability and computational performance
```
# Import python standard library for operating system functionality.
# This improves portability
import os
# Library for random numbers
import random
# Blank line convention to separate the standard libraries and the other libraries.
# Data structure and analysis library
import pandas as pd
# Data visualization based on `matplotlib`
import seaborn as sns
# Plotting library
import matplotlib.pyplot as plt
```
### 3 Notebook variables and settings
By declaring variables with at the top means that they are in
scope for the entire `Jupyter` notebook
**Note:**
- The scope of the variables in a `Jupyter` notebook can be confusing if your programing experience is in a different
environment.
- A code structure can reduce confusion and reproducability
- Sensible variable names provides better readability
- Editors with auto-complete maintains typing efficiency
```
# Where am I
print(os.getcwd())
# Declare constants
DATA_FOLDER = '../data'
# Set visualization styles with a predefined `seaborn` style
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
```
### 4 Load raw data
We want to work with data in the `DATA_FOLDER`
- What is the size of the data you want to work with?
- Can it fit in memory on the the hardware you are using?
- **Note:** Too large data can reduce the performance.
- Is all the data needed at this point?
**Note:** When writing output, remember to be consistent, that makes searching outupt, e.g. files or content.
```
print('File name: File size')
# List files in the `DATA_FOLDER`
files = os.listdir(DATA_FOLDER)
# Iterate over each file in the folder
for file_name in files:
# Get the file stats
file_stat = os.stat(os.path.join(DATA_FOLDER, file_name))
# Convert the file size in bytes to MB
size_MB = file_stat.st_size / 1024**2
# Print the file name and size
print('{}: {:.3f} MB'.format(file_name, size_MB))
```
What is in the data that can help answer the research question?
- Break down the exploration into small steps, sub questions.
- `cources.csv` seems promising and not too large.
Initial sub question is
- How many courses are there in the data set?
```
# Load "raw" data regarding courses.
# Loading data in a separate cell can avoid computationally expensive file IO.
# Declare the path to the data file with course info
courses_path = os.path.join(DATA_FOLDER, 'courses.csv')
# Use `pandas` `read_csv` to read the CSV data file in as a `pandas` `DataFrame`
courses = pd.read_csv(courses_path)
```
When can we work with a subset of the the data and why would we?
- Early in development to speed up parts not dependent
on all data by both reducing computational time and analysis.
**Note:** avoid drawing too strong conclusions on data subsets.
```
# Define functions in separate cells for code separation and structure.
def count_lines(file_path):
"""
Count total number of lines in a file.
Not optimized for speed. See e.g. https://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python
:param file_path: Path to file
:type file_path: str
:return: Total number of lines in the file
:rtype int:
"""
with open(file_path, 'r') as file_descriptor:
_n_lines = 0
for _ in file_descriptor:
_n_lines += 1
return _n_lines
```
Get a data sample from the `courses.csv` data
```
# Ratio of lines to sample
RATIO_OF_SAMPLES_FROM_DATA_FILE = 0.2
# Get number of lines in the file
n_lines = count_lines(courses_path)
# Get number of lines to sample. Cast it to an integer
n_samples_course = int(n_lines * RATIO_OF_SAMPLES_FROM_DATA_FILE)
# `pandas` `read_csv` API specifies number of lines(rows) to skip
n_lines_to_skip = n_lines - n_samples_course
# Uniformly randomly sample which lines to skip. They need to be ordered
skip_lines = sorted(random.sample(range(1, n_lines), n_lines_to_skip))
# Read file the sampled lines of the file
sample_courses = pd.read_csv(courses_path, skiprows=skip_lines)
# Print sampled data. Note the difference in size with the complete data frame
print("Rows and columns in the data sample: {}".format(sample_courses.shape))
# Assert that the sample has fewer (or equal) lines than the original
# `assert` is a very convenient keyword to check TODO elaborate
assert n_lines >= sample_courses.shape[0]
```
What does the data look like
```
print("Information about the data frame")
print(courses.info())
print("First row in dataframe")
print(courses.head(1))
# What are the names of the columns
print("Columns: {}".format(courses.columns))
# There are often prettier ways to display things.
import IPython.display as display
# Use the `IPython` display function
display.display(courses.head(1))
```
### 5 Explore the data
The data is now loaded. So we can see if we can answer some questions.
- How many unique modules (`code_module`) are there?
- **Note:** It can be useful to formulate questions to guide the exploration to avoid getting lost.
- How many unique module presentations (`code_presentation`) are there?
```
# Columns of interest
cols = ['code_module', 'code_presentation']
# Iterate over columns in the data frame
for col in cols:
# Get unique column values
unique_values = courses[col].unique()
# Get number of unique values
n_unique_values = len(unique_values)
print('Categories for {}: {}; n categories: {}'.format(col, unique_values, n_unique_values))
```
What is the presentation length for each code_module?
- What could the difference depend on?
```
# Column name for x-axis values
xs = 'code_module'
# Column name for y-axis values
ys = 'module_presentation_length'
# Column name for the colors in the plot
group_name = 'code_presentation'
# Plot the data points
ax = sns.stripplot(x=xs, y=ys, hue=group_name, data=courses)
# Set the legend
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
# We call `matplotlib` instead of using the `seaborn` api
# Set plot title
ax.set_title('Presentation Length of Modules')
# Lazy programmer showoff. Create an anonymous function (lambda) that splits the function argument on `_` to a list and
# captalizes each element. Then the elements of the list are joined as a string separated by ` `
pretty_label = lambda x: ' '.join([_.capitalize() for _ in x.split('_')])
# Set x label
ax.set_xlabel(pretty_label(xs))
# Set y label
ax.set_ylabel(pretty_label(ys))
```
Tabular description of the groups based on descriptive statistics
```
# Get the groups
code_modules = courses.groupby(by=xs)
# Iterate over the groups
for name, group in code_modules:
print('Descriptive stats for {} grouped by {}: {}'.format(ys, xs, name))
print(group[ys].describe())
```
#### What is the descriptive statistics and visualization of the other tables in the data?
### 6 Explore the concept of learning as measured by final grade
- What is the final grade?
- In this data it is `final_result` in the `studentInfo` table
```
# Load data
student_info_path = os.path.join(DATA_FOLDER, 'studentInfo.csv')
student_info = pd.read_csv(student_info_path)
print(student_info.info())
```
**Note:** With unfamiliar APIs and dynamically typed languages such as `python` it can be difficult to know which
variable operations are syntactically correct.
```
# Get final results column values
# Get the unique values
print('Final result values (categories): {}'.format(student_info['final_result'].unique()))
# Get the number of values for each category
final_results = student_info['final_result'].value_counts()
print(final_results.head())
# These values are now a `pandas.Series` indexed by the category
print(type(final_results), final_results.index)
# Normalize the value counts
final_results = final_results.div(final_results.sum(), axis=0)
# Plot the final results categories
ax = final_results.plot(kind='bar')
ax.set_title('Final result ratios for all students')
ax.set_xlabel('Final Result')
ax.set_ylabel('Ratio')
```
What is the completion rate?
```
# Sum the values for non-completion
# Find the rows that has Fail or Withdrawn and sum the values
def get_completion_rate(df):
not_completed = df.loc[['Fail', 'Withdrawn']].sum()
completed = 1.0 - not_completed
print("Final result:")
print("not completed: {:.3f}".format(not_completed))
print("completed: {:.3f}".format(completed))
get_completion_rate(final_results)
```
What is the final grade for module `AAA`?
- Now we need to filter the data based on the module we are interested in
**Note:** The code seems repetitive
```
# Define code module
code_module = 'AAA'
# Get the number of values for each category for the code module
student_info_f = student_info.loc[student_info['code_module'] == code_module]
final_results_f = student_info_f['final_result'].value_counts()
print(final_results_f.head())
# Normalize the value counts
final_results_f = final_results_f.div(final_results_f.sum(), axis=0)
# Plot the final results categories
ax = final_results_f.plot(kind='bar')
ax.set_title('Final result ratios for all students on {}'.format(code_module))
ax.set_xlabel('Final Result')
ax.set_ylabel('Ratio')
```
What is the completion rate for `AAA`?
```
get_completion_rate(final_results_f)
```
#### What are the final results for each code_module?
| github_jupyter |
```
import model as model
import math
import anchor as anchor
import random
import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from nyu import my_dataloader as nyu_dataloader
from nyu import testingImageDir, center_test, test_lefttop_pixel, test_rightbottom_pixel, keypointsUVD_test, keypointsNumber
from nyu import cropWidth, cropHeight, depth_thres, xy_thres, downsample, keypointsNumber, net_stacks
from anchor import get_sparse_anchors
import cv2
test_image_datasets = nyu_dataloader(testingImageDir, center_test, test_lefttop_pixel, test_rightbottom_pixel, keypointsUVD_test, augment=False)
'''
joint_color = {
0: '#CC0029',
1: '#CC0029',
2: '#FFFF00',
3: '#FFFF00',
4: '#008020',
5: '#008020',
6: '#007399',
7: '#007399',
8: '#CC9933',
9: '#CC9933',
10: '#CC9933',
11: '#C7C7C7',
12: '#C7C7C7',
13: '#BF00FF',
}
'''
joint_color = {
0: '#FF6600',
1: '#FF3300',
2: '#FFFF00',
3: '#FFCC00',
4: '#00FF00',
5: '#00CC00',
6: '#00FFFF',
7: '#00CCFF',
8: '#999900',
9: '#CC9900',
10: '#FF9900',
11: '#DDDDDD',
12: '#969696',
13: '#BF00FF',
}
def view_cropimg():
i = random.randint(0, len(test_image_datasets)-1)
img, label = test_image_datasets[i]
img, label = img.numpy(), label.numpy()
img = img.squeeze(0)
plt.plot(label[:,1], label[:,0], 'r*')
plt.imshow(img)
def step_cut():
i = random.randint(0, len(test_image_datasets)-1)
img, label = test_image_datasets[i]
img, label = img.numpy(), label.numpy()
img = img.squeeze(0)
mylabel = label.copy()
mylabel[:, 0] = label[:, 1]
mylabel[:, 1] = label[:, 0]
label = mylabel
plt.subplot(221)
plt.plot(label[:,0], label[:,1], 'r*')
plt.imshow(img)
img, label = shape_transform(img, label)
plt.subplot(222)
plt.plot(label[:,0], label[:,1], 'r*')
plt.imshow(img)
plt.subplot(223)
plt.plot(label[:,0], label[:,1], 'r*')
plt.imshow(img)
def view_cropimg_with_anchor():
batch_size = 1
feature_size = int(cropHeight / downsample)
i = random.randint(0, len(test_image_datasets)-1)
img, label = test_image_datasets[i]
joint_num, _ = label.shape
post_process = anchor.MyProcess(cropHeight, keypointsNumber, downsample, net_stacks)
net = model.A2J_model(num_classes = keypointsNumber, downsample=downsample, stack=net_stacks)
net.load_state_dict(torch.load('result/model_store/50_stack4_34_8.31_sample.pth'))
net = net.cuda()
net.eval()
heads = net(torch.unsqueeze(img.cuda(), dim=0))
preds = post_process(heads)
preds = preds.squeeze().cpu().detach().numpy()
anchor_segmentation = post_process.get_anchor_segmentation(heads)
anchor_segmentation = anchor_segmentation.squeeze().cpu().numpy()
anchor_count = {i:0 for i in range(keypointsNumber)}
for r in range(feature_size):
for c in range(feature_size):
anchor_count[anchor_segmentation[r, c]] += 1
label_dis = {}
for i in range(keypointsNumber):
label_dis[i] = math.sqrt((label[i,0] - preds[i,0])**2 + (label[i,1] - preds[i,1])**2)
print(i, label_dis[i], anchor_count[i])
img = img.squeeze(0)
for i in range(joint_num):
plt.plot(label[i,1], label[i,0], '*', color=joint_color[i])
plt.plot(preds[i,1], preds[i,0], '+', color=joint_color[i])
plt.imshow(img)
for r in range(feature_size):
for c in range(feature_size):
val = anchor_segmentation[r, c]
plt.plot(c*downsample + downsample//2, r*downsample + downsample//2, 'o', color=joint_color[val])
view_cropimg_with_anchor()
import model as model
from nyu import keypointsNumber, downsample
net = model.A2J_model(num_classes = keypointsNumber, downsample=downsample)
net.load_state_dict(torch.load('result/model_store/1.pth'))
net = net.cuda()
net.eval()
post_precess = anchor.MyProcess(cropHeight, keypointsNumber, downsample)
img, label = test_image_datasets[2145]
img, label = img.cuda(), label.cuda()
img, label = img.unsqueeze(0), label.unsqueeze(0)
output = net(img)
label_pred = post_precess(output)
label_pred = label_pred.squeeze(0)
img = img.squeeze().cpu().detach().numpy()
label = label.squeeze().cpu().detach().numpy()
label_pred = label_pred.squeeze().cpu().detach().numpy()
plt.plot(label[:,1], label[:,0], 'r*')
plt.plot(label_pred[:,1], label_pred[:,0], 'bo')
plt.imshow(img)
```
| github_jupyter |
# Session 1: Introduction to Tensorflow
<p class='lead'>
Creative Applications of Deep Learning with Tensorflow<br />
Parag K. Mital<br />
Kadenze, Inc.<br />
</p>
<a name="learning-goals"></a>
# Learning Goals
* Learn the basic idea behind machine learning: learning from data and discovering representations
* Learn how to preprocess a dataset using its mean and standard deviation
* Learn the basic components of a Tensorflow Graph
# Table of Contents
<!-- MarkdownTOC autolink=true autoanchor=true bracket=round -->
- [Introduction](#introduction)
- [Promo](#promo)
- [Session Overview](#session-overview)
- [Learning From Data](#learning-from-data)
- [Deep Learning vs. Machine Learning](#deep-learning-vs-machine-learning)
- [Invariances](#invariances)
- [Scope of Learning](#scope-of-learning)
- [Existing datasets](#existing-datasets)
- [Preprocessing Data](#preprocessing-data)
- [Understanding Image Shapes](#understanding-image-shapes)
- [The Batch Dimension](#the-batch-dimension)
- [Mean/Deviation of Images](#meandeviation-of-images)
- [Dataset Preprocessing](#dataset-preprocessing)
- [Histograms](#histograms)
- [Histogram Equalization](#histogram-equalization)
- [Tensorflow Basics](#tensorflow-basics)
- [Variables](#variables)
- [Tensors](#tensors)
- [Graphs](#graphs)
- [Operations](#operations)
- [Tensor](#tensor)
- [Sessions](#sessions)
- [Tensor Shapes](#tensor-shapes)
- [Many Operations](#many-operations)
- [Convolution](#convolution)
- [Creating a 2-D Gaussian Kernel](#creating-a-2-d-gaussian-kernel)
- [Convolving an Image with a Gaussian](#convolving-an-image-with-a-gaussian)
- [Convolve/Filter an image using a Gaussian Kernel](#convolvefilter-an-image-using-a-gaussian-kernel)
- [Modulating the Gaussian with a Sine Wave to create Gabor Kernel](#modulating-the-gaussian-with-a-sine-wave-to-create-gabor-kernel)
- [Manipulating an image with this Gabor](#manipulating-an-image-with-this-gabor)
- [Homework](#homework)
- [Next Session](#next-session)
- [Reading Material](#reading-material)
<!-- /MarkdownTOC -->
<a name="introduction"></a>
# Introduction
This course introduces you to deep learning: the state-of-the-art approach to building artificial intelligence algorithms. We cover the basic components of deep learning, what it means, how it works, and develop code necessary to build various algorithms such as deep convolutional networks, variational autoencoders, generative adversarial networks, and recurrent neural networks. A major focus of this course will be to not only understand how to build the necessary components of these algorithms, but also how to apply them for exploring creative applications. We'll see how to train a computer to recognize objects in an image and use this knowledge to drive new and interesting behaviors, from understanding the similarities and differences in large datasets and using them to self-organize, to understanding how to infinitely generate entirely new content or match the aesthetics or contents of another image. Deep learning offers enormous potential for creative applications and in this course we interrogate what's possible. Through practical applications and guided homework assignments, you'll be expected to create datasets, develop and train neural networks, explore your own media collections using existing state-of-the-art deep nets, synthesize new content from generative algorithms, and understand deep learning's potential for creating entirely new aesthetics and new ways of interacting with large amounts of data.
<a name="promo"></a>
## Promo
Deep learning has emerged at the forefront of nearly every major computational breakthrough in the last 4 years. It is no wonder that it is already in many of the products we use today, from netflix or amazon's personalized recommendations; to the filters that block our spam; to ways that we interact with personal assistants like Apple's Siri or Microsoft Cortana, even to the very ways our personal health is monitored. And sure deep learning algorithms are capable of some amazing things. But it's not just science applications that are benefiting from this research.
Artists too are starting to explore how Deep Learning can be used in their own practice. Photographers are starting to explore different ways of exploring visual media. Generative artists are writing algorithms to create entirely new aesthetics. Filmmakers are exploring virtual worlds ripe with potential for procedural content.
In this course, we're going straight to the state of the art. And we're going to learn it all. We'll see how to make an algorithm paint an image, or hallucinate objects in a photograph. We'll see how to train a computer to recognize objects in an image and use this knowledge to drive new and interesting behaviors, from understanding the similarities and differences in large datasets to using them to self organize, to understanding how to infinitely generate entirely new content or match the aesthetics or contents of other images. We'll even see how to teach a computer to read and synthesize new phrases.
But we won't just be using other peoples code to do all of this. We're going to develop everything ourselves using Tensorflow and I'm going to show you how to do it. This course isn't just for artists nor is it just for programmers. It's for people that want to learn more about how to apply deep learning with a hands on approach, straight into the python console, and learn what it all means through creative thinking and interaction.
I'm Parag Mital, artist, researcher and Director of Machine Intelligence at Kadenze. For the last 10 years, I've been exploring creative uses of computational models making use of machine and deep learning, film datasets, eye-tracking, EEG, and fMRI recordings exploring applications such as generative film experiences, augmented reality hallucinations, and expressive control of large audiovisual corpora.
But this course isn't just about me. It's about bringing all of you together. It's about bringing together different backgrounds, different practices, and sticking all of you in the same virtual room, giving you access to state of the art methods in deep learning, some really amazing stuff, and then letting you go wild on the Kadenze platform. We've been working very hard to build a platform for learning that rivals anything else out there for learning this stuff.
You'll be able to share your content, upload videos, comment and exchange code and ideas, all led by the course I've developed for us. But before we get there we're going to have to cover a lot of groundwork. The basics that we'll use to develop state of the art algorithms in deep learning. And that's really so we can better interrogate what's possible, ask the bigger questions, and be able to explore just where all this is heading in more depth. With all of that in mind, Let's get started>
Join me as we learn all about Creative Applications of Deep Learning with Tensorflow.
<a name="session-overview"></a>
## Session Overview
We're first going to talk about Deep Learning, what it is, and how it relates to other branches of learning. We'll then talk about the major components of Deep Learning, the importance of datasets, and the nature of representation, which is at the heart of deep learning.
If you've never used Python before, we'll be jumping straight into using libraries like numpy, matplotlib, and scipy. Before starting this session, please check the resources section for a notebook introducing some fundamentals of python programming. When you feel comfortable with loading images from a directory, resizing, cropping, how to change an image datatype from unsigned int to float32, and what the range of each data type should be, then come back here and pick up where you left off. We'll then get our hands dirty with Tensorflow, Google's library for machine intelligence. We'll learn the basic components of creating a computational graph with Tensorflow, including how to convolve an image to detect interesting features at different scales. This groundwork will finally lead us towards automatically learning our handcrafted features/algorithms.
<a name="learning-from-data"></a>
# Learning From Data
<a name="deep-learning-vs-machine-learning"></a>
## Deep Learning vs. Machine Learning
So what is this word I keep using, Deep Learning. And how is it different to Machine Learning? Well Deep Learning is a *type* of Machine Learning algorithm that uses Neural Networks to learn. The type of learning is "Deep" because it is composed of many layers of Neural Networks. In this course we're really going to focus on supervised and unsupervised Deep Learning. But there are many other incredibly valuable branches of Machine Learning such as Reinforcement Learning, Dictionary Learning, Probabilistic Graphical Models and Bayesian Methods (Bishop), or Genetic and Evolutionary Algorithms. And any of these branches could certainly even be combined with each other or with Deep Networks as well. We won't really be able to get into these other branches of learning in this course. Instead, we'll focus more on building "networks", short for neural networks, and how they can do some really amazing things. Before we can get into all that, we're going to need to understand a bit more about data and its importance in deep learning.
<a name="invariances"></a>
## Invariances
Deep Learning requires data. A lot of it. It's really one of the major reasons as to why Deep Learning has been so successful. Having many examples of the thing we are trying to learn is the first thing you'll need before even thinking about Deep Learning. Often, it is the biggest blocker to learning about something in the world. Even as a child, we need a lot of experience with something before we begin to understand it. I find I spend most of my time just finding the right data for a network to learn. Getting it from various sources, making sure it all looks right and is labeled. That is a lot of work. The rest of it is easy as we'll see by the end of this course.
Let's say we would like build a network that is capable of looking at an image and saying what object is in the image. There are so many possible ways that an object could be manifested in an image. It's rare to ever see just a single object in isolation. In order to teach a computer about an object, we would have to be able to give it an image of an object in every possible way that it could exist.
We generally call these ways of existing "invariances". That just means we are trying not to vary based on some factor. We are invariant to it. For instance, an object could appear to one side of an image, or another. We call that translation invariance. Or it could be from one angle or another. That's called rotation invariance. Or it could be closer to the camera, or farther. and That would be scale invariance. There are plenty of other types of invariances, such as perspective or brightness or exposure to give a few more examples for photographic images.
<a name="scope-of-learning"></a>
## Scope of Learning
With Deep Learning, you will always need a dataset that will teach the algorithm about the world. But you aren't really teaching it everything. You are only teaching it what is in your dataset! That is a very important distinction. If I show my algorithm only faces of people which are always placed in the center of an image, it will not be able to understand anything about faces that are not in the center of the image! Well at least that's mostly true.
That's not to say that a network is incapable of transfering what it has learned to learn new concepts more easily. Or to learn things that might be necessary for it to learn other representations. For instance, a network that has been trained to learn about birds, probably knows a good bit about trees, branches, and other bird-like hangouts, depending on the dataset. But, in general, we are limited to learning what our dataset has access to.
So if you're thinking about creating a dataset, you're going to have to think about what it is that you want to teach your network. What sort of images will it see? What representations do you think your network could learn given the data you've shown it?
One of the major contributions to the success of Deep Learning algorithms is the amount of data out there. Datasets have grown from orders of hundreds to thousands to many millions. The more data you have, the more capable your network will be at determining whatever its objective is.
<a name="existing-datasets"></a>
## Existing datasets
With that in mind, let's try to find a dataset that we can work with. There are a ton of datasets out there that current machine learning researchers use. For instance if I do a quick Google search for Deep Learning Datasets, i can see for instance a link on deeplearning.net, listing a few interesting ones e.g. http://deeplearning.net/datasets/, including MNIST, CalTech, CelebNet, LFW, CIFAR, MS Coco, Illustration2Vec, and there are ton more. And these are primarily image based. But if you are interested in finding more, just do a quick search or drop a quick message on the forums if you're looking for something in particular.
* MNIST
* CalTech
* CelebNet
* ImageNet: http://www.image-net.org/
* LFW
* CIFAR10
* CIFAR100
* MS Coco: http://mscoco.org/home/
* WLFDB: http://wlfdb.stevenhoi.com/
* Flickr 8k: http://nlp.cs.illinois.edu/HockenmaierGroup/Framing_Image_Description/KCCA.html
* Flickr 30k
<a name="preprocessing-data"></a>
# Preprocessing Data
In this section, we're going to learn a bit about working with an image based dataset. We'll see how image dimensions are formatted as a single image and how they're represented as a collection using a 4-d array. We'll then look at how we can perform dataset normalization. If you're comfortable with all of this, please feel free to skip to the next video.
We're first going to load some libraries that we'll be making use of.
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
```
I'll be using a popular image dataset for faces called the CelebFaces dataset. I've provided some helper functions which you can find on the resources page, which will just help us with manipulating images and loading this dataset.
```
from libs import utils
# utils.<tab>
files = utils.get_celeb_files()
```
Let's get the 50th image in this list of files, and then read the file at that location as an image, setting the result to a variable, `img`, and inspect a bit further what's going on:
```
img = plt.imread(files[50])
# img.<tab>
print(img)
```
When I print out this image, I can see all the numbers that represent this image. We can use the function `imshow` to see this:
```
# If nothing is drawn and you are using notebook, try uncommenting the next line:
#%matplotlib inline
plt.imshow(img)
```
<a name="understanding-image-shapes"></a>
## Understanding Image Shapes
Let's break this data down a bit more. We can see the dimensions of the data using the `shape` accessor:
```
img.shape
# (218, 178, 3)
```
This means that the image has 218 rows, 178 columns, and 3 color channels corresponding to the Red, Green, and Blue channels of the image, or RGB. Let's try looking at just one of the color channels.
```
plt.imshow(img[:, :, 0], cmap='gray')
plt.imshow(img[:, :, 1], cmap='gray')
plt.imshow(img[:, :, 2], cmap='gray')
```
We use the special colon operator to say take every value in this dimension. This is saying, give me every row, every column, and the 0th dimension of the color channels. What we're seeing is the amount of Red, Green, or Blue contributing to the overall color image.
Let's use another helper function which will load every image file in the celeb dataset rather than just give us the filenames like before. By default, this will just return the first 1000 images because loading the entire dataset is a bit cumbersome. In one of the later sessions, I'll show you how tensorflow can handle loading images using a pipeline so we can load this same dataset. For now, let's stick with this:
```
imgs = utils.get_celeb_imgs()
```
We now have a list containing our images. Each index of the `imgs` list is another image which we can access using the square brackets:
```
plt.imshow(imgs[0])
```
<a name="the-batch-dimension"></a>
## The Batch Dimension
Remember that an image has a shape describing the height, width, channels:
```
imgs[0].shape
```
It turns out we'll often use another convention for storing many images in an array using a new dimension called the batch dimension. The resulting image shape will be exactly the same, except we'll stick on a new dimension on the beginning... giving us number of images x the height x the width x the number of color channels.
N x H x W x C
A Color image should have 3 color channels, RGB.
We can combine all of our images to have these 4 dimensions by telling numpy to give us an array of all the images.
```
data = np.array(imgs)
data.shape
```
This will only work if every image in our list is exactly the same size. So if you have a wide image, short image, long image, forget about it. You'll need them all to be the same size. If you are unsure of how to get all of your images into the same size, then please please refer to the online resources for the notebook I've provided which shows you exactly how to take a bunch of images of different sizes, and crop and resize them the best we can to make them all the same size.
<a name="meandeviation-of-images"></a>
## Mean/Deviation of Images
Now that we have our data in a single numpy variable, we can do alot of cool stuff. Let's look at the mean of the batch channel:
```
mean_img = np.mean(data, axis=0)
plt.imshow(mean_img.astype(np.uint8))
```
This is the first step towards building our robot overlords. We've reduced down our entire dataset to a single representation which describes what most of our dataset looks like. There is one other very useful statistic which we can look at very easily:
```
std_img = np.std(data, axis=0)
plt.imshow(std_img.astype(np.uint8))
```
So this is incredibly cool. We've just shown where changes are likely to be in our dataset of images. Or put another way, we're showing where and how much variance there is in our previous mean image representation.
We're looking at this per color channel. So we'll see variance for each color channel represented separately, and then combined as a color image. We can try to look at the average variance over all color channels by taking their mean:
```
plt.imshow(np.mean(std_img, axis=2).astype(np.uint8))
```
This is showing us on average, how every color channel will vary as a heatmap. The more red, the more likely that our mean image is not the best representation. The more blue, the less likely that our mean image is far off from any other possible image.
<a name="dataset-preprocessing"></a>
## Dataset Preprocessing
Think back to when I described what we're trying to accomplish when we build a model for machine learning? We're trying to build a model that understands invariances. We need our model to be able to express *all* of the things that can possibly change in our data. Well, this is the first step in understanding what can change. If we are looking to use deep learning to learn something complex about our data, it will often start by modeling both the mean and standard deviation of our dataset. We can help speed things up by "preprocessing" our dataset by removing the mean and standard deviation. What does this mean? Subtracting the mean, and dividing by the standard deviation. Another word for that is "normalization".
<a name="histograms"></a>
## Histograms
Let's have a look at our dataset another way to see why this might be a useful thing to do. We're first going to convert our `batch` x `height` x `width` x `channels` array into a 1 dimensional array. Instead of having 4 dimensions, we'll now just have 1 dimension of every pixel value stretched out in a long vector, or 1 dimensional array.
```
flattened = data.ravel()
print(data[:1])
print(flattened[:10])
```
We first convert our N x H x W x C dimensional array into a 1 dimensional array. The values of this array will be based on the last dimensions order. So we'll have: [<font color='red'>251</font>, <font color='green'>238</font>, <font color='blue'>205</font>, <font color='red'>251</font>, <font color='green'>238</font>, <font color='blue'>206</font>, <font color='red'>253</font>, <font color='green'>240</font>, <font color='blue'>207</font>, ...]
We can visualize what the "distribution", or range and frequency of possible values are. This is a very useful thing to know. It tells us whether our data is predictable or not.
```
plt.hist(flattened.ravel(), 255)
```
The last line is saying give me a histogram of every value in the vector, and use 255 bins. Each bin is grouping a range of values. The bars of each bin describe the frequency, or how many times anything within that range of values appears.In other words, it is telling us if there is something that seems to happen more than anything else. If there is, it is likely that a neural network will take advantage of that.
<a name="histogram-equalization"></a>
## Histogram Equalization
The mean of our dataset looks like this:
```
plt.hist(mean_img.ravel(), 255)
```
When we subtract an image by our mean image, we remove all of this information from it. And that means that the rest of the information is really what is important for describing what is unique about it.
Let's try and compare the histogram before and after "normalizing our data":
```
bins = 20
fig, axs = plt.subplots(1, 3, figsize=(12, 6), sharey=True, sharex=True)
axs[0].hist((data[0]).ravel(), bins)
axs[0].set_title('img distribution')
axs[1].hist((mean_img).ravel(), bins)
axs[1].set_title('mean distribution')
axs[2].hist((data[0] - mean_img).ravel(), bins)
axs[2].set_title('(img - mean) distribution')
```
What we can see from the histograms is the original image's distribution of values from 0 - 255. The mean image's data distribution is mostly centered around the value 100. When we look at the difference of the original image and the mean image as a histogram, we can see that the distribution is now centered around 0. What we are seeing is the distribution of values that were above the mean image's intensity, and which were below it. Let's take it one step further and complete the normalization by dividing by the standard deviation of our dataset:
```
fig, axs = plt.subplots(1, 3, figsize=(12, 6), sharey=True, sharex=True)
axs[0].hist((data[0] - mean_img).ravel(), bins)
axs[0].set_title('(img - mean) distribution')
axs[1].hist((std_img).ravel(), bins)
axs[1].set_title('std deviation distribution')
axs[2].hist(((data[0] - mean_img) / std_img).ravel(), bins)
axs[2].set_title('((img - mean) / std_dev) distribution')
```
Now our data has been squished into a peak! We'll have to look at it on a different scale to see what's going on:
```
axs[2].set_xlim([-150, 150])
axs[2].set_xlim([-100, 100])
axs[2].set_xlim([-50, 50])
axs[2].set_xlim([-10, 10])
axs[2].set_xlim([-5, 5])
```
What we can see is that the data is in the range of -3 to 3, with the bulk of the data centered around -1 to 1. This is the effect of normalizing our data: most of the data will be around 0, where some deviations of it will follow between -3 to 3.
If our data does not end up looking like this, then we should either (1): get much more data to calculate our mean/std deviation, or (2): either try another method of normalization, such as scaling the values between 0 to 1, or -1 to 1, or possibly not bother with normalization at all. There are other options that one could explore, including different types of normalization such as local contrast normalization for images or PCA based normalization but we won't have time to get into those in this course.
<a name="tensorflow-basics"></a>
# Tensorflow Basics
Let's now switch gears and start working with Google's Library for Numerical Computation, TensorFlow. This library can do most of the things we've done so far. However, it has a very different approach for doing so. And it can do a whole lot more cool stuff which we'll eventually get into. The major difference to take away from the remainder of this session is that instead of computing things immediately, we first define things that we want to compute later using what's called a `Graph`. Everything in Tensorflow takes place in a computational graph and running and evaluating anything in the graph requires a `Session`. Let's take a look at how these both work and then we'll get into the benefits of why this is useful:
<a name="variables"></a>
## Variables
We're first going to import the tensorflow library:
```
import tensorflow as tf
```
Let's take a look at how we might create a range of numbers. Using numpy, we could for instance use the linear space function:
```
x = np.linspace(-3.0, 3.0, 100)
# Immediately, the result is given to us. An array of 100 numbers equally spaced from -3.0 to 3.0.
print(x)
# We know from numpy arrays that they have a `shape`, in this case a 1-dimensional array of 100 values
print(x.shape)
# and a `dtype`, in this case float64, or 64 bit floating point values.
print(x.dtype)
```
<a name="tensors"></a>
## Tensors
In tensorflow, we could try to do the same thing using their linear space function:
```
x = tf.linspace(-3.0, 3.0, 100)
print(x)
```
Instead of a `numpy.array`, we are returned a `tf.Tensor`. The name of it is "LinSpace:0". Wherever we see this colon 0, that just means the output of. So the name of this Tensor is saying, the output of LinSpace.
Think of `tf.Tensor`s the same way as you would the `numpy.array`. It is described by its `shape`, in this case, only 1 dimension of 100 values. And it has a `dtype`, in this case, `float32`. But *unlike* the `numpy.array`, there are no values printed here! That's because it actually hasn't computed its values yet. Instead, it just refers to the output of a `tf.Operation` which has been already been added to Tensorflow's default computational graph. The result of that operation is the tensor that we are returned.
<a name="graphs"></a>
## Graphs
Let's try and inspect the underlying graph. We can request the "default" graph where all of our operations have been added:
```
g = tf.get_default_graph()
```
<a name="operations"></a>
## Operations
And from this graph, we can get a list of all the operations that have been added, and print out their names:
```
[op.name for op in g.get_operations()]
```
So Tensorflow has named each of our operations to generally reflect what they are doing. There are a few parameters that are all prefixed by LinSpace, and then the last one which is the operation which takes all of the parameters and creates an output for the linspace.
<a name="tensor"></a>
## Tensor
We can request the output of any operation, which is a tensor, by asking the graph for the tensor's name:
```
g.get_tensor_by_name('LinSpace' + ':0')
```
What I've done is asked for the `tf.Tensor` that comes from the operation "LinSpace". So remember, the result of a `tf.Operation` is a `tf.Tensor`. Remember that was the same name as the tensor `x` we created before.
<a name="sessions"></a>
## Sessions
In order to actually compute anything in tensorflow, we need to create a `tf.Session`. The session is responsible for evaluating the `tf.Graph`. Let's see how this works:
```
# We're first going to create a session:
sess = tf.Session()
# Now we tell our session to compute anything we've created in the tensorflow graph.
computed_x = sess.run(x)
print(computed_x)
# Alternatively, we could tell the previous Tensor to evaluate itself using this session:
computed_x = x.eval(session=sess)
print(computed_x)
# We can close the session after we're done like so:
sess.close()
```
We could also explicitly tell the session which graph we want to manage:
```
sess = tf.Session(graph=g)
sess.close()
```
By default, it grabs the default graph. But we could have created a new graph like so:
```
g2 = tf.Graph()
```
And then used this graph only in our session.
To simplify things, since we'll be working in iPython's interactive console, we can create an `tf.InteractiveSession`:
```
sess = tf.InteractiveSession()
x.eval()
```
Now we didn't have to explicitly tell the `eval` function about our session. We'll leave this session open for the rest of the lecture.
<a name="tensor-shapes"></a>
## Tensor Shapes
```
# We can find out the shape of a tensor like so:
print(x.get_shape())
# %% Or in a more friendly format
print(x.get_shape().as_list())
```
<a name="many-operations"></a>
## Many Operations
Lets try a set of operations now. We'll try to create a Gaussian curve. This should resemble a normalized histogram where most of the data is centered around the mean of 0. It's also sometimes refered to by the bell curve or normal curve.
```
# The 1 dimensional gaussian takes two parameters, the mean value, and the standard deviation, which is commonly denoted by the name sigma.
mean = 0.0
sigma = 1.0
# Don't worry about trying to learn or remember this formula. I always have to refer to textbooks or check online for the exact formula.
z = (tf.exp(tf.neg(tf.pow(x - mean, 2.0) /
(2.0 * tf.pow(sigma, 2.0)))) *
(1.0 / (sigma * tf.sqrt(2.0 * 3.1415))))
```
Just like before, amazingly, we haven't actually computed anything. We *have just added a bunch of operations to Tensorflow's graph. Whenever we want the value or output of this operation, we'll have to explicitly ask for the part of the graph we're interested in before we can see its result. Since we've created an interactive session, we should just be able to say the name of the Tensor that we're interested in, and call the `eval` function:
```
res = z.eval()
plt.plot(res)
# if nothing is drawn, and you are using ipython notebook, uncomment the next two lines:
#%matplotlib inline
#plt.plot(res)
```
<a name="convolution"></a>
# Convolution
<a name="creating-a-2-d-gaussian-kernel"></a>
## Creating a 2-D Gaussian Kernel
Let's try creating a 2-dimensional Gaussian. This can be done by multiplying a vector by its transpose. If you aren't familiar with matrix math, I'll review a few important concepts. This is about 98% of what neural networks do so if you're unfamiliar with this, then please stick with me through this and it'll be smooth sailing. First, to multiply two matrices, their inner dimensions must agree, and the resulting matrix will have the shape of the outer dimensions.
So let's say we have two matrices, X and Y. In order for us to multiply them, X's columns must match Y's rows. I try to remember it like so:
<pre>
(X_rows, X_cols) x (Y_rows, Y_cols)
| | | |
| |___________| |
| ^ |
| inner dimensions |
| must match |
| |
|__________________________|
^
resulting dimensions
of matrix multiplication
</pre>
But our matrix is actually a vector, or a 1 dimensional matrix. That means its dimensions are N x 1. So to multiply them, we'd have:
<pre>
(N, 1) x (1, N)
| | | |
| |___________| |
| ^ |
| inner dimensions |
| must match |
| |
|__________________________|
^
resulting dimensions
of matrix multiplication
</pre>
```
# Let's store the number of values in our Gaussian curve.
ksize = z.get_shape().as_list()[0]
# Let's multiply the two to get a 2d gaussian
z_2d = tf.matmul(tf.reshape(z, [ksize, 1]), tf.reshape(z, [1, ksize]))
# Execute the graph
plt.imshow(z_2d.eval())
```
<a name="convolving-an-image-with-a-gaussian"></a>
## Convolving an Image with a Gaussian
A very common operation that we'll come across with Deep Learning is convolution. We're going to explore what this means using our new gaussian kernel that we've just created. For now, just think of it a way of filtering information. We're going to effectively filter our image using this Gaussian function, as if the gaussian function is the lens through which we'll see our image data. What it will do is at every location we tell it to filter, it will average the image values around it based on what the kernel's values are. The Gaussian's kernel is basically saying, take a lot the center, a then decesasingly less as you go farther away from the center. The effect of convolving the image with this type of kernel is that the entire image will be blurred. If you would like an interactive exploratin of convolution, this website is great:
http://setosa.io/ev/image-kernels/
```
# Let's first load an image. We're going to need a grayscale image to begin with. skimage has some images we can play with. If you do not have the skimage module, you can load your own image, or get skimage by pip installing "scikit-image".
from skimage import data
img = data.camera().astype(np.float32)
plt.imshow(img, cmap='gray')
print(img.shape)
```
Notice our img shape is 2-dimensional. For image convolution in Tensorflow, we need our images to be 4 dimensional. Remember that when we load many iamges and combine them in a single numpy array, the resulting shape has the number of images first.
N x H x W x C
In order to perform 2d convolution with tensorflow, we'll need the same dimensions for our image. With just 1 grayscale image, this means the shape will be:
1 x H x W x 1
```
# We could use the numpy reshape function to reshape our numpy array
img_4d = img.reshape([1, img.shape[0], img.shape[1], 1])
print(img_4d.shape)
# but since we'll be using tensorflow, we can use the tensorflow reshape function:
img_4d = tf.reshape(img, [1, img.shape[0], img.shape[1], 1])
print(img_4d)
```
Instead of getting a numpy array back, we get a tensorflow tensor. This means we can't access the `shape` parameter like we did with the numpy array. But instead, we can use `get_shape()`, and `get_shape().as_list()`:
```
print(img_4d.get_shape())
print(img_4d.get_shape().as_list())
```
The H x W image is now part of a 4 dimensional array, where the other dimensions of N and C are 1. So there is only 1 image and only 1 channel.
We'll also have to reshape our Gaussian Kernel to be 4-dimensional as well. The dimensions for kernels are slightly different! Remember that the image is:
Number of Images x Image Height x Image Width x Number of Channels
we have:
Kernel Height x Kernel Width x Number of Input Channels x Number of Output Channels
Our Kernel already has a height and width of `ksize` so we'll stick with that for now. The number of input channels should match the number of channels on the image we want to convolve. And for now, we just keep the same number of output channels as the input channels, but we'll later see how this comes into play.
```
# Reshape the 2d kernel to tensorflow's required 4d format: H x W x I x O
z_4d = tf.reshape(z_2d, [ksize, ksize, 1, 1])
print(z_4d.get_shape().as_list())
```
<a name="convolvefilter-an-image-using-a-gaussian-kernel"></a>
## Convolve/Filter an image using a Gaussian Kernel
We can now use our previous Gaussian Kernel to convolve our image:
```
convolved = tf.nn.conv2d(img_4d, z_4d, strides=[1, 1, 1, 1], padding='SAME')
res = convolved.eval()
print(res.shape)
```
There are two new parameters here: `strides`, and `padding`. Strides says how to move our kernel across the image. Basically, we'll only ever use it for one of two sets of parameters:
[1, 1, 1, 1], which means, we are going to convolve every single image, every pixel, and every color channel by whatever the kernel is.
and the second option:
[1, 2, 2, 1], which means, we are going to convolve every single image, but every other pixel, in every single color channel.
Padding says what to do at the borders. If we say "SAME", that means we want the same dimensions going in as we do going out. In order to do this, zeros must be padded around the image. If we say "VALID", that means no padding is used, and the image dimensions will actually change.
```
# Matplotlib cannot handle plotting 4D images! We'll have to convert this back to the original shape. There are a few ways we could do this. We could plot by "squeezing" the singleton dimensions.
plt.imshow(np.squeeze(res), cmap='gray')
# Or we could specify the exact dimensions we want to visualize:
plt.imshow(res[0, :, :, 0], cmap='gray')
```
<a name="modulating-the-gaussian-with-a-sine-wave-to-create-gabor-kernel"></a>
## Modulating the Gaussian with a Sine Wave to create Gabor Kernel
We've now seen how to use tensorflow to create a set of operations which create a 2-dimensional Gaussian kernel, and how to use that kernel to filter or convolve another image. Let's create another interesting convolution kernel called a Gabor. This is a lot like the Gaussian kernel, except we use a sine wave to modulate that.
<graphic: draw 1d gaussian wave, 1d sine, show modulation as multiplication and resulting gabor.>
We first use linspace to get a set of values the same range as our gaussian, which should be from -3 standard deviations to +3 standard deviations.
```
xs = tf.linspace(-3.0, 3.0, ksize)
```
We then calculate the sine of these values, which should give us a nice wave
```
ys = tf.sin(xs)
plt.figure()
plt.plot(ys.eval())
```
And for multiplication, we'll need to convert this 1-dimensional vector to a matrix: N x 1
```
ys = tf.reshape(ys, [ksize, 1])
```
We then repeat this wave across the matrix by using a multiplication of ones:
```
ones = tf.ones((1, ksize))
wave = tf.matmul(ys, ones)
plt.imshow(wave.eval(), cmap='gray')
```
We can directly multiply our old Gaussian kernel by this wave and get a gabor kernel:
```
gabor = tf.mul(wave, z_2d)
plt.imshow(gabor.eval(), cmap='gray')
```
<a name="manipulating-an-image-with-this-gabor"></a>
## Manipulating an image with this Gabor
We've already gone through the work of convolving an image. The only thing that has changed is the kernel that we want to convolve with. We could have made life easier by specifying in our graph which elements we wanted to be specified later. Tensorflow calls these "placeholders", meaning, we're not sure what these are yet, but we know they'll fit in the graph like so, generally the input and output of the network.
Let's rewrite our convolution operation using a placeholder for the image and the kernel and then see how the same operation could have been done. We're going to set the image dimensions to `None` x `None`. This is something special for placeholders which tells tensorflow "let this dimension be any possible value". 1, 5, 100, 1000, it doesn't matter.
```
# This is a placeholder which will become part of the tensorflow graph, but
# which we have to later explicitly define whenever we run/evaluate the graph.
# Pretty much everything you do in tensorflow can have a name. If we don't
# specify the name, tensorflow will give a default one, like "Placeholder_0".
# Let's use a more useful name to help us understand what's happening.
img = tf.placeholder(tf.float32, shape=[None, None], name='img')
# We'll reshape the 2d image to a 3-d tensor just like before:
# Except now we'll make use of another tensorflow function, expand dims, which adds a singleton dimension at the axis we specify.
# We use it to reshape our H x W image to include a channel dimension of 1
# our new dimensions will end up being: H x W x 1
img_3d = tf.expand_dims(img, 2)
dims = img_3d.get_shape()
print(dims)
# And again to get: 1 x H x W x 1
img_4d = tf.expand_dims(img_3d, 0)
print(img_4d.get_shape().as_list())
# Let's create another set of placeholders for our Gabor's parameters:
mean = tf.placeholder(tf.float32, name='mean')
sigma = tf.placeholder(tf.float32, name='sigma')
ksize = tf.placeholder(tf.int32, name='ksize')
# Then finally redo the entire set of operations we've done to convolve our
# image, except with our placeholders
x = tf.linspace(-3.0, 3.0, ksize)
z = (tf.exp(tf.neg(tf.pow(x - mean, 2.0) /
(2.0 * tf.pow(sigma, 2.0)))) *
(1.0 / (sigma * tf.sqrt(2.0 * 3.1415))))
z_2d = tf.matmul(
tf.reshape(z, tf.pack([ksize, 1])),
tf.reshape(z, tf.pack([1, ksize])))
ys = tf.sin(x)
ys = tf.reshape(ys, tf.pack([ksize, 1]))
ones = tf.ones(tf.pack([1, ksize]))
wave = tf.matmul(ys, ones)
gabor = tf.mul(wave, z_2d)
gabor_4d = tf.reshape(gabor, tf.pack([ksize, ksize, 1, 1]))
# And finally, convolve the two:
convolved = tf.nn.conv2d(img_4d, gabor_4d, strides=[1, 1, 1, 1], padding='SAME', name='convolved')
convolved_img = convolved[0, :, :, 0]
```
What we've done is create an entire graph from our placeholders which is capable of convolving an image with a gabor kernel. In order to compute it, we have to specify all of the placeholders required for its computation.
If we try to evaluate it without specifying placeholders beforehand, we will get an error `InvalidArgumentError: You must feed a value for placeholder tensor 'img' with dtype float and shape [512,512]`:
```
convolved_img.eval()
```
It's saying that we didn't specify our placeholder for `img`. In order to "feed a value", we use the `feed_dict` parameter like so:
```
convolved_img.eval(feed_dict={img: data.camera()})
```
But that's not the only placeholder in our graph! We also have placeholders for `mean`, `sigma`, and `ksize`. Once we specify all of them, we'll have our result:
```
res = convolved_img.eval(feed_dict={
img: data.camera(), mean:0.0, sigma:1.0, ksize:100})
plt.imshow(res, cmap='gray')
```
Now, instead of having to rewrite the entire graph, we can just specify the different placeholders.
```
res = convolved_img.eval(feed_dict={
img: data.camera(),
mean: 0.0,
sigma: 0.5,
ksize: 32
})
plt.imshow(res, cmap='gray')
```
<a name="homework"></a>
# Homework
For your first assignment, we'll work on creating our own dataset. You'll need to find at least 100 images and work through the [notebook](session-1.ipynb).
<a name="next-session"></a>
# Next Session
In the next session, we'll create our first Neural Network and see how it can be used to paint an image.
<a name="reading-material"></a>
# Reading Material
Abadi, M., Agarwal, A., Barham, P., Brevdo, E., Chen, Z., Citro, C., … Zheng, X. (2015). TensorFlow : Large-Scale Machine Learning on Heterogeneous Distributed Systems.
https://arxiv.org/abs/1603.04467
Yoshua Bengio, Aaron Courville, Pascal Vincent. Representation Learning: A Review and New Perspectives. 24 Jun 2012.
https://arxiv.org/abs/1206.5538
J. Schmidhuber. Deep Learning in Neural Networks: An Overview. Neural Networks, 61, p 85-117, 2015.
https://arxiv.org/abs/1404.7828
LeCun, Yann, Yoshua Bengio, and Geoffrey Hinton. “Deep learning.” Nature 521, no. 7553 (2015): 436-444.
Ian Goodfellow Yoshua Bengio and Aaron Courville. Deep Learning. 2016.
http://www.deeplearningbook.org/
| github_jupyter |
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
#download mnist data and split into train and test sets
df = pd.read_csv('NeutralData.csv')
X = df.drop(['Label'], axis = 1).values
Y = df['Label']
X = StandardScaler().fit_transform(X)
Xnew = []
for i in range(0, len(X), 250):
Xnew.append(X[i:250+i])
Ynew = []
for j in range(0, 187250, 250):
Ynew.append(0)
for k in range(0, 194500, 250):
Ynew.append(1)
from itertools import groupby
print([len(list(group)) for key, group in groupby(Y)])
Xnew = np.array(Xnew)
print(Xnew[0].shape)
print(Xnew.shape)
#X = StandardScaler().fit_transform(Xnew)
X_train, X_test, y_train, y_test = train_test_split(Xnew, Ynew, test_size = 0.30, random_state = 101)
X_test.shape
#reshape data to fit model
X_train = X_train.reshape(1068,250,128,1)
X_test = X_test.reshape(459,250,128,1)
from keras.utils import to_categorical
#one-hot encode target column
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
y_train[0]
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
#create model
model = Sequential()
#add model layers
model.add(Conv2D(32, (5,5), activation='relu', input_shape=(250,128,1),padding='SAME'))
model.add(Conv2D(32, (5,5), activation='relu',padding='SAME'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))
#compile model using accuracy to measure model performance
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
#train the model
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=5, batch_size=10, verbose=0)
print(history)
# https://machinelearningmastery.com/display-deep-learning-model-training-history-in-keras/
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
#predict first 4 images in the test set
model.predict(X_test[:4])
#actual results for first 4 images in test set
y_test[:4]
score = model.evaluate(X_test, y_test, verbose=0)
print(score)
model.summary()
# Visualising the filter
top_layer = model.layers[0]
plt.imshow(top_layer.get_weights()[0][:, :, :, 0].squeeze(), cmap='gray')
```
| github_jupyter |
# Preliminary experiment to examine the effect of the numbers of forward passes to the consistency of the certainty estimate
### Import the libraries
```
import os
import csv
import numpy as np
import pickle
import seaborn as sns
import pandas as pd
from itertools import chain
import matplotlib.pyplot as plt
%matplotlib inline
```
### Initialize some paths and parameters
```
resultsdir = "/home/pieter/maskAL/results/preliminary_exp1"
font_size = 15
digit_size = 14
fps = [2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
ranges = [[0.0, 0.25], [0.25, 0.50], [0.50, 0.75], [0.75, 1.0]]
probs = [0.25, 0.50, 0.75]
```
### Plot the processed data - absolute difference
```
for p in range(len(probs)):
prob = probs[p]
pkl_file = "uncertainty_metrics_prob_{:.2f}.pkl".format(prob)
strs = ["fp_{:d}".format(fps[f]) for f in range(len(fps))]
strs.insert(0,"val_100")
strs.insert(0,"image")
fr = {}
df = pd.DataFrame(columns=strs)
with open(os.path.join(resultsdir, pkl_file), 'rb') as handle:
uncertainties = pickle.load(handle)
for key, val in uncertainties.items():
transposed = list(zip(*val))
for t in range(len(transposed)):
obs = transposed[t]
abs_diff = [abs(obs[o]-obs[-1]) for o in range(len(obs))]
data = [key, obs[-1]]
for apd in range(len(abs_diff)):
data.append(abs_diff[apd])
df_length = len(df)
df.loc[df_length] = data
f, ax = plt.subplots(figsize=(13, 9))
legends = []
for r in range(len(ranges)):
sel = df[df['val_100'].between(ranges[r][0], ranges[r][1])].loc[:, 'fp_2':'fp_100']
dff = pd.DataFrame(columns=['fp', 'abs_diff'])
selnp = sel.to_numpy()
selnp.transpose(1,0)
for i in range(selnp.shape[0]):
for j in range(len(selnp[i,:])):
data = [fps[j], selnp[i,j]]
dff_length = len(dff)
dff.loc[dff_length] = data
legends.append("observations with c_h value between {:.2f} - {:.2f} at 100 forward passes (n={:d})".format(ranges[r][0], ranges[r][1], int((len(dff)/(len(fps)-1)))))
if not dff.empty:
ax = sns.lineplot(x='fp', y='abs_diff', ci=95, data=dff, palette = "tab10", legend="full")
ax.tick_params(labelrotation=0, labelsize=digit_size)
ax.legend(legends, fontsize=digit_size, loc='upper right')
ax.yaxis.grid(True)
plt.ylim([0, 0.5])
plt.xticks(np.arange(0, 110, step=10))
plt.xlabel("Number of forward passes", fontsize=font_size)
plt.ylabel("Absolute c_h difference with the c_h value of 100 forward passes", fontsize=font_size)
plt.tight_layout()
plt.title('Dropout probability: {:.2f}'.format(prob), fontsize = font_size)
plt.savefig(os.path.join(resultsdir, 'prob_{:.2f}.jpg'.format(prob)))
plt.show()
dff = pd.DataFrame(columns=['prob', 'fp', 'abs_diff'])
legends = []
for p in range(len(probs)):
prob = probs[p]
pkl_file = "uncertainty_metrics_prob_{:.2f}.pkl".format(prob)
strs = ["fp_{:d}".format(fps[f]) for f in range(len(fps))]
strs.insert(0,"val_100")
strs.insert(0,"image")
fr = {}
df = pd.DataFrame(columns=strs)
with open(os.path.join(resultsdir, pkl_file), 'rb') as handle:
uncertainties = pickle.load(handle)
for key, val in uncertainties.items():
transposed = list(zip(*val))
for t in range(len(transposed)):
obs = transposed[t]
abs_diff = [abs(obs[o]-obs[-1]) for o in range(len(obs))]
data = [key, obs[-1]]
for apd in range(len(abs_diff)):
data.append(abs_diff[apd])
df_length = len(df)
df.loc[df_length] = data
sel = df[df['val_100'].between(0.0, 1.0)].loc[:, 'fp_2':'fp_90']
selnp = sel.to_numpy()
selnp.transpose(1,0)
for i in range(selnp.shape[0]):
for j in range(len(selnp[i,:])):
data = [prob, fps[j], selnp[i,j]]
dff_length = len(dff)
dff.loc[dff_length] = data
legends.append("dropout probability: {:.2f}, number of instance sets: {:d}".format(prob, len(df)))
if not dff.empty:
f, ax = plt.subplots(figsize=(13, 9))
ax = sns.lineplot(x='fp', y='abs_diff', hue='prob', ci=95, data=dff, palette = "tab10", legend="full")
ax.tick_params(labelrotation=0, labelsize=digit_size)
ax.legend(legends, fontsize=digit_size, loc='upper right')
ax.yaxis.grid(True)
plt.ylim([0, 0.1])
plt.xticks((2, 10, 20, 30, 40, 50, 60, 70, 80, 90))
plt.xlabel("Number of forward passes", fontsize=font_size)
plt.ylabel("Absolute difference with the certainty estimate at 100 forward passes", fontsize=font_size)
plt.tight_layout()
plt.savefig(os.path.join(resultsdir, 'combined.jpg'))
plt.show()
```
| github_jupyter |
## BUILDING A RECOMMENDER SYSTEM ON USER-USER COLLABORATIVE FILTERING (MOVIELENS DATASET)
We will load the data sets firsts.
```
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import math
#column headers for the dataset
data_cols = ['user id','movie id','rating','timestamp']
item_cols = ['movie id','movie title','release date','video release date','IMDb URL','unknown','Action',
'Adventure','Animation','Childrens','Comedy','Crime','Documentary','Drama','Fantasy','Film-Noir','Horror',
'Musical','Mystery','Romance ','Sci-Fi','Thriller','War' ,'Western']
user_cols = ['user id','age','gender','occupation','zip code']
#importing the data files onto dataframes
data_df = pd.read_csv('ml-100k/u.data', sep='\t', names=data_cols, encoding='latin-1')
item_df = pd.read_csv('ml-100k/u.item', sep='|', names=item_cols, encoding='latin-1')
user_df = pd.read_csv('ml-100k/u.user', sep='|', names=user_cols, encoding='latin-1')
#dropping unecessary columns
#Voting Timestamp - Removed
data_df.drop(data_df.columns[[3]], axis = 1, inplace = True)
#Movie Title, Video Release Date and IMDB URL - Removed
item_df.drop(item_df.columns[[1,3,4]], axis = 1, inplace = True)
#Occupation and Zip Code - Removed
user_df.drop(user_df.columns[[3,4]], axis = 1, inplace = True)
print(data_df.head())
print(item_df.head())
#Ajust release date to get only the year
item_df['release date'] = pd.to_datetime(item_df['release date'], errors='coerce').dt.year
print(item_df.head())
print(user_df.head())
#Convert Gender column to numeric
user_df['gender'].replace('F', 1,inplace=True)
user_df['gender'].replace('M', 2,inplace=True)
#Adjust columns replacing NaN with the mean
meanYear = int(round(item_df['release date'].mean()))
print(meanYear)
item_df['release date'] = item_df['release date'].fillna(meanYear)
print(item_df['release date'].hasnans)
#merge it all
data_item = pd.merge(data_df, item_df, left_on = "movie id", right_on = "movie id")
data_item_user = pd.merge(data_item, user_df, left_on = "user id", right_on = "user id")
dataset = data_item_user
print(dataset.head())
# Data distribution
display(dataset.describe())
# Show the current Dataset Structure
from IPython.display import display
display(dataset)
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
# Calculate Feature Relevance to the Dataset
for name, values in dataset.iteritems():
# Clone Dataset for Feature Relevance calculation
backupData = dataset.copy()
# Clone the Column to be predicted
y = backupData[name].copy()
# Drop column, that will be used for prediction
X = backupData.drop(name, 1)
# Split Data for Model calibration
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=72)
regressor = DecisionTreeRegressor(random_state=72)
regressor.fit(X_train, y_train)
score = regressor.score(X_test, y_test)
print('Genre {} score = {}').format(name, score)
# User Id and Movie Id have a weak relation within the other features, but
# Based on Feature Relevance we are going to
# 1st Remove the user id from the dataset
smartdata = dataset.copy()
smartdata.drop(smartdata.columns[[0]], axis = 1, inplace = True)
print(smartdata.head())
# 2nd Lets translate the Ratingo into a more discrete evalution (like and dislike)
# 1 - 2.9 : DILIKE
# 3 - 5 : LIKE
for name, values in smartdata['rating'].iteritems():
print(values)
# Produce a scatter matrix for each pair of features in the data
pd.plotting.scatter_matrix(dataset, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
# Feature Scaling
# Scale the data using the natural logarithm
log_data = np.log(dataset)
# Scale the sample data using the natural logarithm
log_samples = np.log(samples)
# Produce a scatter matrix for each pair of newly-transformed features
pd.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
item_list = (((pd.merge(item,data).sort_values(by = 'movie id')).groupby('movie title')))['movie id', 'movie title', 'rating']
item_list = item_list.mean()
item_list['movie title'] = item_list.index
item_list = item_list.as_matrix()
recommendation_list = []
for i in recommendation:
recommendation_list.append(item_list[i-1])
recommendation = (pd.DataFrame(recommendation_list,columns = ['movie id','mean rating' ,'movie title'])).sort_values(by = 'mean rating', ascending = False)
print(recommendation[['mean rating','movie title']])
```
| github_jupyter |
# Ask the Calculator Glass Questions
Here we are going to ask the calculator questions about glass.
```
import os
from pathlib import Path
testfolder = str(Path().resolve().parent.parent / 'PV_DEMICE' / 'TEMP')
# Another option using relative address; for some operative systems you might need '/' instead of '\'
# testfolder = os.path.abspath(r'..\..\PV_DEMICE\TEMP')
print ("Your simulation will be stored in %s" % testfolder)
import PV_DEMICE
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams.update({'font.size': 22})
plt.rcParams['figure.figsize'] = (12, 5)
```
## 0% & 100% Recycle of Glass
First, create the simulation and the scenarios, pointing them at the Temp folder.
```
sim1 = PV_DEMICE.Simulation(name='Recycle Extremes', path=testfolder)
sim1.createScenario(name='Recycle_0', file=r'..\baselines\baseline_modules_US.csv')
sim1.scenario['Recycle_0'].addMaterial('glass', file=r'..\baselines\baseline_material_glass.csv')
sim1.createScenario(name='Recycle_100', file=r'..\baselines\baseline_modules_US.csv')
sim1.scenario['Recycle_100'].addMaterial('glass', file=r'..\baselines\baseline_material_glass.csv')
sim1.scenario['Recycle_0'].data.keys()
sim1.scenario['Recycle_100'].material['glass'].materialdata.keys()
```
Now set the variables within the scenarios to the relevant quantities
```
#Set 0% recycled for both MFG and EOL - pure linear
sim1.scenario['Recycle_0'].data['mod_EOL_collected_Recycled']=0
sim1.scenario['Recycle_0'].data['mod_Repowering']=0
sim1.scenario['Recycle_0'].data['mod_Repairing']=0
sim1.scenario['Recycle_0'].material['glass'].materialdata['mat_MFG_scrap_Recycled'] = 0
sim1.scenario['Recycle_0'].material['glass'].materialdata['mat_EOL_collected_Recycled'] = 0
#directs all glass back to mfg to offset virgin, both MFG and EOL
sim1.scenario['Recycle_100'].data['mod_EOL_collected_Recycled']=100
sim1.scenario['Recycle_100'].data['mod_EOL_collection_eff']=100
sim1.scenario['Recycle_100'].data['mod_Repowering']=0
sim1.scenario['Recycle_100'].data['mod_Repairing']=0
sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_MFG_scrap_Recycled'] = 100
sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_MFG_scrap_Recycling_eff'] = 100
sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_MFG_scrap_Recycled_into_HQ'] = 100 #directs all to close loop
sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_MFG_scrap_Recycled_into_HQ_Reused4MFG'] = 100
sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_EOL_Recycling_eff'] = 100
sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_EOL_Recycled_into_HQ'] = 100 #directs all to close loop
sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_EOL_RecycledHQ_Reused4MFG'] = 100
sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_EoL_Recycled_HQ_into_MFG'] = 100
#plt.plot(sim1.scenario['Recycle_100'].data['mod_EOL_collection_eff']) #check out what module paramaters settings
#plt.plot(sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_EoL_Recycled_HQ_into_MFG']) #check out what material parameters settings
```
Now run the simulation
```
sim1.calculateMassFlow()
#plt.plot(sim1.scenario['Recycle_100'].data['mod_EOL_collection_eff']) #check out what module paramaters settings
#plt.plot(sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_MFG_scrap_Recycled']) #check out what material parameters settings
```
Now make some pretty pretty plots
```
#sim1.scenario['Recycle_0'].data.keys() #choices of what to plot
#sim1.plotScenariosComparison(keyword='Installed_Capacity_[W]') #make sure installed capacity is same
```
There is a separate plotting function for materials
```
sim1.plotMaterialComparisonAcrossScenarios(material='glass', keyword='mat_Total_Landfilled')
#sim1.plotMaterialComparisonAcrossScenarios(material='glass', keyword='mat_Total_MFG_Landfilled')
#sim1.plotMaterialComparisonAcrossScenarios(material='glass', keyword='mat_Total_EOL_Landfilled')
sim1.plotMaterialComparisonAcrossScenarios(material='glass', keyword='mat_Virgin_Stock')
#summ the virgin stock column 1995 through 2050 for the two senarios
#will give a mass difference in extraction needed all time
R_0_virginmass = sim1.scenario['Recycle_0'].material['glass'].materialdata['mat_Virgin_Stock'].sum(axis=0)
R_0_virginmass_kg = R_0_virginmass/1000 #grams in a kg
R_0_virginmass_mtons = R_0_virginmass/1000000 # grams in a metric ton
print('0% recycling scenario requires' , R_0_virginmass_mtons , 'metric tons of virgin glass from 1995 through 2050.')
R_100_virginmass = sim1.scenario['Recycle_100'].material['glass'].materialdata['mat_Virgin_Stock'].sum(axis=0)
R_100_virginmass_kg = R_100_virginmass/1000 #grams in a kg
R_100_virginmass_mtons = R_100_virginmass/1000000 # grams in a metric ton
print('100% recycling scenario requires' , R_100_virginmass_mtons , 'metric tons of virgin glass from 1995 through 2050.')
pct_less_virgin = 100*(R_100_virginmass/R_0_virginmass)
print('100% closed loop recycling scenario requires', pct_less_virgin, 'of the mass of 0% recycling, linear.')
```
## Backsheet VS Glass-Glass
What will be the effect if all modules become glass-glass versus if all in future are backsheet-glass.
SHOULD MODIFY THIS TO DRAW ON MODIFIED INPUT FILES, NOT JUST MULTIPLY BY TWO
```
sim2 = PV_DEMICE.Simulation(name='Tech-Evolution', path=testfolder)
sim2.createScenario(name='Glass-Glass', file=r'..\baselines\baseline_modules_US.csv')
sim2.scenario['Glass-Glass'].addMaterial('glass', file=r'..\baselines\baseline_material_glass.csv')
sim2.createScenario(name='Backsheet', file=r'..\baselines\baseline_modules_US.csv')
sim2.scenario['Backsheet'].addMaterial('glass', file=r'..\baselines\baseline_material_glass.csv')
```
Modify the parameters to express these extreme scenarios. Using 2x as serrogate for glass-glass.
```
sim2.scenario['Glass-Glass'].material['glass'].materialdata['mat_massperm2'] = 2*sim2.scenario['Glass-Glass'].material['glass'].materialdata['mat_massperm2']
#sim2.scenario['Backsheet'].material['glass'].materialdata['mat_massperm2'] =0.5*sim2.scenario['Backsheet'].material['glass'].materialdata['mat_massperm2']
sim2.calculateMassFlow()
sim2.plotMaterialComparisonAcrossScenarios(material='glass', keyword='mat_Total_Landfilled')
sim2.plotMaterialComparisonAcrossScenarios(material='glass', keyword='mat_Virgin_Stock')
glass_virginmass = sim2.scenario['Glass-Glass'].material['glass'].materialdata['mat_Virgin_Stock'].sum(axis=0)
glass_virginmass_tons = glass_virginmass/1000000 # grams in a metric ton
backsheet_virginmass = sim2.scenario['Backsheet'].material['glass'].materialdata['mat_Virgin_Stock'].sum(axis=0)
backsheet_virginmass_tons = backsheet_virginmass/1000000 # grams in a metric ton
sim2_virgin_pct = 100*(glass_virginmass/backsheet_virginmass)
print('All glass-glass modules in future could use', sim2_virgin_pct, '% more glass than backsheet-glass.')
```
| github_jupyter |
```
password = None
%reload_ext autoreload
%autoreload 2
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import json
import getpass
import pandas as pd
import numpy as np
from utils import load_json_benchmarks, filter_results, plot_comparison
```
repetitions = 10
```
if password is None:
password = getpass.getpass()
# Disable cpu frequency scaling
!echo $password | sudo -S cpupower frequency-set -g performance
```
```
../../cmake-build-release/benchmark/comparison/benchmark-s3rvac-cpp-bencoding \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-s3rvac-cpp-bencoding.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-jimporter-bencode \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-jimporter-bencode.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-jimporter-bencode-boost \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-jimporter-bencode-boost.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-arvidn-libtorrent \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-arvidn-libtorrent.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-fbdtemme-bencode \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-fbdtemme-bencode.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-rakshasa-libtorrent \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-rakshasa-libtorrent.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-kriben-bencode \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-kriben-bencode.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-theanti9-cppbencode \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-theanti9-cppbencode.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-outputenable-bencode \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-outputenable-bencode.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-aetf-qbencode \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-aetf-qbencode.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-irajul-bencode \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-irajul-bencode.json"
```
```
../../cmake-build-release/benchmark/comparison/benchmark-s3ponia-bencodeparser \
--benchmark_repetitions=$repetitions \
--benchmark_out_format=json \
--benchmark_out="benchmark-s3ponia-bencodeparser.json"
```
```
# reenable cpu frequency scaling
!echo $password | sudo -S cpupower frequency-set -g powersave
libraries = [
("benchmark-fbdtemme-bencode.json", "fbdtemme/bencode"),
("benchmark-jimporter-bencode.json", "jimporter/bencode"),
("benchmark-jimporter-bencode-boost.json", "jimporter/bencode (boost)"),
# ("benchmark-arvidn-libtorrent.json", "arvidn/libtorrent"),
("benchmark-s3rvac-cpp-bencoding.json", "s3rvac/cpp-bencoding"),
("benchmark-rakshasa-libtorrent.json", "rakshasa/libtorrent"),
("benchmark-kriben-bencode.json", "kriben/bencode"),
("benchmark-theanti9-cppbencode.json", "theanti9/cppbencode"),
("benchmark-outputenable-bencode.json", "outputenable/bencode"),
("benchmark-aetf-qbencode.json", "Aetf/QBencode"),
("benchmark-s3ponia-bencodeparser.json", "s3ponia/BencodeParser"),
# ("benchmark-irajul-bencode.json", "iRajul/bencode"), // Invalid parser
]
df = pd.concat([
filter_results(load_json_benchmarks(result), lib_name) for result, lib_name in libraries
])
grouped_df = df.groupby(["library", "test_type", "test_file"])["bytes_per_second"]
results = pd.DataFrame({"mean" : grouped_df.mean(), "stddev": grouped_df.std()})
results_value = results.loc[results.index.get_level_values("test_type") == "decode_value", :]
results_value = results_value.droplevel(1)
drop_list = ["arvidn/libtorrent", "outputenable/bencode"]
for lib_name in drop_list:
results_value = results_value.drop(index=lib_name)
results_value[~np.isfinite(results_value)] = 0
drop_list = ["s3rvac/cpp-bencoding", "kriben/bencode",
"rakshasa/libtorrent", "theanti9/cppbencode",
"Aetf/QBencode", "s3ponia/BencodeParser"]
results_view = results.loc[results.index.get_level_values("test_type") == "decode_view", :]
results_view = results_view.droplevel(1)
for lib_name in drop_list:
results_view = results_view.drop(index=lib_name)
results_view
ax = plot_comparison(results_value, figsize=(10, 4))
ax.set_xlabel("Benchmark")
ax.figure.tight_layout()
# ax.figure.savefig("../../docs/images/benchmark-decoding-value.svg")
ax = plot_comparison(results_view, figsize=(10, 4))
ax.set_xlabel("Benchmark")
ax.figure.tight_layout()
# ax.figure.savefig("../../docs/images/benchmark-decoding-view.svg")
```
| github_jupyter |
# EXTRA STUFF: Day 8
First, import our usual things:
```
import ipywidgets
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import bqplot.pyplot as bplt
# also:
import bqplot
```
Load data:
```
planets = pd.read_csv('https://jnaiman.github.io/csci-p-14110_su2020/lesson08/planets_2020.06.17_14.04.11.csv',
sep=",", comment="#")
```
Let's take a quick look:
```
planets
```
## Heatmap dashboard
Let's make a 2D histogram showing how the NASA planets are distributed across these 2 parameters.
First, looking at the plots of the individual distributions, we can make some guesses for bins along each parameter:
```
ecc = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
```
We can also do this with NumPy:
```
ecc = np.arange(0.0, 1.1, step=0.1) # start, stop, step => note step+stop there!
ecc
```
And semi-major axis:
```
sa = np.arange(0.0, 50+5, step=5)
sa
```
Let's also use NumPy to make a 2D histogram with these bins:
```
myHist, xedges, yedges = np.histogram2d(planets['pl_orbeccen'], planets['pl_orbsmax'],
bins=[ecc,sa])
yedges
myHist
```
We see that we mostly have entries between 0-25 AU, so we can update our binning:
```
sa = np.arange(0.0, 24+4, step=4)
myHist, xedges, yedges = np.histogram2d(planets['pl_orbeccen'], planets['pl_orbsmax'],
bins=[ecc,sa])
yedges
myHist
```
xedges & yedges give the bin *edges* but we want the centers:
```
xcenter = (xedges[:-1] + xedges[1:]) / 2
ycenter = (yedges[:-1] + yedges[1:]) / 2
myLabel = ipywidgets.Label()# make label
```
Function to print out data values:
```
def get_data_value(change): # redefine this function to now use myHist, not data
i,j = change['owner'].selected[0]
v = myHist[i,j] # grab data value
myLabel.value = 'Value of data = ' + str(v)
```
Put all together:
```
fig = bplt.figure(padding_y=0.0) # set up a figure object
# use bqplot's plt interface to plot:
heat_map = bplt.gridheatmap(myHist, row=xcenter, column=ycenter, interactions={'click':'select'})
# hook heat_maps selected value to the label
heat_map.observe(get_data_value, 'selected')
# show both the fig and label in a vertical box
ipywidgets.VBox([myLabel,fig])
```
We can change the color scale as well:
```
fig = bplt.figure(padding_y=0.0) # set up a figure object
# add in color:
col_sc = bqplot.ColorScale(scheme='Reds')
# use bqplot's plt interface to plot:
heat_map = bplt.gridheatmap(myHist, row=xcenter, column=ycenter, interactions={'click':'select'},
scales={'color':col_sc})
# hook heat_maps selected value to the label
heat_map.observe(get_data_value, 'selected')
# show both the fig and label in a vertical box
ipywidgets.VBox([myLabel,fig])
```
However, doing things like adding in x/y labels is somewhat familiar, but we call fig.axes instead of ax[#] to set axis labels. You can check out what fig.axes[0], fig.axes[1], fig.axes[2] is by:
```
fig.axes
```
So, it looks like the 0th axes is color, the 1th one is the horizontal axis and the 2th is the vertical axes. We can change x/y labels as follows:
```
fig = bplt.figure(padding_y=0.0) # set up a figure object
bplt.scales(scales={'color':bqplot.ColorScale(scheme='Reds')})
# use bqplot's plt interface to plot:
heat_map = bplt.gridheatmap(myHist, row=xcenter, column=ycenter, interactions={'click':'select'})
# hook heat_maps selected value to the label
heat_map.observe(get_data_value, 'selected')
# change labels
fig.axes[0].side = 'top' # so it doesn't overlap with scale
fig.axes[1].label = 'semi-major axes in AU' # xaxes label
fig.axes[2].label = 'eccentricity' # yaxes label
# show both the fig and label in a vertical box
ipywidgets.VBox([myLabel,fig])
```
Now let's generate our line plot -- this will use the $r(\theta)$ equation to plot orbits:
```
fig_lines = bplt.figure(padding_y=0.0) # set up a figure object
# use bqplot's plt interface to plot:
lines = bplt.plot([],[]) # empty to start
# change labels
fig_lines.axes[0].label = 'x in AU' # xaxes label
fig_lines.axes[1].label = 'y in AU' # yaxes label
fig_lines # empty plot of x/y
```
Now, lets first put all of our plots in the alighment we want, keeping in mind that the x/y plot of the analytical trajectory won't be updated when we click anything yet:
```
ipywidgets.VBox([myLabel,ipywidgets.HBox([fig,fig_lines])])
```
Oh but it looks squished, lets try messing with the layout:
```
fig.layout.min_width='500px'
fig_lines.layout.min_width='500px'
ipywidgets.VBox([myLabel,ipywidgets.HBox([fig,fig_lines])])
#figOut = ipywidgets.VBox([myLabel,ipywidgets.HBox([fig,fig_lines])])
#figOut.layout.min_width='1000px'
#figOut
```
To make this interactive first we need to update our `get_data_value` function to *also* update our lines plot when the heatmap plot is selected:
```
theta = np.arange(0, 2*np.pi, 0.001) # theta array
def get_data_value(change): # redefine this function to now use myHist, not data
# 1. Update the label
i,j = change['owner'].selected[0]
v = myHist[i,j] # grab data value
myLabel.value = 'Value of data = ' + str(v)
# 2. Update the x/y values in our lines plot
a = ycenter[j] # semi major axis based on bins in heatmap
ecc = xcenter[i] # eccentricity for bins on heatmap
r = a*(1-ecc**2)/(1+ecc*np.cos(theta)) # calculate r(theta)
x = r*np.cos(theta) # translate into x/y
y = r*np.sin(theta)
lines.x = x
lines.y = y
```
Finally before we plot, we have to re-hook this back into our heatmap figure:
```
heat_map.observe(get_data_value, 'selected')
```
Now use the orientation of our plots we had above to re-plot with new interactivity:
```
ipywidgets.VBox([myLabel,ipywidgets.HBox([fig,fig_lines])])
```
If we want to keep the x/y range static when we plot, we can re-do our trajectory plot with:
```
fig_lines = bplt.figure(padding_y=0.0) # set up a figure object
# use bqplot's plt interface to plot:
lines = bplt.plot([],[]) # empty to start
# set x/y lim in the bqplot way
bplt.set_lim(-30,30,'x')
bplt.set_lim(-30,30, 'y')
# change labels
fig_lines.axes[0].label = 'x in AU' # xaxes label
fig_lines.axes[1].label = 'y in AU' # yaxes label
# to be sure:
fig_lines.layout.min_width='500px'
fig_lines # empty plot of x/y
```
And finally put it all together:
```
ipywidgets.VBox([myLabel,ipywidgets.HBox([fig,fig_lines])])
```
| github_jupyter |
# 5. Neural Networks
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml, make_moons
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import accuracy_score
from prml import nn
np.random.seed(1234)
```
## 5.1 Feed-forward Network Functions
```
class RegressionNetwork(nn.Network):
def __init__(self, n_input, n_hidden, n_output):
super().__init__()
with self.set_parameter():
self.w1 = nn.random.truncnormal(-2, 2, 1, (n_input, n_hidden))
self.b1 = nn.zeros(n_hidden)
self.w2 = nn.random.truncnormal(-2, 2, 1, (n_hidden, n_output))
self.b2 = nn.zeros(n_output)
def __call__(self, x):
h = nn.tanh(x @ self.w1 + self.b1)
return h @ self.w2 + self.b2
def create_toy_data(func, n=50):
x = np.linspace(-1, 1, n)[:, None]
return x, func(x)
def sinusoidal(x):
return np.sin(np.pi * x)
def heaviside(x):
return 0.5 * (np.sign(x) + 1)
func_list = [np.square, sinusoidal, np.abs, heaviside]
plt.figure(figsize=(20, 10))
x = np.linspace(-1, 1, 1000)[:, None]
for i, func, n_iter in zip(range(1, 5), func_list, [1000, 10000, 10000, 10000]):
plt.subplot(2, 2, i)
x_train, y_train = create_toy_data(func)
model = RegressionNetwork(1, 3, 1)
optimizer = nn.optimizer.Adam(model.parameter, 0.1)
for _ in range(n_iter):
model.clear()
loss = nn.square(y_train - model(x_train)).sum()
optimizer.minimize(loss)
y = model(x).value
plt.scatter(x_train, y_train, s=10)
plt.plot(x, y, color="r")
plt.show()
```
## 5.3 Error Backpropagation
```
class ClassificationNetwork(nn.Network):
def __init__(self, n_input, n_hidden, n_output):
super().__init__()
with self.set_parameter():
self.w1 = nn.random.truncnormal(-2, 2, 1, (n_input, n_hidden))
self.b1 = nn.zeros(n_hidden)
self.w2 = nn.random.truncnormal(-2, 2, 1, (n_hidden, n_output))
self.b2 = nn.zeros(n_output)
def __call__(self, x):
h = nn.tanh(x @ self.w1 + self.b1)
return h @ self.w2 + self.b2
def create_toy_data():
x = np.random.uniform(-1., 1., size=(100, 2))
labels = np.prod(x, axis=1) > 0
return x, labels.reshape(-1, 1)
x_train, y_train = create_toy_data()
model = ClassificationNetwork(2, 4, 1)
optimizer = nn.optimizer.Adam(model.parameter, 1e-3)
history = []
for i in range(10000):
model.clear()
logit = model(x_train)
log_likelihood = -nn.loss.sigmoid_cross_entropy(logit, y_train).sum()
optimizer.maximize(log_likelihood)
history.append(log_likelihood.value)
plt.plot(history)
plt.xlabel("iteration")
plt.ylabel("Log Likelihood")
plt.show()
x0, x1 = np.meshgrid(np.linspace(-1, 1, 100), np.linspace(-1, 1, 100))
x = np.array([x0, x1]).reshape(2, -1).T
y = nn.sigmoid(model(x)).value.reshape(100, 100)
levels = np.linspace(0, 1, 11)
plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train.ravel())
plt.contourf(x0, x1, y, levels, alpha=0.2)
plt.colorbar()
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.gca().set_aspect('equal')
plt.show()
```
## 5.5 Regularization in Neural Networks
```
def create_toy_data(n=10):
x = np.linspace(0, 1, n)[:, None]
return x, np.sin(2 * np.pi * x) + np.random.normal(scale=0.25, size=(10, 1))
x_train, y_train = create_toy_data()
x = np.linspace(0, 1, 100)[:, None]
plt.figure(figsize=(20, 5))
for i, m in enumerate([1, 3, 30]):
plt.subplot(1, 3, i + 1)
model = RegressionNetwork(1, m, 1)
optimizer = nn.optimizer.Adam(model.parameter, 0.1)
for j in range(10000):
model.clear()
y = model(x_train)
optimizer.minimize(nn.square(y - y_train).sum())
if j % 1000 == 0:
optimizer.learning_rate *= 0.9
y = model(x)
plt.scatter(x_train.ravel(), y_train.ravel(), marker="x", color="k")
plt.plot(x.ravel(), y.value.ravel(), color="k")
plt.annotate("M={}".format(m), (0.7, 0.5))
plt.show()
class RegularizedRegressionNetwork(nn.Network):
def __init__(self, n_input, n_hidden, n_output):
super().__init__()
with self.set_parameter():
self.w1 = nn.random.truncnormal(-2, 2, 1, (n_input, n_hidden))
self.b1 = nn.zeros(n_hidden)
self.w2 = nn.random.truncnormal(-2, 2, 1, (n_hidden, n_output))
self.b2 = nn.zeros(n_output)
self.prior = nn.Gaussian(0, 1)
def __call__(self, x):
h = nn.tanh(x @ self.w1 + self.b1)
return h @ self.w2 + self.b2
def log_prior(self):
logp = 0
for param in self.parameter.values():
logp += self.prior.log_pdf(param)
return logp
model = RegularizedRegressionNetwork(1, 30, 1)
optimizer = nn.optimizer.Adam(model.parameter, 0.1)
for i in range(10000):
model.clear()
pred = model(x_train)
log_posterior = -nn.square(pred - y_train).sum() + model.log_prior()
optimizer.maximize(log_posterior)
if i % 1000 == 0:
optimizer.learning_rate *= 0.9
y = model(x).value
plt.scatter(x_train, y_train, marker="x", color="k")
plt.plot(x, y, color="k")
plt.annotate("M=30", (0.7, 0.5))
plt.show()
def load_mnist():
x, label = fetch_openml("mnist_784", return_X_y=True)
x = x / np.max(x, axis=1, keepdims=True)
x = x.reshape(-1, 28, 28, 1)
label = label.astype(np.int)
x_train, x_test, label_train, label_test = train_test_split(x, label, test_size=0.1)
y_train = LabelBinarizer().fit_transform(label_train)
return x_train, x_test, y_train, label_test
x_train, x_test, y_train, label_test = load_mnist()
class ConvolutionalNeuralNetwork(nn.Network):
def __init__(self):
super().__init__()
with self.set_parameter():
self.conv1 = nn.image.Convolve2d(
nn.random.truncnormal(-2, 2, 1, (5, 5, 1, 20)),
stride=(1, 1), pad=(0, 0))
self.b1 = nn.array([0.1] * 20)
self.conv2 = nn.image.Convolve2d(
nn.random.truncnormal(-2, 2, 1, (5, 5, 20, 20)),
stride=(1, 1), pad=(0, 0))
self.b2 = nn.array([0.1] * 20)
self.w3 = nn.random.truncnormal(-2, 2, 1, (4 * 4 * 20, 100))
self.b3 = nn.array([0.1] * 100)
self.w4 = nn.random.truncnormal(-2, 2, 1, (100, 10))
self.b4 = nn.array([0.1] * 10)
def __call__(self, x):
h = nn.relu(self.conv1(x) + self.b1)
h = nn.max_pooling2d(h, (2, 2), (2, 2))
h = nn.relu(self.conv2(h) + self.b2)
h = nn.max_pooling2d(h, (2, 2), (2, 2))
h = h.reshape(-1, 4 * 4 * 20)
h = nn.relu(h @ self.w3 + self.b3)
return h @ self.w4 + self.b4
model = ConvolutionalNeuralNetwork()
optimizer = nn.optimizer.Adam(model.parameter, 1e-3)
while True:
indices = np.random.permutation(len(x_train))
for index in range(0, len(x_train), 50):
model.clear()
x_batch = x_train[indices[index: index + 50]]
y_batch = y_train[indices[index: index + 50]]
logit = model(x_batch)
log_likelihood = -nn.loss.softmax_cross_entropy(logit, y_batch).mean(0).sum()
if optimizer.iter_count % 100 == 0:
accuracy = accuracy_score(
np.argmax(y_batch, axis=-1), np.argmax(logit.value, axis=-1)
)
print("step {:04d}".format(optimizer.iter_count), end=", ")
print("accuracy {:.2f}".format(accuracy), end=", ")
print("Log Likelihood {:g}".format(log_likelihood.value[0]))
optimizer.maximize(log_likelihood)
if optimizer.iter_count == 1000:
break
else:
continue
break
print("accuracy (test):", accuracy_score(np.argmax(model(x_test).value, axis=-1), label_test))
```
## 5.6 Mixture Density Networks
```
def create_toy_data(func, n=300):
t = np.random.uniform(size=(n, 1))
x = func(t) + np.random.uniform(-0.05, 0.05, size=(n, 1))
return x, t
def func(x):
return x + 0.3 * np.sin(2 * np.pi * x)
def sample(x, t, n=None):
assert len(x) == len(t)
N = len(x)
if n is None:
n = N
indices = np.random.choice(N, n, replace=False)
return x[indices], t[indices]
x_train, y_train = create_toy_data(func)
class MixtureDensityNetwork(nn.Network):
def __init__(self, n_input, n_hidden, n_components):
self.n_components = n_components
super().__init__()
with self.set_parameter():
self.w1 = nn.random.truncnormal(-2, 2, 1, (n_input, n_hidden))
self.b1 = nn.zeros(n_hidden)
self.w2c = nn.random.truncnormal(-2, 2, 1, (n_hidden, n_components))
self.b2c = nn.zeros(n_components)
self.w2m = nn.random.truncnormal(-2, 2, 1, (n_hidden, n_components))
self.b2m = nn.zeros(n_components)
self.w2s = nn.random.truncnormal(-2, 2, 1, (n_hidden, n_components))
self.b2s = nn.zeros(n_components)
def __call__(self, x):
h = nn.tanh(x @ self.w1 + self.b1)
coef = nn.softmax(h @ self.w2c + self.b2c)
mean = h @ self.w2m + self.b2m
std = nn.exp(h @ self.w2s + self.b2s)
return coef, mean, std
def gaussian_mixture_pdf(x, coef, mu, std):
gauss = (
nn.exp(-0.5 * nn.square((x - mu) / std))
/ std / np.sqrt(2 * np.pi)
)
return (coef * gauss).sum(axis=-1)
model = MixtureDensityNetwork(1, 5, 3)
optimizer = nn.optimizer.Adam(model.parameter, 1e-4)
for i in range(30000):
model.clear()
coef, mean, std = model(x_train)
log_likelihood = nn.log(gaussian_mixture_pdf(y_train, coef, mean, std)).sum()
optimizer.maximize(log_likelihood)
x = np.linspace(x_train.min(), x_train.max(), 100)[:, None]
y = np.linspace(y_train.min(), y_train.max(), 100)[:, None, None]
coef, mean, std = model(x)
plt.figure(figsize=(20, 15))
plt.subplot(2, 2, 1)
plt.plot(x[:, 0], coef.value[:, 0], color="blue")
plt.plot(x[:, 0], coef.value[:, 1], color="red")
plt.plot(x[:, 0], coef.value[:, 2], color="green")
plt.title("weights")
plt.subplot(2, 2, 2)
plt.plot(x[:, 0], mean.value[:, 0], color="blue")
plt.plot(x[:, 0], mean.value[:, 1], color="red")
plt.plot(x[:, 0], mean.value[:, 2], color="green")
plt.title("means")
plt.subplot(2, 2, 3)
proba = gaussian_mixture_pdf(y, coef, mean, std).value
levels_log = np.linspace(0, np.log(proba.max()), 21)
levels = np.exp(levels_log)
levels[0] = 0
xx, yy = np.meshgrid(x.ravel(), y.ravel())
plt.contour(xx, yy, proba.reshape(100, 100), levels)
plt.xlim(x_train.min(), x_train.max())
plt.ylim(y_train.min(), y_train.max())
plt.subplot(2, 2, 4)
argmax = np.argmax(coef.value, axis=1)
for i in range(3):
indices = np.where(argmax == i)[0]
plt.plot(x[indices, 0], mean.value[(indices, np.zeros_like(indices) + i)], color="r", linewidth=2)
plt.scatter(x_train, y_train, facecolor="none", edgecolor="b")
plt.show()
```
## 5.7 Bayesian Neural Networks
```
x_train, y_train = make_moons(n_samples=500, noise=0.2)
y_train = y_train[:, None]
class Gaussian(nn.Network):
def __init__(self, shape):
super().__init__()
with self.set_parameter():
self.m = nn.zeros(shape)
self.s = nn.zeros(shape)
def __call__(self):
self.q = nn.Gaussian(self.m, nn.softplus(self.s) + 1e-8)
return self.q.draw()
class BayesianNetwork(nn.Network):
def __init__(self, n_input, n_hidden, n_output=1):
super().__init__()
with self.set_parameter():
self.qw1 = Gaussian((n_input, n_hidden))
self.qb1 = Gaussian(n_hidden)
self.qw2 = Gaussian((n_hidden, n_hidden))
self.qb2 = Gaussian(n_hidden)
self.qw3 = Gaussian((n_hidden, n_output))
self.qb3 = Gaussian(n_output)
self.posterior = [self.qw1, self.qb1, self.qw2, self.qb2, self.qw3, self.qb3]
self.prior = nn.Gaussian(0, 1)
def __call__(self, x):
h = nn.tanh(x @ self.qw1() + self.qb1())
h = nn.tanh(h @ self.qw2() + self.qb2())
return nn.Bernoulli(logit=h @ self.qw3() + self.qb3())
def kl(self):
kl = 0
for pos in self.posterior:
kl += nn.loss.kl_divergence(pos.q, self.prior).mean()
return kl
model = BayesianNetwork(2, 5, 1)
optimizer = nn.optimizer.Adam(model.parameter, 0.1)
for i in range(1, 2001, 1):
model.clear()
py = model(x_train)
elbo = py.log_pdf(y_train).mean(0).sum() - model.kl() / len(x_train)
optimizer.maximize(elbo)
if i % 100 == 0:
optimizer.learning_rate *= 0.9
x_grid = np.mgrid[-2:3:100j, -2:3:100j]
x1, x2 = x_grid[0], x_grid[1]
x_grid = x_grid.reshape(2, -1).T
y = np.mean([model(x_grid).mean.value.reshape(100, 100) for _ in range(10)], axis=0)
plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train.ravel(), s=5)
plt.contourf(x1, x2, y, np.linspace(0, 1, 11), alpha=0.2)
plt.colorbar()
plt.xlim(-2, 3)
plt.ylim(-2, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
```
| github_jupyter |
```
from timeatlas import TimeSeries, models, detectors, metrics
import pandas as pd
import matplotlib.pyplot as plt
pd.plotting.register_matplotlib_converters()
from fbprophet.diagnostics import cross_validation, performance_metrics
from fbprophet.plot import plot_cross_validation_metric
```
# Anomaly Detection on Artificial Data
---
## Paths
```
ROOT_PATH = "../data/households/"
DATASET_NAME = "household"
DATA_PATH = "/0/data.csv"
LABEL_SUFFIX = "_labels.csv"
TRAIN_SET = ROOT_PATH + DATASET_NAME + DATA_PATH
ANOMALOUS_SET = [
ROOT_PATH + DATASET_NAME + "_change_point_data" + DATA_PATH,
ROOT_PATH + DATASET_NAME + "_clipping_data" + DATA_PATH,
ROOT_PATH + DATASET_NAME + "_electric_feedback_data" + DATA_PATH,
ROOT_PATH + DATASET_NAME + "_flatline_data" + DATA_PATH,
ROOT_PATH + DATASET_NAME + "_hard_knee_data" + DATA_PATH,
ROOT_PATH + DATASET_NAME + "_increase_noise_data" + DATA_PATH,
ROOT_PATH + DATASET_NAME + "_max_smoothing_data" + DATA_PATH,
ROOT_PATH + DATASET_NAME + "_outlier_data" + DATA_PATH,
ROOT_PATH + DATASET_NAME + "_ratio_compression_data" + DATA_PATH,
ROOT_PATH + DATASET_NAME + "_trend_data" + DATA_PATH,
ROOT_PATH + DATASET_NAME + "_zeroing_data" + DATA_PATH
]
ANOMALOUS_LABELS = [
ROOT_PATH + DATASET_NAME + "_change_point_data" + "/" + DATASET_NAME + "_change_point_labels.csv",
ROOT_PATH + DATASET_NAME + "_clipping_data" + "/" + DATASET_NAME + "_clipping_labels.csv",
ROOT_PATH + DATASET_NAME + "_electric_feedback_data" + "/" + DATASET_NAME + "_electric_feedback_labels.csv",
ROOT_PATH + DATASET_NAME + "_flatline_data" + "/" + DATASET_NAME + "_flatline_labels.csv",
ROOT_PATH + DATASET_NAME + "_hard_knee_data" + "/" + DATASET_NAME + "_hard_knee_labels.csv",
ROOT_PATH + DATASET_NAME + "_increase_noise_data" + "/" + DATASET_NAME + "_increase_noise_labels.csv",
ROOT_PATH + DATASET_NAME + "_max_smoothing_data" + "/" + DATASET_NAME + "_max_smoothing_labels.csv",
ROOT_PATH + DATASET_NAME + "_outlier_data" + "/" + DATASET_NAME + "_outlier_labels.csv",
ROOT_PATH + DATASET_NAME + "_ratio_compression_data" + "/" + DATASET_NAME + "_ratio_compression_labels.csv",
ROOT_PATH + DATASET_NAME + "_trend_data" + "/" + DATASET_NAME + "_trend_labels.csv",
ROOT_PATH + DATASET_NAME + "_zeroing_data" + "/" + DATASET_NAME + "_zeroing_labels.csv",
]
```
## Data Loading
### Training Data
```
train = pd.read_csv(TRAIN_SET)
train.index = pd.to_datetime(train["index"])
train = train.drop(columns=["index"])
ts_train = TimeSeries(train["values"])
ts_train.series.head()
```
### Anomalous Sets
Let's create some sets of time series with anomalies and their associated labels
#### with anomalies only
```
tsd_anomalous = []
for i in ANOMALOUS_SET:
df = pd.read_csv(i)
df.index = pd.to_datetime(df["index"])
df = df.drop(columns=["index"])
ts = TimeSeries(df["values"])
tsd_anomalous.append(ts)
tsd_anomalous
tsd_anomalous[0].series.astype(float).plot();
```
#### with anomalies and labels
```
tsd_anomalous_w_labels = []
for i, label_path in enumerate(ANOMALOUS_LABELS):
# Load the anomalies positions
label = pd.read_csv(label_path)
anomalies_boundaries = label[["start","end"]].values
# Load the anomalous time series
data = pd.read_csv(ANOMALOUS_SET[i])
# Add a time series of boolean representing the presence of anomaly for each time steps
data["labels"] = False
for i in anomalies_boundaries:
start = i[0]
end = i[1]
if start == end:
data["labels"][start] = True
else:
data["labels"][start:end] = True
# Add all this in a TimeSeries object
data.index = pd.to_datetime(data["index"])
data = data.drop(columns=["index"])
ts = TimeSeries(data[["values", "labels"]])
# Finish!
tsd_anomalous_w_labels.append(ts)
tsd_anomalous_w_labels
tsd_anomalous_w_labels[0].series.astype(float).plot();
```
### Modelling
#### Select shorter time window
```
ts_train.boundaries()
```
Knowing that allow us to say that a window of 3 years from 2007-01-01 to 2009-12-31 seems good for modelling
```
ts_train.series = ts_train.series["2007-01-01":"2009-12-31"]
```
#### Resampling
```
ts_train.series.head()
```
At the moment, there is one data point per minute. For the purpose of modelling, we will take the average of the data point per hour. This will drastically reduce our model training time.
```
ts_train.series = ts_train.series.resample("1H").mean()
ts_train.series.head()
ts_train.plot()
```
#### Make a model
```
m = models.Prophet()
m.fit(ts_train)
future = m.make_future_dataframe("7 days")
pred = m.model.predict(future)
m.model.plot_components(pred);
```
Now that the model is trained, let's briefly check it's validity by plotting it.
```
fcst = m.predict("7 days")
fcst.series.head()
fig = plt.figure(figsize=(20,4))
ts_train["12-20-2009":].plot()
fcst.plot()
plt.axvline(x="2010-01-01", color='k', linestyle='--');
```
### Model Diagnostic
```
df_cv = cross_validation(m.model, initial='800 days', period='10 days', horizon = '30 days')
df_p = performance_metrics(df_cv)
df_p["mape"].plot()
fig = plot_cross_validation_metric(df_cv, metric='mape')
```
### Detect anomalies
```
tsd_detected_anomalies = tsd_anomalous_w_labels
thresholds = [
[0.999],
[0.999],
[0.999],
[0.999],
[0.999],
[0.999],
[0.999],
[0.999],
[0.95],
[0.95],
[0.95]
]
# Create a detector
s = detectors.Surprise(m, metrics.relative_error)
for i, ts in enumerate(tsd_anomalous_w_labels):
# Set the alerts
s.alerts("quantile", thresholds[i])
# Fit the detector to find the thresholds
s.fit(ts_train)
# Create an anomaly time series
anomalies = s.detect(tsd_anomalous[i])
# save it
tsd_detected_anomalies[i].series["detected_anomalies"] = anomalies.series
for i, ts in enumerate(tsd_detected_anomalies):
anomaly_file_path = ANOMALOUS_LABELS[i]
# Load the anomalies positions
label = pd.read_csv(anomaly_file_path)
anomaly_name = label["function_name"].values[0]
fig = plt.figure()
ts.series.astype(float).plot(title="{} : {}".format(i,anomaly_name));
```
## Performance Measurement
### On all samples
```
def find_tp(injected, detected):
if injected == 1 and detected == 1:
return 1
else:
return 0
def find_fp(injected, detected):
if injected == 0 and detected == 1:
return 1
else:
return 0
def find_fn(injected, detected):
if injected == 1 and detected == 0:
return 1
else:
return 0
scores = {}
for i, ts in enumerate(tsd_detected_anomalies):
anomaly_file_path = ANOMALOUS_LABELS[i]
# Load the anomalies positions
label = pd.read_csv(anomaly_file_path)
anomaly_name = label["function_name"].values[0]
res = pd.DataFrame()
res["tp"] = ts.series.astype(float).apply(lambda x : find_tp(x["labels"], x["detected_anomalies"]), axis=1)
res["fp"] = ts.series.astype(float).apply(lambda x : find_fp(x["labels"], x["detected_anomalies"]), axis=1)
res["fn"] = ts.series.astype(float).apply(lambda x : find_fn(x["labels"], x["detected_anomalies"]), axis=1)
res = res.astype(float).sum()
precision = res["tp"] / (res["tp"] + res["fp"])
recall = res["tp"] / (res["tp"] + res["fn"])
f1 = 2 * (precision * recall) / (precision + recall)
scores[anomaly_name] = {
"precision": round(precision,2),
"recall": round(recall,2),
"f1": round(f1,2)
}
scores
scores_df = pd.DataFrame(index=scores.keys(), data=scores.values())
scores_df
scores_df.to_latex()
```
| github_jupyter |
```
%matplotlib inline
```
Analyze Merfish data
====================
This tutorial shows how to apply Squidpy for the analysis of Merfish
data.
The data used here was obtained from `Moffitt2018-me`. We provide a
pre-processed subset of the data, in `anndata.AnnData` format. For
details on how it was pre-processed, please refer to the original paper.
::: {.seealso}
See `sphx_glr_auto_tutorials_tutorial_slideseqv2.py` and
`sphx_glr_auto_tutorials_tutorial_seqfish.py` for additional analysis
examples.
:::
Import packages & data
----------------------
To run the notebook locally, create a conda environment as *conda env
create -f environment.yml* using this
[environment.yml](https://github.com/theislab/squidpy_notebooks/blob/master/environment.yml).
```
import scanpy as sc
import squidpy as sq
sc.logging.print_header()
print(f"squidpy=={sq.__version__}")
# load the pre-processed dataset
adata = sq.datasets.merfish()
adata
```
This datasets consists of consecutive slices from the mouse hypothalamic
preoptic region. It represents an interesting example of how to work
with 3D spatial data in Squidpy. Let\'s start with visualization: we can
either visualize the 3D stack of slides using `scanpy.pl.embedding`:
```
sc.pl.embedding(adata, basis="spatial3d", projection="3d", color="Cell_class")
```
Or visualize a single slide with `scanpy.pl.spatial`. Here the slide
identifier is stored in [adata.obs\[\"Bregma\"\]]{.title-ref}, see
original paper for definition.
```
sc.pl.spatial(adata[adata.obs.Bregma == -9], color="Cell_class", spot_size=0.01)
```
Neighborhood enrichment analysis in 3D
======================================
It is important to consider whether the analysis should be performed on
the 3D spatial coordinates or the 2D coordinates for a single slice.
Functions that make use of the spatial graph can already support 3D
coordinates, but it is important to consider that the z-stack coordinate
is in the same unit metrics as the x, y coordinates. Let\'s start with
the neighborhood enrichment score. You can read more on the function in
the docs at `sphx_glr_auto_examples_graph_compute_spatial_neighbors.py`.
First, we need to compute a neighbor graph with
`squidpy.gr.spatial_neighbors`. If we want to compute the neighbor graph
on the 3D coordinate space, we need to specify
`spatial_key = "spatial3d"`. Then we can use
`squidpy.gr.nhood_enrichment` to compute the score, and visualize it
with `squidpy.gr.nhood_enrichment`.
```
sq.gr.spatial_neighbors(adata, coord_type="generic", spatial_key="spatial3d")
sq.gr.nhood_enrichment(adata, cluster_key="Cell_class")
sq.pl.nhood_enrichment(adata, cluster_key="Cell_class", method="single", cmap="inferno", vmin=-50, vmax=100)
```
We can visualize some of the co-enriched clusters with
`scanpy.pl.embedding`. We will set [na\_colors=(1,1,1,0)]{.title-ref} to
make transparent the other observations, in order to better visualize
the clusters of interests across z-stacks.
```
sc.pl.embedding(
adata,
basis="spatial3d",
groups=["OD Mature 1", "OD Mature 2", "OD Mature 4"],
na_color=(1, 1, 1, 0),
projection="3d",
color="Cell_class",
)
```
We can also visualize gene expression in 3D coordinates. Let\'s perform
differential expression testing with `scanpy.tl.rank_genes_groups` and
visualize the results
```
sc.tl.rank_genes_groups(adata, groupby="Cell_class")
sc.pl.rank_genes_groups(adata, groupby="Cell_class")
```
and the expression in 3D.
```
sc.pl.embedding(adata, basis="spatial3d", projection="3d", color=["Gad1", "Mlc1"])
```
If the same analysis should be performed on a single slice, then it is
advisable to copy the sample of interest in a new `anndata.AnnData` and
use it as a standard 2D spatial data object.
```
adata_slice = adata[adata.obs.Bregma == -9].copy()
sq.gr.spatial_neighbors(adata_slice, coord_type="generic")
sq.gr.nhood_enrichment(adata, cluster_key="Cell_class")
sc.pl.spatial(
adata_slice,
color="Cell_class",
groups=["Ependymal", "Pericytes", "Endothelial 2"],
spot_size=0.01,
)
```
Spatially variable genes with spatial autocorrelation statistics
================================================================
With Squidpy we can investigate spatial variability of gene expression.
This is an example of a function that only supports 2D data.
`squidpy.gr.spatial_autocorr` conveniently wraps two spatial
autocorrelation statistics: *Moran\'s I* and *Geary\'s C*. They provide
a score on the degree of spatial variability of gene expression. The
statistic as well as the p-value are computed for each gene, and FDR
correction is performed. For the purpose of this tutorial, let\'s
compute the *Moran\'s I* score. The results are stored in
[adata.uns\[\'moranI\'\]]{.title-ref} and we can visualize selected
genes with `scanpy.pl.spatial`.
```
sq.gr.spatial_autocorr(adata_slice, mode="moran")
adata_slice.uns["moranI"].head()
sc.pl.spatial(
adata_slice,
color=["Cd24a", "Necab1", "Mlc1"],
spot_size=0.01,
)
```
| github_jupyter |
# TensorFlow-Slim
[TensorFlow-Slim](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/slim) is a high-level API for building TensorFlow models. TF-Slim makes defining models in TensorFlow easier, cutting down on the number of lines required to define models and reducing overall clutter. In particular, TF-Slim shines in image domain problems, and weights pre-trained on the [ImageNet dataset](http://www.image-net.org/) for many famous CNN architectures are provided for [download](https://github.com/tensorflow/models/tree/master/research/slim#pre-trained-models).
*Note: Unlike previous notebooks, not every cell here is necessarily meant to run. Some are just for illustration.*
## VGG-16
To show these benefits, this tutorial will focus on [VGG-16](https://arxiv.org/abs/1409.1556). This style of architecture came in 2nd during the 2014 ImageNet Large Scale Visual Recognition Challenge and is famous for its simplicity and depth. The model looks like this:

The architecture is pretty straight-forward: simply stack multiple 3x3 convolutional filters one after another, interleave with 2x2 maxpools, double the number of convolutional filters after each maxpool, flatten, and finish with fully connected layers. A couple ideas behind this model:
- Instead of using larger filters, VGG notes that the receptive field of two stacked layers of 3x3 filters is 5x5, and with 3 layers, 7x7. Using 3x3's allows VGG to insert additional non-linearities and requires fewer weight parameters to learn.
- Doubling the width of the network every time the features are spatially downsampled (maxpooled) gives the model more representational capacity while achieving spatial compression.
### TensorFlow Core
In code, setting up the computation graph for prediction with just TensorFlow Core API is kind of a lot:
```
import tensorflow as tf
# Set up the data loading:
images, labels = ...
# Define the model
with tf.name_scope('conv1_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 3, 64], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[64], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv1 = tf.nn.relu(bias, name=scope)
with tf.name_scope('conv1_2') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 64], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(conv1, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[64], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv1 = tf.nn.relu(bias, name=scope)
pool1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool1')
with tf.name_scope('conv2_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 64, 128], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(pool1, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv2 = tf.nn.relu(bias, name=scope)
with tf.name_scope('conv2_2') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 128, 128], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(conv2, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[128], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv2 = tf.nn.relu(bias, name=scope)
pool2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool2')
with tf.name_scope('conv3_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 128, 256], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(pool2, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv3 = tf.nn.relu(bias, name=scope)
with tf.name_scope('conv3_2') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 256], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(conv3, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv3 = tf.nn.relu(bias, name=scope)
with tf.name_scope('conv3_3') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 256], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(conv3, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv3 = tf.nn.relu(bias, name=scope)
pool3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool3')
with tf.name_scope('conv4_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 512], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(pool3, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv4 = tf.nn.relu(bias, name=scope)
with tf.name_scope('conv4_2') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(conv4, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv4 = tf.nn.relu(bias, name=scope)
with tf.name_scope('conv4_3') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(conv4, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv4 = tf.nn.relu(bias, name=scope)
pool4 = tf.nn.max_pool(conv4, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool4')
with tf.name_scope('conv5_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(pool4, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv5 = tf.nn.relu(bias, name=scope)
with tf.name_scope('conv5_2') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(conv5, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv5 = tf.nn.relu(bias, name=scope)
with tf.name_scope('conv5_3') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 512, 512], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(conv5, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[512], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv5 = tf.nn.relu(bias, name=scope)
pool5 = tf.nn.max_pool(conv5, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool5')
with tf.name_scope('fc_6') as scope:
flat = tf.reshape(pool5, [-1, 7*7*512])
weights = tf.Variable(tf.truncated_normal([7*7*512, 4096], dtype=tf.float32, stddev=1e-1), name='weights')
mat = tf.matmul(flat, weights)
biases = tf.Variable(tf.constant(0.0, shape=[4096], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(mat, biases)
fc6 = tf.nn.relu(bias, name=scope)
fc6_drop = tf.nn.dropout(fc6, keep_prob=0.5, name='dropout')
with tf.name_scope('fc_7') as scope:
weights = tf.Variable(tf.truncated_normal([4096, 4096], dtype=tf.float32, stddev=1e-1), name='weights')
mat = tf.matmul(fc6, weights)
biases = tf.Variable(tf.constant(0.0, shape=[4096], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(mat, biases)
fc7 = tf.nn.relu(bias, name=scope)
fc7_drop = tf.nn.dropout(fc7, keep_prob=0.5, name='dropout')
with tf.name_scope('fc_8') as scope:
weights = tf.Variable(tf.truncated_normal([4096, 1000], dtype=tf.float32, stddev=1e-1), name='weights')
mat = tf.matmul(fc7, weights)
biases = tf.Variable(tf.constant(0.0, shape=[1000], dtype=tf.float32), trainable=True, name='biases')
bias = tf.nn.bias_add(mat, biases)
predictions = bias
```
Understanding every line of this model isn't important. The main point to notice is how much space this takes up. Several of the above lines (conv2d, bias_add, relu, maxpool) can obviously be combined to cut down on the size a bit, and you could also try to compress the code with some clever `for` looping, but all at the cost of sacrificing readability. With this much code, there is high potential for bugs or typos (to be honest, there are probably a few up there^), and modifying or refactoring the code becomes a huge pain.
By the way, although VGG-16's paper was titled "Very Deep Convolutional Networks for Large-Scale Image Recognition", it isn't even considered a particularly deep network by today's standards. [Residual Networks](https://arxiv.org/abs/1512.03385) (2015) started beating state-of-the-art results with 50, 101, and 152 layers in their first incarnation, before really going off the deep end and getting up to 1001 layers and beyond. I'll spare you from me typing out the uncompressed TensorFlow Core code for that.
### TF-Slim
Enter TF-Slim. The same VGG-16 model can be expressed as follows:
```
import tensorflow as tf
slim = tf.contrib.slim
# Set up the data loading:
images, labels = ...
# Define the model:
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=tf.nn.relu,
weights_initializer=tf.truncated_normal_initializer(0.0, 0.01),
weights_regularizer=slim.l2_regularizer(0.0005)):
net = slim.repeat(images, 2, slim.conv2d, 64, [3, 3], scope='conv1')
net = slim.max_pool2d(net, [2, 2], scope='pool1')
net = slim.repeat(net, 2, slim.conv2d, 128, [3, 3], scope='conv2')
net = slim.max_pool2d(net, [2, 2], scope='pool2')
net = slim.repeat(net, 3, slim.conv2d, 256, [3, 3], scope='conv3')
net = slim.max_pool2d(net, [2, 2], scope='pool3')
net = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], scope='conv4')
net = slim.max_pool2d(net, [2, 2], scope='pool4')
net = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], scope='conv5')
net = slim.max_pool2d(net, [2, 2], scope='pool5')
net = slim.fully_connected(net, 4096, scope='fc6')
net = slim.dropout(net, 0.5, scope='dropout6')
net = slim.fully_connected(net, 4096, scope='fc7')
net = slim.dropout(net, 0.5, scope='dropout7')
net = slim.fully_connected(net, 1000, activation_fn=None, scope='fc8')
predictions = net
```
Much cleaner. For the TF-Slim version, it's much more obvious what the network is doing, writing it is faster, and typos and bugs are much less likely.
Things to notice:
- Weight and bias variables for every layer are automatically generated and tracked. Also, the "in_channel" parameter for determining weight dimension is automatically inferred from the input. This allows you to focus on what layers you want to add to the model, without worrying as much about boilerplate code.
- The repeat() function allows you to add the same layer multiple times. In terms of variable scoping, repeat() will add "_#" to the scope to distinguish the layers, so we'll still have layers of scope "`conv1_1`, `conv1_2`, `conv2_1`, etc...".
- The non-linear activation function (here: ReLU) is wrapped directly into the layer. In more advanced architectures with batch normalization, that's included as well.
- With slim.argscope(), we're able to specify defaults for common parameter arguments, such as the type of activation function or weights_initializer. Of course, these defaults can still be overridden in any individual layer, as demonstrated in the finally fully connected layer (fc8).
If you're reusing one of the famous architectures (like VGG-16), TF-Slim already has them defined, so it becomes even easier:
```
import tensorflow as tf
slim = tf.contrib.slim
vgg = tf.contrib.slim.nets.vgg
# Set up the data loading:
images, labels = ...
# Define the model:
predictions = vgg.vgg16(images)
```
## Pre-Trained Weights
TF-Slim provides weights pre-trained on the ImageNet dataset available for [download](https://github.com/tensorflow/models/tree/master/research/slim#pre-trained-models). First a quick tutorial on saving and restoring models:
### Saving and Restoring
One of the nice features of modern machine learning frameworks is the ability to save model parameters in a clean way. While this may not have been a big deal for the MNIST logistic regression model because training only took a few seconds, it's easy to see why you wouldn't want to have to re-train a model from scratch every time you wanted to do inference or make a small change if training takes days or weeks.
TensorFlow provides this functionality with its [Saver()](https://www.tensorflow.org/programmers_guide/variables#saving_and_restoring) class. While I just said that saving the weights for the MNIST logistic regression model isn't necessary because of how it is easy to train, let's do it anyway for illustrative purposes:
```
import tensorflow as tf
from tqdm import trange
from tensorflow.examples.tutorials.mnist import input_data
# Import data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Create the model
x = tf.placeholder(tf.float32, [None, 784], name='x')
W = tf.Variable(tf.zeros([784, 10]), name='W')
b = tf.Variable(tf.zeros([10]), name='b')
y = tf.nn.bias_add(tf.matmul(x, W), b, name='y')
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10], name='y_')
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# Variable Initializer
init_op = tf.global_variables_initializer()
# Create a Saver object for saving weights
saver = tf.train.Saver()
# Create a Session object, initialize all variables
sess = tf.Session()
sess.run(init_op)
# Train
for _ in trange(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# Save model
save_path = saver.save(sess, "./log_reg_model.ckpt")
print("Model saved in file: %s" % save_path)
# Test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('Test accuracy: {0}'.format(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})))
sess.close()
```
Note, the differences from what we worked with yesterday:
- In lines 9-12, 15, there are now 'names' properties attached to certain ops and variables of the graph. There are many reasons to do this, but here, it will help us identify which variables are which when restoring.
- In line 23, we create a Saver() object, and in line 35, we save the variables of the model to a checkpoint file. This will create a series of files containing our saved model.
Otherwise, the code is more or less the same.
To restore the model:
```
import tensorflow as tf
from tqdm import trange
from tensorflow.examples.tutorials.mnist import input_data
# Import data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Create a Session object, initialize all variables
sess = tf.Session()
# Restore weights
saver = tf.train.import_meta_graph('./log_reg_model.ckpt.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
print("Model restored.")
graph = tf.get_default_graph()
x = graph.get_tensor_by_name("x:0")
y = graph.get_tensor_by_name("y:0")
y_ = graph.get_tensor_by_name("y_:0")
# Test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('Test accuracy: {0}'.format(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})))
sess.close()
```
Importantly, notice that we didn't have to retrain the model. Instead, the graph and all variable values were loaded directly from our checkpoint files. In this example, this probably takes just as long, but for more complex models, the utility of saving/restoring is immense.
### TF-Slim Model Zoo
One of the biggest and most surprising unintended benefits of the ImageNet competition was deep networks' transfer learning properties: CNNs trained on ImageNet classification could be re-used as general purpose feature extractors for other tasks, such as object detection. Training on ImageNet is very intensive and expensive in both time and computation, and requires a good deal of set-up. As such, the availability of weights already pre-trained on ImageNet has significantly accelerated and democratized deep learning research.
Pre-trained models of several famous architectures are listed in the TF Slim portion of the [TensorFlow repository](https://github.com/tensorflow/models/tree/master/research/slim#pre-trained-models). Also included are the papers that proposed them and their respective performances on ImageNet. Side note: remember though that accuracy is not the only consideration when picking a network; memory and speed are important to keep in mind as well.
Each entry has a link that allows you to download the checkpoint file of the pre-trained network. Alternatively, you can download the weights as part of your program. A tutorial can be found [here](https://github.com/tensorflow/models/blob/master/research/slim/slim_walkthrough.ipynb), but the general idea:
```
from datasets import dataset_utils
import tensorflow as tf
url = "http://download.tensorflow.org/models/vgg_16_2016_08_28.tar.gz"
checkpoints_dir = './checkpoints'
if not tf.gfile.Exists(checkpoints_dir):
tf.gfile.MakeDirs(checkpoints_dir)
dataset_utils.download_and_uncompress_tarball(url, checkpoints_dir)
import os
import tensorflow as tf
from nets import vgg
slim = tf.contrib.slim
# Load images
images = ...
# Pre-process
processed_images = ...
# Create the model, use the default arg scope to configure the batch norm parameters.
with slim.arg_scope(vgg.vgg_arg_scope()):
logits, _ = vgg.vgg_16(processed_images, num_classes=1000, is_training=False)
probabilities = tf.nn.softmax(logits)
# Load checkpoint values
init_fn = slim.assign_from_checkpoint_fn(
os.path.join(checkpoints_dir, 'vgg_16.ckpt'),
slim.get_model_variables('vgg_16'))
```
| github_jupyter |
# Gaussian mixture model with expectation maximization algorithm
GMM with EM.
This notebook implements the following:
1) Function that avoids computing inverse of matrix when computing $y = A^{-1}x$ by solving system of linear equations.
2) Log sum trick to avoid underflow when multiplying small numbers.
3) pdf of the Multivariate normal distribution
4) E-step function of the EM algorithm
5) M-step function of the EM algorithm
6) Variational lower bound function
7) GMM function
8) Training function for GMM
9) Scatter plot of clusters (Plot at the bottom of this notebook shows 8 clusters from a dataset of 100 points)
# Imports
```
import sys
import numpy as np
from numpy.linalg import det, solve
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
```
# Variables info
N: number of data (rows)
d: dimension of data
X: (N x d), data points
C: int, number of clusters
Computed from E-step:
gamma: (N x C), distribution q(T), probabilities of clusters for objects
Initial values are also subsequently computed & updated from M-step:
pi: (C), mixture component weights, initial weights of T (latent variable), sum to 1, t=1, 2 or 3.
mu: (C x d), mixture component means
sigma: (C x d x d), # mixture component covariance matrices
# Generate random data.
```
N = 100
d = 2
X = np.random.rand(N,d)
print(X[:5])
print(X.shape)
fig, ax = plt.subplots(1,1, figsize=(15,10))
ax.set_title('Data')
ax.scatter(X[:, 0], X[:, 1], c='black', s=100)
#plt.axis('equal')
plt.show()
```
# Generate initial values
```
epsilon = 1e-10 # Use in stopping criterion as well as in preventing numerical errors.
C = 7
def rand_input(C, d):
# https://stackoverflow.com/questions/18659858/generating-a-list-of-random-numbers-summing-to-1
pi0 = np.random.dirichlet(np.ones(C),size=1)[0] # Generating a list of random numbers, summing to 1
mu0 = np.random.rand(C,d)
sigma0 = np.random.rand(C,d,d)
return pi0, mu0, sigma0
pi0, mu0, sigma0 = rand_input(C, d)
print(pi0)
print(pi0.shape)
print(mu0)
print(mu0.shape)
print(sigma0)
print(sigma0.shape)
```
# Avoid computing inverse of matrix when computing y=(A_inverse)x.
```
# Function which avoids computing inverse of matrix when computing y=(A_inverse)x by solving linear equations.
# Use in E-step.
def _A_inverse_times_X(A, X):
# A is nxn
# X is rxn
Y = []
for row_data in X:
Y_new = np.linalg.solve(A, row_data)
Y.append(Y_new)
Y = np.asarray(Y)
assert Y.shape == X.shape, "Output shape must be equal to shape of X."
return Y
```
# Multivariate normal (Gaussian) distribution
$MVN = \frac{1}{\sqrt{(2\pi)^n|\boldsymbol\Sigma_c|}}
\exp\left(-\frac{1}{2}({x}-{\mu_c})^T{\boldsymbol\Sigma_c}^{-1}({x}-{\mu_c})\right)$
Computes pdf of Multivariate normal (Gaussian) distribution.
```
# Alternatively, one could also use multivariate_normal.pdf from scipy.stats
# instead of this function
def __mvg(cov, X, mean):
diff = X - mean
Y = _A_inverse_times_X(cov, diff)
pow_term = -0.5 * np.matmul(Y, diff.T)
e_term = np.exp(pow_term)
const_term = (2*np.pi)**(X.shape[1])
det_term = np.linalg.det(cov)
deno_term = np.sqrt(np.multiply(const_term, det_term))
P = np.divide(e_term, deno_term)
return P.diagonal() # returns the pdf, shape=(num_X,)
# Returns pdf for multiple components.
def _mvg(cov, X, mean):
P = []
for i, r in enumerate(mean):
P.append(__mvg(cov[i], X, mean[i]))
return P # shape=(C, num_X)
```
# Log sum trick
```
# log sum trick to prevent underflow in E-step.
# https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/
# https://web.archive.org/web/20150502150148/http://machineintelligence.tumblr.com/post/4998477107/the-log-sum-exp-trick
# https://www.quora.com/Why-is-e-log_-e-x-equal-to-x
def exp_normalize(x):
b = x.max()
y = np.exp(x - b)
return y / y.sum()
```
# E-step
Multiply the initial weight of the class with the multivariate guassian pdf of each data from the class.
```
def E_step(X, pi, mu, sigma):
N = X.shape[0] # number of objects
C = pi.shape[0] # number of clusters
d = mu.shape[1] # dimension of each object
gamma = np.zeros((N, C)) # distribution q(T)
gamma = np.mat(np.zeros((N, C)))
prob = _mvg(sigma, X, mu) # pdf of data X in each class
prob = np.mat(prob)
for c in range(C):
# Instead of multiplying probabilities directly which could result in underflow,
# we'll work in log scale.
# pi[c] = P(T=c), prob[c, :] = P(X|T=c)
#gamma[:, c] = np.multiply(pi[c], prob[c, :].T)
gamma[:, c] = np.log(pi[c] + epsilon) + np.log(prob[c, :].T + epsilon)
for i in range(N):
# Instead of summing the denominator, we'll use the log sum trick coded in exp_normalize function.
gamma[i, :] = exp_normalize(gamma[i, :])
return gamma # Q(T) = P(T|X,theta), weights of each model (class) for each data in X.
```
# M-Step
Compute the following:
[Equations from wiki](https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm#E_step)



```
def M_step(X, gamma):
N = X.shape[0] # number of objects
C = gamma.shape[1] # number of clusters
d = X.shape[1] # dimension of each object
mu = np.zeros((C, d))
sigma = []
pi = np.zeros(C)
# for each model in C
for c in range(C):
# sum of all Q(t) of model c
sum_Q_t = np.sum(gamma[:, c])
# mean of model c
mu[c, :] = np.sum(np.multiply(X, gamma[:, c]), axis=0) / sum_Q_t
# cov of model c
diff = X - mu[c]
sigma.append(diff.T @ np.multiply(diff, gamma[:, c]) / sum_Q_t)
# weight of model c
pi[c] = sum_Q_t / N
return pi, mu, np.asarray(sigma)
```
# Variational lower bound
Computes the scalar output of the following:
$$\sum_{i=1}^{N} \sum_{c=1}^{C} q(t_i =c) (\log \pi_c + \log(MVN)) - \sum_{i=1}^{N} \sum_{c=1}^{K} q(t_i =c) \log q(t_i =c)$$
```
def compute_vlb(X, pi, mu, sigma, gamma):
"""
Each input is numpy array:
X: (N x d), data points
gamma: (N x C), distribution q(T)
pi: (C)
mu: (C x d)
sigma: (C x d x d)
Returns value of variational lower bound
"""
N = X.shape[0] # number of objects
C = gamma.shape[1] # number of clusters
d = X.shape[1] # dimension of each object
VLB = 0.0
for c in range(C):
mu_c = np.expand_dims(mu[c,:], axis=0)
sigma_c = np.expand_dims(sigma[c,:], axis=0)
gamma_c = gamma[:,c]
mvg = np.asarray(_mvg(sigma_c, X, mu_c)) # 1xc
sum = np.log(pi[c] + epsilon) + np.log(mvg + epsilon) # 1xc, + 1e-30 to prevent log(0)
prod = np.multiply(gamma_c, sum.T) # transpose sum for element wise multiplication
prod2 = np.multiply(gamma_c, np.log(gamma_c + epsilon)) # element wise multiplication, + 1e-30 to prevent log(0)
VLB += (prod - prod2)
VLB = np.sum(VLB, axis=0) # sum all values for all rows
return VLB
```
# GMM
Find the best parameters by optimizing with the following criterion:
Stopping threshold: ($|\frac{\mathcal{L}_i-\mathcal{L}_{i-1}}{\mathcal{L}_{i-1}}| \le \text{threshold}$)
```
def GMM(X, C, d, threshold=epsilon, max_iter=1000, trial=500):
N = X.shape[0] # number of objects
d = X.shape[1] # dimension of each object
best_VLB = None
best_pi = None
best_mu = None
best_sigma = None
for rs in range(trial):
try:
pi, mu, sigma = rand_input(C, d) # Try random initial values
curr_LVB, prev_LVB = 0.0, 0.0
iter = 0
while iter < max_iter:
#print('iter, rs', iter, rs)
prev_LVB = curr_LVB
gamma = E_step(X, pi, mu, sigma)
pi, mu, sigma = M_step(X, gamma)
curr_LVB = compute_vlb(X, pi, mu, sigma, gamma)
#print('prev_LVB', prev_LVB)
#print('curr_LVB', curr_LVB)
# LVB is the variation lower bound function. It must NOT be decreasing.
# We are trying to maximize LVB so that the gap between LVB & GMM is minimized.
if prev_LVB != 0.0 and curr_LVB < prev_LVB:
print('VLB ERROR EXIT!: curr_LVB < prev_LVB')
sys.exit(1)
# If numerical error in LVB, goto next trial.
if np.isnan(curr_LVB) == True:
break
if prev_LVB != 0.0 and abs((curr_LVB - prev_LVB) / (prev_LVB)) <= threshold:
if best_VLB == None or curr_LVB > np.float32(best_VLB):
best_VLB = curr_LVB
best_pi = pi
best_mu = mu
best_sigma = sigma
break # end while loop, goto for loop
iter += 1
except np.linalg.LinAlgError:
print("Singular matrix not allowed.")
pass
return best_VLB, best_pi, best_mu, best_sigma
```
# Train
```
# Train
# If numerical errors occured, run a couple of more times.
best_VLB, best_pi, best_mu, best_sigma = GMM(X, C, d)
print('best_VLB', best_VLB)
print('best_pi', best_pi)
print('best_mu', best_mu)
print('best_sigma', best_sigma)
# Use the best values to do 1 more E-step to get gamma.
gamma = E_step(X, best_pi, best_mu, best_sigma)
labels = np.ravel(gamma.argmax(axis=1))
```
# Scatter plot
```
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
'''
# Generate colors for each class.
# only works for max of 4 classes.
def gen_col(C):
colors =[]
for c in range(C):
colors.append(np.random.randint(0, 255, C) / 255)
print(colors)
return colors
colors = gen_col(C)
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap=matplotlib.colors.ListedColormap(colors), s=30)
plt.axis('equal')
plt.show()
'''
# https://stackoverflow.com/questions/12487060/matplotlib-color-according-to-class-labels
N = C # Number of labels
# setup the plot
fig, ax = plt.subplots(1,1, figsize=(15,10))
# define the data
x = X[:, 0]
y = X[:, 1]
tag = labels
# define the colormap
cmap = plt.cm.jet
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# create the new map
cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)
# define the bins and normalize
bounds = np.linspace(0,N,N+1)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
# make the scatter
scat = ax.scatter(x, y, c=tag, s=np.random.randint(100,500,N), cmap=cmap, norm=norm)
# create the colorbar
cb = plt.colorbar(scat, spacing='proportional',ticks=bounds)
cb.set_label('Custom cbar')
ax.set_title('Discrete color mappings')
plt.show()
```
| github_jupyter |
# Lesson 3: In-class exercises
---
Sarah Middleton (http://sarahmid.github.io/)
http://github.com/sarahmid/python-tutorials
---
**Instructions: For each problem, write code in the provided code block. Don't forget to run your code to make sure it works.**
---
**1\. Simple loop practice**
Write code to accomplish each of the following tasks using a `for` loop or a `while` loop. Choose whichever type of loop you want for each problem (you can try both, if you want extra practice). Note: you may want to refer to the Lesson 3 "extra material" for some hints on how to use `range()` to make these problems easier.
**(A)** Print the integers between 3 and 35, inclusive.
**(B)** Print the positive integers less than 100 that are multiples of 7.
**(C)** Starting with x = 1, double x until it's greater than 1000. Print each value of x as you go along.
**(D)** Print each character of the string "supercalifragilisticexpialidocious" on a separate line.
---
**2\. File reading practice**
For these problems, use the file `sequences.txt` provided with this document. This file contains several DNA sequences of different lengths. You can assume each sequence is on a separate line.
**(A)** Using a loop, read in each sequence from the file and print it. Make sure to remove any newline characters (\n) while reading in the data.
**(B)** Now, instead of printing the sequences, output the *length* of each sequence to the terminal screen. At the end, print the average length of the sequences. (You should get 77.56 as the average.)
*Hint: use the concept of an "accumulator" variable to help with computing the average.*
---
**3\. File writing practice**
**(A)** Write a script that prints "Hello, world" to a file called `hello.txt`
**(B)** Write a script that prints the following pieces of data to a file called `meow.txt`. Each piece of data must be printed to a separate line.
```
# data to be printed:
name = "Mitsworth"
age = 11
birthday = "9/1/04"
coloring = "Tabby"
livesRemaining = 8
# write your code here:
```
---
# Homework exercise
---
**String manipulation 101**
These problems follow from problem **2** above. Continue using the file `sequences.txt`.
**(A)** Instead of printing lengths as before, print the *GC content* of each sequence (GC content is the number of G's and C's in a DNA sequence divided by the total sequence length). Make sure not to do integer division! (You should get ~0.4877 as the average.)
**(B)** Convert each sequence to its reverse complement. This means changing each nucleotide to its complement (A->T, T->A, G->C, C->G) and reversing the entire sequence.
*Hint: we've already touched on everything you need to know to do this. See the practice problems from Lesson 3 for some hints on reversing..*
| github_jupyter |
# Preparing for ISF '21
### Results analysis and graphing
---
## Plumbing
```
import sys
import os
import importlib
is_colab = importlib.util.find_spec("google")
found = is_colab is not None
import_path = ''
if found:
from google.colab import drive
drive.mount('/content/gdrive/', force_remount=True)
import_path += '/content/gdrive/My Drive/Thesis/pairs/'
else:
import_path += 'data/pairs/'
print(import_path)
from utils.subsets import *
from utils.simulations import cumret
import pickle
oneyr = pickle.load(open('data/raw/26-coins_1D-returns.pkl', 'rb'))
twoyr = pickle.load(open('data/raw/14-coins_1D-returns.pkl', 'rb'))
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import pandas as pd
import numpy as np
import seaborn as sns
plt.style.use("ggplot")
oneyravg = oneyr.mean(axis=1)
twoyravg = twoyr.mean(axis=1)
fig = plt.figure(figsize=(9,6))
plt.plot(cumret(oneyravg), label='oneyr B&H')
plt.plot(cumret(twoyravg), label="twoyr B&H")
plt.legend()
plt.show()
# 14 & 147, 26 & 83
one_yr_res = []
two_yr_res = []
import_path = 'results/pickle/'
for dirname, _, filenames in os.walk(import_path):
for filename in filenames:
if '.pkl' in filename:
try:
res = pickle.load(open(import_path + filename, 'rb'))
except EOFError:
print(f"EOFError on {filename}")
continue
f = filename.split('.')[0]
yhat = res.get_predictions()
if yhat.shape == (83, 26):
one_yr_res.append(res)
rets = res.cumulative_portfolio_returns()
# print(f"{f.split('_')}: {yhat.shape[0]}")
# print(f"{f.split('_')}: {rets.iloc[-1]}")
# print()
elif yhat.shape == (147, 14):
two_yr_res.append(res)
rets = res.cumulative_portfolio_returns()
# print(f"{f.split('_')}: {yhat.shape[0]}")
# print(f"{f.split('_')}: {rets.iloc[-1]}")
# print()
from utils.plotting import plot_portfolio_sims
oneyrmodels = {}
for res in one_yr_res:
# print(res.get_model_name())
oneyrmodels[res.get_model_name()] = []
for res in one_yr_res:
oneyrmodels[res.get_model_name()].append(res)
print(oneyrmodels.keys())
print()
print('----------------------')
print()
twoyrmodels = {}
for res in two_yr_res:
# print(res.get_model_name())
twoyrmodels[res.get_model_name()] = []
for res in two_yr_res:
twoyrmodels[res.get_model_name()].append(res)
print(twoyrmodels.keys())
```
----
# Top 14 coins (two years of available data)
```
two_mvpcalstm = twoyrmodels['Multivariate PCA(2)-LSTM(4,6)']
two_aelstm = twoyrmodels['AE(2,200)-LSTM(4,6)']
two_aemmlstm = twoyrmodels['AE(2,200)-MultiModel(20)LSTMs(4,6)']
two_ar = twoyrmodels['Auto-Regressive (1) latent variable model']
two_arma = twoyrmodels['Auto-Regressive Moving-Average (1, 1) latent variable model']
two_ffnn = twoyrmodels['AE(2,200)-FFNN(15,6)']
two_lasso = twoyrmodels['LASSO_alpha-0.1']
models_results = [two_mvpcalstm, two_aelstm, two_ar, two_arma, two_ffnn, two_lasso]
buy_and_hold = []
for arr_i, arr in enumerate(models_results):
min_rmse = np.Inf
rmse_i = 999
max_ret = 0
ret_i = 999
max_sharpe = 0
sharpe_i = 999
count = 0
for i, m in enumerate(arr):
if arr_i == 0 and i == 0: buy_and_hold = m.get_buy_and_hold()
cumret = m.cumulative_portfolio_returns().iloc[-1]
rmse = m.get_rmse()
sharpe = m.get_sharpe()
if rmse < min_rmse:
rmse_i = i
min_rmse = rmse
if cumret > max_ret:
ret_i = i
max_ret = cumret
if sharpe > max_sharpe:
sharpe_i = i
max_sharpe = sharpe
count +=1
print(f'{count}-total simulations')
print(f'Arr at entry {arr_i}:')
print(f'Max ret = {max_ret} @ entry {ret_i}')
print(f'Min rmse = {min_rmse} @ entry {rmse_i}')
print(f'Max Sharpe = {max_sharpe} @ entry {sharpe_i}')
print()
buy_and_hold
models = ["AR(1)", "ARMA(1,1)", "LASSO", "PCALSTM", "FFNN", "AELSTM"]
arrs = [two_ar, two_arma, two_lasso, two_mvpcalstm, two_ffnn, two_aemmlstm]
modnames, rmses, cumrets, sharpes = [], [], [], []
for i, model in enumerate(models):
for j, m in enumerate(arrs[i]):
modnames.append(model)
rmses.append(m.get_rmse())
cumrets.append(m.cumulative_portfolio_returns().iloc[-1])
sharpes.append(m.get_sharpe())
twoyrdf = pd.DataFrame({"Model":modnames, "RMSE": rmses, "Cumulative Return": cumrets, "Sharpe": sharpes})
twoyrdf
fig, ax = plt.subplots(figsize=(8,6))
sns.boxplot(x='Model', y='RMSE', data=twoyrdf[(twoyrdf != 'PCALSTM').any(axis=1)])
# sns.swarmplot(x='Model', y='RMSE', data=twoyrdf)
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.title("RMSE on Top 14 Coins Over 147 Days")
plt.yscale('log')
plt.ylabel("RMSE (log-scaled)")
plt.show()
cleaner_twoyrdf = twoyrdf.loc[~twoyrdf['Model'].isin(['PCALSTM'])]
plt.figure(figsize=(8,6))
sns.boxplot(x='Model', y='RMSE', data=cleaner_twoyrdf)
# sns.swarmplot(x='Model', y='RMSE', data=twoyrdf)
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.title("RMSE on Top 14 Coins Over 147 Days")
# plt.yscale('log')
plt.show()
y = 7.35
x1, x2 = -1, 10
fig, ax = plt.subplots(figsize=(10,8))
sns.boxplot(x='Model', y='Cumulative Return', data=twoyrdf)
sns.swarmplot(x='Model', y='Cumulative Return', data=twoyrdf, color=".25")
plt.plot([x1, x2], [y, y], '--', color='0.25', label='B&H')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.title("Returns on Top 14 Coins Over 147 Days")
plt.legend()
# plt.yscale('log')
plt.show()
from utils.plotting import cumret as calc_cumret
# Calculate the portfolio_returns and their standard deviation
rets = buy_and_hold
crets = calc_cumret(buy_and_hold)
std = np.std(rets)
sim_return = (crets.iloc[-1] - 1) / 100
# Calculate the risk free return over the period
periods_per_day = 1
risk_free_rate_apy = 0.03
daily_rfr = risk_free_rate_apy / 365
n_days = len(rets) / periods_per_day
rfr = daily_rfr * n_days
bnh_sharpe = (sim_return - rfr) / std
print(f'Buy and Hold Sharpe: {bnh_sharpe}')
y = bnh_sharpe
x1, x2 = -1, 10
fig, ax = plt.subplots(figsize=(10,8))
sns.boxplot(x='Model', y='Sharpe', data=twoyrdf)
sns.swarmplot(x='Model', y='Sharpe', data=twoyrdf, color=".25")
plt.plot([x1, x2], [y, y], '--', color='0.25', label='B&H')
plt.title("Simulation Sharpe Ratios Top 14 Coins Over 147 Days")
plt.legend()
# plt.yscale('log')
plt.show()
y = bnh_sharpe
x1, x2 = -1, 10
fig, ax = plt.subplots(figsize=(10,8))
sns.boxplot(x='Model', y='Sharpe', data=cleaner_twoyrdf)
sns.swarmplot(x='Model', y='Sharpe', data=cleaner_twoyrdf, color=".25")
plt.plot([x1, x2], [y, y], '--', color='0.25', label='B&H')
plt.title("Simulation Sharpe Ratios Top 14 Coins Over 147 Days")
plt.legend()
# plt.yscale('log')
plt.show()
```
-----
# Top 26 coins (one year of available historical data)
```
one_mvpcalstm = oneyrmodels['Multivariate PCA(2)-LSTM(4,6)']
one_aelstm = oneyrmodels['AE(2,200)-LSTM(4,6)']
one_lasso = oneyrmodels['LASSO_alpha-0.1']
one_ffn = oneyrmodels['AE(2,200)-FFNN(15,6)']
one_aemmlstm = oneyrmodels['AE(2,200)-MultiModel(20)LSTMs(4,6)']
one_ar = oneyrmodels['Auto-Regressive (1) latent variable model']
one_arma = oneyrmodels['Auto-Regressive Moving-Average (1, 1) latent variable model']
models_results = [one_mvpcalstm, one_aelstm, one_lasso, two_arma, one_ar, one_aemmlstm]
buy_and_hold = []
for arr_i, arr in enumerate(models_results):
min_rmse = np.Inf
rmse_i = 999
max_ret = 0
ret_i = 999
max_sharpe = 0
sharpe_i = 999
count = 0
for i, m in enumerate(arr):
if arr_i == 0 and i == 0: buy_and_hold = m.get_buy_and_hold()
cumret = m.cumulative_portfolio_returns().iloc[-1]
rmse = m.get_rmse()
sharpe = m.get_sharpe()
if rmse < min_rmse:
rmse_i = i
min_rmse = rmse
if cumret > max_ret:
ret_i = i
max_ret = cumret
if sharpe > max_sharpe:
sharpe_i = i
max_sharpe = sharpe
count +=1
print(f'{count}-total simulations')
print(f'Arr at entry {arr_i}:')
print(f'Max ret = {max_ret} @ entry {ret_i}')
print(f'Min rmse = {min_rmse} @ entry {rmse_i}')
print(f'Max Sharpe = {max_sharpe} @ entry {sharpe_i}')
print()
models = ["AR(1)", "ARMA(1,1)", "LASSO", "PCALSTM", "FFNN", "AELSTM"]
arrs = [one_ar, one_arma, one_lasso, one_mvpcalstm, one_ffnn, one_aemmlstm]
modnames, rmses, cumrets, sharpes = [], [], [], []
for i, model in enumerate(models):
for j, m in enumerate(arrs[i]):
modnames.append(model)
rmses.append(m.get_rmse())
cumrets.append(m.cumulative_portfolio_returns().iloc[-1])
sharpes.append(m.get_sharpe())
oneyrdf = pd.DataFrame({"Model":modnames, "RMSE": rmses, "Cumulative Return": cumrets, "Sharpe": sharpes})
oneyrdf
fig, ax = plt.subplots(figsize=(8,6))
sns.boxplot(x='Model', y='RMSE', data=twoyrdf[(twoyrdf != 'PCALSTM').any(axis=1)])
# sns.swarmplot(x='Model', y='RMSE', data=twoyrdf)
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.title("RMSE on Top 14 Coins Over 147 Days")
plt.yscale('log')
plt.ylabel("RMSE (log-scaled)")
plt.show()
cleaner_twoyrdf = twoyrdf.loc[~twoyrdf['Model'].isin(['PCALSTM'])]
plt.figure(figsize=(8,6))
sns.boxplot(x='Model', y='RMSE', data=cleaner_twoyrdf)
# sns.swarmplot(x='Model', y='RMSE', data=twoyrdf)
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.title("RMSE on Top 14 Coins Over 147 Days")
# plt.yscale('log')
plt.show()
y = 7.35
x1, x2 = -1, 10
fig, ax = plt.subplots(figsize=(10,8))
sns.boxplot(x='Model', y='Cumulative Return', data=twoyrdf)
sns.swarmplot(x='Model', y='Cumulative Return', data=twoyrdf, color=".25")
plt.plot([x1, x2], [y, y], '--', color='0.25', label='B&H')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.title("Returns on Top 14 Coins Over 147 Days")
plt.legend()
# plt.yscale('log')
plt.show()
from utils.plotting import cumret as calc_cumret
# Calculate the portfolio_returns and their standard deviation
rets = buy_and_hold
crets = calc_cumret(buy_and_hold)
std = np.std(rets)
sim_return = (crets.iloc[-1] - 1) / 100
# Calculate the risk free return over the period
periods_per_day = 1
risk_free_rate_apy = 0.03
daily_rfr = risk_free_rate_apy / 365
n_days = len(rets) / periods_per_day
rfr = daily_rfr * n_days
bnh_sharpe = (sim_return - rfr) / std
print(f'Buy and Hold Sharpe: {bnh_sharpe}')
y = bnh_sharpe
x1, x2 = -1, 10
fig, ax = plt.subplots(figsize=(10,8))
sns.boxplot(x='Model', y='Sharpe', data=twoyrdf)
sns.swarmplot(x='Model', y='Sharpe', data=twoyrdf, color=".25")
plt.plot([x1, x2], [y, y], '--', color='0.25', label='B&H')
plt.title("Simulation Sharpe Ratios Top 14 Coins Over 147 Days")
plt.legend()
# plt.yscale('log')
plt.show()
y = bnh_sharpe
x1, x2 = -1, 10
fig, ax = plt.subplots(figsize=(10,8))
sns.boxplot(x='Model', y='Sharpe', data=cleaner_twoyrdf)
sns.swarmplot(x='Model', y='Sharpe', data=cleaner_twoyrdf, color=".25")
plt.plot([x1, x2], [y, y], '--', color='0.25', label='B&H')
plt.title("Simulation Sharpe Ratios Top 14 Coins Over 147 Days")
plt.legend()
# plt.yscale('log')
plt.show()
```
| github_jupyter |
## Search for nearby Amenities for all site locations of each city
List of Amenities by Categories:
Categories:
A. Emergency Facilities
'''How accesible are these facilities in case of mass emergency on/around
sites for containing the situation and resuming business asap'''
1. Hospital
2. Fire Station
3. Doctor
B. Accomodation
'''Many executive employees travel from outside the city for fews days a week and might need lodging
facility as close to the company as possible. Also lot of local/not-local employees use vehicle
for commute and will need parking nearby'''
1. Lodging
2. Parking
C. Recreation
'''MNC(s) often arrange for team building activities on and near site. Also employees might look for group
recreational activities close to work'''
1. Movies Theatres
2. Parks
3. Malls
4. Amusement park
5. Cafe/Restaurants
D. Basic Errands/appointments
'''By large employees tend to take care of daily errands and appoinments in lunch breaks or before/after
work hours and prefer it to be as close to work as possible for obvious reasons'''
1. Super markets
2. Post Office
3. Doctor
E. Fitness
'''Fitness is top on priority list for a significant amount of employees now a days may be in gym or a
jog/walk in park.'''
1. Gym
2. Parks
```
# Dependencies
import requests
import json
import pandas as pd
from pprint import pprint
import time
# Google developer API key
from config import g_key
# read places
xls = pd.ExcelFile('BC_Project1/Project1_AmazonSites.xlsx')
places_df=xls.parse('AmazonSites', dtype=str)
places_df = places_df[['Amazon City','Site','Site Name','Latitude','Longitude']]
places_df.head()
#len(places_df)
accomodation = {'lodging':'Lodging', 'parking':'Parking'}
all_accomodation_rating = []
for key in accomodation.keys():
accomodation_rating = []
for site in places_df.values:
# geocoordinates
target_coordinates = str(site[3]) + ',' + str(site[4])
target_search = accomodation[key]
target_radius = 2500
target_type = key
print("{} For {}: {}, {}".format(key, site[0], site[1], target_coordinates))
print("----------")
# set up a parameters dictionary
params = {
"location": target_coordinates,
"keyword": target_search,
"radius": target_radius,
"type": target_type,
"key": g_key
}
# base url
base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
# run a request using our params dictionary
response = requests.get(base_url, params=params).json()
results = response.get('results')
total_counts = len(results)
print(total_counts)
# Print the name and address of the first restaurant that appears
for x in range(total_counts):
if "rating" in results[x].keys():
rating = results[x]["rating"]
else:
rating = 'NAN'
accomodation_rating.append({"Site Name":site[2],
key+" Total Count":total_counts,
"Latitude":site[3],
"Longitude":site[4],
"Facility "+key:results[x]["name"],
"Rating":rating})
time.sleep(2)
time.sleep(2)
all_accomodation_rating.append(accomodation_rating)
print("ALL Done!!!!!")
#all_eatingout_rating
all_accomodation_rating
all_lodging_rating_df = pd.DataFrame(all_accomodation_rating[0])
all_lodging_rating_df.head()
all_parking_rating_df = pd.DataFrame(all_accomodation_rating[1])
all_parking_rating_df.head()
all_lodging_rating_df.to_csv("Lodging_Rating.csv")
all_parking_rating_df.to_csv("Parking_Rating.csv")
# geocoordinates
target_coordinates = '38.96,-77.42'
target_search = 'restaurant'
target_radius = 2500
target_type = 'Restaurant'
#print("{} For {}: {}, {}".format(key, site[0], site[1], target_coordinates))
print("----------")
# set up a parameters dictionary
params = {
"location": target_coordinates,
"keyword": target_search,
"radius": target_radius,
"type": target_type,
"key": g_key
}
# base url
base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
# run a request using our params dictionary
response = requests.get(base_url, params=params).json()
results = response.get('results')
results
```
| github_jupyter |
# Aim
1. **Introduce the python ecosystem**
* How do I run a `.py` script?
* Where do I enter python commands?
* What is `Python 2` and `Python 3`?
* wait!, there is something called `Anaconda`?
* `JupyterLab`, `Jupyter Notebooks` and reproducible research
2. **Why should I use python?**
* Is python as easy as `Ferret`?
* Is python as fast as `Fortran`?
* Does python have many toolboxes like in `MATLAB`?
* Can python read and write `netCDF` files?
* Can python plot geographic maps and coastlines?
* Can it handle larger than memory files (say >2 GB)?
3. **Possibilities with python**
* Exploratory Data Analysis
* Interactive plotting
* Parallel processing
* Cloud computing
---
## Python ecosystem
### Running a `.py` script
* Activate your environment, and run the script by
```bash
python your_script.py
```
### Three ways to spawn a python interpreter
* old fashioned `python` console
* rich and colorful `ipython` console
* `JupyterLab`
#### Starting the console
* In terminal, type `python`
* In terminal, type `ipython`
* In terminal, type `jupyter lab`
#### IPython
* Old python interface is boring and less interactive
* `IPython` supports tab completion, syntax highlighting, documentation lookup
* [cell magics](https://ipython.org/ipython-doc/3/interactive/magics.html)
like `%run`, `%debug`, `%edit` and `%bookmark` makes interactive coding easier
```{note}
More info can be found [here](https://ipython.org/ipython-doc/3/interactive/tutorial.html)
```
#### JupyterLab and Jupyter Notebook
* [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) is an interface where you can
* create notebooks
* manage files and folders
* display images
* start terminal
* display csv files and much more
* [Notebooks](https://jupyter-notebook.readthedocs.io/en/stable/notebook.html)
holds your code, plots and discussion in a single space
* Notebook sharing promotes reproducible research
* Notebooks are future of scientific communication,
([Nature article](https://www.nature.com/news/interactive-notebooks-sharing-the-code-1.16261))
* Jupyter is not limited to Python. You can run codes in
* `Julia`
* `Bash`
* `R`
* `Pyferret` and much more
````{tip}
**Additional benefits of `JupyterLab/Notebook`**
* Start jupyter in a remote computer say HPC and connect in your local browser
```bash
# in remote machine type:
jupyter lab --no-browser --ip="$HOSTNAME" --port=8888
# in local machine type:
ssh -N -L 8888:localhost:8888 username@remoteIP
```
* Open browser and type address as `localhost:8888` and press `Enter`
* No more waiting for the slow X-window forwarding to pop-up
* Easily access and view remote files
````
## Anaconda, miniconda and conda env
* `Anaconda` and `miniconda` differs only in the number of pre-packed packages
* `Anaconda` comes with many common-use packages (> 500 MB)
* While `miniconda` is a lite version (<60 MB)
* Both installs `conda`, which is the package manager
* `Conda` helps you isolate environments, allowing you to update/install certain packages without affecting
other working environment.
```{attention}
* **Stay away from Python 2**
* Avoid Python 2. It is now in *legacy* mode
* Packages are dropping support for Python 2
* Most scientific packages have moved to Python 3
* Found an old code in Python 2? Use conda to create a Python 2 environment
```
## Further references
* Rather than general python tutorials, look for scientific computing tutorials
* Some such python lessons covering basics are:
* <https://geo-python.github.io/site/index.html>
* <https://scipy-lectures.org/>
* <https://fabienmaussion.info/scientific_programming/html/00-Introduction.html>
* <https://github.com/geoschem/GEOSChem-python-tutorial>
* <https://unidata.github.io/online-python-training/>
* <https://rabernat.github.io/research_computing/>
* <http://swcarpentry.github.io/python-novice-inflammation/>
| github_jupyter |
## Imports
```
import numpy as np
import uproot
data_dir = "/Users/weisser/MIT_Dropbox/LbVMWeisser_shared/Tracking/Simulated_Velo/LHCbPVFinding_DataSets"
import matplotlib.pyplot as plt
%matplotlib inline
#from sklearn.neighbors import KernelDensity
from scipy.signal import find_peaks_cwt
from scipy.signal import argrelextrema
import math
f = uproot.open(data_dir+"/Data_ROOT/pvs_weisser.root")
#f = uproot.open(data_dir+"/Data_ROOT/pvs_weisser_old_smearing.root")
f.classes()
t = f["data"]
t.keys()
```
## Explore
```
if True:
data_dict = t.arrays()
len_pvr = [len(i) for i in data_dict["pvr_z"]]
len_prt = [len(i) for i in data_dict["prt_z"]]
len_hit = [len(i) for i in data_dict["hit_z"]]
plt.hist(len_pvr)
plt.xlabel("len_pvr ")
plt.show()
plt.hist(len_prt)
plt.xlabel("len_prt ")
plt.show()
plt.hist(len_hit)
plt.xlabel("len_hit ")
plt.show()
print "Number of events : \t\t\t\t", len(data_dict["pvr_z"])
print "Average number of pvs per event : \t\t", np.average([len(i) for i in data_dict["pvr_z"]])
print "Average number of particles per event : \t", np.average([len(i) for i in data_dict["prt_z"]])
print "Average number of hits per event : \t\t", np.average([len(i) for i in data_dict["hit_z"]])
print "\npvr_z : \n", data_dict["pvr_z"], "\n\nprt_z : \n", data_dict["prt_z"], "\n\nhit_z : \n", data_dict["hit_z"]
# Simple (2D) Linear Regression. Gaussian uncertainties of std dev beta in y variable. No uncertainties in x variable
# As proxy for x intercept uncertainty take the distance from the x intercept at which the y distance from the x axis
# corresponds to one standard dev in y (beta).
# If y = m * x + c
# Intercept is at - c / m
# Intercept uncertainty proxy is beta / m
# Look at http://science.widener.edu/svb/stats/regress.html
def linear_regression(x, y):
X = np.array([x]).T
train_features = X
train_target = y
if False:
w = np.dot(train_features.T, train_features)
w1 = np.dot(np.linalg.pinv(w), np.dot(train_features.T,train_target))
if False:
mean_x = np.mean(x); mean_y = np.mean(y);
B1 = sum((x(i) - mean_x) * (y(i) - mean_y)) / sum( (x(i) - mean_x)^2 )
B0 = mean(y) - B1 * mean(x)
beta = 1
print w1
c = w1[0]
m = w1[1]
intercept = - c / m
intercept_uncertainty = beta / m
if False:
a = np.linalg.inv(np.dot(X.T,X))
c = np.dot(X.T,Y)
b = np.dot(a,c)
if True:
mean_x = np.mean(x); mean_y = np.mean(y);
N = len(y)
assert N == len(x)
s_xx = sum([(x[i]-mean_x)*(x[i]-mean_x) for i in range(N)])
s_yy = sum([(y[i]-mean_y)*(y[i]-mean_y) for i in range(N)])
s_xy = sum([(x[i]-mean_x)*(y[i]-mean_y) for i in range(N)])
#print s_xx, s_yy, s_xy
m = s_xy / s_xx
c = mean_y - m * mean_x
intercept = mean_x - mean_y / m
#print "m, c, intercept : \t", m, c, intercept
beta = N / sum([(y[i]- c - m*x[i])*(y[i]- c - m*x[i]) for i in range(N)])
s_r = np.sqrt((s_yy - np.square(m)*s_xx)/(N-2) )
s_y = s_r * np.sqrt(1+1./N + (x-mean_x)**2/s_xx)
#s_x = s_r/m * sqrt(1./M + 1./N + (y_unk-mean_y)**2/(m**2*s_xx))
#print beta
#print s_r, np.mean(s_y)
beta = np.mean(s_y) #This is not actually correct
intercept_uncertainty = beta / m
return intercept, intercept_uncertainty
#Testing the linear regression function
if False:
if True:
l = [1, 2, 3, 4 ]
x_train = np.array(l)
y_train = np.array([2*i + 1 + np.random.normal(loc=0., scale=0.001) for i in l])
else:
l = [1, 2, 3, 4 ]
l1 = [1.5, 2.5]
x_train = np.array(l+l1)
y_train = np.array([2*i + 1 + np.random.normal(loc=0., scale=0.001) for i in l] +
[3*i + 0.5 + np.random.normal(loc=0., scale=0.001) for i in l1])
#X_train = np.c_[1, 2, 3, 4 ].T
#y_train = [3, 5, ]
X_test = np.c_[0, 2].T
linear_regression(x_train, y_train)
```
## Fill Bins
```
# 0.1 milliradian corresponds to 63000 bins
binning_scheme = [[10, 0],[10, 0.5]]
binning_scheme = [[63000, 0],[63000, 0.5]] # skipped many events
binning_scheme = [[6300, 0],[6300, 0.5]]
# 10, 0.5 means you divide 2 pi into 10 bins. the offset is 0.5 times a bin
data_dict = t.arrays()
pvr_x_pred = []
n_events = len(data_dict["hit_x"])
status = []
print "e_i :\t ",
counter = 0
for e_i in range(n_events):
#for e_i in range(1):
#for e_i in [869]: #Uncertainty valishes
#for e_i in [6700]: #No maxima found
if (e_i%100==0 ): print "|",
if (e_i%1000==0 ): print "\t{} out of {}k\ne_i :\t".format(e_i/1000., n_events/1000. ),
if e_i%10000==0: print_bool=True
else: print_bool=False
counter += 1
bin_contents = []
for n_binning_scheme, (nbins, offset_bin_frac) in enumerate(binning_scheme):
bin_contents.append({})
hit_phi = np.arctan2(data_dict["hit_y"][e_i], data_dict["hit_x"][e_i])
hit_r = np.sqrt(np.square(data_dict["hit_y"][e_i]) + np.square(data_dict["hit_x"][e_i]))
#print hit_phi
##################################################
### FILL BINS
##################################################
for n_binning_scheme in range(len(binning_scheme)):
nbins, offset_bin_frac = binning_scheme[n_binning_scheme][0], binning_scheme[n_binning_scheme][1]
#vectorised and no bin definitions necessary
hit_phi_obs = hit_phi - 2.*np.pi*offset_bin_frac/nbins #Rotating the bins with angle alpha is the same as rotating the point with angle - alpha
hit_phi_obs = hit_phi_obs % (2 * np.pi ) # taking care of modulo
hit_bins = (hit_phi_obs //(2 * np.pi / nbins)).astype(int)
#print hit_phi_obs
#print len(hit_bins), hit_bins
for j, b in enumerate(hit_bins):
#bin_contents[n_binning_scheme][b].append([data_dict["hit_z"][i][j], hit_r[j]])
if b in bin_contents[n_binning_scheme]:
bin_contents[n_binning_scheme][b].append([data_dict["hit_z"][e_i][j], hit_r[j]])
else:
bin_contents[n_binning_scheme][b]=[[data_dict["hit_z"][e_i][j], hit_r[j]]]
#print counter
#print bin_contents
##################################################
### DO REGRESSION
##################################################
kernel_inputs_orig = []
for n_binning_scheme, (nbins, offset_bin_frac) in enumerate(binning_scheme):
kernel_inputs_orig.append([])
n_skipped_few_hits = 0
n_skipped_vanishing_uncertainty = 0
n_total = 0
for n_binning_scheme in range(len(binning_scheme)):
nbins, offset_bin_frac = binning_scheme[n_binning_scheme][0], binning_scheme[n_binning_scheme][1]
for key in bin_contents[n_binning_scheme]:
n_total +=1
data = np.array(bin_contents[n_binning_scheme][key])
#print data.shape[0],
if (data.shape[0] < 3): n_skipped_few_hits+=1; continue
intercept, intercept_uncertainty = linear_regression(data[:, 0], data[:,1])
if (math.isnan(intercept_uncertainty) or intercept_uncertainty==0 ):
n_skipped_vanishing_uncertainty += 1
intercept_uncertainty = 1E-6
l1, l2= data[:, 0], data[:,1]
m1 = float(l2[1]-l2[0])/(l1[1]-l1[0])
m2 = float(l2[2]-l2[1])/(l1[2]-l1[1])
#print "gradients : ", m1, m2
#print "data[:, 0], data[:,1] :", data[:, 0], data[:,1]
#print [ 126.034164473, 176.0073111, 250.986510331][2], data[:, 0][2]
#print [ 126.034164473, 176.0073111, 250.986510331][0] ==data[:, 0][0], [ 14.61113696, 21.20112183, 31.0886678 ]==data[:,1].tolist()
#print linear_regression(data[:, 0], np.random.normal(data[:,1],1E-8*np.average(data[:,1])))
#print linear_regression(data[:, 0], data[:,1])
#print linear_regression([ 126.03416447, 176.0073111, 250.98651033], [ 14.61113696, 21.20112183, 31.0886678 ])
else:
#print " intercept, intercept_uncertainty : ", intercept, intercept_uncertainty
kernel_inputs_orig[n_binning_scheme].append([intercept, intercept_uncertainty])
#print kernel_inputs_orig
if print_bool : print "\nn_skipped_few_hits, n_skipped_vanishing_uncertainty / n_total : ", n_skipped_few_hits, " , ", n_skipped_vanishing_uncertainty, " / ", n_total
if n_skipped_few_hits + n_skipped_vanishing_uncertainty == n_total:
no_usable_bins = 1
no_maxima_found = 1
status.append([n_skipped_few_hits, n_skipped_vanishing_uncertainty, n_total, no_usable_bins ,no_maxima_found])
pvr_x_pred.append([ [-300], [-1]])
continue
##################################################
### KERNEL DENSITY ESTIMATION
##################################################
# Neither scipy.stats (gaussian_kde) not sklearn implementations allow to vary bandwidth on a per entry level
# Had to implement it myself
x_plot = np.linspace(-200, 400, 1200)
#x_plot = np.linspace(100, 200, 200)
#x_plot = np.linspace(-200, 400, 5)
y_plot = np.zeros(len(x_plot))
#X_plot = np.linspace(-200, 400, 1200)[:, np.newaxis]
kernel_inputs = []
for a in kernel_inputs_orig: kernel_inputs.extend(a) #flatten binning scheme
kernel_inputs = np.array(kernel_inputs)
#print kernel_inputs
#print "kernel_inputs.shape : ", kernel_inputs.shape
#print kernel_inputs
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
for a in range(kernel_inputs.shape[0]):
#print "y_plot : ", y_plot
y_plot += gaussian(x_plot, kernel_inputs[a,0], kernel_inputs[a,1])
#print "y_plot : ", y_plot
#Normalise
# Compute the area using the composite trapezoidal rule.
area = np.trapz(y_plot, dx=(x_plot[1]- x_plot[0]))
#area = np.trapz(y_plot, dx=1./len(y_plot)) #Assuming x_max - x_min is 1
y_plot = y_plot/ area
#y_plot = y_plot/ np.linalg.norm(y_plot)
if print_bool : print "Real PVs : ", data_dict["pvr_z"][e_i]
#if print_bool :
if True:
plt.clf()
plt.fill_between(x_plot, 0, y_plot)
plt.axvline(x=data_dict["pvr_z"][e_i], color='r', lw=1., linestyle = '-.')
plt.fill_between(x_plot, 0, y_plot, color='b')
#widths = np.linspace(5,200,40)
#indexes = find_peaks_cwt(y_plot, widths)
#print "indexes : ", indexes
if True:
# for local maxima
indices = argrelextrema(y_plot, np.greater)[0]
#print indices
if len(indices) > 0:
index_max = indices[np.argmax(y_plot[indices])]
if print_bool : print "Max predicted : ", x_plot[index_max], y_plot[index_max]
pvr_x_pred.append([ [x_plot[index_max]], [y_plot[index_max]]])
no_maxima_found = 0
else :
print "y_plot : ", y_plot
no_maxima_found = 1
print "No maxima found, e_i = ", e_i
pvr_x_pred.append([ [-300], [-1]])
no_usable_bins = 0
status.append([n_skipped_few_hits, n_skipped_vanishing_uncertainty, n_total, no_usable_bins ,no_maxima_found])
print "\nn_skipped_few_hits, n_skipped_vanishing_uncertainty, n_total, no_usable_bins ,no_maxima_found\n", np.sum(np.array(status), axis=0)
#print pvr_x_pred
cntr = 0
for i in range(n_events):
if pvr_x_pred[i][0][0]==-300:
cntr +=1
print cntr
# This can only be used for 1 PV per event
diff = []
for i in range(n_events):
#for i in range(1):
assert len(data_dict["pvr_z"][i])==1
diff.append(abs(data_dict["pvr_z"][i][0] - pvr_x_pred[i][0][0]))
diff_reasonable = []
error_counter = 0
for _ in diff:
if _ < 2: diff_reasonable.append(_)
else: error_counter +=1
print "error_counter : ", error_counter, " / ", n_events
n, bins, patches = plt.hist(np.clip(diff, 0, 2), bins=np.linspace(0,2,100)) # Make the last bin an overflow bin
plt.xlabel("pvr_z : abs(truth - pred)")
plt.ylabel("Events")
```
| 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.
```
# Transfer learning and fine-tuning
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/keras/transfer_learning"><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/snapshot-keras/site/en/guide/keras/transfer_learning.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/keras-team/keras-io/blob/master/guides/transfer_learning.py"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/keras/transfer_learning.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
## Setup
```
import numpy as np
import tensorflow as tf
from tensorflow import keras
```
## Introduction
**Transfer learning** consists of taking features learned on one problem, and
leveraging them on a new, similar problem. For instance, features from a model that has
learned to identify racoons may be useful to kick-start a model meant to identify
tanukis.
Transfer learning is usually done for tasks where your dataset has too little data to
train a full-scale model from scratch.
The most common incarnation of transfer learning in the context of deep learning is the
following workflow:
1. Take layers from a previously trained model.
2. Freeze them, so as to avoid destroying any of the information they contain during
future training rounds.
3. Add some new, trainable layers on top of the frozen layers. They will learn to turn
the old features into predictions on a new dataset.
4. Train the new layers on your dataset.
A last, optional step, is **fine-tuning**, which consists of unfreezing the entire
model you obtained above (or part of it), and re-training it on the new data with a
very low learning rate. This can potentially achieve meaningful improvements, by
incrementally adapting the pretrained features to the new data.
First, we will go over the Keras `trainable` API in detail, which underlies most
transfer learning & fine-tuning workflows.
Then, we'll demonstrate the typical workflow by taking a model pretrained on the
ImageNet dataset, and retraining it on the Kaggle "cats vs dogs" classification
dataset.
This is adapted from
[Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python)
and the 2016 blog post
["building powerful image classification models using very little
data"](https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html).
## Freezing layers: understanding the `trainable` attribute
Layers & models have three weight attributes:
- `weights` is the list of all weights variables of the layer.
- `trainable_weights` is the list of those that are meant to be updated (via gradient
descent) to minimize the loss during training.
- `non_trainable_weights` is the list of those that aren't meant to be trained.
Typically they are updated by the model during the forward pass.
**Example: the `Dense` layer has 2 trainable weights (kernel & bias)**
```
layer = keras.layers.Dense(3)
layer.build((None, 4)) # Create the weights
print("weights:", len(layer.weights))
print("trainable_weights:", len(layer.trainable_weights))
print("non_trainable_weights:", len(layer.non_trainable_weights))
```
In general, all weights are trainable weights. The only built-in layer that has
non-trainable weights is the `BatchNormalization` layer. It uses non-trainable weights
to keep track of the mean and variance of its inputs during training.
To learn how to use non-trainable weights in your own custom layers, see the
[guide to writing new layers from scratch](https://keras.io/guides/making_new_layers_and_models_via_subclassing/).
**Example: the `BatchNormalization` layer has 2 trainable weights and 2 non-trainable
weights**
```
layer = keras.layers.BatchNormalization()
layer.build((None, 4)) # Create the weights
print("weights:", len(layer.weights))
print("trainable_weights:", len(layer.trainable_weights))
print("non_trainable_weights:", len(layer.non_trainable_weights))
```
Layers & models also feature a boolean attribute `trainable`. Its value can be changed.
Setting `layer.trainable` to `False` moves all the layer's weights from trainable to
non-trainable. This is called "freezing" the layer: the state of a frozen layer won't
be updated during training (either when training with `fit()` or when training with
any custom loop that relies on `trainable_weights` to apply gradient updates).
**Example: setting `trainable` to `False`**
```
layer = keras.layers.Dense(3)
layer.build((None, 4)) # Create the weights
layer.trainable = False # Freeze the layer
print("weights:", len(layer.weights))
print("trainable_weights:", len(layer.trainable_weights))
print("non_trainable_weights:", len(layer.non_trainable_weights))
```
When a trainable weight becomes non-trainable, its value is no longer updated during
training.
```
# Make a model with 2 layers
layer1 = keras.layers.Dense(3, activation="relu")
layer2 = keras.layers.Dense(3, activation="sigmoid")
model = keras.Sequential([keras.Input(shape=(3,)), layer1, layer2])
# Freeze the first layer
layer1.trainable = False
# Keep a copy of the weights of layer1 for later reference
initial_layer1_weights_values = layer1.get_weights()
# Train the model
model.compile(optimizer="adam", loss="mse")
model.fit(np.random.random((2, 3)), np.random.random((2, 3)))
# Check that the weights of layer1 have not changed during training
final_layer1_weights_values = layer1.get_weights()
np.testing.assert_allclose(
initial_layer1_weights_values[0], final_layer1_weights_values[0]
)
np.testing.assert_allclose(
initial_layer1_weights_values[1], final_layer1_weights_values[1]
)
```
Do not confuse the `layer.trainable` attribute with the argument `training` in
`layer.__call__()` (which controls whether the layer should run its forward pass in
inference mode or training mode). For more information, see the
[Keras FAQ](
https://keras.io/getting_started/faq/#whats-the-difference-between-the-training-argument-in-call-and-the-trainable-attribute).
## Recursive setting of the `trainable` attribute
If you set `trainable = False` on a model or on any layer that has sublayers,
all children layers become non-trainable as well.
**Example:**
```
inner_model = keras.Sequential(
[
keras.Input(shape=(3,)),
keras.layers.Dense(3, activation="relu"),
keras.layers.Dense(3, activation="relu"),
]
)
model = keras.Sequential(
[keras.Input(shape=(3,)), inner_model, keras.layers.Dense(3, activation="sigmoid"),]
)
model.trainable = False # Freeze the outer model
assert inner_model.trainable == False # All layers in `model` are now frozen
assert inner_model.layers[0].trainable == False # `trainable` is propagated recursively
```
## The typical transfer-learning workflow
This leads us to how a typical transfer learning workflow can be implemented in Keras:
1. Instantiate a base model and load pre-trained weights into it.
2. Freeze all layers in the base model by setting `trainable = False`.
3. Create a new model on top of the output of one (or several) layers from the base
model.
4. Train your new model on your new dataset.
Note that an alternative, more lightweight workflow could also be:
1. Instantiate a base model and load pre-trained weights into it.
2. Run your new dataset through it and record the output of one (or several) layers
from the base model. This is called **feature extraction**.
3. Use that output as input data for a new, smaller model.
A key advantage of that second workflow is that you only run the base model once on
your data, rather than once per epoch of training. So it's a lot faster & cheaper.
An issue with that second workflow, though, is that it doesn't allow you to dynamically
modify the input data of your new model during training, which is required when doing
data augmentation, for instance. Transfer learning is typically used for tasks when
your new dataset has too little data to train a full-scale model from scratch, and in
such scenarios data augmentation is very important. So in what follows, we will focus
on the first workflow.
Here's what the first workflow looks like in Keras:
First, instantiate a base model with pre-trained weights.
```python
base_model = keras.applications.Xception(
weights='imagenet', # Load weights pre-trained on ImageNet.
input_shape=(150, 150, 3),
include_top=False) # Do not include the ImageNet classifier at the top.
```
Then, freeze the base model.
```python
base_model.trainable = False
```
Create a new model on top.
```python
inputs = keras.Input(shape=(150, 150, 3))
# We make sure that the base_model is running in inference mode here,
# by passing `training=False`. This is important for fine-tuning, as you will
# learn in a few paragraphs.
x = base_model(inputs, training=False)
# Convert features of shape `base_model.output_shape[1:]` to vectors
x = keras.layers.GlobalAveragePooling2D()(x)
# A Dense classifier with a single unit (binary classification)
outputs = keras.layers.Dense(1)(x)
model = keras.Model(inputs, outputs)
```
Train the model on new data.
```python
model.compile(optimizer=keras.optimizers.Adam(),
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[keras.metrics.BinaryAccuracy()])
model.fit(new_dataset, epochs=20, callbacks=..., validation_data=...)
```
## Fine-tuning
Once your model has converged on the new data, you can try to unfreeze all or part of
the base model and retrain the whole model end-to-end with a very low learning rate.
This is an optional last step that can potentially give you incremental improvements.
It could also potentially lead to quick overfitting -- keep that in mind.
It is critical to only do this step *after* the model with frozen layers has been
trained to convergence. If you mix randomly-initialized trainable layers with
trainable layers that hold pre-trained features, the randomly-initialized layers will
cause very large gradient updates during training, which will destroy your pre-trained
features.
It's also critical to use a very low learning rate at this stage, because
you are training a much larger model than in the first round of training, on a dataset
that is typically very small.
As a result, you are at risk of overfitting very quickly if you apply large weight
updates. Here, you only want to readapt the pretrained weights in an incremental way.
This is how to implement fine-tuning of the whole base model:
```python
# Unfreeze the base model
base_model.trainable = True
# It's important to recompile your model after you make any changes
# to the `trainable` attribute of any inner layer, so that your changes
# are take into account
model.compile(optimizer=keras.optimizers.Adam(1e-5), # Very low learning rate
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[keras.metrics.BinaryAccuracy()])
# Train end-to-end. Be careful to stop before you overfit!
model.fit(new_dataset, epochs=10, callbacks=..., validation_data=...)
```
**Important note about `compile()` and `trainable`**
Calling `compile()` on a model is meant to "freeze" the behavior of that model. This
implies that the `trainable`
attribute values at the time the model is compiled should be preserved throughout the
lifetime of that model,
until `compile` is called again. Hence, if you change any `trainable` value, make sure
to call `compile()` again on your
model for your changes to be taken into account.
**Important notes about `BatchNormalization` layer**
Many image models contain `BatchNormalization` layers. That layer is a special case on
every imaginable count. Here are a few things to keep in mind.
- `BatchNormalization` contains 2 non-trainable weights that get updated during
training. These are the variables tracking the mean and variance of the inputs.
- When you set `bn_layer.trainable = False`, the `BatchNormalization` layer will
run in inference mode, and will not update its mean & variance statistics. This is not
the case for other layers in general, as
[weight trainability & inference/training modes are two orthogonal concepts](
https://keras.io/getting_started/faq/#whats-the-difference-between-the-training-argument-in-call-and-the-trainable-attribute).
But the two are tied in the case of the `BatchNormalization` layer.
- When you unfreeze a model that contains `BatchNormalization` layers in order to do
fine-tuning, you should keep the `BatchNormalization` layers in inference mode by
passing `training=False` when calling the base model.
Otherwise the updates applied to the non-trainable weights will suddenly destroy
what the model has learned.
You'll see this pattern in action in the end-to-end example at the end of this guide.
## Transfer learning & fine-tuning with a custom training loop
If instead of `fit()`, you are using your own low-level training loop, the workflow
stays essentially the same. You should be careful to only take into account the list
`model.trainable_weights` when applying gradient updates:
```python
# Create base model
base_model = keras.applications.Xception(
weights='imagenet',
input_shape=(150, 150, 3),
include_top=False)
# Freeze base model
base_model.trainable = False
# Create new model on top.
inputs = keras.Input(shape=(150, 150, 3))
x = base_model(inputs, training=False)
x = keras.layers.GlobalAveragePooling2D()(x)
outputs = keras.layers.Dense(1)(x)
model = keras.Model(inputs, outputs)
loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)
optimizer = keras.optimizers.Adam()
# Iterate over the batches of a dataset.
for inputs, targets in new_dataset:
# Open a GradientTape.
with tf.GradientTape() as tape:
# Forward pass.
predictions = model(inputs)
# Compute the loss value for this batch.
loss_value = loss_fn(targets, predictions)
# Get gradients of loss wrt the *trainable* weights.
gradients = tape.gradient(loss_value, model.trainable_weights)
# Update the weights of the model.
optimizer.apply_gradients(zip(gradients, model.trainable_weights))
```
Likewise for fine-tuning.
## An end-to-end example: fine-tuning an image classification model on a cats vs. dogs dataset
To solidify these concepts, let's walk you through a concrete end-to-end transfer
learning & fine-tuning example. We will load the Xception model, pre-trained on
ImageNet, and use it on the Kaggle "cats vs. dogs" classification dataset.
### Getting the data
First, let's fetch the cats vs. dogs dataset using TFDS. If you have your own dataset,
you'll probably want to use the utility
`tf.keras.preprocessing.image_dataset_from_directory` to generate similar labeled
dataset objects from a set of images on disk filed into class-specific folders.
Transfer learning is most useful when working with very small datasets. To keep our
dataset small, we will use 40% of the original training data (25,000 images) for
training, 10% for validation, and 10% for testing.
```
import tensorflow_datasets as tfds
tfds.disable_progress_bar()
train_ds, validation_ds, test_ds = tfds.load(
"cats_vs_dogs",
# Reserve 10% for validation and 10% for test
split=["train[:40%]", "train[40%:50%]", "train[50%:60%]"],
as_supervised=True, # Include labels
)
print("Number of training samples: %d" % tf.data.experimental.cardinality(train_ds))
print(
"Number of validation samples: %d" % tf.data.experimental.cardinality(validation_ds)
)
print("Number of test samples: %d" % tf.data.experimental.cardinality(test_ds))
```
These are the first 9 images in the training dataset -- as you can see, they're all
different sizes.
```
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
for i, (image, label) in enumerate(train_ds.take(9)):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(image)
plt.title(int(label))
plt.axis("off")
```
We can also see that label 1 is "dog" and label 0 is "cat".
### Standardizing the data
Our raw images have a variety of sizes. In addition, each pixel consists of 3 integer
values between 0 and 255 (RGB level values). This isn't a great fit for feeding a
neural network. We need to do 2 things:
- Standardize to a fixed image size. We pick 150x150.
- Normalize pixel values between -1 and 1. We'll do this using a `Normalization` layer as
part of the model itself.
In general, it's a good practice to develop models that take raw data as input, as
opposed to models that take already-preprocessed data. The reason being that, if your
model expects preprocessed data, any time you export your model to use it elsewhere
(in a web browser, in a mobile app), you'll need to reimplement the exact same
preprocessing pipeline. This gets very tricky very quickly. So we should do the least
possible amount of preprocessing before hitting the model.
Here, we'll do image resizing in the data pipeline (because a deep neural network can
only process contiguous batches of data), and we'll do the input value scaling as part
of the model, when we create it.
Let's resize images to 150x150:
```
size = (150, 150)
train_ds = train_ds.map(lambda x, y: (tf.image.resize(x, size), y))
validation_ds = validation_ds.map(lambda x, y: (tf.image.resize(x, size), y))
test_ds = test_ds.map(lambda x, y: (tf.image.resize(x, size), y))
```
Besides, let's batch the data and use caching & prefetching to optimize loading speed.
```
batch_size = 32
train_ds = train_ds.cache().batch(batch_size).prefetch(buffer_size=10)
validation_ds = validation_ds.cache().batch(batch_size).prefetch(buffer_size=10)
test_ds = test_ds.cache().batch(batch_size).prefetch(buffer_size=10)
```
### Using random data augmentation
When you don't have a large image dataset, it's a good practice to artificially
introduce sample diversity by applying random yet realistic transformations to
the training images, such as random horizontal flipping or small random rotations. This
helps expose the model to different aspects of the training data while slowing down
overfitting.
```
from tensorflow import keras
from tensorflow.keras import layers
data_augmentation = keras.Sequential(
[layers.RandomFlip("horizontal"), layers.RandomRotation(0.1),]
)
```
Let's visualize what the first image of the first batch looks like after various random
transformations:
```
import numpy as np
for images, labels in train_ds.take(1):
plt.figure(figsize=(10, 10))
first_image = images[0]
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
augmented_image = data_augmentation(
tf.expand_dims(first_image, 0), training=True
)
plt.imshow(augmented_image[0].numpy().astype("int32"))
plt.title(int(labels[0]))
plt.axis("off")
```
## Build a model
Now let's built a model that follows the blueprint we've explained earlier.
Note that:
- We add a `Rescaling` layer to scale input values (initially in the `[0, 255]`
range) to the `[-1, 1]` range.
- We add a `Dropout` layer before the classification layer, for regularization.
- We make sure to pass `training=False` when calling the base model, so that
it runs in inference mode, so that batchnorm statistics don't get updated
even after we unfreeze the base model for fine-tuning.
```
base_model = keras.applications.Xception(
weights="imagenet", # Load weights pre-trained on ImageNet.
input_shape=(150, 150, 3),
include_top=False,
) # Do not include the ImageNet classifier at the top.
# Freeze the base_model
base_model.trainable = False
# Create new model on top
inputs = keras.Input(shape=(150, 150, 3))
x = data_augmentation(inputs) # Apply random data augmentation
# Pre-trained Xception weights requires that input be scaled
# from (0, 255) to a range of (-1., +1.), the rescaling layer
# outputs: `(inputs * scale) + offset`
scale_layer = keras.layers.Rescaling(scale=1 / 127.5, offset=-1)
x = scale_layer(x)
# The base model contains batchnorm layers. We want to keep them in inference mode
# when we unfreeze the base model for fine-tuning, so we make sure that the
# base_model is running in inference mode here.
x = base_model(x, training=False)
x = keras.layers.GlobalAveragePooling2D()(x)
x = keras.layers.Dropout(0.2)(x) # Regularize with dropout
outputs = keras.layers.Dense(1)(x)
model = keras.Model(inputs, outputs)
model.summary()
```
## Train the top layer
```
model.compile(
optimizer=keras.optimizers.Adam(),
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[keras.metrics.BinaryAccuracy()],
)
epochs = 20
model.fit(train_ds, epochs=epochs, validation_data=validation_ds)
```
## Do a round of fine-tuning of the entire model
Finally, let's unfreeze the base model and train the entire model end-to-end with a low
learning rate.
Importantly, although the base model becomes trainable, it is still running in
inference mode since we passed `training=False` when calling it when we built the
model. This means that the batch normalization layers inside won't update their batch
statistics. If they did, they would wreck havoc on the representations learned by the
model so far.
```
# Unfreeze the base_model. Note that it keeps running in inference mode
# since we passed `training=False` when calling it. This means that
# the batchnorm layers will not update their batch statistics.
# This prevents the batchnorm layers from undoing all the training
# we've done so far.
base_model.trainable = True
model.summary()
model.compile(
optimizer=keras.optimizers.Adam(1e-5), # Low learning rate
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[keras.metrics.BinaryAccuracy()],
)
epochs = 10
model.fit(train_ds, epochs=epochs, validation_data=validation_ds)
```
After 10 epochs, fine-tuning gains us a nice improvement here.
| github_jupyter |
# Importing Libraries
```
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
from matplotlib.ticker import MaxNLocator
```
# Creating Erdos Renyi Graph and Plotting Degree Centrality
```
def visualiseER(nodes,p):
G = nx.erdos_renyi_graph(nodes,p)
d = nx.degree_centrality(G)
fig = plt.figure(figsize = (6,5))
colors = list(d.values())
pos = nx.kamada_kawai_layout(G)
nx.draw(G,
with_labels=True,
pos = pos,
node_size = 350,
node_color = colors,
edge_color = 'k')
fig.set_facecolor('white')
plt.title("Erdos Renyi Graph with nodes = {} and p = {}".format(nodes, p))
plt.show()
fig = plt.figure(figsize = (8,5))
w = 0.01
bins = np.arange(min(list(d.values())), max(list(d.values())) + w, w)
plt.hist(list(d.values()),bins = bins, density = True, alpha = 0.65, edgecolor = "black")
plt.title("Degree Centrality Histogram")
plt.gca().yaxis.set_major_locator(MaxNLocator(integer=True))
plt.xlabel("Degree Centrality Values")
plt.ylabel("Frequency")
plt.show()
return(d)
d1 = visualiseER(100, 0.3)
d2 = visualiseER(100,0.6)
```
## Inferences
1. The more connected nodes can be seen in Yellow Color. As the connectivity decreases, the color moves from **Yellow -> Green -> Blue -> Violet**.
2. As the probability of connections (p) increases, there will be a higher frequency of those nodes with a higher degree centrality. It means that overall **nodes get more connected**.
3. Below curve gives a comparison between the two ER Models. It follows a **Binomial Distribution**.
# Comparative ER Models
```
fig = plt.figure(figsize = (8,5))
sns.kdeplot(list(d1.values()), shade = True, label = "ER1")
sns.kdeplot(list(d2.values()), shade = True, label = "ER2")
plt.title("Degree Centrality Density Plot")
plt.gca().yaxis.set_major_locator(MaxNLocator(integer=True))
plt.legend()
plt.xlabel("Degree Centrality Values")
plt.ylabel("Frequency")
```
# Creating Barabasi Albert Random Graph and Plotting Degree Centrality
```
def visualiseBAR(nodes,m):
G = nx.barabasi_albert_graph(nodes,m)
d = nx.degree_centrality(G)
fig = plt.figure(figsize = (6,5))
colors = list(d.values())
pos = nx.kamada_kawai_layout(G)
nx.draw(G,
with_labels=True,
pos = pos,
node_size = 350,
node_color = colors,
edge_color = 'k')
fig.set_facecolor('white')
plt.title("Barabasi Albert Random Graph with nodes = {} and m = {}".format(nodes, m))
plt.show()
fig = plt.figure(figsize = (8,5))
w = 0.01
bins = np.arange(min(list(d.values())), max(list(d.values())) + w, w)
plt.hist(list(d.values()), bins = bins, density = True, alpha = 0.65, edgecolor = "black")
plt.title("Degree Centrality Histogram")
plt.gca().yaxis.set_major_locator(MaxNLocator(integer=True))
plt.xlabel("Degree Centrality Values")
plt.ylabel("Frequency")
plt.show()
visualiseBAR(100,3)
```
## Inferences
1. The Node that is most connected will be in Yellow. As the connectivity decreases it moves from **Yellow -> Green -> Blue -> Violet**.
2. The Histogram shows that most nodes are having lower degree centrality. They are less connected to their neighbours.
3. Barabasi Albert Model follows a **Power Law distribution.**
## Conclusion
1. **Degree Centrality**:<br>
It is a measure of node connectivity in a Graph. It is simply a measure of the number of edges it has w.r.t to the rest of nodes in a network. Here, in directed networks, nodes are having both In-degree and Out-degree, and both are used to calculate it.
2. **Erdos Renyi Model**:<br>
a. The edges are set in this Graph such that each edge has a fixed probability of being present or absent, independently of the other edges.<br>
b. They follow a binomial distribution. As p increases, the curve shifts as connectivity increases.<br>
c. Most real world networks are not ER Random Graphs. They are scale free or BA Graphs.
3. **Barabasi Albert Model:** <br>
They have two main characteristics:<br>
a. **Growth** : They start with an initial number of nodes. They keep adding the nodes to an initial small network.<br>
b. **Preferential Attachment:** Follows **Rich gets Richer** Phenomenon. In this model, an edge is most likely to attach to nodes with higher
degrees.<br>
This is the reason why for Barabasi we see a higher frequency of nodes with lesser degree centrality. These could be the initial set of nodes that are initially less connected and have lower chance of getting the new nodes, to be connected to them. There are a few nodes that will have a higher degree centrality and that becomes the **hubs** in these types of Networks.This follows a **Scale free or Power law distribution**.<br>
*Examples for further analysis : Social Networks, Citation Networks, World Wide Web Network (WWW)*
| github_jupyter |
# Quantum Phase Estimation on the Hubbard molecule
We would like to study the "Hubbard dimer" molecule, whose Hamiltonian reads:
$$H=-t\sum_{\sigma=\uparrow,\downarrow}\left(c_{1\sigma}^{\dagger}c_{2\sigma}+c_{2\sigma}^{\dagger}c_{1\sigma}\right)-\mu\sum_{i=1,2}\sum_{\sigma=\uparrow,\downarrow}n_{i\sigma}+U\sum_{i=1,2}n_{i\uparrow}n_{i\downarrow}$$
with $n_{i\sigma} = c^\dagger_{i\sigma} c_{i\sigma}$. We will choose $\mu=U/2$ to keep the number of electrons at one per site.
## Defining the Hubbard dimer Hamiltonian
```
%load_ext autoreload
%autoreload 2
import numpy as np
import itertools
from qat.dqs.hamiltonians import make_hubbard_model
U = 1.0
t = 0.2
t_mat = - t * np.array([[0., 1.],
[1., 0.]])
hamilt = make_hubbard_model(t_mat, U, mu=U/2)
eigvals = np.linalg.eigvalsh(hamilt.get_matrix())
E0 = min(eigvals)
print("Exact energy = ", E0)
```
## Performing phase estimation
```
from qat.qpus import LinAlg
from qat.dqs.phase_estimation import perform_phase_estimation
qpu = LinAlg()
nqbits_adiab = 6
nqbits_phase = 6
target_energy = E0 + 0.05
print("Guess energy =", target_energy)
for n_adiab_steps, n_trotter_steps in itertools.product([2, 4, 6], [4]):
energy, prob, eigvec = perform_phase_estimation(hamilt, nqbits_adiab, nqbits_phase,
n_adiab_steps, n_trotter_steps,
target_energy, 0.2, 0.2,
qpu=qpu,
n_shots=np.inf, verbose=True)
print("-> n_adiab_steps = %s, n_trotter = %s ==> E = %s"%(n_adiab_steps,n_trotter_steps, energy))
```
Note that one can of course replace an ideal QPU with a noisy one.
The circuit used for phase estimation is accessible via the function ``make_phase_estimation_circuit``:
```
from qat.dqs.phase_estimation import make_phase_estimation_circuit
n_adiab_steps = 2
n_trotter_steps = 1
circ = make_phase_estimation_circuit(hamilt,
nqbits_adiab,
nqbits_phase,
n_adiab_steps,
n_trotter_steps,
target_energy, 0.2, 0.2)
print("Depth of PEA circuit =", len(circ))
```
## Trotterisation
The ``qat.dqs.trotterisation`` module also provides a trotterization routine (in Jordan-Wigner representation) that returns a ``QRoutine`` approximating the unitary evolution $\exp(-i H t)$. In the cell below, $H$ is ``hamilt``, and $t$ is ``final_time``.
```
from qat.dqs.trotterisation import make_trotterisation_routine
from qat.lang.AQASM import Program
n_trotter_steps = 1
final_time = 1
prog = Program()
reg = prog.qalloc(hamilt.hpq.shape[0])
prog.apply(make_trotterisation_routine(hamilt, n_trotter_steps, final_time), reg)
circ = prog.to_circ()
%qatdisplay circ
```
| github_jupyter |
```
import pandas as pd
import csv
import nltk
import re
import matplotlib.pyplot as plt
from nltk.tokenize import TweetTokenizer
from tokenizer import *
from nltk.corpus import stopwords
from ekphrasis.classes.preprocessor import TextPreProcessor
from ekphrasis.classes.tokenizer import SocialTokenizer
from ekphrasis.dicts.emoticons import emoticons
from nltk.stem import SnowballStemmer
import ast
import emoji
import unicodedata
import gzip
import spacy_udpipe
import language_tool_python
import sys
import os
sys.path.append('..')
pd.set_option("display.max_colwidth", None)
# names of files to read from
train_val_AB_TSV = '../../../SaRaH/dataset/haspeede2/raw/haspeede2_dev/haspeede2_dev_taskAB.tsv'
italian_words = '../../../SaRaH/dataset/words/parole_uniche.txt'
bad_words = '../../../SaRaH/dataset/words/lista_badwords.txt'
test_tweets_AB_TSV = '../../../SaRaH/dataset/haspeede2/raw/haspeede2_test/haspeede2_test_taskAB-tweets.tsv'
test_news_AB_TSV = '../../../SaRaH/dataset/haspeede2/raw/haspeede2_test/haspeede2-test_taskAB-news.tsv'
reference_tweets_AB_TSV = '../../../SaRaH/dataset/haspeede2/raw/haspeede2_reference/haspeede2_reference_taskAB-tweets.tsv'
reference_news_AB_TSV = '../../../SaRaH/dataset/haspeede2/raw/haspeede2_reference/haspeede2_reference_taskAB-news.tsv'
#Italian dictionary
f1 = open(italian_words, 'r', encoding='utf8')
italian_dict = [] #list of lowercase words
for x in f1:
y = x.rstrip()
y = y.lower()
if y != '':
italian_dict.append(y)
#Bad Words
f2 = open(bad_words, 'r', encoding='utf8')
bad_words_dict = [] #list of lowercase words
for x in f2:
y = x.rstrip()
y = y.lower()
if y != '':
bad_words_dict.append(y)
#Dataset
df = pd.read_csv(train_val_AB_TSV, sep='\t')
```
<h2> Fixing the dataset
```
df.rename(columns={"text ": "text"}, inplace=True) #the text column is identified by 'text ' (with a space at the end), change
df
```
<h2> Preprocessing
<h3> Removing URLs
```
def clean_url(text):
return re.sub(r'URL', ' ', text)
df['text'] = df['text'].apply(clean_url)
```
<h3> Removing Tags
```
def clean_tag(text):
return re.sub(r'@user', ' ', text)
df['text'] = df['text'].apply(clean_tag)
```
<h3> Feature extraction: length of the comment
```
def text_length(text):
return len(text)
df['text_length'] = df['text'].apply(text_length)
```
<h3> Translation of emoji
```
def translate_emoticon(text):
text_result = emoji.demojize(text, language='it')
return text_result
df['text'] = df['text'].apply(translate_emoticon)
```
<h3> Removing Hashtags
```
def find_hashtags(text):
result = re.findall(r'#\S+', text)
if result:
return result
else:
return None
df['hashtags'] = df['text'].apply(find_hashtags)
#https://github.com/cbaziotis/ekphrasis
text_processor = TextPreProcessor(
# terms that will be normalized
normalize=['email', 'percent', 'money', 'phone', 'user', 'time', 'date', 'number'],
# terms that will be annotated
annotate={"hashtag"},
fix_html=True, # fix HTML tokens
unpack_hashtags=True, # perform word segmentation on hashtags
# select a tokenizer. You can use SocialTokenizer, or pass your own
# the tokenizer, should take as input a string and return a list of tokens
tokenizer=SocialTokenizer(lowercase=False).tokenize,
# list of dictionaries, for replacing tokens extracted from the text,
# with other expressions. You can pass more than one dictionaries.
dicts=[emoticons]
)
def clean_hashtags(text):
return " ".join(text_processor.pre_process_doc(text))
df['text'] = df['text'].apply(clean_hashtags)
```
<h3> Removing number, percent, money, time, email, date and phone (and others)
```
numbers_to_remove = ['<number>', '<percent>', '<money>', '<time>', '<email>', '<date>', '<phone>', '<br/>']
def remove_numbers1(text):
text_words = text.split()
new_words = [word for word in text_words if word not in numbers_to_remove]
return ' '.join(new_words)
df['text'] = df['text'].apply(remove_numbers)
```
<h3> Convert all emoticons written in text
```
emoticons_text = {
'<kiss>': 'bacio',
'<happy>': 'felice',
'<laugh>': 'risata',
'<sad>': 'triste',
'<surprise>': 'sorpreso',
'<wink>': 'occhiolino',
'<tong>': 'faccia con lingua',
'<annoyed>': 'annoiato',
'<seallips>': 'labbra sigillate',
'<angel>': 'angelo',
'<devil>': 'diavolo',
'<highfive>' : 'batti il cinque',
'<heart>': 'cuore',
'<user>' : 'persona'
}
def clean_emoticon_text(text):
text_words = text.split()
new_words = [emoticons_text.get(ele, ele) for ele in text_words]
return ' '.join(new_words)
df['text'] = df['text'].apply(clean_emoticon_text)
```
<h3> Replace the characters ‘&’, ‘@’ respectively in the letters ‘e’, ‘a’
```
def replace_atand(text):
text_words = text.split()
for i, word in enumerate(text_words):
if word == '&':
text_words[i] = 'e'
elif word == '@':
text_words[i] = 'a'
return ' '.join(text_words)
df['text'] = df['text'].apply(replace_atand)
```
<h3> Add space
```
def add_space(text):
words = text.split()
newwords = []
for word in words:
for i in range(0, len(word)):
if i != len(word)-1 and word[i] != ' ':
if word[i].islower() and word[i+1].isupper():
word = word[:i+1] + ' ' + word[i+1:]
newwords.append(word)
return ' '.join(newwords)
df['text'] = df['text'].apply(add_space)
```
<h3> Feature extraction: percentage of words written in CAPS-LOCK
```
def caps_lock_words(text):
words = text.split()
count_caps_lock = 0
number_of_words = len(words)
for word in words:
if word.isupper() == True:
count_caps_lock = count_caps_lock + 1
return ((count_caps_lock*100)//number_of_words)
df['%CAPS-LOCK words'] = df['text'].apply(caps_lock_words)
```
<h3> Feature extraction: number of ‘!’ inside the comment
```
def esclamations(text):
return text.count('!')
df['esclamations'] = df['text'].apply(esclamations)
```
<h3> Feature extraction: number of ‘?’ inside the comment
```
def questions(text):
return text.count('?')
df['questions'] = df['text'].apply(questions)
```
<h3> Convert all characters into lowercase
```
def lowercase(text):
return str(text).lower()
df['text'] = df['text'].apply(lowercase)
```
<h3> Normalizing Words #1
```
word_norm = {'wi-fi':'wifi'}
def normalizing_words1(text):
text_words = text.split()
new_words = [word_norm.get(ele, ele) for ele in text_words]
return ' '.join(new_words)
df['text'] = df['text'].apply(normalizing_words1)
```
<h3> Removing Punctuation #1
```
def clean_punctuation1(text):
text = re.sub(r'[•]', ' ', text)
text = re.sub(r'<', ' ', text) #<
text = re.sub(r'>', ' ', text) #>
return re.sub(r'[’]', ' ', text)
df['text'] = df['text'].apply(clean_punctuation1)
```
<h3> Replacement of accented characters with their unaccented characters
```
def strip_accents(text):
try:
text = unicode(text, 'utf-8')
except (TypeError, NameError): # unicode is a default on python 3
pass
text = unicodedata.normalize('NFD', text)
text = text.encode('ascii', 'ignore')
text = text.decode("utf-8")
return str(text)
df['text'] = df['text'].apply(strip_accents)
```
<h3> Cleaning Censured Bad Words
```
def clean_censured_bad_words(text):
text = " " + text + " "
text = re.sub(r' c[.x*@%#$^]+i ', ' coglioni ', text)
text = re.sub(r' c[.x*@%#$^]+e ', ' coglione ', text)
text = re.sub(r' c[.x*@%#$^]+o ', ' cazzo ', text)
text = re.sub(r' c[.x*@%#$^]+i ', ' cazzi ', text)
text = re.sub(r' m[.x*@%#$^]+a ', ' merda ', text)
text = re.sub(r' m[.x*@%#$^]+e ', ' merde ', text)
text = re.sub(r' c[.x*@%#$^]+ulo ', ' culo ', text)
text = re.sub(r' p[.x*@%#$^]+a ', ' puttana ', text)
text = re.sub(r' p[.x*@%#$^]+e ', ' puttane ', text)
text = re.sub(r' t[.x*@%#$^]+a ', ' troia ', text)
text = re.sub(r' t[.x*@%#$^]+e ', ' troie ', text)
text = re.sub(r' s[.x*@%#$^]+o ', ' stronzo ', text)
text = re.sub(r' s[.x*@%#$^]+i ', ' stronzi ', text)
return text
df['text'] = df['text'].apply(clean_censured_bad_words)
```
<h3> Removing Punctuation #2
```
def clean_punctuation2(text):
text = re.sub(r"[()[\]{}]", ' ', text)
text = re.sub(r"[.,:;_-]", ' ', text)
text = re.sub(r"[+*]", ' ', text)
text = re.sub(r"[!?]", ' ', text)
text = re.sub(r"[£$%&'~\\|`=^]", ' ', text)
return re.sub(r'["@]', ' ', text)
df['text'] = df['text'].apply(clean_punctuation2)
```
<h3> Removing nearby equal vowels
```
vowels = ['a', 'e', 'i', 'o', 'u']
def clean_vowels(text):
new_text = text
words = text.split()
for word in words:
if word not in italian_dict:
new_string = word[0]
for i in range(1, len(word)):
if word[i] not in vowels:
new_string = new_string + word[i]
else:
if(word[i] != word[i-1]):
new_string = new_string + word[i]
new_text = new_text.replace(word, new_string)
return new_text
df['text'] = df['text'].apply(clean_vowels)
```
<h3> Removing nearby equal consonants if they are more than 2
```
consonants = ['b','c','d','f','g','h','k','l','m','n','p','q','r','s','t','v','x','y','z']
def clean_consonants(text):
new_text = text
words = text.split()
for word in words:
new_string = word[0]
for i in range(1, len(word)):
if word[i] not in consonants:
new_string = new_string + word[i]
else:
if(word[i] != word[i-1]):
new_string = new_string + word[i]
elif i>=2 and (word[i] != word[i-2]):
new_string = new_string + word[i]
new_text = new_text.replace(word, new_string)
return new_text
df['text'] = df['text'].apply(clean_consonants)
#Save the dataset
df.to_csv('df_new1.csv', index=False)
#Dataset
df = pd.read_csv('df_new1.csv', sep=',')
df
```
<h3> Fixing Hashtags
```
fixed_hashtags = {'pala di na':'paladina', 'ponti na':'pontina', 'ms na':'msna', 'drago na':'dragona', 'sp accio':'spaccio',
'bianco enero':'bianco nero', 'laria chet ira':'lariachetira', 'nom as':'nomas', 'mi granti':'migranti',
'as roma':'associazione sportiva roma', 'as li erdogan':'asli erdogan', 'hates pech':'hate speech',
'razz ismo':'razzismo', 'prima gl italiani':'prima italiani', 'ios to con':'io sto con', 'sp rar':'sprar',
'str as burgo':'strasburgo', 'is is':'isis', 'aria che ti rala':'lariachetira', 'immi grati':'immigrati',
'blas femia':'blasfemia', 'imp icc agi one':'impiccagione', 'multicultural ismo':'multicultural ismo',
'don neve late':'donne velate', 'bambi ne':'bambine', 'in fibula zi oni':'infibulazioni',
'audi zi one':'audizione', 'mig razi one':'migrazione', 'so luzi one':'soluzione', 'stu pri':'stupri',
'sosti tuzi one':'sostituzione', 'lariachetirala':'lariachetira', 'an is amri':'anis amri',
'different is possible':'differente possibile', 'cassim at is':'cassimatis', 'chalie hebdo':'charlie hebdo',
'terror is to':'terrorista', 'terror is ta':'terrorista', 'terrorist id is tratti':'terroristi distratti',
'sopra vv is sut':'sopravvissut', 'is petto rio nu':'ispettori onu', 'islam ici':'islamici',
'is lame violenza':'islam violenza', 'islam ed is educazione':'islam diseducazione', 'bo gabo xi':'bogaboxi',
'islam ep rev aric azione':'islam prevaricazione', 'sp ese':'spese', 'prost it uzi one':'prostituzione',
'chil ha visto':'chilhavisto', 'acalciinculo':'calci culo', 'clan destin':'clandestin',
'wl italia':'viva italia', 'wil popolo':'viva popolo', 'toc chi':'tocchi', 'luss em burgo':'lussemburgo',
'otto em ezo':'ottoemezzo', 'ipo crit':'ipocrit', 'ipo crisia':'ipocrisia', 'ipo cris ie':'ipocrisie',
'sb arcano':'sbarcano', 'terror ist':'terrorist', 'cog lioni':'coglioni', 'sap eva telo':'sapevatelo',
'piazza puli ta':'piazzapulita', 'nuove rosor se':'nuove risorse', 'per if eri':'periferi', 'in ps':'inps',
'de grado':'degrado', 'prof ugh if vg':'profughi friuli venezia giulia', 'das po':'daspo',
'animal if an at ici':'animali fanatici', 'if antas midi porto palo':'fantasmi porto palo',
'crimini mmi grati':'crimini immigrati', 'face bok':'facebook', 'occulta men to':'occultamento',
'infant ici d':'infanticid', 'reda zion ale':'redazionale', 'braccia let to':'braccialetto',
'ri sorsa':'risorsa', 'stu prato r':'stuprator', 'per messi rim patri':'permessi rimpatri',
'loc azione':'locazione', 'as tener si':'astenersi', 'appart amenti':'appartamenti', 'razzi sti':'razzisti',
'servizi mmo bili ari':'servizi immobiliari', 'strag emigranti':'strage migranti', 'im be cilli':'imbecilli',
'responsa bil it as oggetti va':'responsabilita soggettiva', 'centrisociale':'centri sociali',
'as segni assist enzi ali':'assegni assistenziali', 'inter dici amol as an tanche':'interdiciamo santanche',
'libere tco gitans':'liberetcogitans', 'sb archi':'sbarchi', 'rifugi ati':'rifugiati', 'sb ronzi':'sbronzi',
'stocco lma':'stoccolma', 'pid dino':'piddino', 'com pl ici':'complici', 'pale rm':'palermo',
'porta porta':'portaaporta', 'decretosalvini':'decreto salvini', 'decretosicurezza':'decreto sicurezza',
'governodelcambiamento':'governo cambiamento', 'quartarepubblica':'quarta repubblica', 'asiabibi':'asia bibi',
'desiremariottini':'desiree mariottini', 'virginiaraggi':'virginia raggi', 'fur ti':'furti',
'multicultural ism':'multiculturalism', 'arrest at':'arrestat', 'differenz iata':'differenziata',
'rifi uti':'rifiuti', 'mer de':'merde', 'quartarepubblica':'quarta repubblica', 'de linqu enza':'delinquenza',
'fem mini st':'femminist', 'solid arieta':'solidarieta', 'acc og lie':'accogliere',
'dirittiumani':'diritti umani', 'davidegerbino':'davide gerbino', 'whitegenocide':'genocidio bianco',
'robertosaviano':'roberto saviano', 'lad re':'ladre', 'attu alita':'attualita', 'cial tron':'cialtron',
'tu rust':'turist', 'sc hifo':'schifo', 'romaostia':'roma ostia', 'legal izzi amo':'legalizziamo',
'risco priamo':'riscopriamo', 'fal sari':'falsari', 'rapina tor':'rapinator', 'tu rist':'turist',
'se questra tor':'sequestrator', 'patron agg io':'patronaggio', 'acc oglio ni':'accoglioni',
're at odium anita':'reato umanita', 'pid occhi':'pidocchi', 'dis occupazione':'disoccupazione',
'fec cia':'feccia', 'rif lettere':'riflettere', 'tru ffa tor':'truffator', 'nazis ti':'nazisti',
'civil tal los bando':'civilta allo sbando', 'imm grazi one':'immigrazione', 'populi sti':'populisti',
'sovran isti':'sovranisti', 'fasciorazzisti':'fascisti razzisti', 'fintosinistra':'finto sinistra',
'imp icc at':'impiccat', 'populis mo':'populismo', 'migrant ima italiani':'migranti mai italiani',
'migrant our':'migrantour', 'sionis mo':'sionismo', 'olocau sto':'olocausto',
'giulianopisapia':'giuliano pisapia', 'traffic ant':'trafficant', 'schiavi st':'schiavist',
'immi gr ofili':'immigrofili', 'preocc up ante':'preoccupante', 'legit tima':'legittima',
'terrorist ifil occidentali':'terroristi filoccidentali', 'cimb ro':'cimbro', 'traffic ant':'trafficant',
'schiavi st':'schiavist', 'tru ffa':'truffa', 'freddoimmigrati':'freddo immigrati',
'riscaldamentoitaliani':'riscaldamento italiani', 'dopoillegali':'dopo illegali',
'vediamoterromotati':'vediamo terremotati', 'maisicurezza':'mai sicurezza', 'bar coni':'barconi',
'approvatoitalexit':'approvato italexit', 'bar caccia':'barcaccia',
'islam izz azione':'islamizzazione', 'organ izz azione':'organizzazione', 'immi ingrati':'immigrati ingrati',
'imm irati':'immigrati', 'islamstop':'islam stop', 'combat ti amo':'combattiamo',
'bastabergoglio':'basta bergoglio', 'dit tatura':'dittatura', 'sus sidi':'sussidi', 'pag are':'pagare',
'spa rite':'sparite', 'pen sioni':'pensioni', 'imp unita':'impunita', 'primi tivi':'primitivi',
'vio lenze':'violenze', 'eli mini amolo':'eliminiamolo', 'nazis mo':'nazismo',
'uman it aris mo':'umanitarismo', 'ger archi':'gerarchi', 'imm ingrati':'immigrati ingrati',
'iostoconsalvini':'io sto con salvini', 'stopinvasione':'stop invasione',
'bastamoraledelcaxxo':'basta morale del cazzo', 'iostocon':'io sto con', 'lintervista':'intervista'}
def hashtag_fix(text):
for word in fixed_hashtags:
text = text.replace(word, fixed_hashtags[word])
return text
df['text'] = df['text'].apply(hashtag_fix)
```
<h3> Removing Numbers
```
def clean_numbers(text):
text = " " + text + " "
#text = re.sub(r'\d+[.,]\d+', ' ', text)
#text = re.sub(r'\d+/\d+/\d', ' ', text)
#return re.sub(r' [\d]+', ' ', text)
return re.sub(r' \d+', ' ', text)
df['text'] = df['text'].apply(clean_numbers)
numbers = ['uno', 'due', 'tre', 'quattro', 'cinque', 'sette', 'otto', 'nove', 'dieci', 'undici', 'dodici', 'tredici',
'quattordici', 'quindici', 'sedici', 'diciasette', 'diciotto', 'diciannove', 'venti', 'venticinque', 'trenta', 'quaranta',
'cinquanta', 'sessanta', 'settanta', 'ottanta', 'novanta', 'cento', 'mille', 'milioni', 'miliardi']
def clean_letters_numbers(text):
text_words = text.split()
resultwords = [word for word in text_words if word not in numbers]
return ' '.join(resultwords)
#df['text'] = df['text'].apply(clean_letters_numbers)
```
<h3> Removing laughs
```
laughs = ['ah', 'eh', 'he' 'ih', 'hi'] #non elimina ahahahah, ma solo ah
vowels = ['a', 'e', 'i', 'o', 'u']
def clean_laughs(text):
#s = "ahahahah ho fame io, eh eh" -> " ho fame io,"
text_words = text.split()
new_words = [word for word in text_words if word not in laughs]
new_text = ' '.join(new_words)
for i in new_words:
for k in vowels:
if ('h' in i) and (len(i) >= 4):
if (len(i) - 2) <= (i.count(k) + i.count('h')):
new_text = new_text.replace(i, '')
return new_text
df['text'] = df['text'].apply(clean_laughs)
```
<h3> Removing articles and preposition #1
```
articles = ['il', 'lo', 'i', 'gli', 'la', 'le', 'un', 'uno', 'una', 'l']
prepositions = ['del', 'della', 'dello', 'dell', 'dei', 'degli', 'delle', 'al', 'allo', 'alla', 'all', 'ai', 'alle', 'agli',
'dal', 'dallo', 'dalla', 'dall', 'dai', 'dagli', 'dalle', 'nel', 'nello', 'nella', 'nell', 'nei', 'negli',
'nelle', 'sul', 'sullo', 'sulla', 'sull', 'sui', 'sugli', 'sulle', 'di', 'a', 'da', 'in', 'con', 'per', 'su',
'fra', 'tra']
def clean_articles_prepositions1(text):
text_words = text.split()
resultwords = [word for word in text_words if word not in articles and word not in prepositions]
return ' '.join(resultwords)
df['text'] = df['text'].apply(clean_articles_prepositions1)
```
<h3> Removing Stopwords #1
```
print(stopwords.words('italian'))
stop_words = set(stopwords.words('italian')) #Non ci sono tutte
def clean_stopwords(text):
text_words = text.split()
resultwords = [word for word in text_words if word not in stop_words]
return ' '.join(resultwords)
df['text'] = df['text'].apply(clean_stopwords)
```
<h3> Removing Punctuation #3
```
def clean_punctuation3(text):
return re.sub(r'#', ' ', text)
df['text'] = df['text'].apply(clean_punctuation3)
```
<h3> Tokenization
```
def tokenization(text):
tknzr=SocialTokenizer(lowercase=True)
return tknzr.tokenize(text)
df['tokens'] = df['text'].apply(tokenization)
```
<h3> Removing Punctuation #4
```
def clean_punctuation4(tokens):
punctuation = ['/','<','>']
resultwords = [word for word in tokens if word not in punctuation]
return resultwords
df['tokens'] = df['tokens'].apply(clean_punctuation4)
```
<h3> Replacement of the abbreviations with the respective words
```
abbr_word = {'cmq':'comunque', 'gov':'governatori', 'fb':'facebook', 'tw':'twitter', 'juve':'juventus', 'ing':'ingegnere',
'sx':'sinistra', 'qdo':'quando', 'rep':'repubblica', 'grz':'grazie', 'ita':'italia', 'mln':'milioni',
'mld':'miliardi', 'pke':'perche', 'anke':'anche', 'cm':'come', 'dlla':'della', 'dlle':'delle', 'qst':'questa',
'ke':'che', 'nn':'non', 'sn':'sono', 'cn':'con', 'xk':'perche', 'xke':'perche'}
def replace_abbreviation(tokens):
new_tokens = [abbr_word.get(ele, ele) for ele in tokens]
return new_tokens
df['tokens'] = df['tokens'].apply(replace_abbreviation)
```
<h3> Translating
```
eng_ita = {'europe':'europa', 'migration':'migrazione', 'muslim':'musulmano', 'immigration':'immigrazione',
'fuck':'cazzo', 'problem':'problema', 'refuges':'rifugiati', 'immigrants':'immigrati', 'attack':'attacco',
'error':'errore', 'illegal':'illegale', 'muslims':'musulmani', 'bastard':'bastardo', 'migrants':'migranti',
'wedding':'matrimonio', 'gipsy':'rom', 'belgium':'belgio', 'strasbourg':'strasburgo', 'death':'morte',
'invasion':'invasione', 'uman':'umano', 'rights':'diritti', 'earth':'terra', 'civil':'civile', 'terror':'terrore',
'angels':'angeli', 'low':'basso', 'cost':'costo', 'welcome':'benvenuto', 'attacks':'attacchi', 'berlin':'berlino',
'scum':'feccia', 'action':'azione'}
def translate_tokens(tokens):
new_tokens = [eng_ita.get(ele, ele) for ele in tokens]
return new_tokens
df['tokens'] = df['tokens'].apply(translate_tokens)
```
<h3> Word correction #1
```
error_correct1 = {'facebok':'facebook', 'retweted':'retweeted', 'coperative':'cooperative', 'coperazione':'cooperazione',
'gogle':'google', 'creranno':'creeranno', 'twet':'tweet', 'bok':'book', 'mediterrane':'mediterranee',
'kep':'keep', 'microare':'microaree', 'ise':'isee', 'desire':'desiree', 'temporane':'temporanee',
'wekend':'weekend', 'coperativa':'cooperativa', 'vodo':'voodoo', 'cop':'coop', 'laure':'lauree',
'canan':'canaan', 'cananiti':'canaaniti', 'bomerang':'boomerang', 'feyenord':'feyenoord',
'scoter':'scooter', 'blomberg':'bloomberg'}
def word_correction1(tokens):
new_tokens = [error_correct1.get(ele, ele) for ele in tokens]
return new_tokens
df['tokens'] = df['tokens'].apply(word_correction1)
```
<h3> Word correction #2
```
error_correct2 = {'pdioti':'pidioti', 'caxxo':'cazzo', 'dev':'deve', 'merd':'merda', 'terrorist':'terrorista',
'multicultural':'multiculturale', 'litalia':'italia', 'mezz':'mezzo', 'responsab':'responsabile',
'difender':'difendere', 'merdamma':'merda', 'mantener':'mantenere', 'uropa':'europa', 'strupri':'stupri',
'mettetevelo':'mettere', 'uccideteli':'uccidere', 'laggente':'gente', 'kompagni':'compagni',
'deiterroristi':'terroristi', 'leuropa':'europa', 'pdiota':'pidiota', 'kienge':'kyenge',
'poracci':'poveracci', 'lislam':'islam', 'acquarius':'aquarius', 'pdoti':'pidioti', 'pdote':'pidiote',
'democraziae':'democrazia', 'capode':'capodanno', 'eur':'euro', 'munnezz':'spazzatura', 'renzie':'renzi',
'accoglioni':'coglioni', 'demmerda':'merda', 'tagliagolla':'tagliagola', 'pidoti':'pidioti',
'pidote':'pidiote', 'immigrat':'immigrato', 'terroris':'terrorista', 'quant':'quanto', 'quanno':'quando',
'tornar':'tornare', 'selfini':'selfie', 'selfi':'selfie', 'delinquent':'delinquenti', 'metidate':'meditate',
'primat':'primato', 'perfavore':'favore', 'portono':'portano', 'atendono':'attendono',
'cladestini':'clandestini', 'terrotisti':'terroristi', 'rosika':'rosica', 'piddiota':'pidiota',
'aiutoamoli':'aiutiamoli', 'penicillin':'penicillina', 'invasone':'invasione', 'imprendittore':'imprenditore',
'nindagini':'indagini', 'nferito':'ferito', 'sntenze':'sentenze', 'sullideologia':'ideologia',
'ilcapoluogo':'capoluogo', 'quaeda':'qaeda', 'kossovaro':'kosovaro', 'nellappartamento':'appartamento',
'attacheremo':'attaccheremo', 'chepalle':'palle', 'ilterrorismo':'terrorismo', 'partecipenti':'partecipanti',
'sosituzione':'sostituzione', 'qaresima':'quaresima', 'carabineri':'carabinieri', 'ebbravo':'bravo',
'alitalia':'italia', 'ridistrubuzione':'ridistribuzione', 'espusione':'espulsione', 'lonu':'onu',
'leggittima':'legittima', 'glimmigrati':'immigrati', 'giovenissni':'giovanissimi', 'caxxi':'cazzi',
'italini':'italiani', 'colgioni':'coglioni', 'marzagrato':'massacrato', 'inmersa':'immersa',
'ilegali':'illegali', 'laddri':'ladri', 'santache':'santanche', 'quatar':'qatar', 'amazo':'ammazzo',
'botiglia':'bottiglia', 'spaco':'spacco', 'assasino':'assassino', 'xfavore':'favore',
'xbenismo':'perbenismo', 'kenia':'kenya', 'minkia':'minchia', 'cojone':'coglione',
'immigratti':'immigrati', 'slvini':'salvini', 'xpregare':'pregare', 'mediocro':'mediocre',
'tortutati':'torturati', 'antocostituzionale':'anticostituzionale', 'rassista':'razzista',
'milirdi':'miliardi', 'eccerto':'certo', 'gnurant':'ignorante', 'immigrzione':'immigrazione',
'spigazione':'spiegazione', 'medeglia':'medaglia', 'poltici':'politici', 'scomettiamo':'scommettiamo',
'senegalwsi':'senegalesi', 'matrattano':'maltrattano', 'scapperano':'scapperanno',
'mygranti':'migranti', 'djffondetelo':'diffondetelo', 'autirizzare':'autorizzare', 'notiziaro':'notiziario',
'rivistano':'rovistano', 'immigrazi':'immigrati', 'islamophobia':'islamofobia', 'pisqua':'pasqua',
'ncazzi':'cazzi', 'burqua':'burqa', 'halilovich':'halilovic', 'monologale':'monolocale',
'pablovic':'pavlovic', 'schenghen':'schengen', 'incazare':'incazzare', 'spacare':'spaccare',
'botilia':'bottiglia', 'faciamo':'facciamo', 'bizanzio':'bisanzio', 'nonvuole':'vuole',
'leggittimati':'legittimati', 'ribiombare':'ripiombare', 'inportando':'importando', 'chidere':'chiedere',
'specialnente':'specialmente', 'abbettere':'abbattere', 'ijaidisti':'jihadisti', 'ilpd':'pd',
'giudce':'giudice', 'islamizzazzione':'islamizzazione', 'itaiani':'italiani', 'continuamo':'continuiamo',
'mantenereli':'mantenerli', 'nonostate':'nonostante', 'bomberdate':'bombardate', 'buonusti':'buonisti',
'riempendola':'riempiendola', 'rassisti':'razzisti', 'exstacomunitari':'extracomunitari',
'conksciuto':'conosciuto', 'dimmerda':'merda', 'retroguadie':'retroguardie', 'terrosristi':'terroristi',
'bussiness':'business', 'lsciati':'lasciati', 'sopresa':'sorpresa', 'mejo':'meglio', 'muiono':'muoiono',
'distrugere':'distruggere', 'riepire':'riempire', 'deficente':'deficiente', 'fabblicato':'fabbricato',
'sfrontatazza':'sfrontatezza', 'mohomed':'mohamed', 'srmplice':'semplice', 'ocvupazioni':'occupazioni',
'guadeloupean':'guadeloupe', 'costuzionale':'costituzionale', 'drgli':'dirgli', 'kondividi':'condividi',
'lancifiamme':'lanciafiamme', 'cosegnati':'consegnati', 'indistrubati':'indisturbati', 'behqti':'behati',
'nabellezza':'bellezza', 'divertinento':'divertimento', 'smartphon':'smartphone', 'herzegovina':'erzegovina',
'corroti':'corrotti', 'decelebrato':'decerebrato', 'namo':'andiamo', 'lavete':'levati', 'marzuk':'marzouk',
'vaxxngul':'vaffanculo', 'excomunista':'comunista', 'vaccinan':'vaccinano', 'accusadi':'accusa',
'insegnav':'insegnavano', 'jne':'jnews', 'stacon':'sta', 'kompagno':'compagno', 'compactfor':'compact',
'sueddeutsche':'suddeutsche', 'regahliamo':'regaliamo', 'uccidrrebbero':'ucciderebbero',
'starsburgo':'strasburgo', 'spantaneamente':'spontaneamente', 'strasburg':'strasburgo', 'lapacchia':'pacchia',
'deglitaliani':'italiani', 'convinvono':'convivono', 'gravementne':'gravemente', 'kompagne':'compagne',
'disitegreranno':'disintegreranno', 'pwrcentuali':'percentuali', 'judei':'giudei', 'piddioti':'pidioti',
'pdidioti':'pidioti', 'professionoste':'professioniste', 'prwticanti':'praticanti', 'ammore':'amore',
'ovviamemte':'ovviamente', 'ammaxxa':'ammazza', 'buddah':'buddha', 'invadeare':'invadere',
'organizzaziobe':'organizzazione', 'pdjoti':'pidioti', 'tagadala':'tagcda', 'fankulo':'fanculo',
'tru':'truffa', '<rubare>':'rubare'}
def word_correction2(tokens):
new_tokens = [error_correct2.get(ele, ele) for ele in tokens]
return new_tokens
df['tokens'] = df['tokens'].apply(word_correction2)
```
<h3> Removing Words
```
def removing_words(tokens):
words = ['ns', 'bla', 'slarp', 'rt', 'gt', 'lt', 'amp', 'xv', 'tutt', 'alors', 'na', 'cpt', 'je', 'suis',
'jesuis', 'gen', 'gl', 'enne', 'gogo', 'iv', 'perchi', 'enere', 'sennare', 'sap', 'dic', 'feb', 'xo', 'dere',
'daje', 'bom', 'cll', 'dll', 'ctta', 'tut', 'lol', 'cds', 'cvd', 'urc', 'tiv', 'nov', 'xix', 'ele', 'ndo',
'bau', 'xvi']
resultwords = [word for word in tokens if word not in words]
return resultwords
df['tokens'] = df['tokens'].apply(removing_words)
```
<h3> Replacing Acronyms
```
acronyms = {'unhcr':['alto', 'commissariato', 'nazioni', 'unite', 'rifugiati'],
'onu':['organizzazione', 'nazioni', 'unite'],
'fdi':['fratelli', 'italia'],
'msna':['minori', 'stranieri', 'accompagnati'],
'rdc':['reddito', 'cittadinanza'],
'gus':['gruppo', 'umana', 'solidarieta'],
'sprar':['sistema', 'protezione', 'richiedenti', 'asilo'],
'anpi':['associazione', 'nazionale', 'partigiani', 'italia'],
'anac':['autorita', 'nazionale', 'anticorruzione'],
'lgbt':['lesbiche', 'gay', 'bisessuali', 'transgender'],
'ln':['lega', 'nord'],
'ue':['unione', 'europea'],
'msf':['medici','senza','frontiere'],
'ispi':['istituto','studi','politica','internazionale'],
'cpr':['centri','permanenza','rimpatri'],
'pd':['partito', 'democratico'],
'gc':['guardia', 'costiera'],
'inps':['istituto','nazionale','previdenza','sociale'],
'cdm':['consiglio', 'ministri'],
'pdl':['popolo', 'liberta'],
'atac':['azienda', 'tramvie', 'autobus', 'comune', 'roma'],
'tav':['treno', 'alta', 'velocita'],
'isee':['situazione', 'economica', 'equivalente'],
'usa':['stati', 'uniti', 'america'],
'onlus':['organizzazione', 'lucrativa', 'utilita', 'sociale'],
'acsim':['associazione', 'centro', 'servizi', 'immigrati', 'marche'],
'aids':['sindrome', 'immuno', 'deficienza', 'acquisita'],
'eu':['unione', 'europea'],
'ong':['organizzazione', 'governativa'],
'nwo':['nuovo', 'ordine', 'mondiale'],
'pil':['prodotto', 'interno', 'lordo'],
'cgil':['confederazione', 'generale', 'lavoro'],
'cdt':['corriere', 'ticino'],
'ptv':['societa', 'televisiva', 'pakistan'],
'syriza':['coalizione', 'sinistra', 'radicale'],
'fiom':['federazione', 'impiegati', 'operai', 'metallurgici'],
'lgbtq':['lesbiche', 'gay', 'bisessuali', 'transgender', 'queer'],
'rpl':['radio', 'padania', 'libera'],
'arci':['associazione', 'ricreativa', 'culturale', 'italiana'],
'ofcs':['osservatorio', 'focus', 'cultura', 'sicurezza'],
'm5s':['movimento', 'cinque', 'stelle'],
'wm5s':['movimento', 'cinque', 'stelle']}
def replace_acronyms(tokens):
for i in range(0, len(tokens)):
word = tokens[i]
if word in acronyms:
tokens[i] = acronyms[word][0]
if len(acronyms[word]) > 1:
for j in range(1, len(acronyms[word])):
tokens.insert(i+j, acronyms[word][j])
return tokens
df['tokens'] = df['tokens'].apply(replace_acronyms)
```
<h3> Removing tokens of lenth <= 2
```
def clean_length1(tokens):
resultwords = [word for word in tokens if len(word)>2]
return resultwords
df['tokens'] = df['tokens'].apply(clean_length1)
```
<h3> Removing articles and preposition #2
```
articles = ['il', 'lo', 'i', 'gli', 'la', 'le', 'un', 'uno', 'una', 'l']
prepositions = ['del', 'della', 'dello', 'dell', 'dei', 'degli', 'delle', 'al', 'allo', 'alla', 'all', 'ai', 'alle', 'agli',
'dal', 'dallo', 'dalla', 'dall', 'dai', 'dagli', 'dalle', 'nel', 'nello', 'nella', 'nell', 'nei', 'negli',
'nelle', 'sul', 'sullo', 'sulla', 'sull', 'sui', 'sugli', 'sulle', 'di', 'a', 'da', 'in', 'con', 'per', 'su',
'fra', 'tra']
def clean_articles_prepositions2(tokens):
resultwords = [word for word in tokens if word not in articles and word not in prepositions]
return resultwords
df['tokens'] = df['tokens'].apply(clean_articles_prepositions2)
```
<h3> Removing Stopwords #2
```
stop_words = set(stopwords.words('italian')) #Non ci sono tutte
def clean_stopwords2(tokens):
resultwords = [word for word in tokens if word not in stop_words]
return resultwords
df['tokens'] = df['tokens'].apply(clean_stopwords2)
```
<h3> Removing English Stopwords
```
print(stopwords.words('english'))
eng_stop_words = set(stopwords.words('english')) #Non ci sono tutte
def clean_eng_stopwords(tokens):
resultwords = [word for word in tokens if word not in eng_stop_words]
return resultwords
df['tokens'] = df['tokens'].apply(clean_eng_stopwords)
```
<h3> Feature extraction: percentage of Bad Words
```
def percentage_bad_words(tokens):
n_words = 0
n_bad_words = 0
for word in tokens:
if word != '<hashtag>' and word != '</hashtag>':
n_words = n_words + 1
for word in tokens:
if word in bad_words_dict:
n_bad_words = n_bad_words + 1
return ((n_bad_words*100)//n_words)
df['%bad_words'] = df['tokens'].apply(percentage_bad_words)
```
<h3> Word Frequency
```
inverted_index = {}
for i in range(0, len(df)):
for word in df['tokens'][i]:
if word not in inverted_index and word != '<hashtag>' and word != '</hashtag>':
inverted_index[word] = 1
elif word != '<hashtag>' and word != '</hashtag>':
inverted_index[word] = inverted_index[word] + 1
len(inverted_index)
count_1 = 0
for x in inverted_index.values():
if x == 1:
count_1 = count_1 + 1
count_1
```
<h3> Spelling Error Detection
```
no_error = ['lidl', 'isis', 'aquarius', 'soros', 'macron', 'hebdo', 'kyenge', 'jihadisti', 'caritas', 'ilgiornale',
'pidioti', 'sky', 'tagada', 'voxnews', 'casapound', 'immigrazionisti', 'assad', 'selfie', 'iussoli', 'webitalia',
'reddit', 'tgcom', 'padania', 'afroislamici', 'brexit', 'shariah', 'twitter', 'pride', 'censis', 'skytg', 'obama',
'borsoni', 'times', 'today', 'fanpage', 'piddina', 'iphone', 'marenostrum', 'vauro', 'immigrazionista', 'uk',
'mediaset', 'silicon', 'valley', 'santanche', 'repubblicait', 'cyber', 'scampia', 'mondialista', 'lambrate',
'araboafricani', 'juncker', 'italietta', 'thuram', 'euronews', 'mosul', 'zuckerberg', 'sportnews', 'vladimir',
'luxuria', 'ciociaria', 'liberoquotidiano', 'trudeau', 'agenparl', 'schengen', 'mahershala', 'radiorpl',
'primavalle', 'lulic', 'masod', 'lepen', 'gheddafi','lahore', 'afroislamica', 'feyen', 'allahu', 'adolf',
'fakenews', 'bilderberg', 'wifi', 'civilissima', 'bunga', 'salviniani', 'notiziona', 'portaaporta', 'coop',
'cattivisti', 'huffpost', 'rohingya','piddine', 'dirottarli', 'novax', 'profit', 'complottista', 'microaree',
'peppista', 'piddino', 'globalisti','sophia', 'arms', 'facebook', 'juventus', 'frontex', 'social', 'retweeted',
'lariachetira', 'google', 'updated', 'tweet', 'chilhavisto', 'ottoemezzo', 'amnesty', 'piazzapulita', 'maxirissa',
'anticorruzione', 'fake', 'mediterranee', 'keep', 'liberetcogitans', 'daspo', 'rolls', 'royce', 'salvini',
'quintacolonna', 'openarms', 'sovranista', 'sovranisti', 'asia', 'bibi', 'desiree', 'mariottini', 'rugantina',
'virginia', 'raggi', 'bloc', 'boldrina', 'multiculturale', 'porrajmos', 'nomadare', 'tpi', 'cornigliano',
'migrantes', 'straparlare', 'sapevatelo', 'sovranista', 'sovranisti', 'politically', 'globalcompactformigration',
'crocerossa', 'linate', 'iovotono', 'musulmania', 'domenicalive', 'opensociety', 'roberto', 'saviano', 'pidiota',
'cuffiette', 'gender', 'road', 'rss', 'nomas', 'sinistronzi', 'corcolle', 'unar', 'bolzaneto', 'tracing',
'dateci', 'portateli', 'rimandiamoli', 'rimandarli', 'accoglierne', 'pagarci', 'educarli', 'usarli', 'integrarci',
'eliminarlo', 'perdetela', 'mandateli', 'impugnamo', 'apparte', 'cacciamoli', 'sottometterci', 'imporci',
'mandiamola', 'ricordiamolo', 'rimpatriarli', 'riportateli', 'omnimilano', 'riprenderci', 'iuventa', 'alerts',
'synthe', 'pig', 'fdo', 'act', 'jobs', 'work', 'dott', 'selfie', 'mandandoli', 'strafulmini', 'reductio',
'riacesi', 'jane', 'alil', 'vardar', 'testaccio', 'jaunes', 'lets', 'watch', 'pidiote', 'like', 'schmidt', 'bremme',
'caricarli', 'costruirselo', 'malvedenti', 'concertone', 'lineapress', 'costringendoci', 'indebitarci', 'imbonirsi',
'depenalizzazioni', 'startup', 'softair', 'hillary', 'padovaoggi', 'morning', 'dortmund', 'soffocandomi',
'macchinoni', 'mattinonline', 'spiegatelo', 'convertirli', 'sgozzarci', 'rispondetegli', 'segnalarne',
'birmingham', 'raqqa', 'sudtirol', 'carrefour', 'farceli', 'disilluderla', 'definiteli', 'finanziarli', 'domandone',
'dusseldorf', 'radicalizzazioni', 'consegnateci', 'billionaire', 'conviverci', 'sgomberarlo', 'syria',
'rinchiuderle', 'riprenderle', 'mangiarmeli', 'rigopiano', 'xfactor', 'sorelline', 'volevasi', 'erasmus',
'tgpuglia', 'dategliela', 'levatela', 'dubai', 'tagliarli', 'facciamoli', 'riportarli', 'candidabili',
'donarle', 'sterilizzarlo', 'comandarci', 'mattinodinapoli', 'vestirli', 'fornirne', 'aiutiamoli', 'principalmete',
'sputacchiarlo', 'trattiamoli', 'qatar', 'rinchiuderli', 'rimandarle', 'alcatraz', 'rapinarci', 'dominarci',
'cinquestelle', 'mondialisti', 'infilartelo', 'dateli', 'cercasi', 'riprenderseli', 'accogliamoli', 'glorificarli',
'piazzarci', 'eliminandole', 'chiudervi', 'mettervelo', 'allontaniamoli', 'zalando', 'occultandoli', 'bitcoin',
'ultraricchi', 'mostrandola', 'estorcergli', 'furbissimo', 'rolex', 'microimpresa', 'sopraffarci', 'pagarla',
'fenicenews', 'imporlo', 'riflettiamoci', 'gridiamolo', 'sbuffetto', 'spalmandola', 'condizionarle', 'venderti',
'sminuirli', 'spaventatissimo', 'immigrazioniste', 'boldriniana', 'teneteveli', 'descrittoci', 'spenderne',
'gestirseli', 'rosicone', 'promuoverne', 'chiuderlo', 'ciaone', 'votarla', 'cagnolina', 'potenziarsi',
'tutelarli', 'conquistarlo', 'ucciderli', 'integriamoli', 'scriviamolo', 'condannarli', 'confiscarla', 'adibirla',
'cacciandoli', 'afroislamiche', 'trasmetterli', 'contraddirlo', 'ripulirlo', 'popoliamole', 'guardateli',
'mortirolo', 'mastercard', 'isolarci', 'statene', 'visitarne', 'normalissima', 'gestendoli', 'affondatela',
'confondiamoli', 'salvateli', 'risollevarmi', 'uccidili', 'giornaloni', 'imponendoci', 'pulirselo',
'costringendoli', 'dotandoli', 'nostrum', 'chiediamogli', 'mandiamogli', 'costarci', 'diffonderli', 'fourquet',
'cresciutelli', 'follower', 'darglieli', 'dicesi', 'ingozzarti', 'sgombrarli', 'complottisti', 'maxirata',
'guess', 'pluripregiudicata', 'incontrarci', 'qaeda', 'tenerveli', 'bananalandia', 'prendersele', 'heidelberg',
'shabaab','rovistaggio', 'essersela', 'sumaya', 'besiktas', 'risvoltini', 'abbassargli', 'masharipov', 'burqa',
'halilovic', 'ciociariareport', 'buhari', 'ilfattoquotidiano', 'pavlovic', 'volkswagen', 'frustalo',
'sborroni', 'teleuniverso', 'porsche', 'karlov', 'lamezia', 'rispediamoli', 'trattienili', 'luttwak', 'schengen',
'ahadith', 'hamas', 'piegarci', 'samhain', 'jebreal', 'portateveli', 'comunistelli', 'choudary', 'hollande',
'sfigurarla', 'coranisti', 'sterminarci', 'istigarli', 'rimandateli', 'gestirli', 'razzaccia', 'polverizziamoli',
'fermiamoli', 'eliminarli', 'chiudiamoli', 'islamofobi', 'sovvenzionamenti', 'evitiamola', 'islamicamente',
'chiudetele', 'vushaj', 'adidas', 'esodati', 'sajida', 'salvarne', 'excelsior', 'ogboru', 'rapinarlo',
'liberiamola', 'massou', 'cacciateli', 'scarichiamoli', 'amatissimi', 'accollarseli', 'espelleteli', 'occuparvi',
'sfamarli', 'films', 'telefilms', 'mohamed', 'impietosirvi', 'tuscolana', 'bergogliani', 'guadeloupe',
'estinguervi', 'filoimmigrazionisti', 'raccattarli', 'rapinarmi', 'bruciargli', 'pippone', 'chiamiamoli',
'diamogliela', 'corvacci', 'tirargli', 'cacciarla', 'schiavizzarci', 'maledettissime', 'behati', 'kothen',
'allnews', 'qaradawi', 'proteggerti', 'regalargli', 'renziana', 'leuca', 'accogliergli', 'tornarvi', 'ricostruirli',
'arsizio', 'prendeteli', 'difendervi', 'sparkasse', 'disciplinarla', 'ignorantismo', 'bogaboxi', 'salvargli',
'soundcheck', 'erzegovina', 'sovranismi', 'nagativamente', 'venghino', 'interculturalita', 'contenerne', 'capitelo',
'condividili', 'sports', 'aufstehen', 'presuntuosamente', 'wojtyla', 'salvinisti', 'frenarla', 'froidiano',
'ficcatelo', 'afferrali', 'offrila', 'picchiarla', 'portiamone', 'jinping', 'tijuana', 'succhiasangue', 'bep',
'mortacci', 'digital', 'bowl', 'panigarola', 'marzouk', 'sigonella', 'equitalia', 'auchan', 'pulirti', 'orlandik',
'hotspot', 'qibad', 'senadid', 'boomerang', 'canaaniti', 'canaan', 'giornalettismo', 'stef', 'filoccidentali',
'hate', 'cimbro', 'imbecillissima', 'moviment', 'pound', 'feyenoord', 'italexit', 'herrou', 'rothschild',
'fogliettone', 'jnews', 'riccastri', 'verhofstadt', 'suddeutsche', 'zeitung', 'update', 'bokwango', 'cedric',
'passeur', 'beslan', 'maranella', 'convertirgli', 'rimandarne', 'prendeteveli', 'cucciolini', 'rubarla',
'sbarcateli', 'castrarci', 'arrestarli', 'tranquillissima', 'totalitaristi', 'arrivateci', 'bloomberg', 'midterms',
'indignamo', 'impedirvi', 'avengers', 'ricontattarli', 'organizzandoli', 'controllatissimi', 'sottocategoria',
'rimpatriamoli', 'salviniane', 'diffondetelo', 'rimpatriate', 'metterglielo' ,'firmarlo', 'chiuderci', 'cicciolina',
'insegnarglielo', 'accettandone', 'pagarli', 'buddha', 'portarseli', 'rasserenarli', 'sosteniamola', 'concedervi',
'trasformateci', 'stanarli', 'arrestarla', 'deutsche', 'ramallah', 'euroburocrati', 'libya', 'ultimora',
'gabbiaopen', 'la7', 'webitalia360', 'tagadala7', 'rai2', 'tgla7', 'rete4', 'mattino5', 'tg24', 'tg24news',
'tgcom24', 'lariachetira7', 'tg1', 'tg2', 'tg5', 'portaporta', 'news24', 'papamilano2017', 'road2sport',
'dimartedi', 'onsci', 'presadiretta']
spelling_errors = {} #word: (frequency, is_error), is_error = 1(yes), 0(no)
for i in range(0, len(df)):
for word in df['tokens'][i]:
if word not in spelling_errors and word != '<hashtag>' and word != '</hashtag>':
if word not in italian_dict and word not in no_error:
spelling_errors[word] = (inverted_index[word], 1)
elif word not in italian_dict and word in no_error:
spelling_errors[word] = (inverted_index[word], 0)
elif word in italian_dict and word not in no_error:
spelling_errors[word] = (inverted_index[word], 0)
misspelling_words = {} #{word_error1: frequency1, word_error2: frequency2, ...}
for word in spelling_errors.keys():
if spelling_errors[word][1] == 1:
misspelling_words[word] = spelling_errors[word][0]
print("There are {} misspelled words.".format(len(misspelling_words)))
freq_error = {} #{freq1: [word1, word2, ...], freq2: [word5], ...}
for x in misspelling_words:
if misspelling_words[x] not in freq_error:
freq_error[misspelling_words[x]] = [x]
else:
freq_error[misspelling_words[x]].append(x)
print(sorted(freq_error.keys()))
i = 2
print(freq_error[i])
def find(text):
if 'svuotacantine' in text:
return True
else:
return False
#Dataset
df2 = pd.read_csv(train_val_AB_TSV, sep='\t')
j = None
for i in range(0, len(df)):
if find(df.iloc[i]['tokens']):
j = i
print(i)
print(df2.iloc[j]['text '])
print(df.iloc[j]['tokens'])
i = 2192
#Dataset
df2 = pd.read_csv(train_val_AB_TSV, sep='\t')
df2.iloc[i]['text ']
df.iloc[i]['tokens']
df.drop(columns=['text'], inplace=True)
```
<h3> Saving DF with hashtags
```
df.to_csv('../../../SaRaH/dataset/haspeede2/preprocessed/dev/dev.csv', index=False)
```
<h4> Stemming
Saving DF with hashtags and stemming
```
#Dataset
df1 = pd.read_csv('../../../SaRaH/dataset/haspeede2/preprocessed/dev/dev.csv')
df['text'][1]
df1['tokens'][1]
#Convert the string into an array "['vado', 'casa']"-> ['vado', 'casa']
def clean_string(tokens):
return ast.literal_eval(tokens)
df1['tokens'] = df1['tokens'].apply(clean_string)
stemmer = SnowballStemmer('italian')
def stemming(tokens):
result = []
for word in tokens:
if word != '<hashtag>' and word != '</hashtag>':
stemmed_word = stemmer.stem(word)
result.append(stemmed_word)
else:
result.append(word)
return result
df1['tokens'] = df1['tokens'].apply(stemming)
df1.to_csv('../../../SaRaH/dataset/haspeede2/preprocessed/dev/dev_stemmed.csv', index=False)
```
<h3> Removing hashtag tags
```
def removing_hashtag_tags(tokens):
words = ['<hashtag>', '</hashtag>']
resultwords = [word for word in tokens if word not in words]
return resultwords
#Dataset
df2 = pd.read_csv('../../../SaRaH/dataset/haspeede2/preprocessed/dev/dev.csv', sep=',')
df2['tokens'] = df2['tokens'].apply(clean_string)
df2['tokens'] = df2['tokens'].apply(removing_hashtag_tags)
```
<h3> Saving DF without hashtags
```
df2.to_csv('../../../SaRaH/dataset/haspeede2/preprocessed/dev/dev_no_hashtag.csv', index=False)
```
<h4> Stemming
Saving DF without hashtags and with stemming
```
#Dataset
df3 = pd.read_csv('../../../SaRaH/dataset/haspeede2/preprocessed/dev/dev_no_hashtag.csv')
df3['tokens'] = df3['tokens'].apply(clean_string)
df3['tokens'] = df3['tokens'].apply(stemming)
df3.to_csv('../../../SaRaH/dataset/haspeede2/preprocessed/dev/dev_no_hashtag_stemmed.csv', index=False)
```
| github_jupyter |
```
import subprocess
from subprocess import PIPE
import rasterio
import json
import glob
import pandas as pd
import os
import cv2
```
<h3> Define Functions </h3>
```
# This function takes as argument the a string contraining the a path for one image.
# It check if the first band is empty (if all pixels are zero) and if yes it returns True otherwise False.
def check_empty_img(url):
# Reading Image
# You can give path to the
# image as first argument
# print(url)
image = cv2.imread(url+'/B01.tif',0)
# Checking if the image is empty or not
if (cv2.countNonZero(image) == 0):
return True
else:
return False
# This function takes 4 bands and it stacks them into a single image
def stack_bands(path, product_id):
print(path)
band_list = ['B02.tif', 'B03.tif', 'B04.tif', 'B08.tif']
try:
# Read metadata of first file
with rasterio.open(path +'/'+ band_list[0]) as src0:
meta = src0.meta
# Update meta to reflect the number of layers
meta.update(count = len(band_list))
# Read each layer and write it to stack
with rasterio.open(path + '/' + 'stack.tif', 'w', **meta) as dst:
for id, layer in enumerate(band_list, start=1):
with rasterio.open(path +'/'+ layer) as src1:
dst.write_band(id, src1.read(1))
except:
print("Folder with no Data")
remove_empty_folders(path)
pass
def product_name(path):
json_data=open(path+"/stac.json", "rb")
jdata = json.load(json_data)
return jdata['id']
# This functions deletes a folder and its containds if no spectral band is included
def remove_empty_folders(path):
subprocess.run(['rm', '-r', path])
return
def label(path):
# return thr label of each product which should be either Flood or not Flood,
# and convert it into 0 for not flood and 1 for flooded
return
```
<h2> Iterative Throug Folders </h2>
```
# Create a list with all the folders containing spectral bands
flist = []
rootdir = '/Volumes/ADATA_HV620/SEN12-FLOOD/Sentinel_2/Images/sen12floods_s2_source'
for file in os.listdir(rootdir):
d = os.path.join(rootdir, file)
if os.path.isdir(d):
flist.append(d)
print(f"The number of folders are currently = {len(flist)}")
#####################################################################################################################
# Iterate through all folders and create a new image with 4 spectral bands, namely Band2, Band3, Band4 and Band 8.
# These bands correspend to blue, greem, red and infrared respectively
for folder_path in flist:
empty = check_empty_img(folder_path) #check if the first the folder contains empty images
if empty:
print("The images inside the current folder are empty - zero")
remove_empty_folders(folder_path)
else:
product_id = product_name(folder_path)
stack_bands(folder_path, product_id)
# Iterate through the product list and count the number of folders once again an plot the new number.
flist_new = []
rootdir = '/Volumes/ADATA_HV620/SEN12-FLOOD/Sentinel_2/Images/sen12floods_s2_source'
for file in os.listdir(rootdir):
d = os.path.join(rootdir, file)
if os.path.isdir(d):
flist_new.append(d)
print(f"The number of folders after the pre-processing = {len(flist_new)}")
```
| github_jupyter |
## MNIST Dataset Overview
This example is using MNIST handwritten digits. The dataset contains 60,000 examples for training and 10,000 examples for testing. The digits have been size-normalized and centered in a fixed-size image (28x28 pixels) with values from 0 to 1. For simplicity, each image has been flattened and converted to a 1-D numpy array of 784 features (28*28).

More info: http://yann.lecun.com/exdb/mnist/
```
from __future__ import absolute_import, division, print_function
import tensorflow as tf
# Set Eager API
tf.enable_eager_execution()
tfe = tf.contrib.eager
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=False)
# Parameters
learning_rate = 0.1
batch_size = 128
num_steps = 1000
display_step = 100
# Iterator for the dataset
dataset = tf.data.Dataset.from_tensor_slices(
(mnist.train.images, mnist.train.labels))
dataset = dataset.repeat().batch(batch_size).prefetch(batch_size)
dataset_iter = tfe.Iterator(dataset)
# Variables
W = tfe.Variable(tf.zeros([784, 10]), name='weights')
b = tfe.Variable(tf.zeros([10]), name='bias')
# Logistic regression (Wx + b)
def logistic_regression(inputs):
return tf.matmul(inputs, W) + b
# Cross-Entropy loss function
def loss_fn(inference_fn, inputs, labels):
# Using sparse_softmax cross entropy
return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=inference_fn(inputs), labels=labels))
# Calculate accuracy
def accuracy_fn(inference_fn, inputs, labels):
prediction = tf.nn.softmax(inference_fn(inputs))
correct_pred = tf.equal(tf.argmax(prediction, 1), labels)
return tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# SGD Optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
# Compute gradients
grad = tfe.implicit_gradients(loss_fn)
# Training
average_loss = 0.
average_acc = 0.
for step in range(num_steps):
# Iterate through the dataset
d = dataset_iter.next()
# Images
x_batch = d[0]
# Labels
y_batch = tf.cast(d[1], dtype=tf.int64)
# Compute the batch loss
batch_loss = loss_fn(logistic_regression, x_batch, y_batch)
average_loss += batch_loss
# Compute the batch accuracy
batch_accuracy = accuracy_fn(logistic_regression, x_batch, y_batch)
average_acc += batch_accuracy
if step == 0:
# Display the initial cost, before optimizing
print("Initial loss= {:.9f}".format(average_loss))
# Update the variables following gradients info
optimizer.apply_gradients(grad(logistic_regression, x_batch, y_batch))
# Display info
if (step + 1) % display_step == 0 or step == 0:
if step > 0:
average_loss /= display_step
average_acc /= display_step
print("Step:", '%04d' % (step + 1), " loss=",
"{:.9f}".format(average_loss), " accuracy=",
"{:.4f}".format(average_acc))
average_loss = 0.
average_acc = 0.
# Evaluate model on the test image set
testX = mnist.test.images
testY = mnist.test.labels
test_acc = accuracy_fn(logistic_regression, testX, testY)
print("Testset Accuracy: {:.4f}".format(test_acc))
```
| github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.